Beispiel #1
0
        /// <summary>The initialize.</summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="logManager">The log manager.</param>
        /// <param name="cacheManager">The cache manager.</param>
        /// <param name="preprocessingManager">The preprocessing manager.</param>
        /// <param name="runStartTime">The run start time.</param>
        /// <param name="timeMeasure">The time measure.</param>
        private void Initialize(
            WebGreaseConfiguration configuration,
            LogManager logManager,
            ICacheManager cacheManager,
            PreprocessingManager preprocessingManager,
            DateTimeOffset runStartTime,
            ITimeMeasure timeMeasure)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            if (configuration.Global.TreatWarningsAsErrors != null)
            {
                logManager.TreatWarningsAsErrors = configuration.Global.TreatWarningsAsErrors == true;
            }

            // Note: Configuration needs to be set before the other ones.
            this.Configuration = configuration;
            this.Configuration.Validate();

            this.Measure = timeMeasure;

            this.Log = logManager;

            this.Cache = cacheManager;

            this.Preprocessing = preprocessingManager;

            this.SessionStartTime = runStartTime;

            this.Cache.SetContext(this);
            this.Preprocessing.SetContext(this);
        }
Beispiel #2
0
        /// <summary>Initializes a new instance of the <see cref="WebGreaseContext"/> class.</summary>
        /// <param name="parentContext">The parent context.</param>
        /// <param name="configFile">The config file.</param>
        public WebGreaseContext(IWebGreaseContext parentContext, FileInfo configFile)
        {
            var configuration = new WebGreaseConfiguration(parentContext.Configuration, configFile);

            configuration.Validate();

            if (configuration.Global.TreatWarningsAsErrors != null && parentContext.Log != null)
            {
                parentContext.Log.TreatWarningsAsErrors = configuration.Global.TreatWarningsAsErrors == true;
            }

            var parentWebGreaseContext = parentContext as WebGreaseContext;

            if (parentWebGreaseContext != null)
            {
                this.threadedMeasureResults = parentWebGreaseContext.threadedMeasureResults;
            }

            this.Initialize(
                configuration,
                parentContext.Log,
                parentContext.Cache,
                parentContext.Preprocessing,
                parentContext.SessionStartTime,
                parentContext.Measure);
        }
Beispiel #3
0
        public void ResourcePivotConfigurationTest()
        {
            var configuration = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
                                "<WebGrease><Settings>  <ResourcePivot key=\"locales\" applyMode=\"CssApplyAfterParse\">ja-jp;th-th;zh-sg;generic-generic</ResourcePivot>" +
                                "<ResourcePivot key=\"themes\" applyMode=\"CssApplyAfterParse\">red;blue;orange;green;purple</ResourcePivot>" +
                                "<Dpi>1;1.4;1.5;1.8;2;2.25;2.4</Dpi></Settings></WebGrease>";

            var tmpFile = Path.GetTempFileName();

            File.WriteAllText(tmpFile, configuration);
            var configurationFile = new FileInfo(tmpFile);
            var wgc = new WebGreaseConfiguration(configurationFile, configurationFile.DirectoryName, configurationFile.DirectoryName, configurationFile.DirectoryName, configurationFile.DirectoryName);

            Assert.AreEqual(1, wgc.DefaultDpi.Count);
            Assert.AreEqual(string.Empty, wgc.DefaultDpi.Keys.ElementAt(0));

            var dpis = wgc.DefaultDpi.Values.ElementAt(0);

            Assert.AreEqual(7f, dpis.Count);
            Assert.AreEqual(1.4f, dpis.ElementAtOrDefault(1));
            Assert.AreEqual(2.25f, dpis.ElementAtOrDefault(5));
            Assert.AreEqual(2.4f, dpis.ElementAtOrDefault(6));

            Assert.AreEqual(2, wgc.DefaultJsResourcePivots.Count());
            Assert.AreEqual("locales", wgc.DefaultJsResourcePivots.ElementAtOrDefault(0).Key);
            Assert.AreEqual(4, wgc.DefaultJsResourcePivots["locales"].Keys.Count);
            Assert.AreEqual("themes", wgc.DefaultJsResourcePivots.ElementAtOrDefault(1).Key);
            Assert.AreEqual(5, wgc.DefaultJsResourcePivots["themes"].Keys.Count);
        }
