Example #1
0
            public void Should_Throw_If_Extension_Is_Null()
            {
                // Given
                var path = new FilePath("temp/hello.txt");

                // When
                var result = Record.Exception(() => path.AppendExtension(null));

                // Then
                Assert.IsArgumentNullException(result, "extension");
            }
Example #2
0
            public void Can_Append_Extension_To_Windows_Path(string fullPath, string extension, string expected)
            {
                // Given
                var path = new FilePath(fullPath);

                // When
                path = path.AppendExtension(extension);

                // Then
                Assert.Equal(expected, path.ToString());
            }
Example #3
0
            public void Can_Append_Extension_To_Path(string extension, string expected)
            {
                // Given
                var path = new FilePath("temp/hello.txt");

                // When
                path = path.AppendExtension(extension);

                // Then
                Assert.Equal(expected, path.ToString());
            }
Example #4
0
            public void ShouldThrowIfExtensionIsNull()
            {
                // Given
                FilePath path = new FilePath("temp/hello.txt");

                // When
                TestDelegate test = () => path.AppendExtension(null);

                // Then
                Assert.Throws <ArgumentNullException>(test);
            }
Example #5
0
            public void CanAppendExtensionToPath(string extension, string expected)
            {
                // Given
                FilePath path = new FilePath("temp/hello.txt");

                // When
                path = path.AppendExtension(extension);

                // Then
                Assert.AreEqual(expected, path.ToString());
            }
Example #6
0
            public void Should_Throw_If_Extension_Is_Null()
            {
                // Given
                var path = new FilePath("temp/hello.txt");

                // When
                var result = Record.Exception(() => path.AppendExtension(null));

                // Then
                result.ShouldBeOfType <ArgumentNullException>()
                .And().ParamName.ShouldBe("extension");
            }
Example #7
0
        private void Evaluate(string code, FilePath configFilePath)
        {
            if (string.IsNullOrEmpty(code))
            {
                return;
            }

            Stopwatch stopwatch = Stopwatch.StartNew();

            using (Trace.WithIndent().Information("Evaluating configuration script"))
            {
                CacheManager cacheManager = new CacheManager(
                    _engine,
                    _scriptManager,
                    configFilePath?.AppendExtension(".dll"),
                    configFilePath?.AppendExtension(".hash"),
                    configFilePath?.AppendExtension(".generated.cs"));
                cacheManager.EvaluateCode(code, ClassCatalog.GetClasses <IModule>().ToList(), OutputScript, IgnoreConfigHash, NoOutputConfigAssembly);

                stopwatch.Stop();
                Trace.Information($"Evaluated configuration script in {stopwatch.ElapsedMilliseconds} ms");
            }
        }
        private async Task <string> GetFileVariationsAsync(FilePath filePath, FilePath requestedFilePath)
        {
            // ...as specified
            string scss = await GetFileAsync(filePath, requestedFilePath);

            if (scss != null)
            {
                return(scss);
            }

            // ...with extension (if not already)
            if (!filePath.HasExtension || filePath.Extension != ".scss")
            {
                FilePath extensionPath = filePath.AppendExtension(".scss");
                scss = await GetFileAsync(extensionPath, requestedFilePath);

                if (scss != null)
                {
                    return(scss);
                }

                // ...and with underscore prefix (if not already)
                if (!extensionPath.FileName.FullPath.StartsWith("_"))
                {
                    extensionPath = extensionPath.ChangeFileName("_" + extensionPath.FileName.FullPath);
                    scss          = await GetFileAsync(extensionPath, requestedFilePath);

                    if (scss != null)
                    {
                        return(scss);
                    }
                }
            }

            // ...with underscore prefix (if not already)
            if (!filePath.FileName.FullPath.StartsWith("_"))
            {
                filePath = filePath.ChangeFileName("_" + filePath.FileName.FullPath);
                scss     = await GetFileAsync(filePath, requestedFilePath);

                if (scss != null)
                {
                    return(scss);
                }
            }

            return(null);
        }
        private IFile GetInputFile(FilePath filePath)
        {
            // Find the requested file
            // ...as specified
            IFile file = _fileSystem.GetInputFile(filePath);

            if (file.Exists)
            {
                return(file);
            }

            // ...with extension (if not already)
            if (!filePath.HasExtension || filePath.Extension != ".less")
            {
                FilePath extensionPath = filePath.AppendExtension(".less");
                IFile    extensionFile = _fileSystem.GetInputFile(extensionPath);
                if (extensionFile.Exists)
                {
                    return(extensionFile);
                }

                // ...and with underscore prefix (if not already)
                if (!extensionPath.FileName.FullPath.StartsWith("_"))
                {
                    extensionPath = extensionPath.Directory.CombineFile("_" + extensionPath.FileName.FullPath);
                    extensionFile = _fileSystem.GetInputFile(extensionPath);
                    if (extensionFile.Exists)
                    {
                        return(extensionFile);
                    }
                }
            }

            // ...with underscore prefix (if not already)
            if (!filePath.FileName.FullPath.StartsWith("_"))
            {
                filePath = filePath.Directory.CombineFile("_" + filePath.FileName.FullPath);
                IFile underscoreFile = _fileSystem.GetInputFile(filePath);
                if (underscoreFile.Exists)
                {
                    return(underscoreFile);
                }
            }

            // Can't find it, default to the original
            return(file);
        }
