Example #1
0
        public IEnumerable <IDocument> Execute(IReadOnlyList <IDocument> inputs, IExecutionContext context)
        {
            DotlessConfiguration config = DotlessConfiguration.GetDefault();

            config.Logger = typeof(LessLogger);
            EngineFactory engineFactory = new EngineFactory(config);

            return(inputs.AsParallel().Select(x =>
            {
                context.Trace.Verbose("Processing Less for {0}", x.Source);
                ILessEngine engine = engineFactory.GetEngine();

                // TODO: Get rid of RefelectionMagic and this ugly hack as soon as dotless gets better external DI support
                engine.AsDynamic().Underlying.Cache = new LessCache(context.ExecutionCache);

                string path = x.Get <string>(Keys.SourceFilePath, null);
                string fileName = null;
                if (path != null)
                {
                    engine.CurrentDirectory = Path.GetDirectoryName(path);
                    fileName = Path.GetFileName(path);
                }
                else
                {
                    engine.CurrentDirectory = context.InputFolder;
                    fileName = Path.GetRandomFileName();
                }
                string content = engine.TransformToCss(x.Content, fileName);
                return x.Clone(content);
            }));
        }
Example #2
0
        /// <inheritdoc />
        public IEnumerable <IDocument> Execute(IReadOnlyList <IDocument> inputs, IExecutionContext context)
        {
            DotlessConfiguration config = DotlessConfiguration.GetDefault();

            config.Logger = typeof(LessLogger);
            EngineFactory    engineFactory    = new EngineFactory(config);
            FileSystemReader fileSystemReader = new FileSystemReader(context.FileSystem);

            return(inputs.AsParallel().Select(context, input =>
            {
                Trace.Verbose("Processing Less for {0}", input.SourceString());
                ILessEngine engine = engineFactory.GetEngine();

                // TODO: Get rid of RefelectionMagic and this ugly hack as soon as dotless gets better external DI support
                engine.AsDynamic().Underlying.Cache = new LessCache(context.ExecutionCache);
                engine.AsDynamic().Underlying.Underlying.Parser.Importer.FileReader = fileSystemReader;

                FilePath path = input.FilePath(Keys.RelativeFilePath);
                string fileName = null;
                if (path != null)
                {
                    engine.CurrentDirectory = path.Directory.FullPath;
                    fileName = path.FileName.FullPath;
                }
                else
                {
                    engine.CurrentDirectory = string.Empty;
                    fileName = Path.GetRandomFileName();
                }
                string content = engine.TransformToCss(input.Content, fileName);
                return context.GetDocument(input, content);
            }));
        }
Example #3
0
        public void Components_Are_Correct_Registerd_To_Suppress_Import_Error()
        {
            var factory  = new ContainerFactory();
            var services = factory.GetServices(DotlessConfiguration.GetDefault());

            var lessEngineDescriptor = services.FirstOrDefault(s => s.ServiceType == typeof(ILessEngine));
            var importerDescriptor   = services.FirstOrDefault(s => s.ServiceType == typeof(IImporter));
            var parserDescriptor     = services.FirstOrDefault(s => s.ServiceType == typeof(Parser.Parser));

            Assert.NotNull(lessEngineDescriptor);
            Assert.NotNull(importerDescriptor);
            Assert.NotNull(parserDescriptor);

            Assert.AreEqual(lessEngineDescriptor.Lifetime, ServiceLifetime.Transient);
            Assert.AreEqual(importerDescriptor.Lifetime, lessEngineDescriptor.Lifetime);
            Assert.AreEqual(importerDescriptor.Lifetime, lessEngineDescriptor.Lifetime);
        }
        /// <inheritdoc />
        protected override Task <IEnumerable <IDocument> > ExecuteContextAsync(IExecutionContext context)
        {
            DotlessConfiguration config = DotlessConfiguration.GetDefault();

            // config.Logger = typeof(LessLogger);
            EngineFactory    engineFactory    = new EngineFactory(config);
            FileSystemReader fileSystemReader = new FileSystemReader(context.FileSystem);

            return(context.Inputs.ParallelSelectAsync(ProcessLessAsync));

            async Task <IDocument> ProcessLessAsync(IDocument input)
            {
                context.LogDebug("Processing Less for {0}", input.ToSafeDisplayString());

                // This is a hack to get to the underlying engine
                ParameterDecorator parameterDecorator = (ParameterDecorator)engineFactory.GetEngine();
                CacheDecorator     cacheDecorator     = (CacheDecorator)parameterDecorator.Underlying;
                LessEngine         engine             = (LessEngine)cacheDecorator.Underlying;

                engine.Logger = new LessLogger(context);
                ((Importer)engine.Parser.Importer).FileReader = fileSystemReader;

                // Less conversion
                FilePath path = await _inputPath.GetValueAsync(input, context);

                if (path != null)
                {
                    engine.CurrentDirectory = path.Directory.FullPath;
                }
                else
                {
                    engine.CurrentDirectory = string.Empty;
                    path = new FilePath(Path.GetRandomFileName());
                    context.LogWarning($"No input path found for document {input.ToSafeDisplayString()}, using {path.FileName.FullPath}");
                }
                string content = engine.TransformToCss(await input.GetContentStringAsync(), path.FileName.FullPath);

                // Process the result
                FilePath cssPath = path.GetRelativeInputPath(context).ChangeExtension("css");

                return(input.Clone(
                           cssPath,
                           await context.GetContentProviderAsync(content)));
            }
        }