Beispiel #4
0
        public void ResourcePivotResourcesTmxSdkTest1()
        {
            var sourceDirectory = Path.Combine(TestDeploymentPaths.TestDirectory, @"WebGrease.Tests\ResourcesResolutionActivityTest\ResourcePivotTest1");

            LogExtendedError logExtendedError = (subcategory, code, keyword, file, number, columnNumber, lineNumber, endColumnNumber, message) => Assert.Fail(message);
            var             errors            = new List <string>();
            Action <string> logErrorMessage   = errors.Add;
            LogError        logError          = (exception, message, name) => errors.Add(message);

            var start = DateTimeOffset.UtcNow;
            var webGreaseConfiguration = new WebGreaseConfiguration(
                new FileInfo(Path.Combine(sourceDirectory, "LandingPage.xml")),
                "Release",
                sourceDirectory,
                Path.Combine(sourceDirectory, "output1"),
                Path.Combine(sourceDirectory, "logs1"),
                Path.Combine(sourceDirectory, "temp1"),
                sourceDirectory);

            var webGreaseContext = new WebGreaseContext(webGreaseConfiguration, null, null, logExtendedError, logErrorMessage, logError);

            new EverythingActivity(webGreaseContext).Execute();
            var time1 = DateTimeOffset.UtcNow - start;

            start = DateTimeOffset.UtcNow;

            var webGreaseConfiguration2 = new WebGreaseConfiguration(
                new FileInfo(Path.Combine(sourceDirectory, "LandingPage2.xml")),
                "Release",
                sourceDirectory,
                Path.Combine(sourceDirectory, "output2"),
                Path.Combine(sourceDirectory, "logs2"),
                Path.Combine(sourceDirectory, "temp2"),
                sourceDirectory);

            var webGreaseContext2 = new WebGreaseContext(webGreaseConfiguration2, null, null, logExtendedError, logErrorMessage, logError);

            new EverythingActivity(webGreaseContext2).Execute();

            if (errors.Count > 0)
            {
                foreach (var error in errors)
                {
                    Trace.WriteLine("Error: " + error);
                }

                Assert.Fail("Errors occurred, see test output for details.");
            }

            var time2 = DateTimeOffset.UtcNow - start;

            Trace.WriteLine(string.Format("Parsed: {0}ms, Cloned: {1}ms", time1.TotalMilliseconds, time2.TotalMilliseconds));

            Func <string, string> logFileChange = logFileContent => logFileContent.Replace("/output1/", "/output2/");

            CacheTests.DirectoryMatch(Path.Combine(sourceDirectory, "output1"), Path.Combine(sourceDirectory, "output2"), logFileChange);
            CacheTests.DirectoryMatch(Path.Combine(sourceDirectory, "output2"), Path.Combine(sourceDirectory, "output1"), logFileChange);
        }
        /// <summary>
        /// Constructs a instance of WebGrease Semantic CSS minifier
        /// </summary>
        /// <param name="wgConfig">Configuration settings of WebGrease Minifier</param>
        public WgCssMinifier(WgSettings wgConfig)
        {
            CssMinifierSettings cssMinifierConfig = wgConfig.CssMinifier;

            ShouldMinify = cssMinifierConfig.ShouldMinify;
            EjectCharset = cssMinifierConfig.EjectCharset;

            _wgConfiguration = CreateWebGreaseConfiguration();
        }
Beispiel #6
0
        /// <summary>Initializes a new instance of the <see cref="WebGreaseContext"/> class. The web grease context.</summary>
        /// <param name="configuration">The configuration</param>
        /// <param name="logManager">The log Manager.</param>
        /// <param name="parentCacheSection">The parent Cache Section.</param>
        /// <param name="preprocessingManager">The preprocessing Manager.</param>
        public WebGreaseContext(WebGreaseConfiguration configuration, LogManager logManager, ICacheSection parentCacheSection = null, PreprocessingManager preprocessingManager = null)
        {
            var runStartTime = DateTimeOffset.Now;

            configuration.Validate();
            var timeMeasure  = configuration.Measure ? new TimeMeasure() as ITimeMeasure : new NullTimeMeasure();
            var cacheManager = configuration.CacheEnabled ? new CacheManager(configuration, logManager, parentCacheSection) as ICacheManager : new NullCacheManager();

            this.Initialize(
                configuration,
                logManager,
                cacheManager,
                preprocessingManager != null ? new PreprocessingManager(preprocessingManager) : new PreprocessingManager(configuration, logManager, timeMeasure),
                runStartTime,
                timeMeasure);
        }
Beispiel #7
0
        /// <summary>The get file sets.</summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="fileType">The file type.</param>
        /// <returns>The filesets fot the file type.</returns>
        private static IEnumerable <IFileSet> GetFileSets(WebGreaseConfiguration configuration, FileTypes fileType)
        {
            var result = new List <IFileSet>();

            if (fileType.HasFlag(FileTypes.JS))
            {
                result.AddRange(configuration.JSFileSets);
            }

            if (fileType.HasFlag(FileTypes.CSS))
            {
                result.AddRange(configuration.CssFileSets);
            }

            return(result);
        }
