Пример #1
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 is for file names only - not paths", "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 = ProjectHelpers.ToAbsoluteFilePath(node.InnerText, ProjectHelpers.GetProjectFolder(filePath)).Replace("\\\\", "\\");

                if (node.InnerText.Contains(":\\") || node.InnerText.StartsWith("\\\\"))
                {
                    absolute = node.InnerText;
                }

                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(".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);
                }
            }
        }
Пример #2
0
 public static SnapshotPoint?GetCurrentSelection(string contentType)
 {
     return(ProjectHelpers.GetCurentTextView().GetSelection(contentType));
 }
Пример #3
0
 private IEnumerable <ProjectItem> GetSelectedItems(string extension)
 {
     return(ProjectHelpers.GetSelectedItems().Where(p => Path.GetExtension(p.FileNames[1]) == extension));
 }
Пример #4
0
        private static string GetRelativeFolder(string url)
        {
            int end = Math.Max(0, url.LastIndexOf('/'));

            return(ProjectHelpers.ToAbsoluteFilePath(url.Substring(0, end)));
        }
Пример #5
0
        private static void 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;
                }

                var source = File.ReadAllText(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) || File.ReadAllText(bundleSourcePath) != sb.ToString();

            if (bundleChanged)
            {
                ProjectHelpers.CheckOutFileFromSourceControl(bundleSourcePath);
                File.WriteAllText(bundleSourcePath, sb.ToString(), new UTF8Encoding(true));
                Logger.Log("Web Essentials: Updated bundle: " + Path.GetFileName(bundleSourcePath));
            }

            ProjectHelpers.AddFileToProject(bundleFilePath, bundleSourcePath);

            if (bundleNode.Attributes["minify"] != null && bundleNode.Attributes["minify"].InnerText == "true")
            {
                WriteMinFile(bundleSourcePath, extension, bundleChanged);
            }
        }
Пример #6
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");
 }
        public override void Invoke()
        {
            string filePath = ProjectHelpers.ToAbsoluteFilePath(_path);

            ApplyChanges(filePath);
        }
Пример #8
0
        public static async Task <BundleDocument> FromFile(string fileName)
        {
            var    extension = Path.GetExtension(fileName).TrimStart('.').ToLowerInvariant();
            string root      = ProjectHelpers.GetProjectFolder(fileName);
            string folder    = Path.GetDirectoryName(root);

            if (folder == null || root == null)
            {
                return(null);
            }

            XDocument doc = null;

            string contents = await FileHelpers.ReadAllTextRetry(fileName);

            try
            {
                doc = XDocument.Parse(contents);
            }
            catch (XmlException)
            {
                return(null);
            }

            // Migrate old bundles
            doc = await MigrateBundle(doc, fileName, root, folder);

            if (doc == null)
            {
                return(null);
            }

            XElement             element          = null;
            IEnumerable <string> constituentFiles = from f in doc.Descendants("file")
                                                    select ProjectHelpers.ToAbsoluteFilePath(f.Value, root, folder);

            BundleDocument bundle = new BundleDocument(fileName, constituentFiles.ToArray());

            element = doc.Descendants("minify").FirstOrDefault();

            if (element != null)
            {
                bundle.Minified = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase);
            }

            element = doc.Descendants("runOnBuild").FirstOrDefault();

            if (element != null)
            {
                bundle.RunOnBuild = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase);
            }

            if (extension == "css")
            {
                element = doc.Descendants("adjustRelativePaths").FirstOrDefault();

                if (element != null)
                {
                    bundle.AdjustRelativePaths = element.Value.Equals("true", StringComparison.OrdinalIgnoreCase);
                }
            }

            element = doc.Descendants("outputDirectory").FirstOrDefault();

            if (element != null)
            {
                bundle.OutputDirectory = element.Value;
            }

            return(bundle);
        }
Пример #9
0
        public async Task <CompilerResult> CompileAsync(string sourceFileName, string targetFileName)
        {
            if (RequireMatchingFileName &&
                Path.GetFileName(targetFileName) != Path.GetFileNameWithoutExtension(sourceFileName) + TargetExtension &&
                Path.GetFileName(targetFileName) != Path.GetFileNameWithoutExtension(sourceFileName) + ".min" + TargetExtension)
            {
                throw new ArgumentException(ServiceName + " cannot compile to a targetFileName with a different name.  Only the containing directory can be different.", "targetFileName");
            }

            var mapFileName = GetMapFileName(sourceFileName, targetFileName);

            var scriptArgs = GetArguments(sourceFileName, targetFileName, mapFileName);

            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);

                mapFileName = mapFileName ?? targetFileName + ".map";

                if (GenerateSourceMap)
                {
                    ProjectHelpers.CheckOutFileFromSourceControl(mapFileName);
                }

                using (var process = await start.ExecuteAsync())
                {
                    if (targetFileName != null)
                    {
                        await MoveOutputContentToCorrectTarget(targetFileName);
                    }

                    return(await ProcessResult(
                               process,
                               (await FileHelpers.ReadAllTextRetry(errorOutputFile)).Trim(),
                               sourceFileName,
                               targetFileName,
                               mapFileName
                               ));
                }
            }
            finally
            {
                File.Delete(errorOutputFile);

                if (!GenerateSourceMap)
                {
                    File.Delete(mapFileName);
                }
            }
        }
Пример #10
0
 void SolutionEvents_Opened()
 {
     System.Threading.Tasks.Task.Run(() => BundleFilesMenu.BindAllBundlesAssets(ProjectHelpers.GetSolutionFolderPath()));
 }