Exemplo n.º 1
0
        private FilePath GetCommonToolPath(string environmentVariable)
        {
            var visualStudioCommonToolsPath = _environment.GetEnvironmentVariable(environmentVariable);

            if (string.IsNullOrWhiteSpace(visualStudioCommonToolsPath))
            {
                return(null);
            }

            var root = new DirectoryPath(visualStudioCommonToolsPath).Combine("../IDE").Collapse();

            return(root.CombineWithFilePath("mstest.exe"));
        }
Exemplo n.º 2
0
        private string Nuspec(IConfiguration configuration, DirectoryPath nugetContentPath)
        {
            if (!configuration.TryGetSimple(NuGetConstants.NUGET_NUSPEC_FILE_KEY, out string nuspecPath))
            {
                configuration.Context.CakeContext.LogAndThrow("Missing nuspec file path");
            }
            nuspecPath = configuration.AddRootDirectory(nuspecPath);
            configuration.FileExistsOrThrow(nuspecPath);

            XDocument nuspecDocument;

            using (Stream inputStream = configuration.Context.CakeContext.FileSystem.GetFile(nuspecPath).OpenRead())
            {
                nuspecDocument = XDocument.Load(inputStream);
            }

            XElement metadataRoot = GetMetadataRootFromNuspec(configuration, nuspecDocument);
            string   packageId    = configuration.GetSimple <string>(NuGetConstants.NUGET_PACKAGE_ID_KEY);

            UpdateOrCreateNode(metadataRoot, "id", packageId);

            if (configuration.TryGetSimple(NuGetConstants.NUGET_PACKAGE_AUTHOR_KEY, out string author))
            {
                UpdateOrCreateNode(metadataRoot, "authors", author);
            }

            if (configuration.TryGetSimple(NuGetConstants.NUGET_PACKAGE_RELEASE_NOTES_FILE_KEY, out string releaseNoteFile))
            {
                releaseNoteFile = configuration.AddRootDirectory(releaseNoteFile);
                configuration.FileExistsOrThrow(releaseNoteFile);

                string releaseNoteContent = configuration.Context.CakeContext.FileSystem.GetFile(releaseNoteFile).ReadAll();

                UpdateOrCreateNode(metadataRoot, "releaseNotes", releaseNoteContent);
            }

            if (configuration.TryGetSimple(NuGetConstants.NUGET_PACKAGE_VERSION_KEY, out string version) ||
                configuration.TryGetSimple(ConfigurationConstants.VERSION_KEY, out version))
            {
                UpdateOrCreateNode(metadataRoot, "version", version);
            }

            FilePath nuspecOutputPath = nugetContentPath.CombineWithFilePath($"{packageId}.nuspec");

            using (Stream outputStream = configuration.Context.CakeContext.FileSystem.GetFile(nuspecOutputPath).OpenWrite())
            {
                nuspecDocument.Save(outputStream);
            }

            return(nuspecOutputPath.FullPath);
        }
Exemplo n.º 3
0
        public static void IlRepackCli(Context context)
        {
            var frameworks = context.GetSubDirectories(context.CliPackageDir)
                             .Where(x => context.FileExists(x.CombineWithFilePath("VGAudioCli.exe")));

            foreach (DirectoryPath tfm in frameworks)
            {
                DirectoryPath outDir = context.CliPackageDir.Combine($"{tfm.GetDirectoryName()}_standalone");
                context.EnsureDirectoryExists(outDir);
                var libraries = context.GetFiles($"{tfm}/VGAudio.*dll");
                var cliList   = new List <FilePath> {
                    tfm.CombineWithFilePath("VGAudioCli.exe")
                };
                var toolsList = new List <FilePath> {
                    tfm.CombineWithFilePath("VGAudioTools.exe")
                };
                cliList.AddRange(libraries);
                toolsList.AddRange(libraries);

                var cliOptions = new RepackOptions
                {
                    OutputFile        = outDir.CombineWithFilePath("VGAudioCli.exe").FullPath,
                    InputAssemblies   = cliList.Select(x => x.FullPath).ToArray(),
                    SearchDirectories = new[] { "." }
                };

                var toolsOptions = new RepackOptions
                {
                    OutputFile        = outDir.CombineWithFilePath("VGAudioTools.exe").FullPath,
                    InputAssemblies   = toolsList.Select(x => x.FullPath).ToArray(),
                    SearchDirectories = new[] { "." }
                };

                new ILRepack(cliOptions).Repack();
                new ILRepack(toolsOptions).Repack();
                context.CopyFiles(context.GetFiles($"{outDir}/*.exe"), context.PackageDir);
            }
        }
        private FilePath GetPathToMigrate(FilePath pathToEf)
        {
            var efDir      = pathToEf.GetDirectory();
            var libSegment = Array.IndexOf(efDir.Segments, "lib");

            if (libSegment == -1)
            {
                return(efDir.CombineWithFilePath("<TODO migrate.exe>"));
            }
            var segmentsBaseDir = efDir.Segments.Take(libSegment);
            var efBaseDir       = new DirectoryPath(string.Join("/", segmentsBaseDir));

            return(efBaseDir.CombineWithFilePath("tools/migrate.exe"));
        }