Beispiel #8
0
        public void MainActivityDebugIntegrationTest()
        {
            var testSourceDirectory  = Path.Combine(TestDeploymentPaths.TestDirectory, @"WebGrease.Tests\MainActivityTest");
            var configurationFile    = Path.Combine(testSourceDirectory, @"Input\Integration\Debug\Configuration\sample1.webgrease.config");
            var sourceDirectory      = Path.Combine(testSourceDirectory, @"Input\Integration\Debug\Content");
            var destinationDirectory = Path.Combine(testSourceDirectory, @"Output\Integration\Debug\sc");
            var logsDirectory        = Path.Combine(testSourceDirectory, @"Output\Integration\Debug\logs");

            var webGreaseConfigurationRoot = new WebGreaseConfiguration(new FileInfo(configurationFile), "Debug", sourceDirectory, destinationDirectory, logsDirectory);
            var context = new WebGreaseContext(webGreaseConfigurationRoot, logInformation: null, logExtendedWarning: null, logError: LogError, logExtendedError: LogExtendedError);

            var mainActivity = new EverythingActivity(context);
            var success      = mainActivity.Execute();

            Assert.IsTrue(success);
            VerifyStatics(destinationDirectory, logsDirectory);
        }
        public void WebGreaseConfigurationDefaults()
        {
            // parse the configuration file
            var configurationFile          = Path.Combine(TestDeploymentPaths.TestDirectory, @"WebGrease.Tests\WebGreaseConfigurationRootTest\Input\Debug\Configuration\withDefaults.webgrease.config");
            var configDirectory            = Path.GetDirectoryName(configurationFile);
            var webGreaseConfigurationRoot = new WebGreaseConfiguration(new FileInfo(configurationFile), null, configDirectory, configDirectory, configDirectory);

            Assert.IsNotNull(webGreaseConfigurationRoot);

            // there should be two CSS file sets and two JS file sets
            Assert.IsTrue(webGreaseConfigurationRoot.CssFileSets.Count == 2);
            Assert.IsTrue(webGreaseConfigurationRoot.JSFileSets.Count == 2);

            ValidateCssFileSet(webGreaseConfigurationRoot.CssFileSets[0],
                               new[] { "en-us", "en-ca", "fr-ca", "en-gb" },
                               new[] { "Red", "Orange", "Yellow", "Green", "Blue", "Violet" },
                               new CssMinificationConfig {
                Name = "Retail", ShouldMinify = true, ShouldValidateLowerCase = true, ForbiddenSelectors = new[] { "body" }
            },
                               new CssMinificationConfig {
                Name = "Debug", ShouldMinify = false, ShouldValidateLowerCase = false, ForbiddenSelectors = new string[] { }
            });
            ValidateCssFileSet(webGreaseConfigurationRoot.CssFileSets[1],
                               new[] { "zh-sg", "zh-tw", "zh-hk" },
                               new[] { "Pink", "Green" },
                               new CssMinificationConfig {
                Name = "Retail", ShouldMinify = false, ShouldValidateLowerCase = false, ForbiddenSelectors = new string[] { }
            },
                               null);

            ValidateJsFileSet(webGreaseConfigurationRoot.JSFileSets[0],
                              new[] { "en-us", "en-ca", "fr-ca", "en-gb" },
                              new JsMinificationConfig {
                Name = "Retail", ShouldMinify = true, GlobalsToIgnore = "jQuery;$;define", MinificationArugments = "-evals:safe -fnames:lock"
            },
                              new JsMinificationConfig {
                Name = "Debug", ShouldMinify = false, GlobalsToIgnore = "FooBar", MinificationArugments = string.Empty
            });
            ValidateJsFileSet(webGreaseConfigurationRoot.JSFileSets[1],
                              new[] { "es-es", "es-mx", "es-ar" },
                              new JsMinificationConfig {
                Name = "Retail", ShouldMinify = false, GlobalsToIgnore = string.Empty, MinificationArugments = string.Empty
            },
                              null);
        }
Beispiel #10
0
        /// <summary>Initializes a new instance of the <see cref="PreprocessingManager"/> class.
        /// Initializes a new instance of the <see cref="PreprocessingManager"/>.
        /// Can only be called from within the class by the Singleton construction.</summary>
        /// <param name="webGreaseConfiguration">The web Grease Configuration.</param>
        /// <param name="logManager">The log Manager.</param>
        /// <param name="timeMeasure">The time Measure.</param>
        internal PreprocessingManager(WebGreaseConfiguration webGreaseConfiguration, LogManager logManager, ITimeMeasure timeMeasure)
        {
            if (webGreaseConfiguration == null)
            {
                throw new ArgumentNullException("webGreaseConfiguration");
            }

            if (logManager == null)
            {
                throw new ArgumentNullException("logManager");
            }

            if (timeMeasure == null)
            {
                throw new ArgumentNullException("timeMeasure");
            }

            this.Initialize(webGreaseConfiguration.PreprocessingPluginPath, logManager, timeMeasure);
        }
