private string BuildSassFile(string inputFilePath, string outputFilePath, string sourceMapFilePath, bool buildSourceMap = false)
        {
            try
            {
                var options = new CompilationOptions
                {
                    SourceMap = buildSourceMap
                };

                var result = SassCompiler.CompileFile(inputFilePath, outputFilePath, sourceMapFilePath, options);
                _fileService.SaveFile(outputFilePath, result.CompiledContent);
                if (buildSourceMap && sourceMapFilePath.HasValue())
                {
                    _fileService.SaveFile(sourceMapFilePath, result.SourceMap);
                }
            }
            catch (SassCompilationException ex)
            {
                var errorDetails = SassErrorHelpers.GenerateErrorDetails(ex);
                _logger.Error <SassService>(ex, errorDetails);
                return(ex.Message);
            }

            return(string.Empty);
        }
Beispiel #2
0
        public void CompileFile(bool withFileManager)
        {
            SetFileManager(withFileManager);
            Document document = s_documents[DocumentName];

            string compiledContent = SassCompiler.CompileFile(document.AbsolutePath).CompiledContent;
        }
Beispiel #3
0
        async Task CompileFilesAsync(IEnumerable <string> sassFiles)
        {
            foreach (var file in sassFiles)
            {
                var fileInfo = new FileInfo(file);
                if (fileInfo.Name.StartsWith("_"))
                {
                    WriteVerbose($"Skipping: {fileInfo.FullName}");
                    continue;
                }

                WriteVerbose($"Processing: {fileInfo.FullName}");

                var result = SassCompiler.CompileFile(file, options: Options.SassCompilationOptions);

                var newFile = fileInfo.FullName.Replace(fileInfo.Extension, ".css");

                if (File.Exists(newFile) && result.CompiledContent == await File.ReadAllTextAsync(newFile))
                {
                    continue;
                }

                await File.WriteAllTextAsync(newFile, result.CompiledContent);
            }
        }
        public virtual void MappingSyntaxErrorDuringCompilationOfFileIsCorrect()
        {
            // Arrange
            string inputFilePath = Path.Combine(_filesDirectoryPath,
                                                string.Format("invalid-syntax/{0}/style{1}", _subfolderName, _fileExtension));

            SassСompilationException exception = null;

            // Act
            try
            {
                CompilationResult result = SassCompiler.CompileFile(inputFilePath);
            }
            catch (SassСompilationException e)
            {
                exception = e;
            }

            // Assert
            Assert.NotNull(exception);
            Assert.NotEmpty(exception.Message);
            Assert.Equal(GetCanonicalPath(inputFilePath), exception.File);
            Assert.Equal(3, exception.LineNumber);
            Assert.Equal(13, exception.ColumnNumber);
        }
        public virtual void FileWithImportCompilationIsCorrect()
        {
            // Arrange
            string inputFilePath = Path.Combine(_filesDirectoryPath,
                                                string.Format("import/{0}/base{1}", _subfolderName, _fileExtension));
            string importedFilePath = Path.Combine(_filesDirectoryPath,
                                                   string.Format("import/{0}/_reset{1}", _subfolderName, _fileExtension));
            string outputFilePath = Path.Combine(_filesDirectoryPath, "import/base.css");

            string targetOutputCode = File.ReadAllText(outputFilePath);

            var options = new CompilationOptions
            {
                SourceMap = true
            };

            // Act
            CompilationResult result = SassCompiler.CompileFile(inputFilePath, options: options);

            // Assert
            Assert.Equal(targetOutputCode, result.CompiledContent);
            Assert.False(string.IsNullOrEmpty(result.SourceMap));

            var includedFilePaths = result.IncludedFilePaths;

            Assert.Equal(2, includedFilePaths.Count);
            Assert.Equal(GetCanonicalPath(inputFilePath), includedFilePaths[0]);
            Assert.Equal(GetCanonicalPath(importedFilePath), includedFilePaths[1]);
        }
        public virtual void MappingFileNotFoundErrorDuringCompilationOfFileIsCorrect()
        {
            // Arrange
            string inputFilePath = Path.Combine(_filesDirectoryPath,
                                                string.Format("non-existing-files/{0}/style{1}", _subfolderName, _fileExtension));

            SassCompilationException exception = null;

            // Act
            try
            {
                CompilationResult result = SassCompiler.CompileFile(inputFilePath);
            }
            catch (SassCompilationException e)
            {
                exception = e;
            }

            // Assert
            Assert.NotNull(exception);
            Assert.NotEmpty(exception.Message);
            Assert.Null(exception.File);
            Assert.Equal(-1, exception.LineNumber);
            Assert.Equal(-1, exception.ColumnNumber);
        }