Exemplo n.º 5
0
        private ISet <FilePath> GetDefaultReferences(DirectoryPath root)
        {
            // Prepare the default assemblies.
            var references = new HashSet <FilePath>();

            references.Add(typeof(Action).GetTypeInfo().Assembly.Location);     // mscorlib or System.Private.Core
            references.Add(typeof(IQueryable).GetTypeInfo().Assembly.Location); // System.Core or System.Linq.Expressions

            references.Add(root.CombineWithFilePath("Cake.Core.dll").FullPath);
            references.Add(root.CombineWithFilePath("Cake.Common.dll").FullPath);

            references.Add(typeof(Uri).GetTypeInfo().Assembly.Location);                        // System
            references.Add(typeof(XmlReader).GetTypeInfo().Assembly.Location);                  // System.Xml
            references.Add(typeof(XDocument).GetTypeInfo().Assembly.Location);                  // System.Xml.Linq
            references.Add(typeof(DataTable).GetTypeInfo().Assembly.Location);                  // System.Data
            references.Add(typeof(ZipArchive).GetTypeInfo().Assembly.Location);                 // System.IO.Compression
            references.Add(typeof(ZipFile).GetTypeInfo().Assembly.Location);                    // System.IO.Compression.FileSystem
            references.Add(typeof(HttpClient).GetTypeInfo().Assembly.Location);                 // System.Net.Http
            references.Add(typeof(DataContractJsonSerializer).GetTypeInfo().Assembly.Location); // System.Runtime.Serialization

            // Return the assemblies.
            return(references);
        }
Exemplo n.º 6
0
    static NUnit3Settings BuildNUnit3Settings(ParsedProject projectUnderTest, AnyUnitTestSettings settings,
                                              DirectoryPath outputDir)
    {
        var whereClause = BuildNUnit3WhereClause(settings);

        var s = new NUnit3Settings();

        XBuildHelper.ApplyToolSettings(s, NUnitToolArgs);

        s.ShadowCopy = settings.ShadowCopyAssemblies;
        s.X86        = settings.ForceX86 || projectUnderTest.Platform == PlatformTarget.x86;
        var path = outputDir.CombineWithFilePath(projectUnderTest.Project.AssemblyName + ".nunit3.xml");

        NUnit3Result rxx = new NUnit3Result();

        rxx.FileName  = path;
        rxx.Format    = "nunit3";
        rxx.Transform = null;
        s.Results     = new List <NUnit3Result>
        {
            rxx
        };
        s.ArgumentCustomization = args =>
        {
            if (whereClause != null)
            {
                args.Append("--where");
                args.AppendQuoted(whereClause);
            }
            // Additionally generate NUnit2 output.
            AppendNUnit3AlternativeOutput(args,
                                          outputDir.CombineWithFilePath(projectUnderTest.Project.AssemblyName + ".nunit2.xml"));
            return(args);
        };
        return(s);
    }
Exemplo n.º 7
0
 private static ProjectReference[] GetNetFrameworkProjectReferences(XDocument document, XNamespace ns, DirectoryPath rootPath)
 {
     return((from project in document.Elements(ns + ProjectXElement.Project)
             from itemGroup in project.Elements(ns + ProjectXElement.ItemGroup)
             from element in itemGroup.Elements()
             where element.Name == ns + ProjectXElement.ProjectReference
             from include in element.Attributes("Include")
             let value = include.Value
                         where !string.IsNullOrEmpty(value)
                         let filePath = rootPath.CombineWithFilePath(value)
                                        let nameElement = element.Element(ns + ProjectXElement.Name)
                                                          let projectElement = element.Element(ns + ProjectXElement.Project)
                                                                               let packageElement = element.Element(ns + ProjectXElement.Package)
                                                                                                    select new ProjectReference
     {
         FilePath = filePath,
         RelativePath = value,
         Name = nameElement?.Value,
         Project = projectElement?.Value,
         Package = string.IsNullOrEmpty(packageElement?.Value)
                     ? null
                     : rootPath.CombineWithFilePath(packageElement.Value)
     }).ToArray());
 }