Example #5
0
        /// <inheritdoc />
        public IEnumerable <IDocument> Execute(IReadOnlyList <IDocument> inputs, IExecutionContext context)
        {
            DotlessConfiguration config = DotlessConfiguration.GetDefault();

            config.Logger = typeof(LessLogger);
            EngineFactory    engineFactory    = new EngineFactory(config);
            FileSystemReader fileSystemReader = new FileSystemReader(context.FileSystem);

            return(inputs.AsParallel().Select(context, input =>
            {
                Trace.Verbose("Processing Less for {0}", input.SourceString());
                ILessEngine engine = engineFactory.GetEngine();

                // TODO: Get rid of RefelectionMagic and this ugly hack as soon as dotless gets better external DI support
                engine.AsDynamic().Underlying.Cache = new LessCache(context.ExecutionCache);
                engine.AsDynamic().Underlying.Underlying.Parser.Importer.FileReader = fileSystemReader;

                // Less conversion
                FilePath path = _inputPath.Invoke <FilePath>(input, context);
                if (path != null)
                {
                    engine.CurrentDirectory = path.Directory.FullPath;
                }
                else
                {
                    engine.CurrentDirectory = string.Empty;
                    path = new FilePath(Path.GetRandomFileName());
                    Trace.Warning($"No input path found for document {input.SourceString()}, using {path.FileName.FullPath}");
                }
                string content = engine.TransformToCss(input.Content, path.FileName.FullPath);

                // Process the result
                FilePath cssPath = path.ChangeExtension("css");
                return context.GetDocument(
                    input,
                    context.GetContentStream(content),
                    new MetadataItems
                {
                    { Keys.RelativeFilePath, cssPath },
                    { Keys.WritePath, cssPath }
                });
            }));
        }
 public Dotless(DotlessOptions options = null)
 {
     if (options == null)
     {
         options = new DotlessOptions(); // defaults
     }
     _config = DotlessConfiguration.GetDefault();
     _config.KeepFirstSpecialComment = options.KeepFirstSpecialComment;
     _config.RootPath = options.RootPath;
     if (!String.IsNullOrWhiteSpace(_config.RootPath) && !_config.RootPath.EndsWith("/"))
     {
         _config.RootPath += "/";
     }
     _config.InlineCssFiles       = options.InlineCssFiles;
     _config.ImportAllFilesAsLess = options.ImportAllFilesAsLess;
     _config.MinifyOutput         = options.MinifyOutput;
     _config.Debug        = options.Debug;
     _config.Optimization = options.Optimization;
     _config.StrictMath   = options.StrictMath;
     _cssToLess           = new FilenameTransform(options.CssMatchPattern, options.LessSourceFilePattern);
     _stylizer            = new PlainStylizer();
 }
    public void ProcessRequest(HttpContext context)
    {
        var    request   = context.Request;
        var    response  = context.Response;
        var    user      = context.User;
        string assetUrl  = request.Url.LocalPath;
        string assetPath = context.Server.MapPath(assetUrl);
        //load less file into the data.
        var data = "";

        using (var file = new StreamReader(assetPath))
        {
            data = file.ReadToEnd();
        }
        DotlessConfiguration lessEngineConfig = DotlessConfiguration.GetDefault();

        lessEngineConfig.MapPathsToWeb       = false;
        lessEngineConfig.CacheEnabled        = false;
        lessEngineConfig.DisableUrlRewriting = false;
        lessEngineConfig.Web          = false;
        lessEngineConfig.MinifyOutput = true;
        lessEngineConfig.LessSource   = typeof(VirtualFileReader);
        var         lessEngineFactory = new EngineFactory(lessEngineConfig);
        ILessEngine lessEngine        = lessEngineFactory.GetEngine();
        string      vars = "";

        //TODO set default for vars
        if (user != null)
        {
            //TODO get vars for user
        }
        var content = lessEngine.TransformToCss(string.Format("{0}{1}", vars, data), null);

        // Output text content of asset
        response.ContentType = "text/css";
        response.Write(content);
        response.End();
    }