Beispiel #11
0
        public void ResourcePivotConfigurationLegacyTest()
        {
            var configuration = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" +
                                "<WebGrease><Settings>  <Locales>ja-jp;th-th;zh-sg;generic-generic</Locales>" +
                                "<Themes>red;blue;orange;green;purple</Themes>" +
                                "</Settings></WebGrease>";

            var tmpFile = Path.GetTempFileName();

            File.WriteAllText(tmpFile, configuration);
            var configurationFile = new FileInfo(tmpFile);
            var wgc = new WebGreaseConfiguration(configurationFile, configurationFile.DirectoryName, configurationFile.DirectoryName, configurationFile.DirectoryName, configurationFile.DirectoryName);

            Assert.AreEqual(1, wgc.DefaultJsResourcePivots.Count());
            Assert.AreEqual(2, wgc.DefaultCssResourcePivots.Count());
            Assert.AreEqual("locales", wgc.DefaultCssResourcePivots.ElementAtOrDefault(0).Key);
            Assert.AreEqual(4, wgc.DefaultCssResourcePivots["locales"].Keys.Count);

            Assert.AreEqual("themes", wgc.DefaultCssResourcePivots.ElementAtOrDefault(1).Key);
            Assert.AreEqual(5, wgc.DefaultCssResourcePivots["themes"].Keys.Count);
        }
Beispiel #12
0
        /// <summary>Initializes a new instance of the <see cref="CacheManager"/> class.</summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="logManager">The log manager.</param>
        /// <param name="parentCacheSection">The parent Cache Section.</param>
        public CacheManager(WebGreaseConfiguration configuration, LogManager logManager, ICacheSection parentCacheSection)
        {
            this.currentCacheSection = parentCacheSection;

            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            if (logManager == null)
            {
                throw new ArgumentNullException("logManager");
            }

            var cacheRoot = configuration.CacheRootPath.AsNullIfWhiteSpace() ?? "_webgrease.cache";

            if (!Path.IsPathRooted(cacheRoot))
            {
                cacheRoot = Path.Combine(configuration.SourceDirectory, cacheRoot);
            }

            this.cacheRootPath = GetCacheUniquePath(cacheRoot, configuration.CacheUniqueKey);

            if (!Directory.Exists(this.cacheRootPath))
            {
                Directory.CreateDirectory(this.cacheRootPath);
            }

            Safe.Lock(
                First,
                () =>
            {
                // Only log this once when multi threading.
                if (First.Contains(this.cacheRootPath))
                {
                    First.Add(this.cacheRootPath);
                    logManager.Information("Cache enabled using cache path: {0}".InvariantFormat(this.cacheRootPath));
                }
            });
        }