Exemplo n.º 8
0
        private async Task <FilePath> DownloadGradle(string downloadUrl, DirectoryPath toolsFolder)
        {
            var fileName = new FilePath(
                downloadUrl.Substring(downloadUrl.LastIndexOf("/", StringComparison.Ordinal) + 1));
            var downloadTo = toolsFolder.CombineWithFilePath(fileName);

            // downloading gradle package
            await WebAdapter.DownloadFile(new Uri(downloadUrl), downloadTo, progress =>
            {
                _log.Verbose("Downloading gradle: {0}%", progress);
            });

            _log.Verbose("Download complete, saved to: {0}", downloadTo.FullPath);
            return(downloadTo);
        }
Exemplo n.º 9
0
        private Topic ReadTopic(XmlReader reader, DirectoryPath root)
        {
            var file = reader.GetAttribute("file");

            if (string.IsNullOrWhiteSpace(file))
            {
                return(null);
            }

            var id     = reader.GetAttribute("id");
            var title  = reader.GetAttribute("title");
            var body   = string.Empty;
            var hidden = string.Equals("true", reader.GetAttribute("hidden"), StringComparison.OrdinalIgnoreCase);

            if (string.IsNullOrWhiteSpace(id))
            {
                if (!string.IsNullOrWhiteSpace(file))
                {
                    id = Path.GetFileNameWithoutExtension(file);
                }
                else if (!string.IsNullOrWhiteSpace(title))
                {
                    id = title.ToSlug();
                }
                else
                {
                    throw new InvalidOperationException("Could not generate ID from topic.");
                }
            }

            var path = root.CombineWithFilePath(file);

            if (_fileSystem.Exist(path))
            {
                // Read the file and separate front matter from content.
                var content = _contentParser.Parse(path);
                if (content != null)
                {
                    body = _contentProcessor.PreProcess(content.Body);
                    body = _contentConverter.ConvertToHtml(content, body);
                }

                // Process the content.
                body = _contentProcessor.PostProcess(body) ?? body;
            }

            return(new Topic(id, title, body, hidden, file));
        }
Exemplo n.º 10
0
        private async Task <Stream> GetDataStream(DirectoryPath data, string version)
        {
            var url      = GetUrl(version);
            var filename = data.CombineWithFilePath($"{DataFilename}_{version}.txt");

            if (!File.Exists(filename.FullPath))
            {
                AnsiConsole.MarkupLine($"🌍 Downloading [yellow]{url}[/]...");
                using var client = new HttpClient();
                var content = await client.GetStringAsync(url);

                await File.WriteAllTextAsync(filename.FullPath, content);
            }

            return(File.OpenRead(filename.FullPath));
        }
Exemplo n.º 11
0
        internal static FilePath GetAbsolutePath(this string relativePath, DirectoryPath rootPath)
        {
            var isRelative = new FilePath(relativePath).IsRelative;

            Cake.Core.IO.FilePath absolutePath;
            if (isRelative)
            {
                absolutePath = rootPath.CombineWithFilePath(relativePath);
            }
            else
            {
                absolutePath = relativePath;
                Debug.WriteLine($"An absolute path {absolutePath} was used in a project reference. It is recommended that projects contain only relative paths for references");
            }

            return(absolutePath);
        }
Exemplo n.º 12
0
        public bool IsInstalled(DirectoryPath root)
        {
            if (root == null)
            {
                throw new ArgumentNullException("root");
            }

            foreach (var roslynAssembly in _roslynAssemblies)
            {
                var file = _fileSystem.GetFile(root.CombineWithFilePath(roslynAssembly));
                if (!file.Exists)
                {
                    return(false);
                }
            }
            return(true);
        }
Exemplo n.º 13
0
 private bool IsInstalled(DirectoryPath root)
 {
     if (root == null)
     {
         throw new ArgumentNullException("root");
     }
     foreach (var path in _paths)
     {
         var filename = path.GetFilename();
         var file     = _fileSystem.GetFile(root.CombineWithFilePath(filename));
         if (!file.Exists)
         {
             return(false);
         }
     }
     return(true);
 }
Exemplo n.º 14
0
        private static FilePath GetAbsolutePath(this XElement hintPathElement, DirectoryPath rootPath)
        {
            var hintPath = new FilePath(hintPathElement.Value).IsRelative;

            Cake.Core.IO.FilePath absolutePath;
            if (hintPath)
            {
                absolutePath = rootPath.CombineWithFilePath(hintPathElement.Value);
            }
            else
            {
                absolutePath = hintPathElement.Value;
                Debug.WriteLine($"An absolute path {absolutePath} was used in a project reference. It is recommended that projects contain only relative paths for references");
            }

            return(absolutePath);
        }
