Example #1
0
        public static void ProcessBundle(string baseFolder, Bundle bundle)
        {
            StringBuilder sb         = new StringBuilder();
            List <string> inputFiles = bundle.GetAbsoluteInputFiles();

            foreach (string input in inputFiles)
            {
                string file = Path.Combine(baseFolder, input);

                if (File.Exists(file))
                {
                    string content;

                    if (input.EndsWith(".css", StringComparison.OrdinalIgnoreCase) && AdjustRelativePaths(bundle))
                    {
                        content = CssRelativePath.Adjust(file, bundle.GetAbsoluteOutputFile());
                    }
                    else
                    {
                        content = BundleMinifier.ReadAllText(file);
                    }

                    sb.AppendLine(content);
                }
            }

            bundle.Output = sb.ToString().Trim();
        }
Example #2
0
        private void ProcessBundle(string baseFolder, Bundle bundle)
        {
            BundleHandler.ProcessBundle(baseFolder, bundle);

            string outputFile = Path.Combine(baseFolder, bundle.OutputFileName);

            OnBeforeProcess(bundle, baseFolder);

            DirectoryInfo outputFileDirectory = Directory.GetParent(outputFile);

            outputFileDirectory.Create();

            File.WriteAllText(outputFile, bundle.Output, new UTF8Encoding(true));

            OnAfterProcess(bundle, baseFolder);

            if (bundle.Minify.ContainsKey("enabled") && bundle.Minify["enabled"].ToString().Equals("true", StringComparison.OrdinalIgnoreCase))
            {
                var result = BundleMinifier.MinifyBundle(bundle);

                if (result != null && bundle.SourceMaps && !string.IsNullOrEmpty(result.SourceMap))
                {
                    string minFile = FileMinifier.GetMinFileName(bundle.GetAbsoluteOutputFile());
                    string mapFile = minFile + ".map";

                    OnBeforeWritingSourceMap(minFile, mapFile);
                    File.WriteAllText(mapFile, result.SourceMap, new UTF8Encoding(true));
                    OnAfterWritingSourceMap(minFile, mapFile);
                }
            }
        }
Example #3
0
        private bool ProcessBundle(string baseFolder, Bundle bundle)
        {
            OnProcessing(bundle, baseFolder);
            var  inputs  = bundle.GetAbsoluteInputFiles();
            bool changed = false;

            if (bundle.GetAbsoluteInputFiles(true).Count > 1 || bundle.InputFiles.FirstOrDefault() != bundle.OutputFileName)
            {
                BundleHandler.ProcessBundle(baseFolder, bundle);

                if (!bundle.IsMinificationEnabled || !bundle.OutputIsMinFile)
                {
                    string outputFile      = bundle.GetAbsoluteOutputFile();
                    bool   containsChanges = FileHelpers.HasFileContentChanged(outputFile, bundle.Output);

                    if (containsChanges)
                    {
                        OnBeforeBundling(bundle, baseFolder, containsChanges);
                        DirectoryInfo outputFileDirectory = Directory.GetParent(outputFile);
                        outputFileDirectory.Create();

                        File.WriteAllText(outputFile, bundle.Output, new UTF8Encoding(false));
                        OnAfterBundling(bundle, baseFolder, containsChanges);
                        changed = true;
                    }
                }
            }

            string minFile = BundleMinifier.GetMinFileName(bundle.GetAbsoluteOutputFile());

            if (bundle.IsMinificationEnabled || bundle.IsGzipEnabled)
            {
                var result = BundleMinifier.MinifyBundle(bundle);

                changed |= result.Changed;

                if (bundle.IsMinificationEnabled && bundle.SourceMap && !string.IsNullOrEmpty(result.SourceMap))
                {
                    string mapFile   = minFile + ".map";
                    bool   smChanges = FileHelpers.HasFileContentChanged(mapFile, result.SourceMap);

                    if (smChanges)
                    {
                        OnBeforeWritingSourceMap(minFile, mapFile, smChanges);
                        File.WriteAllText(mapFile, result.SourceMap, new UTF8Encoding(false));
                        OnAfterWritingSourceMap(minFile, mapFile, smChanges);
                        changed = true;
                    }
                }
            }

            return(changed);
        }