Beispiel #13
0
        /// <summary>
        /// Overrides the given configuration object withe
        /// </summary>
        /// <param name="wgConfig">config file to override</param>
        /// <param name="logPath">path of the log files</param>
        /// <param name="tokenPath">token file path</param>
        /// <param name="imagePath">image file path</param>
        /// <returns>an overriden config object</returns>
        private static WebGreaseConfiguration OverrideConfig(WebGreaseConfiguration wgConfig, string logPath, string tokenPath, string imagePath)
        {
            // images path
            if (!imagePath.IsNullOrWhitespace())
            {
                // clear out existing config values as cmd line values override.
                wgConfig.ImageDirectories.Clear();

                wgConfig.ImageDirectories.Add(imagePath);
                wgConfig.ImageExtensions = Strings.DefaultImageExtensions;
            }

            // token path
            if (!tokenPath.IsNullOrWhitespace())
            {
                // TODO: should CLI allow specifying override dir as well?
                wgConfig.TokensDirectory = tokenPath;
            }

            wgConfig.LogsDirectory = logPath;

            return(wgConfig);
        }
        public void WebGreaseConfigurationTest()
        {
            var configurationFile          = Path.Combine(TestDeploymentPaths.TestDirectory, @"WebGrease.Tests\WebGreaseConfigurationRootTest\Input\Debug\Configuration\sample1.webgrease.config");
            var configDirectory            = Path.GetDirectoryName(configurationFile);
            var webGreaseConfigurationRoot = new WebGreaseConfiguration(new FileInfo(configurationFile), null, configDirectory, configDirectory, configDirectory);

            Assert.IsNotNull(webGreaseConfigurationRoot);

            var imageDirectories = webGreaseConfigurationRoot.ImageDirectories;

            Assert.IsNotNull(imageDirectories);
            Assert.IsTrue(imageDirectories.Count == 2);
            Assert.IsTrue(imageDirectories[0].EndsWith(@"f1\i"));
            Assert.IsTrue(imageDirectories[1].EndsWith(@"f2\i"));

            var imageExtensions = webGreaseConfigurationRoot.ImageExtensions;

            Assert.IsNotNull(imageExtensions);
            Assert.IsTrue(imageExtensions.Count == 5);
            Assert.IsTrue(imageExtensions[0] == "png");
            Assert.IsTrue(imageExtensions[1] == "jpg");
            var tokensDir = webGreaseConfigurationRoot.TokensDirectory;

            Assert.AreEqual(tokensDir, "App", "TokensDirectory should be 'App' but was '{0}'", tokensDir);
            var tokenOverrideDir = webGreaseConfigurationRoot.OverrideTokensDirectory;

            Assert.AreEqual(tokenOverrideDir, "Site1", "OverrideTokensDirectory should be 'Site1' but was '{0}'", tokenOverrideDir);

            var cssFileSets = webGreaseConfigurationRoot.CssFileSets;

            Assert.IsNotNull(cssFileSets);
            Assert.AreEqual(2, cssFileSets.Count, "should be 2 CssFileSet objects");

            var cssSet1             = cssFileSets[0];
            var minificationConfigs = cssSet1.Minification;

            Assert.IsNotNull(minificationConfigs);
            Assert.IsTrue(minificationConfigs.Count == 2);
            Assert.IsTrue(minificationConfigs.ContainsKey("DeBuG"));
            Assert.IsTrue(minificationConfigs.ContainsKey("RELEASE"));

            var minifyConfig = minificationConfigs["relEASE"];

            Assert.IsNotNull(minifyConfig);
            Assert.IsTrue(minifyConfig.Name == "Release");
            Assert.IsTrue(minifyConfig.ShouldMinify);
            Assert.IsTrue(minifyConfig.ShouldPreventOrderBasedConflict);
            Assert.IsFalse(minifyConfig.ShouldMergeBasedOnCommonDeclarations);
            Assert.IsTrue(minifyConfig.NonMergeSelectors.Contains("@font-face"));
            Assert.IsTrue(minifyConfig.NonMergeSelectors.Contains(".specialSelector"));

            var spriteConfiguration = cssSet1.ImageSpriting["RElease"];

            Assert.IsTrue(spriteConfiguration.ShouldAutoSprite);
            Assert.IsTrue(spriteConfiguration.ShouldAutoVersionBackgroundImages);

            var locales = cssSet1.Locales;

            Assert.IsNotNull(locales);
            Assert.IsTrue(locales.Count() == 2);
            Assert.IsTrue(locales[0] == "en-us");
            Assert.IsTrue(locales[1] == "fr-ca");

            var themes = cssSet1.Themes;

            Assert.IsNotNull(themes);
            Assert.IsTrue(themes.Count() == 2);
            Assert.IsTrue(themes[0] == "red");
            Assert.IsTrue(themes[1] == "blue");

            var inputs = cssSet1.InputSpecs;

            Assert.IsNotNull(inputs);
            Assert.AreEqual(3, inputs.Count);
            var input = inputs[2];

            Assert.AreEqual("*_mobile.css", input.SearchPattern, "search pattern should be '*_mobile.css'.");
            Assert.AreEqual(SearchOption.TopDirectoryOnly, input.SearchOption, "search option should be 'TopDirectoryOnly'.");
            Assert.IsTrue(input.Path.EndsWith(@"content\css"), "path should be 'content/css'.");

            // now the js portion
            var jsFileSets = webGreaseConfigurationRoot.JSFileSets;

            Assert.IsNotNull(jsFileSets);
            Assert.AreEqual(1, jsFileSets.Count, "should be 1 JsFileSet object");
            var jsSet1           = jsFileSets[0];
            var jsConfigurations = jsSet1.Minification;

            Assert.IsNotNull(jsConfigurations);
            Assert.AreEqual(2, jsConfigurations.Count);
            Assert.IsTrue(jsConfigurations.ContainsKey("DEBUG"));
            Assert.IsTrue(jsConfigurations.ContainsKey("RELEASE"));
            var jsConfig = jsConfigurations["RELEASE"];

            Assert.IsNotNull(jsConfig);
            var jsGlobalsToIgnore = jsConfig.GlobalsToIgnore.Split(';');

            Assert.IsNotNull(jsGlobalsToIgnore);
            Assert.IsTrue(jsGlobalsToIgnore.Length == 2);
            Assert.IsTrue(jsGlobalsToIgnore[0] == "jQuery");
            Assert.IsTrue(jsGlobalsToIgnore[1] == "Msn");
        }
        /// <summary>
        /// Constructs a instance of WebGrease Semantic CSS-minifier
        /// </summary>
        /// <param name="wgConfig">Configuration settings of WebGrease Minifier</param>
        public WgCssMinifier(WgSettings wgConfig)
        {
            CssMinifierSettings cssMinifierConfig = wgConfig.CssMinifier;
            ShouldMinify = cssMinifierConfig.ShouldMinify;
            EjectCharset = cssMinifierConfig.EjectCharset;

            _wgConfiguration = CreateWebGreaseConfiguration();
        }