Beispiel #7
0
        public void ShouldNotCompileFileWithEchoOutputStyle()
        {
            // Arrange

            // Act
            Action compile = () => SassCompiler.CompileFile(BasicPath, OutputStyle.Echo);

            // Assert
            compile.ShouldThrow <ArgumentException>();
        }
Beispiel #8
0
        protected override string Update()
        {
            try {
                var options = new CompilationOptions {
                    SourceMap = true
                };
                options.OutputStyle       = OutputStyle.Compact;
                options.SourceMapFileUrls = true;
                //options.IncludePaths = new string[] { Path.Combine(Path.GetDirectoryName(InputFilePath), "Dependencies\\Csml\\Fonts") };


                SassCompiler.FileManager = this;// new FileManager(Path.GetDirectoryName(InputFilePath), LibSassHost.FileManager.Instance);
                CompilationResult result = SassCompiler.CompileFile(InitialFilePath, null, null, options);

                if (DeveloperMode)
                {
                    observableFiles = CaptureModificationTimes(result.IncludedFilePaths);
                }

                //OutputFileName = "style.css";
                var outputMapFileName = "style.css.map";
                if (!DeveloperMode)
                {
                    var hash = Hash.CreateFromString(result.CompiledContent).ToString();
                    OutputFileName    = hash + ".css";
                    outputMapFileName = OutputFileName + ".map";
                }


                string outputFilePath    = Path.Combine(OutputRootDirectory, OutputFileName);
                string sourceMapFilePath = Path.Combine(OutputRootDirectory, outputMapFileName);

                File.WriteAllText(outputFilePath, result.CompiledContent);
                File.WriteAllText(sourceMapFilePath, result.SourceMap);
            } catch (SassCompilationException e) {
                if (e.File != null)
                {
                    if (!observableFiles.ContainsKey(e.File))
                    {
                        observableFiles.Add(e.File, File.GetLastWriteTime(e.File));
                    }
                }

                var files = observableFiles.Select(x => x.Key).ToArray();
                observableFiles = CaptureModificationTimes(files);

                if (!DeveloperMode)
                {
                    throw e;
                }

                return(e.Message);
            }
            return(null);
        }
Beispiel #9
0
        public void ShouldCompileFileWithoutComments()
        {
            // Arrange
            const string expectedResult = "body .class {\n  color: red; }\n";

            // Act
            string compiled = SassCompiler.CompileFile(BasicPath, sourceComments: false);

            // Assert
            compiled.Should().BeEquivalentTo(expectedResult);
        }
Beispiel #10
0
        public void ShouldCompileFileWithCompressedOutputStyle()
        {
            // Arrange
            const string expectedResult = "body .class {color:red;}";

            // Act
            string compiled = SassCompiler.CompileFile(BasicPath, OutputStyle.Compressed);

            // Assert
            compiled.Should().BeEquivalentTo(expectedResult);
        }
