Пример #1
0
        public void Test()
        {
            var compiler = new SassCompiler(new SassSettings());
            var result   = compiler.Compile("../../../TestCases/Scss/error.scss");

            Assert.IsTrue(result.Errors != null && result.Errors.Any());
        }
Пример #2
0
        public void Can_compile_sass_file(string label, int expectedFiles, CompilerOptions options)
        {
            // Arrange
            var cwd = Path.Combine(AppContext.BaseDirectory, "generated", label);

            if (Directory.Exists(cwd))
            {
                Directory.Delete(cwd, recursive: true);
            }
            Directory.CreateDirectory(cwd);
            options.OutputDirectory = cwd;

            // Act
            var result     = SassCompiler.Compile(Sample.GetBasicSCSS().FullName, options);
            var totalFiles = Directory.GetFiles(cwd, "*").Length;

            var builder   = new StringBuilder();
            var separator = string.Concat(Enumerable.Repeat('=', 50));

            foreach (var item in result.GeneratedFiles)
            {
                builder.AppendLine($"== {Path.GetFileName(item)} ({label})")
                .AppendLine(separator)
                .AppendLine(File.ReadAllText(item))
                .AppendLine()
                .AppendLine();
            }

            // Assert
            result.Success.ShouldBeTrue();
            totalFiles.ShouldBe(expectedFiles);
            result.GeneratedFiles.Length.ShouldBe(expectedFiles);

            Diff.Approve(builder, ".txt", label);
        }
Пример #3
0
        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);
        }
        public virtual void MappingFileNotFoundErrorDuringCompilationOfCodeIsCorrect()
        {
            // Arrange
            string inputFilePath = Path.Combine(_filesDirectoryPath,
                                                string.Format("non-existing-files/{0}/base{1}", _subfolderName, _fileExtension));
            string inputCode = File.ReadAllText(inputFilePath);
            var    options   = new CompilationOptions
            {
                SourceMap = true
            };

            SassСompilationException exception = null;

            // Act
            try
            {
                CompilationResult result = SassCompiler.Compile(inputCode, inputFilePath, options: options);
            }
            catch (SassСompilationException e)
            {
                exception = e;
            }

            // Assert
            Assert.NotNull(exception);
            Assert.NotEmpty(exception.Message);
            Assert.Equal(GetCanonicalPath(inputFilePath), exception.File);
            Assert.Equal(_syntaxType == SyntaxType.Sass ? 5 : 6, exception.LineNumber);
            Assert.Equal(1, exception.ColumnNumber);
        }
        protected static void CompileContent()
        {
            WriteHeader("Compilation of SCSS code");

            const string inputContent = @"$font-stack: Helvetica, sans-serif;
$primary-color: #333;

body {
  font: 100% $font-stack;
  color: $primary-color;
}

/* Стрелка вниз */
.down-arrow:before {
  content: ""▼"";
}";

            try
            {
                var options = new CompilationOptions {
                    SourceMap = true
                };
                CompilationResult result = SassCompiler.Compile(inputContent, "input.scss", "output.css",
                                                                options: options);
                WriteOutput(result);
            }
            catch (SassException e)
            {
                WriteError("During compilation of SCSS code an error occurred.", e);
            }
        }
        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);
        }
Пример #7
0
        public void CompileFile(bool withFileManager)
        {
            SetFileManager(withFileManager);
            Document document = s_documents[DocumentName];

            string compiledContent = SassCompiler.CompileFile(document.AbsolutePath).CompiledContent;
        }