Example #4
0
        public override bool Execute()
        {
            try
            {
                FileInfo configFile = new FileInfo(FileName);

                Log.LogMessage(MessageImportance.High, Environment.NewLine + "Bundler: Cleaning output from " + configFile.Name);

                if (!configFile.Exists)
                {
                    Log.LogWarning(configFile.FullName + " does not exist");
                    return(true);
                }

                var bundles = BundleHandler.GetBundles(configFile.FullName);

                if (bundles != null)
                {
                    foreach (Bundle bundle in bundles)
                    {
                        var outputFile = bundle.GetAbsoluteOutputFile();
                        var inputFiles = bundle.GetAbsoluteInputFiles();

                        var minFile  = BundleMinifier.GetMinFileName(outputFile, bundle.MinFileName);
                        var mapFile  = minFile + ".map";
                        var gzipFile = minFile + ".gz";

                        if (!inputFiles.Contains(outputFile))
                        {
                            Deletefile(outputFile);
                        }

                        Deletefile(minFile);
                        Deletefile(mapFile);
                        Deletefile(gzipFile);
                    }

                    Log.LogMessage(MessageImportance.High, "Bundler: Done cleaning output file from " + configFile.Name);

                    return(true);
                }

                Log.LogWarning($"There was an error reading {configFile.Name}");
                return(false);
            }
            catch (Exception e)
            {
                Log.LogErrorFromException(e);
                Log.LogErrorFromException(e.InnerException);
                return(false);
            }
        }
Example #5
0
        private void ProcessBundle(string baseFolder, Bundle bundle)
        {
            var inputLastModified = bundle.GetAbsoluteInputFiles().Max(inputFile => File.GetLastWriteTimeUtc(inputFile));

            if ((bundle.GetAbsoluteInputFiles().Count > 1 || bundle.InputFiles.FirstOrDefault() != bundle.OutputFileName) &&
                inputLastModified > File.GetLastWriteTimeUtc(bundle.GetAbsoluteOutputFile()))
            {
                BundleHandler.ProcessBundle(baseFolder, bundle);

                string outputFile      = Path.Combine(baseFolder, bundle.OutputFileName);
                bool   containsChanges = FileHelpers.HasFileContentChanged(outputFile, bundle.Output);

                if (containsChanges)
                {
                    OnProcessing(bundle, baseFolder);
                    DirectoryInfo outputFileDirectory = Directory.GetParent(outputFile);
                    outputFileDirectory.Create();

                    File.WriteAllText(outputFile, bundle.Output, new UTF8Encoding(false));
                    OnAfterBundling(bundle, baseFolder, containsChanges);
                }
            }

            string minFile = GetMinFileName(bundle.GetAbsoluteOutputFile());

            if (bundle.Minify.ContainsKey("enabled") && bundle.Minify["enabled"].ToString().Equals("true", StringComparison.OrdinalIgnoreCase) &&
                inputLastModified > File.GetLastWriteTimeUtc(minFile))
            {
                var result = BundleMinifier.MinifyBundle(bundle);

                if (result != null && bundle.SourceMap && !string.IsNullOrEmpty(result.SourceMap))
                {
                    string mapFile   = minFile + ".map";
                    bool   smChanges = FileHelpers.HasFileContentChanged(mapFile, result.SourceMap);

                    if (smChanges)
                    {
                        OnBeforeWritingSourceMap(minFile, mapFile, smChanges);
                        File.WriteAllText(mapFile, result.SourceMap, new UTF8Encoding(false));
                        OnAfterWritingSourceMap(minFile, mapFile, smChanges);
                    }
                }
            }

            Telemetry.TrackCompile(bundle);
        }
Example #6
0
        public static string Adjust(string inputFile, string outputPath)
        {
            string cssFileContents    = BundleMinifier.ReadAllText(inputFile);
            string absoluteOutputPath = new FileInfo(outputPath).FullName;

            // apply the RegEx to the file (to change relative paths)
            var matches = _rxUrl.Matches(cssFileContents);

            // Ignore the file if no match
            if (matches.Count > 0)
            {
                string cssDirectoryPath = Path.GetDirectoryName(inputFile);

                foreach (Match match in matches)
                {
                    string quoteDelimiter    = match.Groups[1].Value; //url('') vs url("")
                    string relativePathToCss = match.Groups[2].Value;

                    // Ignore root relative references
                    if (relativePathToCss.StartsWith("/", StringComparison.Ordinal))
                    {
                        continue;
                    }

                    //prevent query string from causing error
                    var pathAndQuery = relativePathToCss.Split(new[] { '?' }, 2, StringSplitOptions.RemoveEmptyEntries);
                    var pathOnly     = pathAndQuery[0];
                    var queryOnly    = pathAndQuery.Length == 2 ? pathAndQuery[1] : string.Empty;

                    string absolutePath      = GetAbsolutePath(cssDirectoryPath, pathOnly);
                    string serverRelativeUrl = FileHelpers.MakeRelative(absoluteOutputPath, absolutePath);

                    if (!string.IsNullOrEmpty(queryOnly))
                    {
                        serverRelativeUrl += "?" + queryOnly;
                    }

                    string replace = string.Format("url({0}{1}{0})", quoteDelimiter, serverRelativeUrl);

                    cssFileContents = cssFileContents.Replace(match.Groups[0].Value, replace);
                }
            }

            return(cssFileContents);
        }
