Example #1
0
        // Less Css..
        public string Execute(RenderContext context, string input)
        {
            //用ConcurrentDictionary每10次出现一次 “集合已经修改” 的错误。不懂为什么...
            //用SiteId 比用website对象好, 因为对象也是取对象的Hash值来做key。这个值会改变。

            var id = context.WebSite.Id;

            if (!_lessEngines.ContainsKey(id))
            {
                lock (_lock)
                {
                    if (!_lessEngines.ContainsKey(id))
                    {
                        var newengine = new LessEngine();
                        newengine.Parser.Importer = new KLessImporter(context.WebSite);
                        _lessEngines.Add(id, newengine);
                    }
                }
            }

            LessEngine engine = _lessEngines[id];

            return(engine.Parse(input ?? string.Empty));

            //return _lessEngines.GetOrAdd(context.WebSite, _ =>
            //{
            //    var engine = new LessEngine();
            //    engine.Parser.Importer = new KLessImporter(context.WebSite);
            //    return engine;
            //}).Parse(input ?? string.Empty);
        }
Example #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)
                       ));
        }
Example #3
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));
            }
        }
Example #4
0
        public void LoadActions()
        {
            try
            {
                if (this.engineManager == null || this.engineManager.IsDisposed)
                {
                    this.engineManager = new EngineManager(this);
                }

                this.engineManager.Clear();
                this.engineManager.Add(YuiCssEngine            = new YuiCssEngine());
                this.engineManager.Add(YuiJsEngine             = new YuiJsEngine());
                this.engineManager.Add(DeanEdwardsPackerEngine = new DeanEdwardsPackerEngine());
                this.engineManager.Add(ClosureCompilerEngine   = new ClosureCompilerEngine());
                this.engineManager.Add(LessEngine         = new LessEngine());
                this.engineManager.Add(MsJsEngine         = new MsJsEngine());
                this.engineManager.Add(MsCssEngine        = new MsCssEngine());
                this.engineManager.Add(ConfigEngine       = new ConfigEngine());
                this.engineManager.Add(ViewEngine         = new ViewEngine());
                this.engineManager.Add(T4Engine           = new T4Engine());
                this.engineManager.Add(CoffeeScriptEngine = new CoffeeScriptEngine());
                this.engineManager.Add(UglifyEngine       = new UglifyEngine());
                this.engineManager.Add(JSHintEngine       = new JSHintEngine());
                this.engineManager.Add(CSSLintEngine      = new CSSLintEngine());
                this.engineManager.Add(TypeScriptEngine   = new TypeScriptEngine());
                this.engineManager.Add(SassEngine         = new SassEngine());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        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));
        }
Example #6
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);
        }
Example #7
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);
        }
Example #8
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);
        }
Example #9
0
        /// <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();
        }
Example #10
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);
        }
        protected virtual ILessEngine GetLessEngine(IBundle bundle, BundleTransformItem bundleTransformItemResult)
        {
            var parser = new Parser(new PlainStylizer(), new Importer(new DotLessVirtualFileReader(bundle.Context.VirtualPathProvider)));

            var compress = bundle.Context.Configuration.Get(LessConfiguration.Compress);
            var debug    = bundle.Context.Configuration.Get(LessConfiguration.Debug);

            var lessEngine = new LessEngine(parser, new DotLessBundleLogger(bundle.Context.Diagnostic), compress, debug)
            {
                CurrentDirectory = Path.GetDirectoryName(bundleTransformItemResult.VirtualFile)
            };

            return(lessEngine);
        }
Example #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));
            }
        }
Example #13
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);
        }
Example #14
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)));
            }
        }
Example #16
0
        public void TestLessDependencies()
        {
            var code = @"
					@import url(test/1);
					@import url('..\test\2');
					@import url(""/test/3"");
					@import '../test/4';
					@import ""./test/5"";              
				"                ;

            var imports = LessEngine.FindDependencies("C:\\test\\temp\\0.less", code, "C:\\test\\");

            Assert.AreEqual(@"C:\test\temp\test\1.less".ToUri(), imports.ElementAtOrDefault(0));
            Assert.AreEqual(@"C:\test\test\2.less".ToUri(), imports.ElementAtOrDefault(1));
            Assert.AreEqual(@"C:\test\test\3.less".ToUri(), imports.ElementAtOrDefault(2));
            Assert.AreEqual(@"C:\test\test\4.less".ToUri(), imports.ElementAtOrDefault(3));
            Assert.AreEqual(@"C:\test\temp\test\5.less".ToUri(), imports.ElementAtOrDefault(4));
        }