Пример #8
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 CodeWithImportCompilationIsCorrect()
        {
            // 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 inputCode        = File.ReadAllText(inputFilePath);
            string targetOutputCode = File.ReadAllText(outputFilePath);

            var options = new CompilationOptions
            {
                SourceMap = true
            };

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

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

            var includedFilePaths = result.IncludedFilePaths;

            Assert.Equal(1, includedFilePaths.Count);
            Assert.Equal(GetCanonicalPath(importedFilePath), includedFilePaths[0]);
        }
        /// <summary>
        /// Return stream for requested  asset file  (used for search current and base themes assets)
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public async Task <Stream> GetAssetStreamAsync(string filePath)
        {
            Stream retVal = null;
            var    filePathWithoutExtension = Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath));
            //file.ext => file.ext || file || file.liquid || file.ext.liquid
            var searchPatterns = new[] { filePath, filePathWithoutExtension, string.Format(_liquidTemplateFormat, filePathWithoutExtension), string.Format(_liquidTemplateFormat, filePath) };


            string currentThemeFilePath = null;

            //try to search in current store theme
            if (_themeBlobProvider.PathExists(Path.Combine(CurrentThemePath, "assets")))
            {
                currentThemeFilePath = searchPatterns.SelectMany(x => _themeBlobProvider.Search(Path.Combine(CurrentThemePath, "assets"), x, true)).FirstOrDefault();
            }
            //If not found by current theme path try find them by base path if it is defined
            if (currentThemeFilePath == null && BaseThemePath != null)
            {
                currentThemeFilePath = searchPatterns.SelectMany(x => _themeBlobProvider.Search(Path.Combine(BaseThemePath, "assets"), x, true)).FirstOrDefault();
            }

            if (currentThemeFilePath != null)
            {
                retVal   = _themeBlobProvider.OpenRead(currentThemeFilePath);
                filePath = currentThemeFilePath;
            }

            if (retVal != null && filePath.EndsWith(".liquid"))
            {
                var context = WorkContext.Clone() as WorkContext;
                context.Settings = GetSettings("''");
                var templateContent = retVal.ReadToString();
                retVal.Dispose();

                var template = await RenderTemplateAsync(templateContent, filePath, context.ToScriptObject());

                retVal = new MemoryStream(Encoding.UTF8.GetBytes(template));
            }

            if (retVal != null && (filePath.Contains(".scss.") && filePath.EndsWith(".liquid") || filePath.EndsWith(".scss")))
            {
                var content = retVal.ReadToString();
                retVal.Dispose();

                try
                {
                    //handle scss resources
                    var result = SassCompiler.Compile(content);
                    content = result.CompiledContent;

                    retVal = new MemoryStream(Encoding.UTF8.GetBytes(content));
                }
                catch (Exception ex)
                {
                    throw new SaasCompileException(filePath, content, ex);
                }
            }

            return(retVal);
        }
Пример #12
0
        public static void CompileCss(string sassFilePath, string cssFilePath, DateTime?folderLastUpdatedUtc = null)
        {
            var sassCompiler = new SassCompiler(new SassOptions
            {
                InputPath             = sassFilePath,
                OutputStyle           = SassOutputStyle.Compact,
                IncludeSourceComments = false,
            });


            var result = sassCompiler.Compile();


            if (result.ErrorStatus != 0)
            {
                throw new InvalidOperationException("Compiling sass caused a scripting host error. " +
                                                    string.Format("Error status: {0}. File: {1}. Line: {2}. Column: {3}. Message: {4}", result.ErrorStatus, result.ErrorFile, result.ErrorLine, result.ErrorColumn, result.ErrorMessage));
            }

            C1File.WriteAllText(cssFilePath, result.Output);

            if (folderLastUpdatedUtc.HasValue)
            {
                File.SetLastWriteTimeUtc(cssFilePath, folderLastUpdatedUtc.Value);
            }
        }
Пример #13
0
        private void InnerTranslate(IAsset asset, CompilationOptions sassOptions, bool enableNativeMinification)
        {
            string         assetTypeName = asset.AssetTypeCode == Constants.AssetTypeCode.Sass ? "Sass" : "SCSS";
            string         newContent;
            string         assetUrl = asset.Url;
            IList <string> dependencies;

            try
            {
                CompilationResult result = SassCompiler.Compile(asset.Content, assetUrl, options: sassOptions);
                newContent   = result.CompiledContent;
                dependencies = result.IncludedFilePaths;
            }
            catch (SassСompilationException e)
            {
                throw new AssetTranslationException(
                          string.Format(CoreStrings.Translators_TranslationSyntaxError,
                                        assetTypeName, OUTPUT_CODE_TYPE, assetUrl, SassErrorHelpers.Format(e)));
            }
            catch (Exception e)
            {
                throw new AssetTranslationException(
                          string.Format(CoreStrings.Translators_TranslationFailed,
                                        assetTypeName, OUTPUT_CODE_TYPE, assetUrl, e.Message), e);
            }

            asset.Content  = newContent;
            asset.Minified = enableNativeMinification;
            asset.RelativePathsResolved   = false;
            asset.VirtualPathDependencies = dependencies;
        }
        public void CompilationOfCodeWithAppAbsolutePaths()
        {
            // Arrange
            var virtualFileManagerMock = new Mock <IFileManager>();

            virtualFileManagerMock
            .SetupGet(fm => fm.SupportsVirtualPaths)
            .Returns(true)
            ;
            virtualFileManagerMock
            .Setup(fm => fm.GetCurrentDirectory())
            .Returns("/")
            ;

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

            // Act
            CompilationResult result;

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

            // Assert
            Assert.AreEqual(_siteOutputFileContent, result.CompiledContent);
            Assert.AreEqual(1, result.IncludedFilePaths.Count);
            Assert.AreEqual(_siteInputFileAbsolutePath, result.IncludedFilePaths[0]);
            Assert.AreEqual(_siteSourceMapFileContent, result.SourceMap);
        }