Example #10
0
        private bool GetFileVariations(FilePath filePath, FilePath requestedFilePath, out string scss)
        {
            // ...as specified
            if (GetFile(filePath, requestedFilePath, out scss))
            {
                return(true);
            }

            // ...with extension (if not already)
            if (!filePath.HasExtension || filePath.Extension != ".scss")
            {
                FilePath extensionPath = filePath.AppendExtension(".scss");
                if (GetFile(extensionPath, requestedFilePath, out scss))
                {
                    return(true);
                }

                // ...and with underscore prefix (if not already)
                if (!extensionPath.FileName.FullPath.StartsWith("_"))
                {
                    extensionPath = extensionPath.Directory.CombineFile("_" + extensionPath.FileName.FullPath);
                    if (GetFile(extensionPath, requestedFilePath, out scss))
                    {
                        return(true);
                    }
                }
            }

            // ...with underscore prefix (if not already)
            if (!filePath.FileName.FullPath.StartsWith("_"))
            {
                filePath = filePath.Directory.CombineFile("_" + filePath.FileName.FullPath);
                if (GetFile(filePath, requestedFilePath, out scss))
                {
                    return(true);
                }
            }

            return(false);
        }
Example #11
0
        internal void InstallPackages(FilePath configFilePath)
        {
            DirectoryPath packagesPath = GetAbsolutePackagesPath();

            Trace.Information($"Installing packages to {packagesPath.FullPath} (using {(UseLocalPackagesFolder ? "local" : "global")} packages folder)");

            try
            {
                // Add the global default sources if requested
                if (UseGlobalPackageSources)
                {
                    _sourceRepositories.AddGlobalDefaults();
                }

                // Add the default package sources
                if (!IgnoreDefaultSources)
                {
                    _sourceRepositories.AddDefaultPackageSources();
                }

                // Get the local repository
                SourceRepository localRepository = _sourceRepositories.CreateRepository(packagesPath.FullPath);

                // Cache the packages in a packages file
                FilePath packagesFilePath = configFilePath?.AppendExtension(".packages.xml");
                if (packagesFilePath == null)
                {
                    Trace.Verbose("Will not write packages file since no config file was provided");
                }
                else
                {
                    Trace.Verbose($"Writing packages file to {packagesFilePath.FullPath}");
                }
                using (InstalledPackagesCache installedPackages = new InstalledPackagesCache(packagesFilePath, UpdatePackages))
                {
                    // Get the package manager and repositories
                    WyamFolderNuGetProject nuGetProject   = new WyamFolderNuGetProject(_fileSystem, _assemblyLoader, _currentFramework, installedPackages, packagesPath.FullPath);
                    NuGetPackageManager    packageManager = new NuGetPackageManager(_sourceRepositories, _settings, packagesPath.FullPath)
                    {
                        PackagesFolderNuGetProject = nuGetProject
                    };
                    IReadOnlyList <SourceRepository> remoteRepositories = _sourceRepositories.GetDefaultRepositories();

                    // Resolve all the versions
                    IReadOnlyList <SourceRepository> installationRepositories = remoteRepositories;
                    try
                    {
                        ResolveVersions(localRepository, remoteRepositories);
                    }
                    catch (Exception ex)
                    {
                        Trace.Verbose($"Exception while resolving package versions: {ex.Message}");
                        Trace.Warning("Error while resolving package versions, attempting without remote repositories");
                        installationRepositories = new[] { localRepository };
                        ResolveVersions(localRepository, Array.Empty <SourceRepository>());
                    }

                    // Install the packages (doing this synchronously since doing it in parallel triggers file lock errors in NuGet on a clean system)
                    try
                    {
                        InstallPackages(packageManager, installationRepositories, installedPackages);
                    }
                    catch (Exception ex)
                    {
                        Trace.Verbose($"Exception while installing packages: {(ex is AggregateException aex ? aex.Flatten() : ex)}");
                        Trace.Warning("Error while installing packages, attempting without remote repositories");
                        InstallPackages(packageManager, Array.Empty <SourceRepository>(), installedPackages);
                    }

                    // Process the package (do this after all packages have been installed)
                    nuGetProject.ProcessAssembliesAndContent();
                }
            }
            catch (Exception ex)
            {
                Trace.Verbose($"Unexpected exception while installing packages: {(ex is AggregateException ? string.Join("; ", ((AggregateException)ex).InnerExceptions.Select(x => x.Message)) : ex.Message)}");
                Trace.Warning("Error while installing packages, attempting to continue anyway");
            }
        }
