コード例 #1
0
        protected void WriteCompiledFile(string content, string currentFileName)
        {
            string extension = Path.GetExtension(currentFileName);
            string fileName  = null;

            switch (extension.ToLowerInvariant())
            {
            case ".less":
                fileName = GetCompiledFileName(currentFileName, ".css", UseCompiledFolder);
                break;

            case ".coffee":
            case ".ts":
                fileName = GetCompiledFileName(currentFileName, ".js", UseCompiledFolder);
                break;

            default:     // For the Diff view
                return;
            }

            bool fileExist   = File.Exists(fileName);
            bool fileWritten = false;

            ProjectHelpers.CheckOutFileFromSourceControl(fileName);
            fileWritten = WriteFile(content, fileName, fileExist, fileWritten);

            if (!fileExist && fileWritten)
            {
                AddFileToProject(currentFileName, fileName);
            }
        }
コード例 #2
0
        private static void WriteMinFile(string filePath, string bundlePath, string content, string extension)
        {
            string minPath = bundlePath.Replace(Path.GetExtension(bundlePath), ".min" + Path.GetExtension(bundlePath));

            if (extension.Equals(".js", StringComparison.OrdinalIgnoreCase))
            {
                JavaScriptSaveListener.Minify(bundlePath, minPath, true);
                MarginBase.AddFileToProject(filePath, minPath);

                if (WESettings.GetBoolean(WESettings.Keys.GenerateJavaScriptSourceMaps))
                {
                    MarginBase.AddFileToProject(filePath, minPath + ".map");
                }

                MarginBase.AddFileToProject(filePath, minPath + ".gzip");
            }
            else if (extension.Equals(".css", StringComparison.OrdinalIgnoreCase))
            {
                string minContent = MinifyFileMenu.MinifyString(extension, content);

                ProjectHelpers.CheckOutFileFromSourceControl(minPath);

                using (StreamWriter writer = new StreamWriter(minPath, false, new UTF8Encoding(true)))
                {
                    writer.Write(minContent);
                }

                MarginBase.AddFileToProject(filePath, minPath);

                if (WESettings.GetBoolean(WESettings.Keys.CssEnableGzipping))
                {
                    CssSaveListener.GzipFile(filePath, minPath, minContent);
                }
            }
        }
コード例 #3
0
        private static void MinifyFile(string file, string minFile, CodeSettings settings, bool isBundle)
        {
            Minifier minifier = new Minifier();

            if (!isBundle)
            {
                minifier.FileName = Path.GetFileName(file);
            }

            string content = minifier.MinifyJavaScript(File.ReadAllText(file), settings);

            if (WESettings.GetBoolean(WESettings.Keys.GenerateJavaScriptSourceMaps))
            {
                content += Environment.NewLine + "//@ sourceMappingURL=" + Path.GetFileName(minFile) + ".map";
            }

            ProjectHelpers.CheckOutFileFromSourceControl(minFile);
            using (StreamWriter writer = new StreamWriter(minFile, false, new UTF8Encoding(true)))
            {
                writer.Write(content);
            }

            if (WESettings.GetBoolean(WESettings.Keys.JavaScriptEnableGzipping))
            {
                CssSaveListener.GzipFile(file, minFile, content);
            }
        }
コード例 #4
0
        public async static Task <bool> MakeBundle(BundleDocument document, string bundleFile, Func <string, bool, Task> updateBundle)
        {
            // filePath must end in ".targetExtension.bundle"
            string extension = Path.GetExtension(Path.GetFileNameWithoutExtension(document.FileName));

            if (string.IsNullOrEmpty(extension))
            {
                Logger.Log("Skipping bundle file " + document.FileName + " without extension.  Bundle files must end with the output extension, followed by '.bundle'.");
                return(false);
            }

            Dictionary <string, string> files = await WatchFiles(document, updateBundle, bundleFile);

            string combinedContent = await CombineFiles(files, extension, document, bundleFile);

            bool bundleChanged = !File.Exists(bundleFile) || await FileHelpers.ReadAllTextRetry(bundleFile) != combinedContent;

            if (bundleChanged)
            {
                if (!ProjectHelpers.CheckOutFileFromSourceControl(bundleFile))
                {
                    throw new Exception("There was a problem checking out the file: " + bundleFile);
                }

                await FileHelpers.WriteAllTextRetry(bundleFile, combinedContent);

                Logger.Log("Web Essentials: Updated bundle: " + Path.GetFileName(bundleFile));
            }

            ProjectHelpers.AddFileToProject(document.FileName, bundleFile);

            return(bundleChanged);
        }