Example #7
0
        private void CleanBundle(string baseFolder, Bundle bundle)
        {
            string outputFile = bundle.GetAbsoluteOutputFile();

            baseFolder = baseFolder.DemandTrailingPathSeparatorChar();
            if (!bundle.GetAbsoluteInputFiles().Contains(outputFile, StringComparer.OrdinalIgnoreCase))
            {
                if (File.Exists(outputFile))
                {
                    FileHelpers.RemoveReadonlyFlagFromFile(outputFile);
                    File.Delete(outputFile);
                    Console.WriteLine($"Deleted {FileHelpers.MakeRelative(baseFolder, outputFile).Cyan().Bright()}");
                }
            }

            string minFile = BundleMinifier.GetMinFileName(bundle.GetAbsoluteOutputFile());
            string mapFile = minFile + ".map";
            string gzFile  = minFile + ".gz";

            if (File.Exists(minFile))
            {
                FileHelpers.RemoveReadonlyFlagFromFile(minFile);
                File.Delete(minFile);
                Console.WriteLine($"Deleted {FileHelpers.MakeRelative(baseFolder, minFile).Cyan().Bright()}");
            }

            if (File.Exists(mapFile))
            {
                FileHelpers.RemoveReadonlyFlagFromFile(mapFile);
                File.Delete(mapFile);
                Console.WriteLine($"Deleted {mapFile.Cyan().Bright()}");
            }

            if (File.Exists(gzFile))
            {
                FileHelpers.RemoveReadonlyFlagFromFile(gzFile);
                File.Delete(gzFile);
                Console.WriteLine($"Deleted {gzFile.Cyan().Bright()}");
            }
        }
        public static void ProcessBundle(string baseFolder, Bundle bundle)
        {
            StringBuilder sb         = new StringBuilder();
            List <string> inputFiles = bundle.GetAbsoluteInputFiles();

            //string ext = Path.GetExtension(bundle.OutputFileName);

            // Support both directories and specific files
            //foreach (string input in bundle.InputFiles)
            //{
            //    string fullPath = Path.Combine(baseFolder, input);

            //    if (Directory.Exists(fullPath))
            //    {
            //        DirectoryInfo dir = new DirectoryInfo(fullPath);
            //        SearchOption search = bundle.Recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
            //        var files = dir.GetFiles("*" + ext, search);
            //        inputFiles.AddRange(files.Select(f => f.FullName));
            //    }
            //}

            foreach (string input in inputFiles)
            {
                string file = Path.Combine(baseFolder, input);
                string content;

                if (input.EndsWith(".css", System.StringComparison.OrdinalIgnoreCase) && AdjustRelativePaths(bundle))
                {
                    content = CssRelativePath.Adjust(file, bundle.GetAbsoluteOutputFile());
                }
                else
                {
                    content = BundleMinifier.ReadAllText(file);
                }

                sb.AppendLine(content);
            }

            bundle.Output = sb.ToString().Trim();
        }
Example #9
0
        private bool ProcessBundle(string baseFolder, Bundle bundle)
        {
            OnProcessing(bundle, baseFolder);
            var  inputs  = bundle.GetAbsoluteInputFiles();
            bool changed = false;

            if (bundle.GetAbsoluteInputFiles(true).Count > 1 || bundle.InputFiles.FirstOrDefault() != bundle.OutputFileName)
            {
                BundleHandler.ProcessBundle(baseFolder, bundle);

                if (!bundle.IsMinificationEnabled || !bundle.OutputIsMinFile)
                {
                    string outputFile      = bundle.GetAbsoluteOutputFile();
                    bool   containsChanges = FileHelpers.HasFileContentChanged(outputFile, bundle.Output);

                    if (containsChanges)
                    {
                        OnBeforeBundling(bundle, baseFolder, containsChanges);
                        DirectoryInfo outputFileDirectory = Directory.GetParent(outputFile);
                        outputFileDirectory.Create();

                        File.WriteAllText(outputFile, bundle.Output, new UTF8Encoding(false));
                        OnAfterBundling(bundle, baseFolder, containsChanges);
                        changed = true;
                    }
                }
            }

            MinificationResult minResult = null;
            var minFile = BundleMinifier.GetMinFileName(bundle.GetAbsoluteOutputFile());

            if (bundle.IsMinificationEnabled)
            {
                var outputWriteTime = File.GetLastWriteTimeUtc(minFile);
                var minifyChanged   = bundle.MostRecentWrite >= outputWriteTime;

                if (minifyChanged)
                {
                    minResult = BundleMinifier.MinifyBundle(bundle);

                    // If no change is detected, then the minFile is not modified, so we need to update the write time manually
                    if (!minResult.Changed && File.Exists(minFile))
                    {
                        File.SetLastWriteTimeUtc(minFile, DateTime.UtcNow);
                    }
                    changed |= minResult.Changed;

                    if (bundle.SourceMap && !string.IsNullOrEmpty(minResult.SourceMap))
                    {
                        string mapFile   = minFile + ".map";
                        bool   smChanges = FileHelpers.HasFileContentChanged(mapFile, minResult.SourceMap);

                        if (smChanges)
                        {
                            OnBeforeWritingSourceMap(minFile, mapFile, smChanges);
                            File.WriteAllText(mapFile, minResult.SourceMap, new UTF8Encoding(false));
                            OnAfterWritingSourceMap(minFile, mapFile, smChanges);
                            changed = true;
                        }
                    }
                }
                else
                {
                    OnMinificationSkipped(bundle, baseFolder, false);
                }
            }

            if (bundle.IsGzipEnabled)
            {
                var fileToGzip = bundle.IsMinificationEnabled ?
                                 minFile : bundle.GetAbsoluteOutputFile();

                if (minResult == null)
                {
                    BundleMinifier.GzipFile(fileToGzip, bundle, false, File.ReadAllText(fileToGzip));
                }
                else
                {
                    BundleMinifier.GzipFile(fileToGzip, bundle, minResult.Changed, minResult.MinifiedContent);
                }
            }

            return(changed);
        }