Пример #15
0
        public virtual void CodeCompilationIsCorrect()
        {
            // Arrange
            string inputFilePath = Path.Combine(_resourcesDirectoryPath,
                string.Format("variables/{0}/style{1}", _subfolderName, _fileExtension));
            string outputFilePath = Path.Combine(_resourcesDirectoryPath, "variables/style.css");

            string inputCode = File.ReadAllText(inputFilePath);
            string targetOutputCode = File.ReadAllText(outputFilePath);

            var options = new CompilationOptions
            {
                IndentedSyntax = _indentedSyntax
            };

            // Act
            CompilationResult result;

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

            // Assert
            Assert.Equal(targetOutputCode, result.CompiledContent);
            Assert.True(string.IsNullOrEmpty(result.SourceMap));
            Assert.Empty(result.IncludedFilePaths);
        }
Пример #16
0
        public void Can_detect_sass_errors(string documentPath, int errorLine)
        {
            // Arrange
            var cwd = Path.Combine(AppContext.BaseDirectory, "generated", "errors");

            if (Directory.Exists(cwd))
            {
                Directory.Delete(cwd, recursive: true);
            }
            Directory.CreateDirectory(cwd);

            var options = new CompilerOptions
            {
                Minify             = false,
                OutputDirectory    = cwd,
                GenerateSourceMaps = false,
            };

            // Act
            var result = SassCompiler.Compile(documentPath, options);
            var error  = result.Errors.FirstOrDefault();

            // Assert
            result.Success.ShouldBeFalse();
            result.Errors.ShouldNotBeEmpty();

            error.Line.ShouldBe(errorLine);
            error.Column.ShouldBeGreaterThan(0);
            error.StatusCode.ShouldBeGreaterThan(0);
            error.Message.ShouldNotBeNullOrEmpty();
        }
Пример #17
0
        private static void Compile()
        {
            var          compiler = new SassCompiler();
            const string input    = "$primary-color: #333; body {color: $primary-color;}";
            var          output   = compiler.Compile(input, OutputStyle.Compressed, false);

            Console.WriteLine(output);
        }
Пример #18
0
        public void Test()
        {
            var compiler = new SassCompiler(new SassSettings());
            var result   = compiler.Compile(new List <(string File, bool Created)> {
                (File: "../../../TestCases/Scss/error.scss", Created: false)
            });

            Assert.IsTrue(result.Errors != null && result.Errors.Any());
        }
Пример #19
0
        /// <summary>
        /// Return stream for requested  asset file  (used for search current and base themes assets)
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public Stream GetAssetStream(string filePath)
        {
            Stream retVal = null;
            var    filePathWithoutExtension = Path.Combine(Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath));
            //file.ext => file.ext || file || file.liquid || file.ext.liquid
            var searchPatterns = new[] { filePath, filePathWithoutExtension, string.Format(_liquidTemplateFormat, filePathWithoutExtension), string.Format(_liquidTemplateFormat, filePath) };

            string currentThemeFilePath = null;

            //try to search in current store theme
            if (_themeBlobProvider.PathExists(Path.Combine(CurrentThemePath, "assets")))
            {
                currentThemeFilePath = searchPatterns.SelectMany(x => _themeBlobProvider.Search(Path.Combine(CurrentThemePath, "assets"), x, true)).FirstOrDefault();
            }

            if (currentThemeFilePath != null)
            {
                retVal   = _themeBlobProvider.OpenRead(currentThemeFilePath);
                filePath = currentThemeFilePath;
            }

            if (retVal != null && filePath.EndsWith(".liquid"))
            {
                var shopifyContext = WorkContext.ToShopifyModel(UrlBuilder);
                var parameters     = shopifyContext.ToLiquid() as Dictionary <string, object>;
                var settings       = GetSettings("''");
                parameters.Add("settings", settings);

                var templateContent = retVal.ReadToString();
                retVal.Dispose();

                var template = RenderTemplate(templateContent, parameters);
                retVal = new MemoryStream(Encoding.UTF8.GetBytes(template));
            }

            if (retVal != null && (filePath.Contains(".scss.") && filePath.EndsWith(".liquid") || filePath.EndsWith(".scss")))
            {
                var content = retVal.ReadToString();
                retVal.Dispose();

                try
                {
                    //handle scss resources
                    CompilationResult result = SassCompiler.Compile(content);
                    content = result.CompiledContent;

                    retVal = new MemoryStream(Encoding.UTF8.GetBytes(content));
                }
                catch (Exception ex)
                {
                    throw new SaasCompileException(filePath, content, ex);
                }
            }

            return(retVal);
        }