コード例 #5
0
        public static IEnumerable <SpriteFragment> CreateImage(SpriteDocument sprite, out string imageFile)
        {
            imageFile = Path.ChangeExtension(sprite.FileName, sprite.FileExtension);
            ProjectHelpers.CheckOutFileFromSourceControl(imageFile);

            Dictionary <string, Image> images = GetImages(sprite);

            int width  = sprite.IsVertical ? images.Values.Max(i => i.Width) : images.Values.Sum(i => i.Width);
            int height = sprite.IsVertical ? images.Values.Sum(img => img.Height) : images.Values.Max(img => img.Height);

            List <SpriteFragment> fragments = new List <SpriteFragment>();

            using (var bitmap = new Bitmap(width, height))
            {
                using (Graphics canvas = Graphics.FromImage(bitmap))
                {
                    if (sprite.IsVertical)
                    {
                        Vertical(images, fragments, canvas);
                    }
                    else
                    {
                        Horizontal(images, fragments, canvas);
                    }
                }

                bitmap.Save(imageFile, PasteImage.GetImageFormat("." + sprite.FileExtension));
            }

            return(fragments);
        }
コード例 #6
0
        private static string ExportJson(IEnumerable <SpriteFragment> fragments, string imageFile)
        {
            var map = new
            {
                images = fragments.Select(fragment =>
                {
                    var item = new
                    {
                        Name    = Path.GetFileName(fragment.FileName),
                        Width   = fragment.Width,
                        Height  = fragment.Height,
                        OffsetX = fragment.X,
                        OffsetY = fragment.Y,
                    };

                    return(item);
                })
            };

            string outputFile = GetFileName(imageFile, ExportFormat.Json);

            ProjectHelpers.CheckOutFileFromSourceControl(outputFile);

            using (StreamWriter sw = new StreamWriter(outputFile))
                using (JsonWriter jw = new JsonTextWriter(sw))
                {
                    jw.Formatting = Formatting.Indented;

                    var serializer = new JsonSerializer();
                    serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    serializer.Serialize(jw, map);
                }

            return(outputFile);
        }
コード例 #7
0
        protected async override Task RtlVariantHandler(CompilerResult result)
        {
            if (!WESettings.Instance.Css.RtlCss || result.RtlTargetFileName == null)
            {
                return;
            }

            string value = PostProcessResult(result.RtlResult, result.RtlTargetFileName, result.RtlSourceFileName);

            // Write output file
            if (result.RtlTargetFileName != null && (MinifyInPlace || !File.Exists(result.RtlTargetFileName) ||
                                                     value != await FileHelpers.ReadAllTextRetry(result.RtlTargetFileName)))
            {
                ProjectHelpers.CheckOutFileFromSourceControl(result.RtlTargetFileName);
                await FileHelpers.WriteAllTextRetry(result.RtlTargetFileName, value);

                ProjectHelpers.AddFileToProject(result.RtlSourceFileName, result.RtlTargetFileName);
            }

            // Write map file
            if (GenerateSourceMap && (!File.Exists(result.RtlMapFileName) ||
                                      result.RtlResultMap != await FileHelpers.ReadAllTextRetry(result.RtlMapFileName)))
            {
                ProjectHelpers.CheckOutFileFromSourceControl(result.RtlMapFileName);
                await FileHelpers.WriteAllTextRetry(result.RtlMapFileName, result.RtlResultMap);

                ProjectHelpers.AddFileToProject(result.RtlTargetFileName, result.RtlMapFileName);
            }
        }
コード例 #8
0
        public static void Minify(string file, string minFile)
        {
            if (file.EndsWith(".min.css"))
            {
                return;
            }

            try
            {
                string content = MinifyFileMenu.MinifyString(".css", File.ReadAllText(file));

                ProjectHelpers.CheckOutFileFromSourceControl(minFile);
                using (StreamWriter writer = new StreamWriter(minFile, false, new UTF8Encoding(true)))
                {
                    writer.Write(content);
                }

                if (WESettings.GetBoolean(WESettings.Keys.CssEnableGzipping))
                {
                    GzipFile(file, minFile, content);
                }
            }
            catch
            {
                Logger.Log("Error minifying: " + file);
            }
        }