Example #17
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);
            }
        }
Example #19
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);
            }
        }
Example #20
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));
            }
        }
Example #21
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));
        }
Example #22
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();
        }
        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);
        }
Example #24
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);
        }
Example #25
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));
        }
Example #26
0
        internal static string Process(ref IEnumerable <BundleFile> files)
        {
            DotlessConfiguration lessConfig = new WebConfigConfigurationLoader().GetConfiguration();

            if (!lessConfig.LessSource.GetInterfaces().Contains(typeof(IFileReaderWithResolver)))
            {
                lessConfig.LessSource = typeof(LessVirtualFileReader);
            }

            // system.Web.Optimization cache is used instead
            lessConfig.CacheEnabled = false;

            var content = new StringBuilder();

            var targetFiles = new List <BundleFile>();

            foreach (BundleFile bundleFile in files)
            {
                // initialize the less engine once for each file.
                // this is to prevent leaking state between files
                ILessEngine lessEngine           = LessWeb.GetEngine(lessConfig);
                LessEngine  underlyingLessEngine = lessEngine.ResolveLessEngine();
                Parser      lessParser           = underlyingLessEngine.Parser;

                targetFiles.Add(bundleFile);
                string filePath = bundleFile.IncludedVirtualPath;
                filePath = filePath.Replace('\\', '/');
                filePath = VirtualPathUtility.ToAppRelative(filePath);

                lessParser.SetCurrentFilePath(filePath);
                string source    = bundleFile.ApplyTransforms();
                string extension = VirtualPathUtility.GetExtension(filePath);

                // if plain CSS file, do not transform LESS
                if (lessConfig.ImportAllFilesAsLess ||
                    ".less".Equals(extension, StringComparison.InvariantCultureIgnoreCase) ||
                    ".less.css".Equals(extension, StringComparison.InvariantCultureIgnoreCase))
                {
                    string lessOutput = lessEngine.TransformToCss(source, filePath);

                    // pass the transformation result if successful
                    if (lessEngine.LastTransformationSuccessful)
                    {
                        source = lessOutput;
                    }
                    else
                    {
                        // otherwise write out error message.
                        // the transformation error is logged in LessEngine.TransformToCss
                        if (lessConfig.Debug)
                        {
                            content.AppendLine(string.Format(
                                                   "/* Error occurred in LESS transformation of the file: {0}. Please see details in the dotless log */",
                                                   bundleFile.IncludedVirtualPath));
                        }
                        continue;
                    }
                }

                source = ConvertUrlsToAbsolute(bundleFile.IncludedVirtualPath, source);

                content.AppendLine(source);

                BundleFile[] fileDependencies = GetFileDependencies(underlyingLessEngine).ToArray();
                targetFiles.AddRange(fileDependencies);

                DependencyCache.SaveFileDependencies(filePath, fileDependencies.Select(file => file.IncludedVirtualPath).ToArray());
            }

            // include imports in bundle files to register cache dependencies
            files = BundleTable.EnableOptimizations ? targetFiles.Distinct() : targetFiles;

            return(content.ToString());
        }
Example #27
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
Example #28
0
        private void IndexDependencies()
        {
            try {
                foreach (Project project in this.App.Solution.Projects)
                {
                    var projectItems = project.ProjectItems.ProcessFolderProjectItemsRecursively();
                    if (projectItems != null)
                    {
                        var configs = projectItems
                                      .Where(x => ConfigEngine.Handles(x.Name) > 0 || LessEngine.Handles(x.Name) > 0);

                        foreach (ProjectItem config in configs)
                        {
                            ConfigEngine.ReloadFileDependencies(config);
                        }
                    }
                }
            } catch (Exception e) {
                this.OutputWindowWriteText(e.ToString());
            }
        }