Beispiel #16
0
        /// <summary>Creates the input spec objects based on input and output paths.</summary>
        /// <param name="wgConfig">Config object to use.</param>
        /// <param name="inputPath">Input path from the command parameters</param>
        /// <param name="outputPath">output path from the command parameters</param>
        private static void AddInputSpecs(WebGreaseConfiguration wgConfig, string inputPath, string outputPath)
        {
            if (inputPath.IsNullOrWhitespace() && outputPath.IsNullOrWhitespace())
            {
                // no paths need to be overriden.
                return;
            }

            string outputPathExtension = Path.GetExtension(outputPath);
            string inputPathExtension  = Path.GetExtension(inputPath);

            bool createCssInput = false;
            bool createJsInput  = false;

            // Set the file filter to the extension of the output path (if it's a file)
            if (!outputPathExtension.IsNullOrWhitespace())
            {
                // if the output path is a file we only process css OR js files into it.
                if (outputPathExtension.EndsWith(Strings.Css, StringComparison.OrdinalIgnoreCase))
                {
                    createCssInput = true;
                }
                else
                {
                    createJsInput = true;
                }
            }
            else if (!inputPathExtension.IsNullOrWhitespace())
            {
                // if the input path is not a folder, only set one of the file sets for processing
                if (inputPathExtension.EndsWith(Strings.Css, StringComparison.OrdinalIgnoreCase))
                {
                    createCssInput = true;
                }
                else
                {
                    createJsInput = true;
                }
            }
            else
            {
                // if both the intput and  output path are not a file, assume they are a folder process both JS and CSS files found within.
                createCssInput = true;
                createJsInput  = true;
            }

            var cssFileSet = new CssFileSet();
            var jsFileSet  = new JSFileSet();

            // set or update input specs
            if (createCssInput)
            {
                cssFileSet.InputSpecs.Add(GetInputSpec(inputPath, Strings.CssFilter));
            }

            if (createJsInput)
            {
                if (jsFileSet.InputSpecs.Any())
                {
                    jsFileSet.InputSpecs.Clear();
                }

                jsFileSet.InputSpecs.Add(GetInputSpec(inputPath, Strings.JsFilter));
            }

            // set output spec
            jsFileSet.Output  = outputPath;
            cssFileSet.Output = outputPath;

            wgConfig.JSFileSets.Add(jsFileSet);
            wgConfig.CssFileSets.Add(cssFileSet);
        }
Beispiel #17
0
 /// <summary>Initializes a new instance of the <see cref="WebGreaseContext"/> class. The web grease context.</summary>
 /// <param name="configuration">The configuration</param>
 /// <param name="logInformation">The log information.</param>
 /// <param name="logWarning">The log Warning.</param>
 /// <param name="logExtendedWarning">The log warning.</param>
 /// <param name="logErrorMessage">The log Error Message.</param>
 /// <param name="logError">The log error.</param>
 /// <param name="logExtendedError">The log extended error.</param>
 public WebGreaseContext(WebGreaseConfiguration configuration, Action <string, MessageImportance> logInformation = null, Action <string> logWarning = null, LogExtendedError logExtendedWarning = null, Action <string> logErrorMessage = null, LogError logError = null, LogExtendedError logExtendedError = null)
     : this(configuration, new LogManager(logInformation, logWarning, logExtendedWarning, logErrorMessage, logError, logExtendedError, configuration.Global.TreatWarningsAsErrors))
 {
 }