コード例 #9
0
        public static void MinifyFile(string lessFileName, string source)
        {
            if (WESettings.GetBoolean(WESettings.Keys.LessMinify))
            {
                string content = MinifyFileMenu.MinifyString(".css", source);
                string minFile = MarginBase.GetCompiledFileName(lessFileName, ".min.css", WESettings.GetBoolean(WESettings.Keys.LessCompileToFolder)); //lessFileName.Replace(".less", ".min.css");
                string old     = File.ReadAllText(minFile);

                if (old != content)
                {
                    bool fileExist = File.Exists(minFile);
                    bool useBom    = WESettings.GetBoolean(WESettings.Keys.UseBom);

                    ProjectHelpers.CheckOutFileFromSourceControl(minFile);
                    using (StreamWriter writer = new StreamWriter(minFile, false, new UTF8Encoding(useBom)))
                    {
                        writer.Write(content);
                    }

                    if (!fileExist)
                    {
                        MarginBase.AddFileToProject(lessFileName, minFile);
                    }
                }
            }
        }
コード例 #10
0
        public static void GzipFile(string file, string minFile, string content)
        {
            string gzipFile = minFile + ".gzip";

            ProjectHelpers.CheckOutFileFromSourceControl(gzipFile);
            byte[] gzipContent = Compress(content);
            File.WriteAllBytes(gzipFile, gzipContent);
            ProjectHelpers.AddFileToActiveProject(gzipFile);
            MarginBase.AddFileToProject(file, gzipFile);
        }
コード例 #11
0
        // Don't try-catch this method: We need to "address" all the bugs,
        // which may occur as the (node.js-based) service implement changes.
        private async Task <CompilerResult> ProcessResult(CompilerResult result, bool onlyPreview, string sourceFileName, string targetFileName)
        {
            if (result == null)
            {
                Logger.Log(ServiceName + ": " + Path.GetFileName(sourceFileName) + " compilation failed: The service failed to respond to this request\n\t\t\tPossible cause: Syntax Error!");
                return(await CompilerResultFactory.GenerateResult(sourceFileName, targetFileName));
            }
            if (!result.IsSuccess)
            {
                var firstError = result.Errors.Where(e => e != null).Select(e => e.Message).FirstOrDefault();

                if (firstError != null)
                {
                    Logger.Log(firstError);
                }

                return(result);
            }

            string resultString = PostProcessResult(result.Result, result.TargetFileName, result.SourceFileName);

            if (!onlyPreview)
            {
                // Write output file
                if (result.TargetFileName != null && (MinifyInPlace || !File.Exists(result.TargetFileName) ||
                                                      resultString != await FileHelpers.ReadAllTextRetry(result.TargetFileName)))
                {
                    ProjectHelpers.CheckOutFileFromSourceControl(result.TargetFileName);
                    await FileHelpers.WriteAllTextRetry(result.TargetFileName, resultString);

                    if (!(this is ILintCompiler))
                    {
                        ProjectHelpers.AddFileToProject(result.SourceFileName, result.TargetFileName);
                    }
                }

                // Write map file
                if (GenerateSourceMap && (!File.Exists(result.MapFileName) ||
                                          result.ResultMap != await FileHelpers.ReadAllTextRetry(result.MapFileName)))
                {
                    ProjectHelpers.CheckOutFileFromSourceControl(result.MapFileName);
                    await FileHelpers.WriteAllTextRetry(result.MapFileName, result.ResultMap);

                    if (!(this is ILintCompiler))
                    {
                        ProjectHelpers.AddFileToProject(result.TargetFileName, result.MapFileName);
                    }
                }

                await RtlVariantHandler(result);
            }

            return(CompilerResult.UpdateResult(result, resultString));
        }
コード例 #12
0
 private static void GzipFile(string file, string minFile, string content)
 {
     if (WESettings.GetBoolean(WESettings.Keys.CssEnableGzipping))
     {
         string gzipFile = minFile + ".gzip";
         ProjectHelpers.CheckOutFileFromSourceControl(gzipFile);
         byte[] gzipContent = CssSaveListener.Compress(content);
         File.WriteAllBytes(gzipFile, gzipContent);
         ProjectHelpers.AddFileToActiveProject(gzipFile);
         MarginBase.AddFileToProject(file, gzipFile);
     }
 }
コード例 #13
0
        public static void GzipFile(string sourcePath)
        {
            var gzipPath = sourcePath + ".gzip";

            ProjectHelpers.CheckOutFileFromSourceControl(gzipPath);

            using (var sourceStream = File.OpenRead(sourcePath))
                using (var targetStream = File.OpenWrite(gzipPath))
                    using (var gzipStream = new GZipStream(targetStream, CompressionMode.Compress))
                        sourceStream.CopyTo(gzipStream);

            ProjectHelpers.AddFileToProject(sourcePath, gzipPath);
        }