Exemplo n.º 15
0
        private FilePath GetFromRegistry()
        {
            // Gets a list of the files we should check.
            var files = new List <FilePath>();

            using (var root = _registry.LocalMachine.OpenKey("Software\\Microsoft\\Microsoft SDKs\\Windows"))
            {
                if (root != null)
                {
                    var keyName = root.GetSubKeyNames();
                    foreach (var key in keyName)
                    {
                        var sdkKey             = root.OpenKey(key);
                        var installationFolder = sdkKey?.GetValue("InstallationFolder") as string;
                        if (!string.IsNullOrWhiteSpace(installationFolder))
                        {
                            var installationPath = new DirectoryPath(installationFolder);
                            files.Add(installationPath.CombineWithFilePath("bin\\signtool.exe"));
                        }
                    }
                }
            }

            using (var root = _registry.LocalMachine.OpenKey("Software\\Microsoft\\Windows Kits\\Installed Roots"))
            {
                if (root != null)
                {
                    var windowsKits = new[] { "KitsRoot", "KitsRoot81", "KitsRoot10" };
                    foreach (var kit in windowsKits)
                    {
                        var kitsRoot = root.GetValue(kit) as string;
                        if (!string.IsNullOrWhiteSpace(kitsRoot))
                        {
                            var kitsPath = new DirectoryPath(kitsRoot);

                            files.Add(_environment.Platform.Is64Bit
                                ? kitsPath.CombineWithFilePath("bin\\x64\\signtool.exe")
                                : kitsPath.CombineWithFilePath("bin\\x86\\signtool.exe"));
                        }
                    }
                }
            }

            // Return the first path that exists.
            return(files.FirstOrDefault(file => _fileSystem.Exist(file)));
        }
Exemplo n.º 16
0
        public static void Move(this ICakeContext context, IEnumerable <FilePath> source, DirectoryPath destination)
        {
            var sourceFiles = source.ThrowIfNull(nameof(source));

            destination.ThrowIfNull(nameof(destination));

            sourceFiles.Each(f =>
            {
                if (!context.FileSystem.Exist(f))
                {
                    throw new CakeException($"{f.FullPath} does not exist");
                }

                var file = context.FileSystem.GetFile(f);
                file.Move(destination.CombineWithFilePath(f.GetFilename()));
            });
        }
Exemplo n.º 17
0
        public static PackageReference GetPackageReference(this ICakeContext context, DirectoryPath path, string packageId)
        {
            if (!path.IsRelative)
            {
                throw new CakeException("DirectoryPath must be relative!");
            }

            var packagePath = path.CombineWithFilePath(new FilePath("packages.config"));

            if (!System.IO.File.Exists(packagePath.FullPath))
            {
                throw new CakeException(string.Format("Could not find a packages.config file in '{0}'", path.FullPath));
            }

            var file = new PackageReferenceFile(packagePath.FullPath);

            return(file.GetPackageReferences().FirstOrDefault(x => x.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase)));
        }
        public static FilePath GetVsixSignToolPath(IFileSystem fileSystem, ICakeEnvironment environment)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException("fileSystem");
            }

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

            var location = typeof(VsixSignToolResolver).Assembly.Location;
            var dir      = new DirectoryPath(System.IO.Path.GetDirectoryName(location));
            var filePath = dir.CombineWithFilePath("VsixSignTool.exe");

            return(fileSystem.GetFile(filePath).Exists ? filePath : null);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Gets alternative file paths which the tool may exist in.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <returns>The default tool path.</returns>
        protected override IEnumerable <FilePath> GetAlternativeToolPaths(InnoSetupSettings settings)
        {
            foreach (var keyPath in GetAlternativeRegistryKeyPathsForVersion(settings.Version))
            {
                using (var innoSetupKey = _registry.LocalMachine.OpenKey(keyPath))
                {
                    var installationPath = innoSetupKey?.GetValue("InstallLocation") as string;
                    if (!string.IsNullOrEmpty(installationPath))
                    {
                        var directory = new DirectoryPath(installationPath);
                        var isccPath  = directory.CombineWithFilePath("iscc.exe");
                        return(new[] { isccPath });
                    }
                }
            }

            return(base.GetAlternativeToolPaths(settings));
        }