Beispiel #11
0
        public void CompilationOfFileWithAppAbsolutePaths()
        {
            // Arrange
            var virtualFileManagerMock = new Mock <IFileManager>();

            virtualFileManagerMock
            .SetupGet(fm => fm.SupportsVirtualPaths)
            .Returns(true)
            ;
            virtualFileManagerMock
            .Setup(fm => fm.GetCurrentDirectory())
            .Returns("/")
            ;
            virtualFileManagerMock
            .Setup(fm => fm.FileExists(It.IsAny <string>()))
            .Returns((string p) => {
                if (p == _siteInputFileAbsolutePath)
                {
                    return(true);
                }

                return(_siteImportedFiles.ContainsKey(p));
            })
            ;
            virtualFileManagerMock
            .Setup(fm => fm.ReadFile(It.IsAny <string>()))
            .Returns((string p) => {
                if (p == _siteInputFileAbsolutePath)
                {
                    return(_siteInputFileContent);
                }

                return(_siteImportedFiles[p]);
            })
            ;

            IFileManager virtualFileManager = new VirtualFileManager(virtualFileManagerMock);
            var          options            = new CompilationOptions {
                SourceMap = true
            };

            // Act
            CompilationResult result;

            using (var compiler = new SassCompiler(virtualFileManager))
            {
                result = compiler.CompileFile(_siteInputFileAbsolutePath, options: options);
            }

            // Assert
            Assert.AreEqual(_siteOutputFileContent, result.CompiledContent);
            Assert.AreEqual(_siteIncludedFilePaths, result.IncludedFilePaths);
            Assert.AreEqual(_siteSourceMapFileContent, result.SourceMap);
        }
Beispiel #12
0
        public void ShouldCompileFile()
        {
            // Arrange
            string expectedResult = String.Format("/* line 3, {0} */\nbody .class {{\n  color: red; }}\n", BasicPath);

            // Act
            string compiled = SassCompiler.CompileFile(BasicPath);

            // Assert
            compiled.Should().BeEquivalentTo(expectedResult);
        }
Beispiel #13
0
        public void ShouldCompileFileWithImport()
        {
            // Arrange
            string expectedResult = String.Format("/* line 1, {0} */\nbody {{\n  border-color: green; }}\n\n/* line 5, {1} */\nbody .class {{\n  color: red; }}\n", ReplaceLastSlash(ImportPath), ImportingPath);

            // Act
            string compiled = SassCompiler.CompileFile(ImportingPath);

            // Assert
            compiled.Should().BeEquivalentTo(expectedResult);
        }
        public void Compile()
        {
            Document document = Documents[DocumentName];
            var      options  = new CompilationOptions {
                SourceMap = true
            };

            using (var compiler = new SassCompiler(options))
            {
                CompilationResult result = compiler.CompileFile(document.AbsolutePath);
            }
        }
        //[Produces("text/css")]
        //[Consumes("text/css")]
        public ContentResult SassConverter(string fileName)
        {
            var fullFilePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "sass", $"{fileName}.scss");
            var result       = SassCompiler.CompileFile(fullFilePath, options: new CompilationOptions
            {
                SourceMap      = false,
                OutputStyle    = OutputStyle.Compact,
                SourceComments = false,
            });

            //Response.ContentType = "text/css";
            return(Content(result.CompiledContent, "text/css"));
            //return result.CompiledContent;
        }
Beispiel #16
0
 public void SimpleFile() => UseTempFolder(folder =>
 {
     var input    = ".a { .b { margin: 0; } .c { margin: 1px; } }";
     var expected = ".a .b{margin:0}.a .c{margin:1px}\n";
     var mainScss = Path.Combine(folder, "main.scss");
     File.WriteAllText(mainScss, input, new UTF8Encoding(false));
     var compiler = new SassCompiler();
     var res      = compiler.CompileFile(mainScss, new SassOptions(
                                             outputStyle: SassOutputStyle.Compressed,
                                             indent: string.Empty,
                                             sourceMapEmbed: false
                                             ));
     Assert.Equal(expected, res.Css);
 });