コード例 #14
0
        public async Task <XDocument> WriteBundleRecipe()
        {
            string root = ProjectHelpers.GetRootFolder();

            if (string.IsNullOrEmpty(root))
            {
                root = ProjectHelpers.GetProjectFolder(FileName);
            }

            XmlWriterSettings settings = new XmlWriterSettings()
            {
                Indent = true
            };
            XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

            ProjectHelpers.CheckOutFileFromSourceControl(FileName);

            using (XmlWriter writer = await Task.Run(() => XmlWriter.Create(FileName, settings)))
            {
                XDocument doc = new XDocument(
                    new XElement("bundle",
                                 new XAttribute(XNamespace.Xmlns + "xsi", xsi),
                                 new XAttribute(xsi + "noNamespaceSchemaLocation", "http://vswebessentials.com/schemas/v1/bundle.xsd"),
                                 new XElement("settings",
                                              new XComment("Determines if the bundle file should be automatically optimized after creation/update."),
                                              new XElement("minify", Minified.ToString().ToLowerInvariant()),
                                              new XComment("Determine whether to generate/re-generate this bundle on building the solution."),
                                              new XElement("runOnBuild", RunOnBuild.ToString().ToLowerInvariant()),
                                              new XComment("Specifies a custom subfolder to save files to. By default, compiled output will be placed in the same folder and nested under the original file."),
                                              new XElement("outputDirectory", OutputDirectory)
                                              ),
                                 new XComment("The order of the <file> elements determines the order of the files in the bundle."),
                                 new XElement("files", BundleAssets.Select(file => new XElement("file", GetRelativePath(file, root))))
                                 )
                    );

                if (isCss)
                {
                    doc.Descendants("runOnBuild").FirstOrDefault().AddAfterSelf(
                        new XComment("Use absolute path in the generated CSS files. By default, the URLs are relative to generated bundled CSS file."),
                        new XElement("adjustRelativePaths", AdjustRelativePaths.ToString().ToLowerInvariant())
                        );
                }

                doc.Save(writer);

                return(doc);
            }
        }
コード例 #15
0
        public async Task <CompilerResult> CompileAsync(string sourceFileName, string targetFileName)
        {
            if (RequireMatchingFileName && Path.GetFileName(targetFileName) != Path.GetFileNameWithoutExtension(sourceFileName) + TargetExtension)
            {
                throw new ArgumentException(ServiceName + " cannot compile to a targetFileName with a different name.  Only the containing directory can be different.", "targetFileName");
            }

            var scriptArgs = GetArguments(sourceFileName, targetFileName);

            var errorOutputFile = Path.GetTempFileName();

            var cmdArgs = string.Format("\"{0}\" \"{1}\"", NodePath, CompilerPath);

            cmdArgs = string.Format("/c \"{0} {1} > \"{2}\" 2>&1\"", cmdArgs, scriptArgs, errorOutputFile);

            ProcessStartInfo start = new ProcessStartInfo("cmd")
            {
                WindowStyle      = ProcessWindowStyle.Hidden,
                WorkingDirectory = Path.GetDirectoryName(sourceFileName),
                Arguments        = cmdArgs,
                UseShellExecute  = false,
                CreateNoWindow   = true
            };

            try
            {
                ProjectHelpers.CheckOutFileFromSourceControl(targetFileName);

                if (GenerateSourceMap)
                {
                    ProjectHelpers.CheckOutFileFromSourceControl(targetFileName + ".map");
                }

                using (var process = await start.ExecuteAsync())
                {
                    return(ProcessResult(
                               process,
                               File.ReadAllText(errorOutputFile).Trim(),
                               sourceFileName,
                               targetFileName
                               ));
                }
            }
            finally
            {
                File.Delete(errorOutputFile);
            }
        }
コード例 #16
0
        private async static Threading.Task WriteBundleRecipe(string filePath, IEnumerable <ProjectItem> files, string output)
        {
            string            projectRoot = ProjectHelpers.GetProjectFolder(files.ElementAt(0).FileNames[1]);
            StringBuilder     sb          = new StringBuilder();
            XmlWriterSettings settings    = new XmlWriterSettings();

            settings.Indent = true;

            using (XmlWriter writer = XmlWriter.Create(sb, settings))
            {
                writer.WriteStartElement("bundle");
                writer.WriteAttributeString("minify", "true");
                writer.WriteAttributeString("runOnBuild", "true");
                writer.WriteAttributeString("output", output);
                writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
                writer.WriteAttributeString("xsi", "noNamespaceSchemaLocation", null, "http://vswebessentials.com/schemas/v1/bundle.xsd");
                writer.WriteComment("The order of the <file> elements determines the order of the file contents when bundled.");

                foreach (ProjectItem item in files)
                {
                    string relative = item.IsLink() ? item.FileNames[1] : "/" + FileHelpers.RelativePath(projectRoot, item.FileNames[1]);
                    writer.WriteElementString("file", relative);
                }

                writer.WriteEndElement();
            }

            sb.Replace(Encoding.Unicode.WebName, Encoding.UTF8.WebName);

            ProjectHelpers.CheckOutFileFromSourceControl(filePath);
            await FileHelpers.WriteAllTextRetry(filePath, sb.ToString());

            ProjectHelpers.AddFileToActiveProject(filePath, "None");

            _dte.ItemOperations.OpenFile(filePath);

            //TODO: Use XLINQ
            XmlDocument doc = await GetXmlDocument(filePath);

            if (doc == null)
            {
                return;
            }

            await Dispatcher.CurrentDispatcher.BeginInvoke(
                new Action(() => WriteBundleFile(filePath, doc).DoNotWait("writing " + filePath + "file")), DispatcherPriority.ApplicationIdle, null);
        }