Example #12
0
    public static void Unzip(FilePath zipPath, DirectoryPath outputPath, Assembly a)
    {
        if (zipPath == null)
        {
            throw new ArgumentNullException("zipPath");
        }
        if (outputPath == null)
        {
            throw new ArgumentNullException("outputPath");
        }

        /*
         * The code with reflection down below is the same as this clean code here.
         * Cake does not add the System.IO.Compression assembly to the script and
         * therefore these standard classes are not directly callable.
         *
         * Thank god for reflection ..
         */
        //var zipArchive = System.IO.Compression.ZipFile.OpenRead(zipPath.FullPath);
        //var nuSpecEntry = zipArchive.Entries.FirstOrDefault(e => e.Name.EndsWith(".nuspec"));
        //if (nuSpecEntry != null)
        //{
        //    var target = outputPath.CombineWithFilePath(nuSpecEntry.Name).MakeAbsolute(Context.Environment).FullPath;
        //    using (var s = nuSpecEntry.Open())
        //    {
        //        using (var f = File.Open(target, FileMode.Create))
        //        {
        //            s.CopyTo(f);
        //        }
        //    }
        //}
        try
        {
            var entryNames  = new List <string>();
            var zipFileType = a.GetType("System.IO.Compression.ZipFile");
            var methodInfo  = zipFileType.GetMethod("OpenRead", new[] { typeof(string) });
            var archive     = methodInfo.Invoke(null, new object[] { zipPath.FullPath });
            var s           = archive as IDisposable;
            using (s)
            {
                var entries =
                    archive.GetType().GetProperty("Entries").GetMethod.Invoke(archive, new object[0]) as IEnumerable;
                foreach (var entry in entries)
                {
                    var fullName = entry.ToString();
                    if (fullName.EndsWith(".nuspec") && !fullName.Contains("/"))
                    {
                        // found the file..
                        Context.Log.Debug(fullName);
                        var stream = entry.GetType().GetMethod("Open").Invoke(entry, new object[0]) as Stream;
                        using (stream)
                        {
                            var target =
                                outputPath.CombineWithFilePath(fullName).MakeAbsolute(Context.Environment).FullPath;
                            // There is a auto-generated File method in the current script context. So we need to fully qualify that reference here.
                            // ReSharper disable once RedundantNameQualifier
                            Stream f = System.IO.File.Open(target, FileMode.Create);
                            using (f)
                            {
                                stream.CopyTo(f);
                            }
                        }
                    }
                    entryNames.Add(fullName);
                }
            }

            var contentsPath = zipPath.AppendExtension(".contents.txt");
            // ReSharper disable once RedundantNameQualifier
            System.IO.File.WriteAllLines(contentsPath.FullPath, entryNames);
        }
        catch (Exception e)
        {
            if (Context.Log.Verbosity > Verbosity.Verbose)
            {
                Context.Log.Information("There was an error extracting the final nuspec file from the nupkg file.", e);
            }
            else
            {
                Context.Log.Information("There was an error extracting the final nuspec file from the nupkg file.");
            }
        }
    }
        private static ProcessArgumentBuilder ProcessArguments(
            ICakeContext cakeContext,
            ProcessArgumentBuilder builder,
            FilePath project,
            XUnit2Settings settings)
        {
            // No shadow copy?
            if (!settings.ShadowCopy)
            {
                throw new CakeException("-noshadow is not supported in .netcoreapp");
            }

            // No app domain?
            if (settings.NoAppDomain)
            {
                throw new CakeException("-noappdomain is not supported in .netcoreapp");
            }

            if (settings.OutputDirectory == null &&
                (settings.HtmlReport || settings.NUnitReport || settings.XmlReport))
            {
                throw new CakeException("OutputDirectory must not be null");
            }

            // Generate NUnit Style XML report?
            if (settings.NUnitReport)
            {
                var reportFileName   = new FilePath(project.GetDirectory().GetDirectoryName());
                var assemblyFilename = reportFileName.AppendExtension(".xml");
                var outputPath       = settings.OutputDirectory.MakeAbsolute(cakeContext.Environment)
                                       .GetFilePath(assemblyFilename);

                builder.Append("-nunit");
                builder.AppendQuoted(outputPath.FullPath);
            }

            // Generate HTML report?
            if (settings.HtmlReport)
            {
                var reportFileName   = new FilePath(project.GetDirectory().GetDirectoryName());
                var assemblyFilename = reportFileName.AppendExtension(".html");
                var outputPath       = settings.OutputDirectory.MakeAbsolute(cakeContext.Environment)
                                       .GetFilePath(assemblyFilename);

                builder.Append("-html");
                builder.AppendQuoted(outputPath.FullPath);
            }

            if (settings.XmlReportV1)
            {
                throw new CakeException("-xmlv1 is not supported in .netcoreapp");
            }

            // Generate XML report?
            if (settings.XmlReport)
            {
                var reportFileName   = new FilePath(project.GetDirectory().GetDirectoryName());
                var assemblyFilename = reportFileName.AppendExtension(".xml");
                var outputPath       = settings.OutputDirectory.MakeAbsolute(cakeContext.Environment)
                                       .GetFilePath(assemblyFilename);

                builder.Append("-xml");
                builder.AppendQuoted(outputPath.FullPath);
            }

            // parallelize test execution?
            if (settings.Parallelism != null && settings.Parallelism != ParallelismOption.None)
            {
                builder.Append($"-parallel {settings.Parallelism.ToString().ToLowerInvariant()}");
            }

            // max thread count for collection parallelization
            if (settings.MaxThreads.HasValue)
            {
                if (settings.MaxThreads.Value == 0)
                {
                    builder.Append("-maxthreads unlimited");
                }
                else
                {
                    builder.Append($"-maxthreads {settings.MaxThreads.Value}");
                }
            }

            foreach (var trait in settings.TraitsToInclude
                     .SelectMany(pair => pair.Value.Select(v => new { Name = pair.Key, Value = v })))
            {
                builder.Append("-trait \"{0}={1}\"", trait.Name, trait.Value);
            }

            foreach (var trait in settings.TraitsToExclude
                     .SelectMany(pair => pair.Value.Select(v => new { Name = pair.Key, Value = v })))
            {
                builder.Append($"-notrait \"{trait.Name}={trait.Value}\"");
            }

            return(builder);
        }