Beispiel #17
0
        public void ShouldCompileFileWithAdditionalImport()
        {
            // Arrange
            string expectedResult = String.Format("/* line 1, {0} */\nbody {{\n  border-color: green; }}\n\n/* line 3, {1} */\nbody > #id {{\n  font-size: 14px; }}\n\n/* line 6, {2} */\nbody .class {{\n  color: red; }}\n",
                                                  ReplaceLastSlash(ImportPath),
                                                  ReplaceLastSlash(AdditionalImportPath),
                                                  ImportingAdditionalPath);

            // Act
            string compiled = SassCompiler.CompileFile(ImportingAdditionalPath, additionalIncludePaths: new[]
            {
                AdditionalImportTestFilesDirectory
            });

            // Assert
            compiled.Should().BeEquivalentTo(expectedResult);
        }
        public void CompilationOfFileWithAppRelativePaths()
        {
            var virtualFileManagerMock = new Mock <IFileManager>();

            virtualFileManagerMock
            .SetupGet(fm => fm.SupportsVirtualPaths)
            .Returns(true)
            ;
            virtualFileManagerMock
            .Setup(fm => fm.GetCurrentDirectory())
            .Returns(_appAbsolutePath)
            ;
            virtualFileManagerMock
            .Setup(fm => fm.FileExists(_appInputFileRelativePath))
            .Returns(true)
            ;
            virtualFileManagerMock
            .Setup(fm => fm.FileExists(_appInputFileAbsolutePath))
            .Returns(true)
            ;
            virtualFileManagerMock
            .Setup(fm => fm.ReadFile(_appInputFileAbsolutePath))
            .Returns(_appInputFileContent)
            ;

            IFileManager virtualFileManager = new VirtualFileManager(virtualFileManagerMock, _appAbsolutePath);
            var          options            = new CompilationOptions {
                SourceMap = true
            };

            // Act
            CompilationResult result;

            using (var compiler = new SassCompiler(virtualFileManager))
            {
                result = compiler.CompileFile(_appInputFileRelativePath, options: options);
            }

            // Assert
            Assert.AreEqual(_appOutputFileContent, result.CompiledContent);
            Assert.AreEqual(1, result.IncludedFilePaths.Count);
            Assert.AreEqual(_appInputFileAbsolutePath, result.IncludedFilePaths[0]);
            Assert.AreEqual(_appSourceMapFileContent, result.SourceMap);
        }
 protected static void CompileContent()
 {
     try
     {
         var options = new CompilationOptions {
             SourceMap = true, OutputStyle = OutputStyle.Compressed, SourceMapFileUrls = true
         };
         CompilationResult compilationResult = SassCompiler.CompileFile(ImportingPath, OutputhPath, OutputhmapPath, options);
         Console.WriteLine("Compiled content:{1}{1}{0}{1}", compilationResult.CompiledContent,
                           Environment.NewLine);
         Console.WriteLine("Source map:{1}{1}{0}{1}", compilationResult.SourceMap, Environment.NewLine);
         Console.WriteLine("Included file paths: {0}",
                           string.Join(", ", compilationResult.IncludedFilePaths));
     }
     catch (SassСompilationException ex)
     {
         Console.WriteLine(SassErrorHelpers.Format(ex));
     }
 }