Exemplo n.º 20
0
        public static FilePathCollection GetFilesByPatterns(this ICakeContext context, DirectoryPath root, string[] includePatterns)
        {
            var res = new FilePathCollection();

            for (var i = 0; i < includePatterns.Length; i++)
            {
                var incl = context.GetFiles(root.CombineWithFilePath(includePatterns[i].TrimStart('/')).ToString());
                var crt  = res.Select(ii => ii.FullPath);
                foreach (var include in incl)
                {
                    if (!crt.Contains(include.FullPath))
                    {
                        res.Add(include);
                    }
                }
            }
            return(res);
        }
Exemplo n.º 21
0
        public static IEnumerable <PackageReference> GetPackageReferences(this ICakeContext context, DirectoryPath path)
        {
            if (!path.IsRelative)
            {
                throw new CakeException("DirectoryPath must be relative!");
            }

            var packagePath = path.CombineWithFilePath(new FilePath("packages.config"));

            if (!System.IO.File.Exists(packagePath.FullPath))
            {
                throw new CakeException(string.Format("Could not find a packages.config file in '{0}'", path.FullPath));
            }

            var file = new PackageReferenceFile(packagePath.FullPath);

            return(file.GetPackageReferences());
        }
Exemplo n.º 22
0
        /// <summary>
        /// Gets the installation folder of sn.exe from the registry.
        /// </summary>
        /// <returns>The install folder to sn.exe from registry.</returns>
        private FilePath GetFromRegistry()
        {
            using (var root = _registry.LocalMachine.OpenKey("Software\\Microsoft\\Microsoft SDKs\\Windows"))
            {
                if (root == null)
                {
                    return(null);
                }

                var keyName = root.GetSubKeyNames();
                foreach (var key in keyName)
                {
                    var sdkKey = root.OpenKey(key);
                    if (sdkKey != null)
                    {
                        IRegistryKey fxKey;
                        if (_environment.Is64BitOperativeSystem())
                        {
                            fxKey = sdkKey.OpenKey("WinSDK-NetFx40Tools-x64");
                        }
                        else
                        {
                            fxKey = sdkKey.OpenKey("WinSDK-NetFx40Tools");
                        }

                        if (fxKey != null)
                        {
                            var installationFolder = fxKey.GetValue("InstallationFolder") as string;
                            if (!string.IsNullOrWhiteSpace(installationFolder))
                            {
                                var installationPath = new DirectoryPath(installationFolder);
                                var signToolPath     = installationPath.CombineWithFilePath("sn.exe");

                                if (_fileSystem.Exist(signToolPath))
                                {
                                    return(signToolPath);
                                }
                            }
                        }
                    }
                }
            }
            return(null);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Creates a configuration from the provided arguments.
        /// </summary>
        /// <param name="path">The directory to look for the configuration file.</param>
        /// <param name="arguments">The arguments.</param>
        /// <returns>The created configuration.</returns>
        public ICakeConfiguration CreateConfiguration(DirectoryPath path, IDictionary <string, string> arguments)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            if (arguments == null)
            {
                throw new ArgumentNullException("arguments");
            }

            var result = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            // Get all environment variables.
            foreach (var variable in _environment.GetEnvironmentVariables())
            {
                if (variable.Key.StartsWith("CAKE_", StringComparison.OrdinalIgnoreCase))
                {
                    var key = variable.Key.Substring(5);
                    result[KeyNormalizer.Normalize(key)] = variable.Value;
                }
            }

            // Parse the configuration file.
            var configurationPath = path.CombineWithFilePath("cake.config").MakeAbsolute(_environment);

            if (_fileSystem.Exist(configurationPath))
            {
                var parser        = new ConfigurationParser(_fileSystem, _environment);
                var configuration = parser.Read(configurationPath);
                foreach (var key in configuration.Keys)
                {
                    result[KeyNormalizer.Normalize(key)] = configuration[key];
                }
            }

            // Add all arguments.
            foreach (var key in arguments.Keys)
            {
                result[KeyNormalizer.Normalize(key)] = arguments[key];
            }

            return(new CakeConfiguration(result));
        }