Example #10
0
        /// <summary>
        /// Returns a list of absolute file paths of all matching input files.
        /// </summary>
        /// <param name="notifyOnPatternMiss">Writes to the Console if any input file is missing on disk.</param>
        public List <string> GetAbsoluteInputFiles(bool notifyOnPatternMiss = false)
        {
            List <string> files = new List <string>();

            if (!InputFiles.Any())
            {
                return(files);
            }

            string  folder  = new DirectoryInfo(Path.GetDirectoryName(FileName)).FullName;
            string  ext     = Path.GetExtension(InputFiles.First());
            Options options = new Options {
                AllowWindowsPaths = true
            };

            foreach (string inputFile in InputFiles.Where(f => !f.StartsWith("!", StringComparison.Ordinal)))
            {
                int globIndex = inputFile.IndexOf('*');

                if (globIndex > -1)
                {
                    string relative = string.Empty;
                    int    last     = inputFile.LastIndexOf('/', globIndex);

                    if (last > -1)
                    {
                        relative = inputFile.Substring(0, last + 1);
                    }

                    var output    = GetAbsoluteOutputFile();
                    var outputMin = BundleMinifier.GetMinFileName(output);

                    string searchDir = new FileInfo(Path.Combine(folder, relative).NormalizePath()).FullName;
                    var    allFiles  = Directory.EnumerateFiles(searchDir, "*" + ext, SearchOption.AllDirectories).Select(f => f.Replace(folder + FileHelpers.PathSeparatorChar, ""));

                    var matches = Minimatcher.Filter(allFiles, inputFile, options).Select(f => Path.Combine(folder, f));
                    matches = matches.Where(match => match != output && match != outputMin).ToList();

                    if (notifyOnPatternMiss && !matches.Any())
                    {
                        Console.WriteLine($"  No files matched the pattern {inputFile}".Orange().Bright());
                    }

                    files.AddRange(matches.Where(f => !files.Contains(f)));
                }
                else
                {
                    string fullPath = Path.Combine(folder, inputFile.NormalizePath());

                    if (Directory.Exists(fullPath))
                    {
                        DirectoryInfo dir       = new DirectoryInfo(fullPath);
                        SearchOption  search    = SearchOption.TopDirectoryOnly;
                        var           dirFiles  = dir.GetFiles("*" + Path.GetExtension(OutputFileName), search);
                        var           collected = dirFiles.Select(f => f.FullName).Where(f => !files.Contains(f)).ToList();

                        if (notifyOnPatternMiss && collected.Count == 0)
                        {
                            Console.WriteLine($"  No files were found in {inputFile}".Orange().Bright());
                        }

                        files.AddRange(collected);
                    }
                    else
                    {
                        files.Add(fullPath);

                        if (notifyOnPatternMiss && !File.Exists(fullPath))
                        {
                            Console.WriteLine($"  {inputFile} was not found".Orange().Bright());
                        }
                    }
                }
            }

            // Remove files starting with a !
            foreach (string inputFile in InputFiles)
            {
                int globIndex = inputFile.IndexOf('!');

                if (globIndex == 0)
                {
                    var allFiles = files.Select(f => f.Replace(folder + FileHelpers.PathSeparatorChar, ""));
                    var matches  = Minimatcher.Filter(allFiles, inputFile, options).Select(f => Path.Combine(folder, f));
                    files = matches.ToList();
                }
            }

            return(files);
        }