コード例 #17
0
        private static void SaveToDisk(string file)
        {
            if (!_inProgress)
            {
                _inProgress = true;
                string path = file ?? GetFilePath();

                lock (_syncFileRoot)
                {
                    string xml = GenerateXml();

                    ProjectHelpers.CheckOutFileFromSourceControl(path);
                    File.WriteAllText(path, xml);
                }

                _inProgress = false;
            }
        }
コード例 #18
0
        private static void HandleResult(string file, CompressionResult result)
        {
            string name = file.Contains(_dataUriPrefix) ? "the dataUri" : Path.GetFileName(file);

            if (result.Saving > 0)
            {
                ProjectHelpers.CheckOutFileFromSourceControl(result.OriginalFileName);
                File.Copy(result.ResultFileName, result.OriginalFileName, true);

                string text = "Compressed " + name + " by " + result.Saving + " bytes / " + result.Percent + "%";
                EditorExtensionsPackage.DTE.StatusBar.Text = text;
                Logger.Log(result.ToString());
            }
            else
            {
                EditorExtensionsPackage.DTE.StatusBar.Text = name + " is already optimized";
            }
        }
コード例 #19
0
        void compiler_Completed(object sender, CompilerEventArgs e)
        {
            _projectFileStep++;
            string file = GetCompiledFileName(e.State, ".js", UseCompiledFolder);

            ProjectHelpers.CheckOutFileFromSourceControl(file);

            using (StreamWriter writer = new StreamWriter(file, false, new UTF8Encoding(true)))
            {
                writer.Write(e.Result);
            }

            MinifyFile(e.State, e.Result);

            if (_projectFileStep == _projectFileCount)
            {
                Logger.Log("CoffeeScript compiled");
            }
        }
コード例 #20
0
        public override void MinifyFile(string fileName, string source)
        {
            if (WESettings.GetBoolean(WESettings.Keys.CoffeeScriptMinify))
            {
                string content   = MinifyFileMenu.MinifyString(".js", source);
                string minFile   = GetCompiledFileName(fileName, ".min.js", UseCompiledFolder);//fileName.Replace(".coffee", ".min.js");
                bool   fileExist = File.Exists(minFile);

                ProjectHelpers.CheckOutFileFromSourceControl(minFile);
                using (StreamWriter writer = new StreamWriter(minFile, false, new UTF8Encoding(true)))
                {
                    writer.Write(content);
                }

                if (!fileExist)
                {
                    AddFileToProject(fileName, minFile);
                }
            }
        }
コード例 #21
0
        public override void MinifyFile(string fileName, string source)
        {
            if (WESettings.GetBoolean(WESettings.Keys.LessMinify) && !Path.GetFileName(fileName).StartsWith("_"))
            {
                string content   = MinifyFileMenu.MinifyString(".css", source);
                string minFile   = GetCompiledFileName(fileName, ".min.css", UseCompiledFolder);// fileName.Replace(".less", ".min.css");
                bool   fileExist = File.Exists(minFile);

                ProjectHelpers.CheckOutFileFromSourceControl(minFile);
                using (StreamWriter writer = new StreamWriter(minFile, false, new UTF8Encoding(true)))
                {
                    writer.Write(content);
                }

                if (!fileExist)
                {
                    AddFileToProject(Document.FilePath, minFile);
                }
            }
        }