Exemplo n.º 24
0
    public BuildContext(ICakeContext context)
        : base(context)
    {
        BuildConfiguration = context.Argument("Configuration", "Release");
        SkipTests          = context.Argument("SkipTests", false);
        SkipSlowTests      = context.Argument("SkipSlowTests", false);

        RootDirectory       = new DirectoryPath(new DirectoryInfo(Directory.GetCurrentDirectory()).Parent.FullName);
        ArtifactsDirectory  = RootDirectory.Combine("artifacts");
        ToolsDirectory      = RootDirectory.Combine("tools");
        DocsDirectory       = RootDirectory.Combine("docs");
        DocfxDirectory      = ToolsDirectory.Combine("docfx");
        DocfxExeFile        = DocfxDirectory.CombineWithFilePath("docfx.exe");
        DocfxJsonFile       = DocsDirectory.CombineWithFilePath("docfx.json");
        TestOutputDirectory = RootDirectory.Combine("TestResults");

        ChangeLogDirectory    = RootDirectory.Combine("docs").Combine("changelog");
        ChangeLogGenDirectory = RootDirectory.Combine("docs").Combine("_changelog");

        SolutionFile         = RootDirectory.CombineWithFilePath("BenchmarkDotNet.sln");
        UnitTestsProjectFile = RootDirectory.Combine("tests").Combine("BenchmarkDotNet.Tests")
                               .CombineWithFilePath("BenchmarkDotNet.Tests.csproj");
        IntegrationTestsProjectFile = RootDirectory.Combine("tests").Combine("BenchmarkDotNet.IntegrationTests")
                                      .CombineWithFilePath("BenchmarkDotNet.IntegrationTests.csproj");
        TemplatesTestsProjectFile = RootDirectory.Combine("templates")
                                    .CombineWithFilePath("BenchmarkDotNet.Templates.csproj");
        AllPackableSrcProjects = new FilePathCollection(context.GetFiles(RootDirectory.FullPath + "/src/**/*.csproj")
                                                        .Where(p => !p.FullPath.Contains("Disassembler")));

        MsBuildSettings = new DotNetCoreMSBuildSettings
        {
            MaxCpuCount = 1
        };
        MsBuildSettings.WithProperty("UseSharedCompilation", "false");

        // NativeAOT build requires VS C++ tools to be added to $path via vcvars64.bat
        // but once we do that, dotnet restore fails with:
        // "Please specify a valid solution configuration using the Configuration and Platform properties"
        if (context.IsRunningOnWindows())
        {
            MsBuildSettings.WithProperty("Platform", "Any CPU");
        }
    }
Exemplo n.º 25
0
        private AppxManifestAsset ParseImage(DirectoryPath root, Func <string> func)
        {
            var resource = func();

            if (string.IsNullOrWhiteSpace(resource))
            {
                return(null);
            }

            var file = root.CombineWithFilePath(new FilePath(resource));

            if (_fileSystem.Exist(file))
            {
                return(new AppxManifestAsset
                {
                    Name = resource,
                    Path = file
                });
            }

            var stack = new Stack <string>(new[] { "400", "300", "200", "150", "125", "100" });

            while (stack.Count > 0)
            {
                var current = stack.Pop();

                var scale = file.RemoveExtension()
                            .AppendExtension(new FileExtension($"scale-{current}"))
                            .AppendExtension(file.GetExtension());

                if (_fileSystem.Exist(scale))
                {
                    return(new AppxManifestAsset
                    {
                        Name = resource,
                        Path = scale
                    });
                }
            }

            return(null);
        }
Exemplo n.º 26
0
 private string ReadBody(DirectoryPath root, string path, string uri)
 {
     if (!string.IsNullOrWhiteSpace(path))
     {
         var file = _fileSystem.GetFile(root.CombineWithFilePath(path));
         if (file.Exists)
         {
             using (var stream = file.OpenRead())
                 using (var reader = new StreamReader(stream))
                 {
                     return(reader.ReadToEnd());
                 }
         }
     }
     else if (!string.IsNullOrWhiteSpace(uri))
     {
         return(new System.Net.WebClient().DownloadString(uri));
     }
     return(null);
 }
Exemplo n.º 27
0
        /// <summary>
        /// Gets alternative file paths which the tool may exist in
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <returns>The default tool path.</returns>
        protected override IEnumerable <FilePath> GetAlternativeToolPaths(InnoSetupSettings settings)
        {
            // On 64-bit Windows, the registry key for Inno Setup will be accessible under Wow6432Node
            string keyPath = _environment.Platform.Is64Bit
                    ? @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Inno Setup 5_is1"
                    : @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Inno Setup 5_is1";

            using (var innoSetupKey = _registry.LocalMachine.OpenKey(keyPath))
            {
                string installationPath = innoSetupKey?.GetValue("InstallLocation") as string;
                if (!string.IsNullOrEmpty(installationPath))
                {
                    var directory = new DirectoryPath(installationPath);
                    var isccPath  = directory.CombineWithFilePath("iscc.exe");
                    return(new[] { isccPath });
                }
            }

            return(base.GetAlternativeToolPaths(settings));
        }