Example #14
0
        /// <inheritdoc />
        public IEnumerable <IDocument> Execute(IReadOnlyList <IDocument> inputs, IExecutionContext context)
        {
            // Iterate redirects and generate all of the per-redirect documents (I.e., meta refresh pages)
            ConcurrentDictionary <FilePath, string> redirects = new ConcurrentDictionary <FilePath, string>();
            List <IDocument> outputs = inputs
                                       .AsParallel()
                                       .SelectMany(context, input =>
            {
                IReadOnlyList <FilePath> paths = _paths.Invoke <IReadOnlyList <FilePath> >(input, context, "while getting paths");
                if (paths != null)
                {
                    List <IDocument> metaRefreshDocuments = new List <IDocument>();
                    foreach (FilePath fromPath in paths.Where(x => x != null))
                    {
                        // Make sure it's a relative path
                        if (!fromPath.IsRelative)
                        {
                            Trace.Warning($"The redirect path must be relative for document {input.SourceString()}: {fromPath}");
                            continue;
                        }

                        // Record the redirect for additional processing
                        string url = context.GetLink(input, _includeHost);
                        redirects.TryAdd(fromPath, url);

                        // Meta refresh documents
                        FilePath outputPath = fromPath;
                        if (!string.Equals(outputPath.Extension, ".html", StringComparison.OrdinalIgnoreCase))
                        {
                            outputPath = outputPath.AppendExtension(".html");
                        }

                        if (_metaRefreshPages)
                        {
                            metaRefreshDocuments.Add(
                                context.GetDocument(
                                    context.GetContentStream($@"
<!doctype html>
<html>    
  <head>      
    <title>Redirected</title>      
    <meta http-equiv=""refresh"" content=""0;url='{url}'"" />    
  </head>    
  <body> 
    <p>This page has moved to a <a href=""{url}"">{url}</a></p> 
  </body>  
</html>"),
                                    new MetadataItems
                            {
                                { Keys.RelativeFilePath, outputPath },
                                { Keys.WritePath, outputPath }
                            }));
                        }
                    }
                    return((IEnumerable <IDocument>)metaRefreshDocuments);
                }
                return(new IDocument[] { });
            })
                                       .ToList(); // Need to materialize the parallel operation before creating the additional outputs

            // Generate other output documents if requested
            if (redirects.Count > 0)
            {
                foreach (KeyValuePair <FilePath, Func <IDictionary <FilePath, string>, string> > additionalOutput in _additionalOutputs)
                {
                    string content = additionalOutput.Value(redirects);
                    if (!string.IsNullOrEmpty(content))
                    {
                        outputs.Add(
                            context.GetDocument(
                                context.GetContentStream(content),
                                new MetadataItems
                        {
                            { Keys.RelativeFilePath, additionalOutput.Key },
                            { Keys.WritePath, additionalOutput.Key }
                        }));
                    }
                }
            }

            return(outputs);
        }
Example #15
0
        /// <inheritdoc />
        protected override async Task <IEnumerable <IDocument> > ExecuteContextAsync(IExecutionContext context)
        {
            // Iterate redirects and generate all of the per-redirect documents (I.e., meta refresh pages)
            ConcurrentDictionary <FilePath, string> redirects = new ConcurrentDictionary <FilePath, string>();

            // Need to materialize the parallel operation before creating the additional outputs
            List <IDocument> outputs = new List <IDocument>();

            foreach (IDocument input in context.Inputs)
            {
                await foreach (IDocument output in GetOutputsAsync(input))
                {
                    outputs.Add(output);
                }
            }

            // Generate other output documents if requested
            if (redirects.Count > 0)
            {
                foreach (KeyValuePair <FilePath, Func <IDictionary <FilePath, string>, string> > additionalOutput in _additionalOutputs)
                {
                    string content = additionalOutput.Value(redirects);
                    if (!string.IsNullOrEmpty(content))
                    {
                        outputs.Add(
                            context.CreateDocument(
                                additionalOutput.Key,
                                await context.GetContentProviderAsync(content)));
                    }
                }
            }

            return(outputs);

            async IAsyncEnumerable <IDocument> GetOutputsAsync(IDocument input)
            {
                IReadOnlyList <FilePath> paths = await _paths.GetValueAsync(input, context);

                if (paths != null)
                {
                    foreach (FilePath fromPath in paths.Where(x => x != null))
                    {
                        // Make sure it's a relative path
                        if (!fromPath.IsRelative)
                        {
                            context.LogWarning($"The redirect path must be relative for document {input.Source.ToSafeDisplayString()}: {fromPath}");
                            continue;
                        }

                        // Record the redirect for additional processing
                        string url = context.GetLink(input, _includeHost);
                        redirects.TryAdd(fromPath, url);

                        // Meta refresh documents
                        FilePath outputPath = fromPath;
                        if (!string.Equals(outputPath.Extension, ".html", StringComparison.OrdinalIgnoreCase))
                        {
                            outputPath = outputPath.AppendExtension(".html");
                        }

                        if (_metaRefreshPages)
                        {
                            yield return(context.CreateDocument(
                                             outputPath,
                                             await context.GetContentProviderAsync($@"
<!doctype html>
<html>    
  <head>      
    <title>Redirected</title>      
    <meta http-equiv=""refresh"" content=""0;url='{url}'"" />    
  </head>    
  <body> 
    <p>This page has moved to a <a href=""{url}"">{url}</a></p> 
  </body>  
</html>")));
                        }
                    }
                }
            }
        }
Example #16
0
        public bool TryImport(string requestedFile, string parentPath, out string scss, out string map)
        {
            scss = null;
            map  = null;

            // Get the input relative path to the parent file
            FilePath parentFilePath    = new FilePath(parentPath);
            FilePath requestedFilePath = new FilePath(requestedFile);

            if (parentFilePath.IsRelative && !_parentAbsolutePaths.TryGetValue(parentFilePath, out parentFilePath))
            {
                // Relative parent path and no available absolute path, try with the relative path
                parentFilePath = new FilePath(parentPath);
            }
            DirectoryPath containingPath = _fileSystem.GetContainingInputPath(parentFilePath);

            if (containingPath == null)
            {
                // Couldn't find the containing path, give up at this point
                return(false);
            }
            FilePath parentRelativePath = containingPath.GetRelativePath(parentFilePath);

            // Find the requested file
            // ...as specified
            FilePath filePath = parentRelativePath.Directory.CombineFile(requestedFilePath);

            if (GetFile(filePath, requestedFilePath, out scss))
            {
                return(true);
            }

            // ...with extension (if not already)
            if (!filePath.HasExtension || filePath.Extension != ".scss")
            {
                FilePath extensionPath = filePath.AppendExtension(".scss");
                if (GetFile(extensionPath, requestedFilePath, out scss))
                {
                    return(true);
                }

                // ...and with underscore prefix (if not already)
                if (!extensionPath.FileName.FullPath.StartsWith("_"))
                {
                    extensionPath = extensionPath.Directory.CombineFile("_" + extensionPath.FileName.FullPath);
                    if (GetFile(extensionPath, requestedFilePath, out scss))
                    {
                        return(true);
                    }
                }
            }

            // ...with underscore prefix (if not already)
            if (!filePath.FileName.FullPath.StartsWith("_"))
            {
                filePath = filePath.Directory.CombineFile("_" + filePath.FileName.FullPath);
                if (GetFile(filePath, requestedFilePath, out scss))
                {
                    return(true);
                }
            }

            return(false);
        }