/// <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);
        }
Beispiel #2
0
        /// <summary>
        /// This will never return null. It will throw an exception for a null or blank relativePath.
        /// </summary>
        public TextFileContents Load(string relativePath)
        {
            if (string.IsNullOrWhiteSpace(relativePath))
            {
                throw new ArgumentException("Null/blank relativePath specified");
            }

            var initialFileContents = _contentLoader.Load(relativePath);
            var engine = new LessEngine(
                new Parser(),
                new DotLessCssPassThroughLogger(_logger, _reportedErrorBehaviour),
                true,                 // Compress
                false                 // Debug
                );
            var markerIdLookup = new MarkerIdLookup(_markerIdRetriever());

            engine.Plugins = new[] {
                new SelectorRewriterVisitorPluginConfigurator(markerIdLookup, _optionalTagNameToRemove)
            };
            return(new TextFileContents(
                       initialFileContents.RelativePath,
                       initialFileContents.LastModified,
                       engine.TransformToCss(initialFileContents.Content, null)
                       ));
        }
        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));
        }
Beispiel #4
0
        static AssetProcessingResult DoCompile(string less)
        {
            // LessEngine is not threadsafe, dont make it static
            var logger     = new StringLessLogger(LogLevel.Error);
            var lessEngine = new LessEngine(new Parser(1), logger, true, false);

            try
            {
                var css = lessEngine.TransformToCss(less, null);
                if (logger.HasMessages)
                {
                    return(new AssetProcessingResult(AssetProcessingResult.CompilationStatus.Failure, null, logger.Dump()));
                }

                return(new AssetProcessingResult(AssetProcessingResult.CompilationStatus.Success, css));
            }
            catch (Exception e)
            {
                log.Error(e, "Error compiling less `{less}`", less);

                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }

                return(new AssetProcessingResult(AssetProcessingResult.CompilationStatus.Failure, null, e.Message));
            }
        }
Beispiel #5
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));
            }
        }
Beispiel #6
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);
        }
Beispiel #7
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)))
                });
            }
        }
        /// <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)));
            }
        }
Beispiel #9
0
        /// <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("://"))
                            {
                                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);
            }
        }
        /// <summary>
        /// Processes a single item.
        /// </summary>
        /// <param name="input">The input to process.</param>
        /// <returns>The output of the process.</returns>
        public override IAssetFile Process(IAssetFile input)
        {
            try
            {
                // Select the files we should compile
                var compile = input.Project.Configuration.Less;
                if (compile == null || compile.Count == 0 || !compile.Any(c => input.RelativeName.EndsWith(c)))
                {
                    // Return processed output
                    return(AssetOutputFile.Create(
                               from: input,
                               content: String.Empty,
                               extension: "css"
                               ));
                }

                // Get the content
                var content = input.Content.AsString();

                // Get the LESS engine
                var engine   = new LessEngine();
                var importer = (Importer)engine.Parser.Importer;
                var freader  = (FileReader)importer.FileReader;
                freader.PathResolver = new LessPathResolver(input.FullName);

                // Transform to CSS
                var output = engine.TransformToCss(content, input.FullName);

                // Return processed output
                return(AssetOutputFile.Create(
                           from: input,
                           content: output,
                           extension: "css"
                           ));
            }
            catch (Exception ex)
            {
                // We didn't manage to create anything
                Tracing.Error("Less", ex);
                return(null);
            }
        }
Beispiel #11
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);
            }
        }
Beispiel #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, false, false);

            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));
            }
        }
Beispiel #13
0
        public void Process(BundleContext context, BundleResponse bundle)
        {
            var pathResolver = new ImportedFilePathResolver(context.HttpContext.Server);
            var lessParser   = new Parser();
            var lessEngine   = new LessEngine(lessParser);

            (lessParser.Importer as Importer).FileReader = new FileReader(pathResolver);
            var content = new StringBuilder(bundle.Content.Length);

            foreach (var bundleFile in bundle.Files)
            {
                pathResolver.SetCurrentDirectory(bundleFile.IncludedVirtualPath);
                using (var stream = new StreamReader(bundleFile.VirtualFile.Open()))
                {
                    content.Append(lessEngine.TransformToCss(stream.ReadToEnd(), bundleFile.IncludedVirtualPath));
                }
                content.AppendLine();
            }
            bundle.ContentType = "text/css";
            bundle.Content     = content.ToString();
        }
Beispiel #14
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));
        }
        public string Apply(string filename, IContentProvider provider)
        {
            // transformation is only applied of requested css file is not found
            // and in the folder there is a less file with the same name
            var cssContent = provider.GetContent(filename);

            if (cssContent != null)
            {
                return(cssContent);                    // css content is available
            }
            if (!_cssToLess.Matches(filename))
            {
                return(null);                               // no less file
            }
            var lessFilename = _cssToLess.TrasformFilename(filename);
            var lessContent  = provider.GetContent(lessFilename);

            if (lessContent == null)
            {
                return(null);
            }
            var fileReader = new FileReaderAdapter(provider);
            var importer   = new Importer(fileReader,
                                          _config.DisableUrlRewriting, _config.RootPath, _config.InlineCssFiles, _config.ImportAllFilesAsLess);
            var parser = new Parser(_config, _stylizer, importer);

            fileReader.CurrentLocationGetter = () => parser.FileName;
            var logger = new LoggerAdapter();
            var engine = new LessEngine(parser, logger, _config);
            var css    = engine.TransformToCss(lessContent, filename);

            if (logger.ErrorCount > 0)
            {
                throw new InvalidOperationException(
                          $"Found {logger.ErrorCount} errors while compiling Less:\n{logger.CompilationLog}");
            }
            return(css);
        }