Exemplo n.º 28
0
        /// <summary>
        /// Formats the options for the warning service message.
        /// </summary>
        /// <param name="rootDirectoryPath">The root path of the file, relative to the repository root.</param>
        /// <param name="filePath">The file path relative to the project root.</param>
        /// <param name="line">The line where the issue ocurred.</param>
        /// <param name="column">The column where the issue ocurred.</param>
        /// <returns>Formatted options string for the warning service message.</returns>
        private static string FormatWarningOptions(DirectoryPath rootDirectoryPath, FilePath filePath, int?line, int?column)
        {
            var result = new List <string>();

            if (filePath != null)
            {
                result.Add($"file={rootDirectoryPath.CombineWithFilePath(filePath)}");
            }

            if (line.HasValue)
            {
                result.Add($"line={line.Value}");
            }

            if (column.HasValue)
            {
                result.Add($"col={column}");
            }

            return(string.Join(",", result));
        }
Exemplo n.º 29
0
    static NUnitSettings BuildNUnitSettings(ParsedProject projectUnderTest, AnyUnitTestSettings settings,
                                            DirectoryPath outputDir)
    {
        var s = new NUnitSettings();

        XBuildHelper.ApplyToolSettings(s, NUnitToolArgs);

        if (settings.ExcludedCategories.Count > 0)
        {
            s.Exclude = string.Join(",", settings.ExcludedCategories);
        }
        if (settings.IncludedCategories.Count > 0)
        {
            s.Include = string.Join(",", settings.IncludedCategories);
        }
        s.ShadowCopy = settings.ShadowCopyAssemblies;
        s.UseSingleThreadedApartment = settings.UseSingleThreadedApartment;
        s.X86         = settings.ForceX86 || projectUnderTest.Platform == PlatformTarget.x86;
        s.ResultsFile = outputDir.CombineWithFilePath(projectUnderTest.Project.AssemblyName + ".nunit2.xml");
        return(s);
    }
Exemplo n.º 30
0
        public FilePath Resolve(MavenPackage package)
        {
            var groupId    = package.GroupId;
            var artifactId = package.ArtifactId;
            var version    = package.Version ?? GetLatestVersion(groupId, artifactId);

            var path         = $"{groupId.Replace('.', '/')}/{artifactId}/{version}/{artifactId}-{version}.jar";
            var localJarFile = fileSystem.GetFile(localRepository.CombineWithFilePath(path));

            if (!localJarFile.Exists)
            {
                fileSystem.GetDirectory(localJarFile.Path.GetDirectory()).Create();

                using (var source = remoteRepository.OpenRead(path))
                    using (var target = localJarFile.Open(FileMode.CreateNew))
                    {
                        source.CopyTo(target);
                    }
            }
            return(localJarFile.Path);
        }
Exemplo n.º 31
0
        private Topic ReadTopic(XmlReader reader, DirectoryPath root)
        {
            var file = reader.GetAttribute("file");
            if (string.IsNullOrWhiteSpace(file))
            {
                return null;
            }

            var id = reader.GetAttribute("id");
            var title = reader.GetAttribute("title");
            var body = string.Empty;

            if (string.IsNullOrWhiteSpace(id))
            {
                if (!string.IsNullOrWhiteSpace(file))
                {
                    id = Path.GetFileNameWithoutExtension(file);
                }
                else if(!string.IsNullOrWhiteSpace(title))
                {
                    id = title.ToSlug();
                }
                else
                {
                    throw new InvalidOperationException("Could not generate ID from topic.");
                }
            }

            var path = root.CombineWithFilePath(file);
            if (_fileSystem.Exist(path))
            {
                // Read the file and separate front matter from content.
                var content = _contentParser.Parse(path);
                if (content != null)
                {
                    body = _contentProcessor.PreProcess(content.Body);
                    body = _contentConverter.ConvertToHtml(content, body);
                }

                // Process the content.
                body = _contentProcessor.PostProcess(body) ?? body;
            }

            return new Topic(id, title, body, file);
        }
Exemplo n.º 32
0
        public static PackageReference GetPackageReference(this ICakeContext context, DirectoryPath path, string packageId)
        {
            if (!path.IsRelative)
            {
                throw new CakeException("DirectoryPath must be relative!");
            }

            var packagePath = path.CombineWithFilePath(new FilePath("packages.config"));
            if (!System.IO.File.Exists(packagePath.FullPath))
            {
                throw new CakeException(string.Format("Could not find a packages.config file in '{0}'", path.FullPath));
            }

            var file = new PackageReferenceFile(packagePath.FullPath);
            return file.GetPackageReferences().FirstOrDefault(x => x.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase));
        }
