/// <summary>
        /// Processes the specified bundle of LESS files.
        /// </summary>
        /// <param name="context"> </param>
        /// <param name="bundle">The LESS bundle.</param>
        public void Process(BundleContext context, BundleResponse bundle)
        {
            if (bundle == null)
                throw new ArgumentNullException("bundle");

            context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies();

            var parser = new Parser();
            var engine = new LessEngine(parser);
            var content = new StringBuilder();
            
            foreach (var file in bundle.Files)
            {
                // set current file path
                SetCurrentFilePath(parser, file.FullName);
                
                var text = File.ReadAllText(file.FullName);
                var css = engine.TransformToCss(text, file.FullName);
                content.AppendLine(css);
                
                // content.Append(engine.TransformToCss(text, file.FullName));
                // content.AppendLine();

                AddFileDependencies(parser);
            }
            
            bundle.Content = content.ToString();
            bundle.ContentType = "text/css";
        }
예제 #2
0
        public static CompileResult CompileLess(string file, string contents, string theme, Dictionary<string, string> themeLessVariables)
        {
            if (string.IsNullOrEmpty(theme))
                theme = "Default";

            var importedFilePaths = new HashSet<string>();
            var logger = new ThemedLessLogger(theme);
            var engine = new LessEngine(
                new Parser(new ConsoleStylizer(), new Importer(importedFilePaths, file, theme)),
                logger, false, false)
            {
                Plugins = new List<IPluginConfigurator>
                {
                    new VariableOverridePluginConfigurator(themeLessVariables)
                }
            };
            if (string.IsNullOrEmpty(contents))
            {
                using (var sr = new StreamReader(System.Web.Hosting.HostingEnvironment.VirtualPathProvider.GetFile(file).Open()))
                {
                    contents = sr.ReadToEnd();
                }
            }
            var result = engine.TransformToCss(contents, file);
            if (logger.LoggedErrors.Any())
            {
                throw new Exception("Error(s) compiling less. " +
                                    string.Join(" - ", logger.LoggedErrors.Select(x => "\"" + x + "\"").ToArray()));
            }
            return new CompileResult(result, importedFilePaths);
        }
예제 #3
0
 private ILessEngine GetEngine()
 {
     var importer = new Importer(new CustomFileReader(fileSystem, filePath));
     var parser = new Parser(new PlainStylizer(), importer);
     var engine = new LessEngine(parser) { Compress = true };
     return engine;
 }
예제 #4
0
		ILessEngine CreateLessEngine(string path)
		{
			var importer = new Importer(new MulderFileReader(fileSystem, path));
			var parser = new Parser(new PlainStylizer(), importer);
			var engine = new LessEngine(parser) { Compress = true };
			return engine;
		}
예제 #5
0
 private ILessEngine GetEngine()
 {
     var importer = new Importer(new FileReader(new CustomPathResolver(filePath)));
     var parser = new Parser(new PlainStylizer(), importer);
     var engine = new LessEngine(parser);
     return engine;
 }
예제 #6
0
 private ILessEngine GetLessEngine(string physicalPath)
 {
     var basePath = Path.GetDirectoryName(physicalPath);
     var stylizer = new PlainStylizer();
     var importer = new Importer(new FileReader(new BasePathResolver(basePath)));
     var parser = new Parser(stylizer, importer) { NodeProvider = new RawUrlNodeProvider() };
     var lessEngine = new LessEngine(parser);
     return lessEngine;
 }
예제 #7
0
            public static string Generate(string fileName, string less, string color1, string color2)
            {
                var reader = new CustomFileReader(color1, color2);
                var importer = new Importer(reader);
                var parser = new Parser(new PlainStylizer(), importer, false);
                var lessEngine = new LessEngine(parser, NullLogger.Instance, true, false);
                less = Regex.Replace(less, "\\.theme-color\\(([a-z-]+),? ?", Evaluate);

                lessEngine.CurrentDirectory = Path.GetDirectoryName(fileName);

                return lessEngine.TransformToCss(less, Path.GetFileName(fileName));
            }
예제 #8
0
        public ILessEngine GetEngine(IFileSystem fileSystem, string directory)
        {
            IStylizer stylizer = new HtmlStylizer();

            IPathResolver pathResolver = new TestPathResolver(directory);
            IFileReader reader = new TestFileReader(fileSystem, pathResolver);
            var importer = new Importer(reader);
            var parser = new Parser(stylizer, importer);
            ILogger logger = new ConsoleLogger(LogLevel.Error);
            var engine = new LessEngine(parser, logger, true);
            engine.Compress = true;
            return engine;
        }
예제 #9
0
        protected override string ReadFileContent(string fileSystemPath, bool minify)
        {
            var directory = Path.GetDirectoryName(fileSystemPath);
            var pathResolver = new AbsolutePathResolver(directory);
            var fileReader = new FileReader { PathResolver = pathResolver };
            var importer = new Importer { FileReader = fileReader };
            var parser = new Parser { Importer = importer };
            var lessEngine = new LessEngine { Parser = parser };

            var rawFileContent = base.ReadFileContent(fileSystemPath, false);

            return lessEngine.TransformToCss(rawFileContent, fileSystemPath);
        }