Пример #20
0
        public void ShouldNotCompileFileWithEchoOutputStyle()
        {
            // Arrange

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

            // Assert
            compile.ShouldThrow <ArgumentException>();
        }
Пример #21
0
        public void ShouldNotCompileStringWithEchoOutputStyle()
        {
            // Arrange

            // Act
            Action compile = () => SassCompiler.Compile(_basicContent, OutputStyle.Echo);

            // Assert
            compile.ShouldThrow <ArgumentException>();
        }
Пример #22
0
        public static string TransformToCss(string fullFileName, string text, EnvDTE.ProjectItem projectItem)
        {
            string output = string.Empty;
            using (var fixture = new SassCompiler())
            {
                output = fixture.Compile(fullFileName);
            }

            return output;
        }
Пример #23
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);
        }
Пример #24
0
        public void ShouldCompileString()
        {
            // Arrange
            const string expectedResult = "/* line 3, source string */\nbody .class {\n  color: red; }\n";

            // Act
            string compiled = SassCompiler.Compile(_basicContent);

            // Assert
            compiled.Should().BeEquivalentTo(expectedResult);
        }
Пример #25
0
        /* sass to css covert */
        public string sasscompiler(string sourcepath)
        {
            var options = new SassOptions
            {
                InputPath = sourcepath
            };
            var sass   = new SassCompiler(options);
            var result = sass.Compile();

            return(result.Output);
        }
Пример #26
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);
        }
Пример #27
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);
        }
Пример #28
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);
        }
Пример #29
0
        public static string TransformToCss(string fullFileName, string text, EnvDTE.ProjectItem projectItem)
        {
            string output = string.Empty;

            using (var fixture = new SassCompiler())
            {
                output = fixture.Compile(fullFileName);
            }

            return(output);
        }
Пример #30
0
        public void ShouldCompileStringWithImport()
        {
            // Arrange
            string expectedResult = String.Format("/* line 1, {0} */\nbody {{\n  border-color: green; }}\n\n/* line 5, source string */\nbody .class {{\n  color: red; }}\n", ReplaceLastSlash(ImportPath));

            // Act
            string compiled = SassCompiler.Compile(_importingContent, includePaths: new[] { Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles") });

            // Assert
            compiled.Should().BeEquivalentTo(expectedResult);
        }
Пример #31
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);
        }
Пример #32
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);
        }
Пример #33
0
        public static void CompileCss(string sassFilePath, string cssFilePath, DateTime? folderLastUpdatedUtc = null)
        {
            var sassCompiler = new SassCompiler(new SassOptions
            {
                InputPath = sassFilePath,
                OutputStyle = SassOutputStyle.Compact,
                IncludeSourceComments = false,
            });

            var result = sassCompiler.Compile();

            if (result.ErrorStatus != 0)
            {
                throw new InvalidOperationException("Compiling sass caused a scripting host error. " +
                    string.Format("Error status: {0}. File: {1}. Line: {2}. Column: {3}. Message: {4}", result.ErrorStatus, result.ErrorFile, result.ErrorLine, result.ErrorColumn, result.ErrorMessage));
            }

            C1File.WriteAllText(cssFilePath, result.Output);

            if (folderLastUpdatedUtc.HasValue)
            {
                File.SetLastWriteTimeUtc(cssFilePath, folderLastUpdatedUtc.Value);
            }
        }
Пример #34
0
        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]);
        }
Пример #35
0
        public virtual void CodeWithImportCompilationIsCorrect()
        {
            // 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 inputCode = File.ReadAllText(inputFilePath);
            string targetOutputCode = File.ReadAllText(outputFilePath);

            var options = new CompilationOptions
            {
                IndentedSyntax = _indentedSyntax,
                SourceMap = true
            };

            // Act
            CompilationResult result;

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

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

            var includedFilePaths = result.IncludedFilePaths;
            Assert.Equal(1, includedFilePaths.Count);
            Assert.Equal(GetCanonicalPath(importedFilePath), includedFilePaths[0]);
        }
Пример #36
0
 public void SetupContext()
 {
     _compilerOptions = new SassCompilerOptions();
     _compiler = new SassCompiler(_compilerOptions);
 }