Beispiel #18
0
        /// <summary>Finalizes the measure values, stores thejm on disk if configured that way.</summary>
        /// <param name="success">If the activity was successfull.</param>
        /// <param name="activityResults">The activity results.</param>
        /// <param name="logManager">The log manager.</param>
        /// <param name="start">The start time of the current run..</param>
        /// <param name="activity">The current activity name.</param>
        /// <param name="configuration">The configuration.</param>
        private void FinalizeMeasure(bool success, IEnumerable <Tuple <string, bool, IEnumerable <TimeMeasureResult> > > activityResults, LogManager logManager, DateTimeOffset start, ActivityName?activity, WebGreaseConfiguration configuration)
        {
            if (this.Measure && success && activityResults.Any())
            {
                if (configuration != null)
                {
                    var reportFileBase = Path.Combine(configuration.ReportPath, new DirectoryInfo(this.ConfigurationPath).Name);
                    logManager.Information("Writing overal report file to:".InvariantFormat(reportFileBase));
                    TimeMeasure.WriteResults(reportFileBase, activityResults, this.ConfigurationPath, start, activity.ToString());
                }

                this.MeasureResults = activityResults.SelectMany(ar => ar.Item3).ToArray();
            }
        }
        public void ConfigSourceTest()
        {
            var configurationFile = Path.Combine(TestDeploymentPaths.TestDirectory, @"WebGrease.Tests\WebGreaseConfigurationRootTest\ConfigSource\configsource.webgrease.config");
            var configDirectory   = Path.GetDirectoryName(configurationFile);
            var config            = new WebGreaseConfiguration(new FileInfo(configurationFile), null, configDirectory, configDirectory, configDirectory);

            // global1.config
            Assert.IsTrue(config.ImageDirectories.All(id => id.EndsWith("global1imagedirectories")));
            Assert.IsTrue(config.ImageExtensions.Contains("global1imageextensions"));

            // global2.config
            Assert.AreEqual(config.TokensDirectory, "global2tokendirectory");

            // global3.config
            Assert.AreEqual(config.OverrideTokensDirectory, "global3overridetokendirectory");

            // css fileset 1 - settings\css1.config
            var cssfileset1 = config.CssFileSets[0];

            Assert.IsNotNull(cssfileset1);
            Assert.AreEqual(2, cssfileset1.Themes.Count());
            Assert.IsTrue(cssfileset1.Themes.Contains("red"));
            Assert.IsTrue(cssfileset1.Themes.Contains("blue"));
            Assert.AreEqual(2, cssfileset1.Locales.Count());
            Assert.IsTrue(cssfileset1.Locales.Contains("en-us"));
            Assert.IsTrue(cssfileset1.Locales.Contains("fr-ca"));

            var debugMinification   = cssfileset1.Minification.GetNamedConfig("deBUG");
            var defaultMinification = cssfileset1.Minification.GetNamedConfig();

            Assert.AreEqual(debugMinification, defaultMinification);
            Assert.IsNotNull(debugMinification);
            Assert.AreEqual("Debug", debugMinification.Name);
            Assert.AreEqual(false, debugMinification.ShouldValidateLowerCase);

            var releaseMinification = cssfileset1.Minification.GetNamedConfig("release");

            Assert.AreNotEqual(debugMinification, releaseMinification);
            Assert.AreEqual(true, releaseMinification.ShouldValidateLowerCase);

            var defaultSpriting = cssfileset1.ImageSpriting.GetNamedConfig();

            Assert.AreEqual(string.Empty, defaultSpriting.Name);
            Assert.AreEqual(false, defaultSpriting.ShouldAutoSprite);

            var releaseSpriting = cssfileset1.ImageSpriting.GetNamedConfig("Release");

            Assert.AreEqual("Release", releaseSpriting.Name);
            Assert.AreEqual(true, releaseSpriting.ShouldAutoSprite);

            // css fileset 2 - settings\css2.config
            var cssfileset2 = config.CssFileSets.FirstOrDefault(fs => fs.Output.Equals("cssfileset2.css"));

            Assert.IsNotNull(cssfileset2);

            Assert.AreEqual(2, cssfileset2.Themes.Count());
            Assert.IsTrue(cssfileset2.Themes.Contains("themecss2a"));
            Assert.IsTrue(cssfileset2.Themes.Contains("themecss2b"));

            Assert.AreEqual(2, cssfileset2.Locales.Count());
            Assert.IsTrue(cssfileset2.Locales.Contains("localecss2a"));
            Assert.IsTrue(cssfileset2.Locales.Contains("localecss2b"));

            var debugPreprocessing = cssfileset2.Preprocessing.GetNamedConfig("debug");

            Assert.IsNotNull(debugPreprocessing);
            Assert.IsNotNull(debugPreprocessing.Element);
            Assert.AreEqual(debugPreprocessing.Element.Elements("Sass").Attributes("sourceMaps").Select(s => (bool?)s).FirstOrDefault(), true);
            Assert.AreEqual("Debug", debugPreprocessing.Name);
            Assert.AreEqual(1, debugPreprocessing.PreprocessingEngines.Count);
            Assert.AreEqual("sass", debugPreprocessing.PreprocessingEngines[0]);
            Assert.AreEqual(true, debugPreprocessing.Enabled);

            var releasePreprocessing = cssfileset2.Preprocessing.GetNamedConfig("REleasE");

            Assert.IsNotNull(releasePreprocessing);
            Assert.IsNotNull(releasePreprocessing.Element);
            Assert.IsNull(releasePreprocessing.Element.Elements("Sass").Attributes("sourceMaps").Select(s => (bool?)s).FirstOrDefault());
            Assert.AreEqual("Release", releasePreprocessing.Name);
            Assert.AreEqual(1, releasePreprocessing.PreprocessingEngines.Count);
            Assert.AreEqual("sass", releasePreprocessing.PreprocessingEngines[0]);
            Assert.AreEqual(true, releasePreprocessing.Enabled);

            // js fileset 1 - settings\css1.config
            var jsfileset1 = config.JSFileSets.FirstOrDefault(fs => fs.Output.Equals("jsfileset1.js"));

            Assert.IsNotNull(jsfileset1);

            Assert.AreEqual(2, jsfileset1.Locales.Count());
            Assert.IsTrue(jsfileset1.Locales.Contains("jsinclude1"));
            Assert.IsTrue(jsfileset1.Locales.Contains("jsinclude2"));

            var debugJsMinification = jsfileset1.Minification.GetNamedConfig("DEBUG");

            Assert.IsNotNull(debugJsMinification);
            Assert.AreEqual("Debug", debugJsMinification.Name);
            Assert.AreEqual("jQuery;Msn", debugJsMinification.GlobalsToIgnore);

            var releaseJsMinification = jsfileset1.Minification.GetNamedConfig("release");

            Assert.IsNotNull(releaseJsMinification);
            Assert.AreEqual("Release", releaseJsMinification.Name);
            Assert.AreEqual("jQuery2;Msn2", releaseJsMinification.GlobalsToIgnore);
        }
