Ejemplo n.º 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);
            }
        }
Ejemplo n.º 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);
                }
            }
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 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);
                    }
                }
            }
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 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));
        }
Ejemplo n.º 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);
     }
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 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;
            }
        }
Ejemplo n.º 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";
            }
        }
Ejemplo n.º 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");
            }
        }
Ejemplo n.º 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);
                }
            }
        }
Ejemplo n.º 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);
                }
            }
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 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);
                    }
                }
        }
Ejemplo n.º 27
0
        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);
            }
        }
Ejemplo n.º 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);
            }
        }
Ejemplo n.º 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");
 }
Ejemplo n.º 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);
                }
            }
        }