Exemplo n.º 33
0
        protected void Application_Start()
        {
            // Get the application data path.
            var appDataPath = new DirectoryPath(AppDomain.CurrentDomain.GetData("DataDirectory").ToString());

            // Read all addins.
            // TODO: Fix this container hack.
            var addinReader = new AddinReader(new FileSystem());
            var addins = addinReader.Read(appDataPath.CombineWithFilePath("addins.xml"));

            // Define packages.
            var packageDefinitions = new List<PackageDefinition>();
            packageDefinitions.AddRange(addins.GetAddins()
                .Where(x => x.PackageDefinition != null)
                .Where(x => x.PackageDefinition.Filters.Count > 0)
                .Select(x => x.PackageDefinition));

            // Add core packages.
            packageDefinitions.Add(new PackageDefinition
            {
                Filters = new List<string>
                {
                    "/**/Cake.Core.dll",
                    "/**/Cake.Common.dll",
                    "/**/Cake.Core.xml",
                    "/**/Cake.Common.xml"
                },
                PackageName = "Cake",
                Metadata = new CakeMetadata()
            });

            // Create the document model by downloading the nuget package.
            var cakeVersion = (string)null;
            var documentModel = NuGetBootstrapper.Download(appDataPath,
                new NuGetConfiguration {
                    Packages = packageDefinitions
                }, out cakeVersion);

            // Build the DSL model.
            var dslModel = DslModelBuilder.Build(documentModel);

            // Generate packages.config content.
            var packagesConfig = new PackagesConfigContent(cakeVersion);

            // Build the container.
            var builder = new ContainerBuilder();
            builder.RegisterModule<CoreModule>();
            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            builder.RegisterInstance(documentModel).As<DocumentModel>().SingleInstance();
            builder.RegisterInstance(dslModel).As<DslModel>().SingleInstance();
            builder.RegisterType<DocumentModelResolver>().SingleInstance();
            builder.RegisterType<RouteService>().SingleInstance();
            builder.RegisterType<UrlResolver>().As<IUrlResolver>().As<UrlResolver>().SingleInstance();
            builder.RegisterType<SignatureCache>().SingleInstance();
            builder.RegisterType<ApiServices>().SingleInstance();
            builder.RegisterType<LanguageProvider>().SingleInstance();
            builder.RegisterType<SyntaxRenderer>().SingleInstance();
            builder.RegisterType<SignatureRenderer>().SingleInstance();
            builder.RegisterType<ApiServices>().SingleInstance();
            builder.RegisterInstance(packagesConfig).SingleInstance();
            var container = builder.Build();

            // Read the topics and register.
            var reader = container.Resolve<ITopicReader>();
            var topics = reader.Read(appDataPath.CombineWithFilePath("docs.xml"));

            // Read all blog entries.
            var blogReader = container.Resolve<IBlogReader>();
            var blogIndex = blogReader.Parse(appDataPath.Combine("blog"));

            // Update the container.
            builder = new ContainerBuilder();
            builder.RegisterInstance(topics).As<TopicTree>().SingleInstance();
            builder.RegisterInstance(blogIndex).As<BlogIndex>().SingleInstance();
            builder.RegisterInstance(addins).As<AddinIndex>().SingleInstance();
            builder.Update(container);

            // Perform registrations.
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Exemplo n.º 34
0
        public static IEnumerable<PackageReference> GetPackageReferences(this ICakeContext context, DirectoryPath path)
        {
            if (!path.IsRelative)
            {
                throw new CakeException("DirectoryPath must be relative!");
            }

            var packagePath = path.CombineWithFilePath(new FilePath("packages.config"));
            if (!System.IO.File.Exists(packagePath.FullPath))
            {
                throw new CakeException(string.Format("Could not find a packages.config file in '{0}'", path.FullPath));
            }

            var file = new PackageReferenceFile(packagePath.FullPath);
            return file.GetPackageReferences();
        }
Exemplo n.º 35
0
 private string ReadBody(DirectoryPath root, string path, string uri)
 {
     if (!string.IsNullOrWhiteSpace(path))
     {
         var file = _fileSystem.GetFile(root.CombineWithFilePath(path));
         if (file.Exists)
         {
             using (var stream = file.OpenRead())
             using (var reader = new StreamReader(stream))
             {
                 return reader.ReadToEnd();
             }
         }
     }
     else if (!string.IsNullOrWhiteSpace(uri))
     {
         return new System.Net.WebClient().DownloadString(uri);
     }
     return null;
 }