コード例 #22
0
        private static void WriteFile(string filePath, IEnumerable <ProjectItem> files, string extension, string output)
        {
            string            projectRoot = ProjectHelpers.GetProjectFolder(files.ElementAt(0).FileNames[1]);
            StringBuilder     sb          = new StringBuilder();
            XmlWriterSettings settings    = new XmlWriterSettings();

            settings.Indent = true;

            using (XmlWriter writer = XmlWriter.Create(sb, settings))
            {
                writer.WriteStartElement("bundle");
                writer.WriteAttributeString("minify", "true");
                writer.WriteAttributeString("runOnBuild", "true");
                writer.WriteAttributeString("output", output);
                writer.WriteComment("The order of the <file> elements determines the order of them when bundled.");

                foreach (ProjectItem item in files)
                {
                    string relative = item.IsLink() ? item.FileNames[1] : "/" + FileHelpers.RelativePath(projectRoot, item.FileNames[1]);
                    writer.WriteElementString("file", relative);
                }

                writer.WriteEndElement();
            }

            sb.Replace(Encoding.Unicode.WebName, Encoding.UTF8.WebName);

            ProjectHelpers.CheckOutFileFromSourceControl(filePath);
            File.WriteAllText(filePath, sb.ToString());
            ProjectHelpers.AddFileToActiveProject(filePath, "None");

            _dte.ItemOperations.OpenFile(filePath);

            XmlDocument doc = GetXmlDocument(filePath);

            if (doc != null)
            {
                Dispatcher.CurrentDispatcher.BeginInvoke(
                    new Action(() => WriteBundleFile(filePath, doc)), DispatcherPriority.ApplicationIdle, null);
            }
        }
コード例 #23
0
        private static void Completed(CompilerResult result)
        {
            if (result.IsSuccess)
            {
                string cssFileName = MarginBase.GetCompiledFileName(result.FileName, ".css", WESettings.GetBoolean(WESettings.Keys.LessCompileToFolder));// result.FileName.Replace(".less", ".css");

                if (File.Exists(cssFileName))
                {
                    string old = File.ReadAllText(cssFileName);

                    if (old != result.Result)
                    {
                        ProjectHelpers.CheckOutFileFromSourceControl(cssFileName);
                        try
                        {
                            bool useBom = WESettings.GetBoolean(WESettings.Keys.UseBom);
                            using (StreamWriter writer = new StreamWriter(cssFileName, false, new UTF8Encoding(useBom)))
                            {
                                writer.Write(result.Result);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Log(ex);
                        }
                    }
                }

                MinifyFile(result.FileName, result.Result);
            }
            else if (result.Error != null && !string.IsNullOrEmpty(result.Error.Message))
            {
                Logger.Log(result.Error.Message);
            }
            else
            {
                Logger.Log("Error compiling LESS file: " + result.FileName);
            }
        }
コード例 #24
0
        private static string ExportStylesheet(IEnumerable <SpriteFragment> fragments, string imageFile, ExportFormat format)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(GetDescription(format));

            foreach (SpriteFragment fragment in fragments)
            {
                sb.AppendLine(GetSelector(fragment.FileName, format) + " {");
                sb.AppendLine("/* You may have to set 'display: block' */");
                sb.AppendLine("\twidth: " + fragment.Width + "px;");
                sb.AppendLine("\theight: " + fragment.Height + "px;");
                sb.AppendLine("\tbackground: url('" + Path.GetFileName(imageFile) + "') -" + fragment.X + "px -" + fragment.Y + "px;");
                sb.AppendLine("}");
            }

            string outputFile = GetFileName(imageFile, format);

            ProjectHelpers.CheckOutFileFromSourceControl(outputFile);
            File.WriteAllText(outputFile, sb.ToString().Replace("-0px", "0"), Encoding.UTF8);

            return(outputFile);
        }
コード例 #25
0
        public static void Minify(string file, string minFile)
        {
            if (file.EndsWith(".min.css"))
            {
                return;
            }

            try
            {
                string content = MinifyFileMenu.MinifyString(".css", File.ReadAllText(file));
                //Minifier minifier = new Minifier();
                //string content = minifier.MinifyStyleSheet(File.ReadAllText(file));

                ProjectHelpers.CheckOutFileFromSourceControl(minFile);
                using (StreamWriter writer = new StreamWriter(minFile, false, new UTF8Encoding(true)))
                {
                    writer.Write(content);
                }
            }
            catch
            {
                Logger.Log("Error minifying: " + file);
            }
        }
コード例 #26
0
        private static void MinifyFileWithSourceMap(string file, string minFile, CodeSettings settings, bool isBundle)
        {
            string mapPath = minFile + ".map";

            ProjectHelpers.CheckOutFileFromSourceControl(mapPath);

            using (TextWriter writer = new StreamWriter(mapPath, false, new UTF8Encoding(false)))
                using (V3SourceMap sourceMap = new V3SourceMap(writer))
                {
                    settings.SymbolsMap = sourceMap;

                    sourceMap.StartPackage(Path.GetFileName(minFile), Path.GetFileName(mapPath));

                    // This fails when debugger is attached. Bug raised with Ron Logan
                    MinifyFile(file, minFile, settings, isBundle);

                    sourceMap.EndPackage();

                    if (!isBundle)
                    {
                        MarginBase.AddFileToProject(file, mapPath);
                    }
                }
        }