Beispiel #20
0
 static void Main(string[] args)
 {
     UseTempFolder(folder =>
     {
         var input      = "@import './import';\n.a { .b { margin: 0; } }";
         var imported   = ".a { .c { margin: 1px; } }";
         var mainScss   = Path.Combine(folder, "main.scss");
         var importScss = Path.Combine(folder, "_import.scss");
         File.WriteAllText(mainScss, input, new UTF8Encoding(false));
         File.WriteAllText(importScss, imported, new UTF8Encoding(false));
         var compiler = new SassCompiler();
         var res      = compiler.CompileFile(mainScss, new SassOptions(
                                                 outputStyle: SassOutputStyle.Compressed,
                                                 indent: string.Empty,
                                                 sourceMapEmbed: false
                                                 ));
         Console.WriteLine(res.Css);
     });
 }
        public ActionResult SaveStyles(string color, string font)
        {
            //Set the sass variables from the input field
            string scssString = @"$mainColor:" + color + ";$mainFont:" + font + ";";

            //Write the new variables to the custom variables scss file
            System.IO.File.WriteAllText(Server.MapPath("~/Content/scss/_variablesCustom.scss"), scssString);

            //Initiate a new sass compiler
            ISassCompiler sassCompiler = new SassCompiler();

            //Compile the styles.scss sass file
            string sassOutput = sassCompiler.CompileFile(Server.MapPath("~/Content/scss/styles.scss"), OutputStyle.Compressed, sourceComments: false);

            //And write the compiled output to the styles.css file, the one included on your page
            System.IO.File.WriteAllText(Server.MapPath("~/Content/styles.css"), sassOutput);

            return(RedirectToAction("Index"));
        }
        protected static void CompileFile()
        {
            WriteHeader("Compilation of SCSS file");

            string inputFilePath  = Path.Combine(_filesDirectoryPath, "style.scss");
            string outputFilePath = Path.Combine(_filesDirectoryPath, "style.css");

            try
            {
                var options = new CompilationOptions {
                    SourceMap = true, SourceMapFileUrls = true
                };
                CompilationResult result = SassCompiler.CompileFile(inputFilePath, outputFilePath, options: options);
                WriteOutput(result);
            }
            catch (SassException e)
            {
                WriteError("During compilation of SCSS file an error occurred.", e);
            }
        }
Beispiel #23
0
        static void Process(int jobID)
        {
            Console.WriteLine("Start JobID: {0}...", jobID);

            var sw = new Stopwatch();

            sw.Start();

            SassCompiler compiler = new SassCompiler();

            {
                //var result = compiler.CompileFile(Path.Combine(srcpath, @"..\..\bootstrap.scss"), includeSourceComments: false );
                var result = compiler.CompileFile(@"default.scss", OutputStyle.Nested, "http://winfly/", false, 5, true, null);

                File.WriteAllText(String.Format(@"{0}\foundation-libsass{1}.css", OutputDir, jobID), result.CSS);
            }

            sw.Stop();
            Console.WriteLine("JobID: {0} Took: {1}.", jobID, sw.ElapsedMilliseconds);
        }
        public virtual void FileWithUtf8CharactersCompilationIsCorrect()
        {
            // Arrange
            string inputFilePath = Path.Combine(_filesDirectoryPath,
                                                string.Format("ютф-8/{0}/символы{1}", _subfolderName, _fileExtension));
            string outputFilePath = Path.Combine(_filesDirectoryPath, "ютф-8/символы.css");

            string targetOutputCode = File.ReadAllText(outputFilePath);

            // Act
            CompilationResult result = SassCompiler.CompileFile(inputFilePath);

            // Assert
            Assert.Equal(targetOutputCode, result.CompiledContent);
            Assert.True(string.IsNullOrEmpty(result.SourceMap));

            var includedFilePaths = result.IncludedFilePaths;

            Assert.Equal(1, includedFilePaths.Count);
            Assert.Equal(GetCanonicalPath(inputFilePath), includedFilePaths[0]);
        }
        protected static void CompileFile()
        {
            WriteHeader("Compilation of SCSS file");

            string inputFilePath  = Path.Combine(_filesDirectoryPath, "style.scss");
            string outputFilePath = Path.Combine(_filesDirectoryPath, "style.css");

            try
            {
                using (var sassCompiler = new SassCompiler(new CompilationOptions {
                    SourceMap = true
                }))
                {
                    CompilationResult result = sassCompiler.CompileFile(inputFilePath, outputFilePath);
                    WriteVersion(sassCompiler.Version);
                    WriteOutput(result);
                }
            }
            catch (SassException e)
            {
                WriteError("During compilation of SCSS file an error occurred.", e);
            }
        }