Beispiel #16
0
        //--------------------------------------------------------------------------
        //
        //	ICompiler Methods
        //
        //--------------------------------------------------------------------------

        #region CompileResults
        /// <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);
        }
Beispiel #17
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));
        }
Beispiel #18
0
        /// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary>
        /// <param name='commandName'>The name of the command to execute.</param>
        /// <param name='executeOption'>Describes how the command should be run.</param>
        /// <param name='varIn'>Parameters passed from the caller to the command handler.</param>
        /// <param name='varOut'>Parameters passed from the command handler to the caller.</param>
        /// <param name='handled'>Informs the caller if the command was handled or not.</param>
        public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
        {
            handled = false;

            if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
            {
                if (this.App != null)
                {
                    string fileToTry = string.Empty;

                    try {
                        if (commandName == COMMANDNAMESPACE + "." + POPUP_MENU_NAME_MINIFIER)
                        {
                            try {
                                ProjectItem projectItem = this.App.SelectedItems.Item(1).ProjectItem;
                                if (EngineManager.IsHandledWithoutHint(projectItem.FileName()))
                                {
                                    this.ProjectItemsEvents_ItemAdded(projectItem);
                                }
                                else
                                {
                                    string path            = projectItem.FileName();
                                    string code            = System.IO.File.ReadAllText(path);
                                    var    settings        = Settings.Instance(path);
                                    string outputExtension = settings.OutputExtensionJS;
                                    if (this.IsLessFile(path))
                                    {
                                        code            = LessEngine.TransformToCss(path, code, projectItem);
                                        outputExtension = settings.OutputExtensionCSS;
                                    }
                                    else if (this.IsCoffeeScriptFile(path))
                                    {
                                        code            = CoffeeScriptEngine.TransformToJs(path, code, projectItem);
                                        outputExtension = settings.OutputExtensionJS;
                                    }
                                    else if (this.IsSassFile(path))
                                    {
                                        code            = SassEngine.TransformToCss(path, code, projectItem);
                                        outputExtension = settings.OutputExtensionCSS;
                                    }
                                    else if (this.IsCssFile(path))
                                    {
                                        code            = CssEngine.Minify(path, code, projectItem, Xml.MinifyType.Unspecified);
                                        outputExtension = settings.OutputExtensionCSS;
                                    }
                                    else if (this.IsJsFile(path))
                                    {
                                        code            = JsEngine.Minify(path, code, projectItem, Xml.MinifyType.Unspecified, string.Empty);
                                        outputExtension = settings.OutputExtensionJS;
                                    }
                                    using (var manager = new Manager.VSProjectItemManager(this.App, projectItem))
                                    {
                                        manager.AddFileByFileName(Utilities.GetBaseFileName(path) + outputExtension, code);
                                    }
                                }
                            } catch (Exception e) {
                                this.OutputWindowWriteText(e.ToString());
                            }
                        }
                        else if (commandName == COMMANDNAMESPACE + "." + POPUP_MENU_NAME_JSHINT)
                        {
                            try {
                                ProjectItem projectItem = this.App.SelectedItems.Item(1).ProjectItem;
                                string      path        = projectItem.FileName();
                                JSHintEngine.Run(path, projectItem);
                            } catch (Exception e) {
                                this.OutputWindowWriteText(e.ToString());
                            }
                        }
                        else if (commandName == COMMANDNAMESPACE + "." + POPUP_MENU_NAME_CSSLINT)
                        {
                            try {
                                ProjectItem projectItem = this.App.SelectedItems.Item(1).ProjectItem;
                                string      path        = projectItem.FileName();
                                CSSLintEngine.Run(path, projectItem);
                            } catch (Exception e) {
                                this.OutputWindowWriteText(e.ToString());
                            }
                        }
                        else if (commandName == COMMANDNAMESPACE + "." + POPUP_MENU_NAME_TYPESCRIPT)
                        {
                            try
                            {
                                ProjectItem projectItem = this.App.SelectedItems.Item(1).ProjectItem;
                                string      path        = projectItem.FileName();
                                TypeScriptEngine.Run(path, projectItem);
                            }
                            catch (Exception e)
                            {
                                this.OutputWindowWriteText(e.ToString());
                            }
                        }
                    } catch (Exception ex) {
                        this.OutputWindowWriteText(string.Format("Error occured.\r\nFileName:\r\n{0}\r\nException details:\r\n{1}", fileToTry, ex));
                    } // try

                    handled = true;

                    return;
                }
            }
        } // Exec