예제 #10
0
 public static CompileResult CompileLess(string file, string contents = null, string theme = null)
 {
     var importedFilePaths = new HashSet<string>();
     var engine = new LessEngine(new Parser(new ConsoleStylizer(), new Importer(importedFilePaths, file, theme)));
     if (string.IsNullOrEmpty(contents))
     {
         using (var sr = new StreamReader(System.Web.Hosting.HostingEnvironment.VirtualPathProvider.GetFile(file).Open()))
         {
             contents = sr.ReadToEnd();
         }
     }
     var result = engine.TransformToCss(contents, file);
     return new CompileResult(result, importedFilePaths);
 }
        public void Process(BundleContext context, BundleResponse response)
        {
            var engine = new LessEngine() { Logger = new ExceptionLogger() };
            var output = new StringBuilder();
            foreach (var file in response.Files)
            {
                var content = File.ReadAllText(file.FullName);
                content = ResolveImportPaths(content, context.HttpContext);
                var css = engine.TransformToCss(content, null);
                output.Append(css);
            }

            response.ContentType = "text/css";
            response.Content = output.ToString();
        }
예제 #12
0
        public CompileResult Compile(string source, CompileContext context)
        {
            var sourceFile = context.RootDirectory.GetFile(context.SourceFilePath);
            importedFilePaths = new HashedSet<string>();
            var parser = new Parser
            {
                Importer = new Importer(new CassetteLessFileReader(sourceFile.Directory, importedFilePaths))
            };
            var errorLogger = new ErrorLogger();
            var engine = new LessEngine(
                                    parser,
                                    errorLogger,
                                    configuration.MinifyOutput,
                                    configuration.Debug,
                                    configuration.DisableVariableRedefines,
                                    configuration.DisableColorCompression,
                                    configuration.KeepFirstSpecialComment,
                                    configuration.Plugins);

            string css;
            try
            {
                css = engine.TransformToCss(source, sourceFile.FullPath);
            }
            catch (Exception ex)
            {
                throw new LessCompileException(
                    string.Format("Error compiling {0}{1}{2}", context.SourceFilePath, Environment.NewLine, ex.Message),
                    ex
                );
            }

            if (errorLogger.HasErrors)
            {
                var exceptionMessage = string.Format(
                    "Error compiling {0}{1}{2}",
                    context.SourceFilePath,
                    Environment.NewLine,
                    errorLogger.ErrorMessage
                );
                throw new LessCompileException(exceptionMessage);
            }
            else
            {
                return new CompileResult(css, importedFilePaths);
            }
        }
예제 #13
0
        public ParseResult ParseFile(string appRelativePath)
        {
            var physicalPath = GetFullPath(appRelativePath);

            using (new CurrentDirectoryWrapper(Path.GetDirectoryName(physicalPath)))
            {
                var engine = new LessEngine();

                return
                    new ParseResult
                        {
                            // Note, the order here is important
                            Content = engine.TransformToCss(fileReader.GetFileContents(appRelativePath), appRelativePath),
                            FileDependencies = new[] { physicalPath }.Concat(engine.GetImports().Select(x => GetImportPath(appRelativePath, x)))
                        };
            }
        }
예제 #14
0
        public string Compile(string source, IFile sourceFile)
        {
            var parser = new Parser
            {
                Importer = new Importer(new CassetteLessFileReader(sourceFile.Directory))
            };
            var errorLogger = new ErrorLogger();
            var engine = new LessEngine(parser, errorLogger, false);

            var css = engine.TransformToCss(source, sourceFile.FullPath);

            if (errorLogger.HasErrors)
            {
                throw new LessCompileException(errorLogger.ErrorMessage);
            }
            else
            {
                return css;
            }
        }
        /// <summary>
        /// Transforms the content of the given string from Less into CSS. 
        /// </summary>
        /// <param name="input">The input string to transform.</param>
        /// <param name="path">The path to the given input string to transform.</param>
        /// <param name="cruncher">The cruncher that is running the transform.</param>
        /// <returns>The transformed string.</returns>
        public string Transform(string input, string path, CruncherBase cruncher)
        {
            // The standard engine returns a FileNotFoundExecption so I've rolled my own path resolver.
            Parser parser = new Parser();
            DotLessPathResolver dotLessPathResolver = new DotLessPathResolver(path);
            FileReader fileReader = new FileReader(dotLessPathResolver);
            parser.Importer = new Importer(fileReader);
            ILessEngine lessEngine = new LessEngine(parser);

            try
            {
                string result = lessEngine.TransformToCss(input, path);

                if (cruncher.Options.CacheFiles)
                {
                    // Add each import as a file dependency so that the cache will clean itself.
                    IEnumerable<string> imports = lessEngine.GetImports();
                    IList<string> enumerable = imports as IList<string> ?? imports.ToList();

                    if (enumerable.Any())
                    {
                        foreach (string import in enumerable)
                        {
                            if (!import.Contains(Uri.SchemeDelimiter))
                            {
                                string filePath =
                                    HostingEnvironment.MapPath(VirtualPathUtility.Combine(dotLessPathResolver.CurrentFileDirectory, import));

                                cruncher.AddFileMonitor(filePath, "not empty");
                            }
                        }
                    }
                }

                return result;
            }
            catch (Exception ex)
            {
                throw new LessCompilingException(ex.Message, ex.InnerException);
            }
        }
        public string Preprocess(string data, string fileName)
        {
            // Ensure that the current directory for the @import statements
            // is the directory of the file.
            var fullFilePath = Path.Combine(this.appPath, fileName.Replace('/', '\\'));
            Directory.SetCurrentDirectory(Path.GetDirectoryName(fullFilePath));

            // Execute LESS engine but do not compress or optimize. This allows resolving
            // @import statements during debugging as well as a pretty-print version of the CSS.
            // However, when not debugging, all of the statements should be resolved in the Process()
            // method. This is because statements like `filter: progid:DXImageTransform...` can't be parsed
            // if they've been preprocessed to regular CSS.
            if (this.debugState.IsDebugging())
            {
                var e = new LessEngine(new dotless.Core.Parser.Parser(optimization: 0), new IgniteDotLessLogger(), compress: false);
                return e.TransformToCss(data, fileName);
            }
            else
            {
                return data;
            }
        }