Beispiel #26
0
        public override Task Invoke(IOwinContext context)
        {
            var path = FileSystem.MapPath(_options.BasePath, context.Request.Path.Value);
            var ext  = Path.GetExtension(path);

            if (ExtToHandle(ext))
            {
                Trace.WriteLine("Invoke SassMiddleware");

                context.Response.StatusCode  = 200;
                context.Response.ContentType = MimeTypeService.GetMimeType(".css");

                var compiler   = new SassCompiler();
                var compressed = compiler.CompileFile(path, OutputStyle.Compressed, false);
                compressed = compressed.Replace(";}", "}").Replace(" {", "{");

                context.Response.Write(compressed);

                return(Globals.CompletedTask);
            }

            return(Next.Invoke(context));
        }
Beispiel #27
0
        static async Task CompileFilesAsync(IEnumerable <string> sassFiles)
        {
            foreach (var file in sassFiles)
            {
                var fileInfo = new FileInfo(file);
                if (fileInfo.Name.StartsWith("_"))
                {
                    continue;
                }

                var result = SassCompiler.CompileFile(file, options: new CompilationOptions {
                    OutputStyle = OutputStyle.Compressed
                });

                var newFile = fileInfo.FullName.Replace(fileInfo.Extension, ".css");

                if (File.Exists(newFile) && result.CompiledContent == await File.ReadAllTextAsync(newFile))
                {
                    continue;
                }

                await File.WriteAllTextAsync(newFile, result.CompiledContent);
            }
        }
        public virtual void FileWithImportCompilationIsCorrect()
        {
            // Arrange
            string inputFilePath = Path.Combine(_resourcesDirectoryPath,
                string.Format("import/{0}/base{1}", _subfolderName, _fileExtension));
            string importedFilePath = Path.Combine(_resourcesDirectoryPath,
                string.Format("import/{0}/_reset{1}", _subfolderName, _fileExtension));
            string outputFilePath = Path.Combine(_resourcesDirectoryPath, "import/base.css");

            string targetOutputCode = File.ReadAllText(outputFilePath);

            var options = new CompilationOptions
            {
                SourceMap = true
            };

            // Act
            CompilationResult result;

            using (var compiler = new SassCompiler())
            {
                result = compiler.CompileFile(inputFilePath, options: options);
            }

            // Assert
            Assert.Equal(targetOutputCode, result.CompiledContent);
            Assert.False(string.IsNullOrEmpty(result.SourceMap));

            var includedFilePaths = result.IncludedFilePaths;
            Assert.Equal(2, includedFilePaths.Count);
            Assert.Equal(GetCanonicalPath(inputFilePath), includedFilePaths[0]);
            Assert.Equal(GetCanonicalPath(importedFilePath), includedFilePaths[1]);
        }
        public virtual void FileWithUnicodeCharactersCompilationIsCorrect()
        {
            // Arrange
            string inputFilePath = Path.Combine(_resourcesDirectoryPath,
                string.Format("юникод/{0}/символы{1}", _subfolderName, _fileExtension));
            string outputFilePath = Path.Combine(_resourcesDirectoryPath, "юникод/символы.css");

            string targetOutputCode = File.ReadAllText(outputFilePath);

            // Act
            CompilationResult result;

            using (var compiler = new SassCompiler())
            {
                result = compiler.CompileFile(inputFilePath);
            }

            // Assert
            Assert.Equal(targetOutputCode, result.CompiledContent);
            Assert.True(string.IsNullOrEmpty(result.SourceMap));

            var includedFilePaths = result.IncludedFilePaths;
            Assert.Equal(1, includedFilePaths.Count);
            Assert.Equal(GetCanonicalPath(inputFilePath), includedFilePaths[0]);
        }