Example #8
0
        private static CompilerConfiguration GetConfigurationFromArguments(List <string> arguments)
        {
            var configuration = new CompilerConfiguration(DotlessConfiguration.GetDefault());

            foreach (var arg in arguments)
            {
                if (arg.StartsWith("-"))
                {
                    if (arg == "-m" || arg == "--minify")
                    {
                        configuration.MinifyOutput = true;
                    }
                    else if (arg == "-d" || arg == "--debug")
                    {
                        configuration.Debug = true;
                    }
                    else if (arg == "-h" || arg == "--help" || arg == @"/?")
                    {
                        WriteHelp();
                        configuration.Help = true;
                        return(configuration);
                    }
                    else if (arg == "-l" || arg == "--listplugins")
                    {
                        WritePluginList();
                        configuration.Help = true;
                        return(configuration);
                    }
                    else if (arg == "-a" || arg == "--import-all-less")
                    {
                        configuration.ImportAllFilesAsLess = true;
                    }
                    else if (arg == "-c" || arg == "--inline-css")
                    {
                        configuration.InlineCssFiles = true;
                    }
                    else if (arg == "-w" || arg == "--watch")
                    {
                        configuration.Watch = true;
                    }
                    else if (arg.StartsWith("-D") && arg.Contains("="))
                    {
                        var split = arg.Substring(2).Split('=');
                        var key   = split[0];
                        var value = split[1];
                        ConsoleArgumentParameterSource.ConsoleArguments.Add(key, value);
                    }
                    else if (arg.StartsWith("-r") || arg.StartsWith("--disable-url-rewriting"))
                    {
                        configuration.DisableUrlRewriting = true;
                    }
                    else if (arg.StartsWith("-p:") || arg.StartsWith("--plugin:"))
                    {
                        var           pluginName = arg.Substring(arg.IndexOf(':') + 1);
                        List <string> pluginArgs = null;
                        if (pluginName.IndexOf(':') > 0)
                        {
                            pluginArgs = pluginName.Substring(pluginName.IndexOf(':') + 1).Split(',').ToList();
                            pluginName = pluginName.Substring(0, pluginName.IndexOf(':'));
                        }

                        var pluginConfig = GetPluginConfigurators()
                                           .Where(plugin => String.Compare(plugin.Name, pluginName, true) == 0)
                                           .FirstOrDefault();

                        if (pluginConfig == null)
                        {
                            Console.WriteLine("Cannot find plugin {0}.", pluginName);
                            continue;
                        }

                        var pluginParams = pluginConfig.GetParameters();

                        foreach (var pluginParam in pluginParams)
                        {
                            var pluginArg = pluginArgs
                                            .Where(argString => argString.StartsWith(pluginParam.Name + "="))
                                            .FirstOrDefault();

                            if (pluginArg == null)
                            {
                                if (pluginParam.IsMandatory)
                                {
                                    Console.WriteLine("Missing mandatory argument {0} in plugin {1}.", pluginParam.Name, pluginName);
                                }
                                continue;
                            }
                            else
                            {
                                pluginArgs.Remove(pluginArg);
                            }

                            pluginParam.SetValue(pluginArg.Substring(pluginParam.Name.Length + 1));
                        }

                        if (pluginArgs.Count > 0)
                        {
                            for (int i = 0; i < pluginArgs.Count; i++)
                            {
                                Console.WriteLine("Did not recognise argument '{0}'", pluginArgs[i]);
                            }
                        }

                        pluginConfig.SetParameterValues(pluginParams);
                        configuration.Plugins.Add(pluginConfig);
                    }
                    else
                    {
                        Console.WriteLine("Unknown command switch {0}.", arg);
                    }
                }
            }
            arguments.RemoveAll(p => p.StartsWith("-"));
            return(configuration);
        }
Example #9
0
 public static string Parse(string less)
 {
     return(Parse(less, DotlessConfiguration.GetDefault()));
 }
Example #10
0
 public EngineFactory() : this(DotlessConfiguration.GetDefault())
 {
 }
Example #11
0
 public static string Parse(ILessEngine engine, string less)
 {
     return(Parse(engine, less, DotlessConfiguration.GetDefault()));
 }