コード例 #27
0
ファイル: CssCompilerBase.cs プロジェクト: waodng/VSIX
        private async Task HandleRtlCss(CompilerResult result)
        {
            string value = result.RtlResult;

            // Write output file
            if (result.RtlTargetFileName != null && (MinifyInPlace || !File.Exists(result.RtlTargetFileName) ||
                                                     value != await FileHelpers.ReadAllTextRetry(result.RtlTargetFileName)))
            {
                ProjectHelpers.CheckOutFileFromSourceControl(result.RtlTargetFileName);
                await FileHelpers.WriteAllTextRetry(result.RtlTargetFileName, value);

                ProjectHelpers.AddFileToProject(result.RtlSourceFileName, result.RtlTargetFileName);
            }

            // Write map file
            if (GenerateSourceMap && (!File.Exists(result.RtlMapFileName) ||
                                      result.RtlResultMap != await FileHelpers.ReadAllTextRetry(result.RtlMapFileName)))
            {
                ProjectHelpers.CheckOutFileFromSourceControl(result.RtlMapFileName);
                await FileHelpers.WriteAllTextRetry(result.RtlMapFileName, result.RtlResultMap);

                ProjectHelpers.AddFileToProject(result.RtlTargetFileName, result.RtlMapFileName);
            }
        }
コード例 #28
0
        private async static Threading.Task WriteBundleFile(string bundleFilePath, XmlDocument doc)
        {
            XmlNode bundleNode = doc.SelectSingleNode("//bundle");

            if (bundleNode == null)
            {
                return;
            }

            XmlNode outputAttr = bundleNode.Attributes["output"];

            if (outputAttr != null && (outputAttr.InnerText.Contains("/") || outputAttr.InnerText.Contains("\\")))
            {
                Logger.ShowMessage(String.Format(CultureInfo.CurrentCulture, "The 'output' attribute should contain a file name without a path; '{0}' is not valid", outputAttr.InnerText));
                return;
            }

            Dictionary <string, string> files = new Dictionary <string, string>();

            // filePath must end in ".targetExtension.bundle"
            string extension = Path.GetExtension(Path.GetFileNameWithoutExtension(bundleFilePath));

            if (string.IsNullOrEmpty(extension))
            {
                Logger.Log("Skipping bundle file " + bundleFilePath + " without extension.  Bundle files must end with the output extension, followed by '.bundle'.");
                return;
            }

            XmlNodeList nodes = doc.SelectNodes("//file");

            foreach (XmlNode node in nodes)
            {
                string absolute;

                if (node.InnerText.Contains(":\\"))
                {
                    absolute = node.InnerText;
                }
                else
                {
                    absolute = ProjectHelpers.ToAbsoluteFilePath(node.InnerText, bundleFilePath);
                }

                if (File.Exists(absolute))
                {
                    if (!files.ContainsKey(absolute))
                    {
                        files.Add(absolute, node.InnerText);
                    }
                }
                else
                {
                    _dte.ItemOperations.OpenFile(bundleFilePath);
                    Logger.ShowMessage(String.Format(CultureInfo.CurrentCulture, "Bundle error: The file '{0}' doesn't exist", node.InnerText));

                    return;
                }
            }

            string bundleSourcePath = outputAttr != null?Path.Combine(Path.GetDirectoryName(bundleFilePath), outputAttr.InnerText) : bundleFilePath.Replace(_ext, string.Empty);

            StringBuilder sb = new StringBuilder();

            foreach (string file in files.Keys)
            {
                //if (extension.Equals(".css", StringComparison.OrdinalIgnoreCase))
                //{
                //    sb.AppendLine("/*#source " + files[file] + " */");
                //}
                if (extension.Equals(".js", StringComparison.OrdinalIgnoreCase) && WESettings.Instance.JavaScript.GenerateSourceMaps)
                {
                    sb.AppendLine("///#source 1 1 " + files[file]);
                }

                if (!File.Exists(file))
                {
                    continue;
                }

                await new BundleFileWatcher().AttachFileObserverEvent(file);

                var source = await FileHelpers.ReadAllTextRetry(file);

                if (extension.Equals(".css", StringComparison.OrdinalIgnoreCase))
                {
                    // If the bundle is in the same folder as the CSS,
                    // or if does not have URLs, no need to normalize.
                    if (Path.GetDirectoryName(file) != Path.GetDirectoryName(bundleSourcePath) &&
                        source.IndexOf("url(", StringComparison.OrdinalIgnoreCase) > 0 &&
                        WESettings.Instance.Css.AdjustRelativePaths)
                    {
                        source = CssUrlNormalizer.NormalizeUrls(
                            tree: new CssParser().Parse(source, true),
                            targetFile: bundleSourcePath,
                            oldBasePath: file
                            );
                    }
                }

                sb.AppendLine(source);
            }

            bool bundleChanged = !File.Exists(bundleSourcePath) || await FileHelpers.ReadAllTextRetry(bundleSourcePath) != sb.ToString();

            if (bundleChanged)
            {
                ProjectHelpers.CheckOutFileFromSourceControl(bundleSourcePath);
                await FileHelpers.WriteAllTextRetry(bundleSourcePath, sb.ToString());

                Logger.Log("Web Essentials: Updated bundle: " + Path.GetFileName(bundleSourcePath));
            }

            ProjectHelpers.AddFileToProject(bundleFilePath, bundleSourcePath);

            if (bundleNode.Attributes["minify"] != null && bundleNode.Attributes["minify"].InnerText == "true")
            {
                await WriteMinFile(bundleSourcePath, extension, bundleChanged);
            }
        }