Beispiel #20
0
        internal static ActivityMode GenerateConfiguration(IEnumerable <string> args, out WebGreaseConfiguration wgConfig)
        {
            // reset activity flag since this is a new run
            _isActivityAlreadySet = false;

            Contract.Requires(args != null);

            string configFileName = null;
            string inputPath      = Environment.CurrentDirectory;
            string outputPath     = Environment.CurrentDirectory;
            string logPath        = Environment.CurrentDirectory;
            string tokenPath      = null;
            string imagePath      = null;
            string configType     = null;
            var    activityToRun  = ActivityMode.ShowHelp;

            // process the arguments into variables
            foreach (string arg in args)
            {
                // int value of char '-'
                if (arg[0] == '-')
                {
                    // split the arg into a key/value pair using a colon as the delimeter.
                    int    split = arg.IndexOf(':');
                    string key   = arg.Substring(1, (split > 0 ? split : arg.Length) - 1);
                    string value = split > -1 ? arg.Substring(split + 1) : string.Empty;

                    switch (key.ToUpperInvariant())
                    {
                    case "C":
                        // config file .. trumps all CLI parameters when used.
                        configFileName = value;
                        break;

                    case "M":
                        // minification of files
                        activityToRun = TrySetActivity(ActivityMode.Minify);
                        break;

                    case "V":
                        // validation of files
                        activityToRun = TrySetActivity(ActivityMode.Validate);
                        break;

                    case "S":
                        // Spriting of images
                        activityToRun = TrySetActivity(ActivityMode.SpriteImages);
                        break;

                    case "A":
                        // auto naming of files
                        activityToRun = TrySetActivity(ActivityMode.AutoName);
                        break;

                    case "B":
                        // Bundle (merge) files
                        activityToRun = TrySetActivity(ActivityMode.Bundle);
                        break;

                    case "IN":
                        // input file/folder
                        inputPath = value;
                        break;

                    case "OUT":
                        // output file/folder
                        outputPath = value;
                        break;

                    case "IMAGES":
                        // images folder
                        imagePath = value;
                        break;

                    case "LOG":
                        logPath = value;
                        break;

                    case "TYPE":
                        configType = value;
                        break;

                    case "TOKENS":
                        tokenPath = value;
                        break;

                    default:
                        // show usage help
                        activityToRun = ActivityMode.ShowHelp;
                        break;
                    }
                }
            }

            if (activityToRun == ActivityMode.ShowHelp)
            {
                // something wasn't right with the parameter inputs. return false and a null config.
                wgConfig = new WebGreaseConfiguration();
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(configFileName))
                {
                    try
                    {
                        // use the config file as a base, and set overrides based on CLI input
                        wgConfig = new WebGreaseConfiguration(new FileInfo(configFileName), configType, inputPath, outputPath, logPath);
                    }
                    catch (Exception ex)
                    {
                        HandleError(ex, null, ResourceStrings.ConfigurationFileParseError);
                        wgConfig = new WebGreaseConfiguration(configType);
                        return(ActivityMode.ShowHelp);
                    }
                }
                else
                {
                    // manual build up of configuration data
                    wgConfig = new WebGreaseConfiguration(configType);

                    // initialize these to the current directory. Manual CLI paramters (not config files), will have their relative paths
                    // computed into the generated input specs.
                    wgConfig.SourceDirectory      = Environment.CurrentDirectory;
                    wgConfig.DestinationDirectory = Environment.CurrentDirectory;

                    AddInputSpecs(wgConfig, inputPath, outputPath);
                }

                wgConfig = OverrideConfig(wgConfig, logPath, tokenPath, imagePath);
            }

            return(activityToRun);
        }