예제 #17
0
        /// <summary>
        /// Transforms some LESS source code (and any related files) to CSS.
        /// </summary>
        /// <param name="source">The LESS code to transform.</param>
        /// <param name="file">The context file system.</param>
        public string Compile(string source, IFile file)
        {
            var parser = new Parser {Importer = new Importer(new LessFileReader(file.Directory))};

            var engine = new LessEngine(parser, _logger, false, false);

            string css = null;

            try
            {
                css = engine.TransformToCss(source, file.Name);
            }
            catch (FileNotFoundException ex)
            {
                _logger.Error("The file you are trying to import '{0}' cannot be found.".FormatWith(ex.FileName));
            }

            if (_logger.HasErrors)
                throw new LessCompileException(_logger.ErrorMessage);

            return css;
        }
예제 #18
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="inPath"></param>
 /// <param name="outPath"></param>
 public CompileResults Compile(string inPath, string outPath)
 {
     using (StreamReader sr = new StreamReader(inPath))
     {
         LessEngine engine = new LessEngine();
         SetCurrentFilePath(engine.Parser, inPath);
         var fileReader = new FileReader();
         var source = fileReader.GetFileContents(inPath);
         var output = engine.TransformToCss(source, inPath);
         if (engine.LastTransformationSuccessful)
         {
             using (StreamWriter sw = new StreamWriter(outPath))
             {
                 sw.WriteLine(OrangeBits.GetHeader(inPath));
                 sw.Write(output);
             }
         }
         else
         {
             throw new Exception("Error compiling LESS");
         }
     }
     return null;
 }
예제 #19
0
 public string TransformContent(ResourceSet resourceSet, Resource resource, string content)
 {
     var engine = new LessEngine(new Parser(new ConsoleStylizer(), new Importer(new AdeptFileReader(resource.Path))));
     return engine.TransformToCss(content, resource.Path);
 }
        /// <summary>
        ///     Gets the file dependencies (@imports) of the LESS file being parsed.
        /// </summary>
        /// <param name="lessEngine">The LESS engine.</param>
        /// <returns>An array of file references to the dependent file references.</returns>
        private static IEnumerable<BundleFile> GetFileDependencies(LessEngine lessEngine)
        {
            ImportedFilePathResolver pathResolver = lessEngine.Parser.GetPathResolver();
            VirtualPathProvider vpp = BundleTable.VirtualPathProvider;

            foreach (string resolvedVirtualPath in lessEngine.GetImports().Select(pathResolver.GetFullPath))
            {
                // the file was successfully imported, therefore no need to check before vpp.GetFile
                yield return new BundleFile(resolvedVirtualPath, vpp.GetFile(resolvedVirtualPath));
            }

            lessEngine.ResetImports();
        }
예제 #21
0
        public void TestMethod1()
        {
            string rootPath = @"C:\Users\justbe\Dropbox\Code\OrangeBits\Demo\";
            string inPath = rootPath + @"importTest.less";
            string outPath = rootPath + @"importTest.css";

            LessEngine engine = new LessEngine();
            SetCurrentFilePath(engine.Parser, inPath);

            var fileReader = new FileReader();
            var source = fileReader.GetFileContents(inPath);
            var css = engine.TransformToCss(source, inPath);
        }
예제 #22
0
 public DotLessCompiler()
 {
     _engine = new LessEngine();
 }
예제 #23
0
파일: LessToCss.cs 프로젝트: spooky/flair
 public string Transform(string source)
 {
     var engine = new LessEngine(new Parser(), new WeirdLogger(LogLevel.Warn), false, false);
     return engine.TransformToCss(source, null);
 }