コード例 #29
0
 ///<summary>Saves the current settings to the specified settings file.</summary>
 private static void Save(string filename)
 {
     ProjectHelpers.CheckOutFileFromSourceControl(filename);
     WESettings.Instance.WriteJsonFile(filename);
     UpdateStatusBar("updated");
 }
コード例 #30
0
        private static void WriteBundleFile(string filePath, XmlDocument doc)
        {
            XmlNode bundleNode = doc.SelectSingleNode("//bundle");

            if (bundleNode == null)
            {
                return;
            }

            XmlNode outputAttr = bundleNode.Attributes["output"];

            if (outputAttr != null && (outputAttr.InnerText.Contains("/") || outputAttr.InnerText.Contains("\\")))
            {
                MessageBox.Show("The 'output' attribute should contain a file name without a path", "Web Essentials");
                return;
            }

            Dictionary <string, string> files = new Dictionary <string, string>();
            string      extension             = Path.GetExtension(filePath.Replace(_ext, string.Empty));
            XmlNodeList nodes = doc.SelectNodes("//file");

            foreach (XmlNode node in nodes)
            {
                string absolute;
                if (node.InnerText.Contains(":\\"))
                {
                    absolute = node.InnerText;
                }
                else
                {
                    absolute = ProjectHelpers.ToAbsoluteFilePath(node.InnerText, ProjectHelpers.GetProjectFolder(filePath)).Replace("\\\\", "\\");
                }

                if (File.Exists(absolute))
                {
                    if (!files.ContainsKey(absolute))
                    {
                        files.Add(absolute, node.InnerText);
                    }
                }
                else
                {
                    string error = string.Format("Bundle error: The file '{0}' doesn't exist", node.InnerText);
                    _dte.ItemOperations.OpenFile(filePath);
                    MessageBox.Show(error, "Web Essentials");
                    return;
                }
            }

            string bundlePath = outputAttr != null?Path.Combine(Path.GetDirectoryName(filePath), outputAttr.InnerText) : filePath.Replace(_ext, string.Empty);

            StringBuilder sb = new StringBuilder();

            foreach (string file in files.Keys)
            {
                //if (extension.Equals(".css", StringComparison.OrdinalIgnoreCase))
                //{
                //    sb.AppendLine("/*#source " + files[file] + " */");
                //}
                if (extension.Equals(".js", StringComparison.OrdinalIgnoreCase) && WESettings.GetBoolean(WESettings.Keys.GenerateJavaScriptSourceMaps))
                {
                    sb.AppendLine("///#source 1 1 " + files[file]);
                }

                sb.AppendLine(File.ReadAllText(file));
            }

            if (!File.Exists(bundlePath) || File.ReadAllText(bundlePath) != sb.ToString())
            {
                ProjectHelpers.CheckOutFileFromSourceControl(bundlePath);
                using (StreamWriter writer = new StreamWriter(bundlePath, false, new UTF8Encoding(true)))
                {
                    writer.Write(sb.ToString());
                    Logger.Log("Updating bundle: " + Path.GetFileName(bundlePath));
                }
                MarginBase.AddFileToProject(filePath, bundlePath);

                if (bundleNode.Attributes["minify"] != null || bundleNode.Attributes["minify"].InnerText == "true")
                {
                    WriteMinFile(filePath, bundlePath, sb.ToString(), extension);
                }
            }
        }