public static void TestDotNetCoreProjects(ICakeContext context, TaskConfig config) { DotNetCoreConfig dotNetCoreConfig = config.Load <DotNetCoreConfig>(); DotNetCoreConfig.TestConfig test = dotNetCoreConfig.Test; DotNetCoreConfig.CoverageConfig coverage = dotNetCoreConfig.Coverage; if (test.Skip) { context.LogInfo("Skipping tests."); return; } EnvConfig env = config.Load <EnvConfig>(); string testProjectFile = test.ProjectFile; if (testProjectFile is null) { throw new TaskConfigException("Build solution or project file not specified."); } var coverletSettings = new CoverletSettings { CollectCoverage = true, CoverletOutputFormat = CoverletOutputFormat.opencover, CoverletOutputDirectory = Path.Combine(env.Directories.TestOutput, "coverage"), }; IList <string> excludeFilters = coverage.ExcludeFilters; if (excludeFilters.Count > 0) { coverletSettings.Exclude = excludeFilters.ToList(); } IList <string> includeFilters = coverage.IncludeFilters; if (includeFilters.Count > 0) { coverletSettings.Include = includeFilters.ToList(); } var settings = new DotNetCoreTestSettings { Configuration = env.Configuration, OutputDirectory = Path.Combine(env.Directories.BinaryOutput, "__build"), Logger = test.Logger ?? "trx", ResultsDirectory = Path.Combine(env.Directories.TestOutput, "testresults"), NoBuild = true, NoRestore = true, Verbosity = context.Log.Verbosity.ToVerbosity(), }; string filter = test.Filter; if (!string.IsNullOrWhiteSpace(filter)) { settings.Filter = filter; } context.DotNetCoreTest(testProjectFile, settings, coverletSettings); }
public static void ConfigureDotNetCore(TaskConfig config) { DotNetCoreConfig cfg = config.Load <DotNetCoreConfig>(); EnvConfig env = config.Load <EnvConfig>(); string workingDirectory = env.Directories.Working ?? Directory.GetCurrentDirectory(); cfg.Build.ProjectFile = (Func <string>)(() => GetBuildProjectFile(workingDirectory)); cfg.Test.Skip = false; cfg.Test.ProjectFile = (Func <string>)(() => GetBuildProjectFile(workingDirectory)); cfg.Test.Logger = "trx";
/// <summary> /// Registers a task that performs final setup of configuration after all plugin-specific /// config tasks have been run. /// <para/> /// This includes: /// 1. Runs all configuration lambdas from the <c>ConfigureTask</c> methods in the /// build.cake file. /// 2. Override configurations with any matching values from the environment. /// 3. Override configurations with any matching values from the command line. /// </summary> /// <param name="envTasks">List of all plugin tasks for the current CI environment.</param> private void RegisterConfigTask(IReadOnlyList <RegisteredTask> envTasks) { CakeTaskBuilder task = RegisterTask(TaskNames.Config) .Description("Finalizes configurations and displays final configuration values."); // Create dependency on all plugin configuration tasks. IEnumerable <RegisteredTask> configTasks = envTasks .Where(t => t.AttributeType == typeof(ConfigAttribute)) .OrderBy(t => t.Order); foreach (RegisteredTask configTask in configTasks) { task.IsDependentOn(configTask.Name); } task.Does(ctx => { TaskConfig config = TaskConfig.Current; // Run configurations specified in the build.cake file config.PerformDeferredSetup(); // Override configurations from environment variables IDictionary <string, string> envVars = ctx.Environment.GetEnvironmentVariables(); foreach (KeyValuePair <string, string> envVar in envVars) { if (config.Data.ContainsKey(envVar.Key)) { config.Data[envVar.Key] = envVar.Value; } } // Override configurations from command line arguments var keys = config.Data.Keys.ToList(); foreach (string key in keys) { if (ctx.Arguments.HasArgument(key)) { config.Data[key] = ctx.Arguments.GetArgument(key); } } // Display the final configuration values ctx.LogHighlight("Final Configurations"); ctx.LogHighlight("--------------------"); foreach (KeyValuePair <string, object> data in config.Data.OrderBy(kvp => kvp.Key)) { ctx.LogHighlight($"{data.Key} = {data.Value?.Dump() ?? "[NULL]"}"); } EnvConfig env = config.Load <EnvConfig>(); // Clean out output directories or create them //TODO: Can these directories be created on-demand? For some project types like Angular, //these folders are ignored and the dist folder is used. ctx.EnsureDirectoryExists(env.Directories.Artifacts); ctx.EnsureDirectoryExists(env.Directories.BinaryOutput); ctx.EnsureDirectoryExists(env.Directories.TestOutput); }); }
private static void PublishNuGet(ICakeContext ctx, TaskConfig cfg, NuGetPublisher nuget) { EnvConfig env = cfg.Load <EnvConfig>(); ctx.DotNetCorePack(nuget.ProjectFile, new DotNetCorePackSettings { Configuration = env.Configuration, OutputDirectory = nuget.OutputLocation, Verbosity = ctx.Log.Verbosity.ToVerbosity(), ArgumentCustomization = arg => { arg.Append($"/p:Version={env.Version.Build}"); if (nuget.PublishAsSnupkg) { arg.Append("/p:SymbolPackageFormat=snupkg"); } return(arg); }, IncludeSource = true, IncludeSymbols = true, }); IEnumerable <string> packageFiles = Directory.EnumerateFiles(nuget.OutputLocation, nuget.PublishAsSnupkg ? "*.snupkg" : "*.nupkg"); foreach (string packageFile in packageFiles) { ctx.DotNetCoreNuGetPush(packageFile, new DotNetCoreNuGetPushSettings { Source = nuget.Source(env.Branch), ApiKey = nuget.ApiKey?.Invoke(env.Branch), }); } }
public static void PublishDotNetProjects(ICakeContext ctx, TaskConfig config) { EnvConfig env = config.Load <EnvConfig>(); IList <DotNetCorePublisher> publishers = env.Publishers.OfType <DotNetCorePublisher>().ToList(); if (publishers.Count == 0) { ctx.LogInfo("No .NET Core projects to publish. Specify a publisher."); } foreach (DotNetCorePublisher publisher in publishers) { string publishDirectory = Path.Combine(env.Directories.PublishOutput, publisher.GetType().Name + Guid.NewGuid().ToString("N")); if (!Directory.Exists(publishDirectory)) { Directory.CreateDirectory(publishDirectory); } publisher.SetOutput(publishDirectory); switch (publisher) { case AspNetCorePublisher aspnet: PublishAspNetCore(ctx, config, aspnet); break; case NuGetPublisher nuget: DotNetCoreConfig dnc = config.Load <DotNetCoreConfig>(); if (nuget.Source is null) { nuget.Source = dnc.NuGetPublisher.SourceFn; } if (nuget.Source is null) { nuget.Source = _ => "https: //api.nuget.org/v3/index.json"; } if (nuget.ApiKey is null) { nuget.ApiKey = dnc.NuGetPublisher.ApiKeyFn; } PublishNuGet(ctx, config, nuget); break; default: throw new TaskConfigException($"Unrecognized .NET Core publisher type: {publisher.GetType().FullName}."); } } }
private void InitializeConfiguration() { // Setup action to initialize some really core stuff, including directories and version // details. RegisterSetupAction(ctx => { Log.Verbose("Initializing Cake.Tasks configuration."); TaskConfig config = TaskConfig.Current; EnvConfig env = config.Load <EnvConfig>(); env.Name = Path.GetFileName(ctx.Environment.WorkingDirectory.FullPath) .Replace('.', '-') .Replace(' ', '-') .Replace('_', '-') .Trim(); env.Configuration = ctx.Arguments.GetArgument("Configuration") ?? "Release"; env.IsCi = false; env.Branch = null; env.Directories.Working = ctx.Environment.WorkingDirectory.FullPath; string outputDirectory = Path.Combine(env.Directories.Working, ".ci"); env.Directories.Artifacts = Path.Combine(outputDirectory, "artifacts"); env.Directories.BinaryOutput = Path.Combine(outputDirectory, "binaries"); env.Directories.PublishOutput = Path.Combine(outputDirectory, "publish"); env.Directories.TestOutput = Path.Combine(outputDirectory, "testresults"); env.Version.BuildNumber = "1"; env.Version.Primary = (Func <string>)(() => $"0.{env.Version.BuildNumber.Resolve()}.0"); env.Version.Full = (Func <string>)(() => env.Version.Primary.Resolve()); env.Version.Build = (Func <string>)(() => $"{env.Version.Full.Resolve()}+{env.Version.BuildNumber.Resolve()}"); // Display the subdirectories under the tools/Addins directory. // To verify the versions of the addins and tools installed. // Useful for troubleshooting. //TODO: Make this a configuration ctx.LogHighlight("--------------------"); ctx.LogHighlight("Addin subdirectories"); ctx.LogHighlight("--------------------"); string addinsBaseDir = Path.Combine(env.Directories.Working, "tools", "Addins"); if (Directory.Exists(addinsBaseDir)) { IEnumerable <string> addinsDirs = AddinFinder.Find(addinsBaseDir); IEnumerable <string> otherDirs = Directory.EnumerateDirectories(addinsBaseDir, "*", SearchOption.TopDirectoryOnly) .Except(addinsDirs, StringComparer.OrdinalIgnoreCase); foreach (string addinsDir in addinsDirs) { ctx.LogHighlight(Path.GetFileName(addinsDir)); } foreach (string otherDir in otherDirs) { ctx.Log.Information(Path.GetFileName(otherDir)); } } return(config); }); }
private static void PublishAspNetCore(ICakeContext ctx, TaskConfig cfg, AspNetCorePublisher publisher) { EnvConfig env = cfg.Load <EnvConfig>(); ctx.DotNetCorePublish(publisher.ProjectFile, new DotNetCorePublishSettings { Configuration = env.Configuration, OutputDirectory = publisher.OutputLocation, Verbosity = ctx.Log.Verbosity.ToVerbosity(), ArgumentCustomization = arg => arg.Append($"/p:Version={env.Version.Build}"), }); }
public static void BuildDotNetCoreSolution(ICakeContext context, TaskConfig config) { DotNetCoreConfig.BuildConfig build = config.Load <DotNetCoreConfig>().Build; string buildProjectFile = build.ProjectFile; if (buildProjectFile is null) { throw new TaskConfigException("Build solution or project file not specified."); } EnvConfig env = config.Load <EnvConfig>(); string outputDirectory = Path.Combine(env.Directories.BinaryOutput, "__build"); context.DotNetCoreBuild(buildProjectFile, new DotNetCoreBuildSettings { OutputDirectory = outputDirectory, Configuration = env.Configuration, Verbosity = context.Log.Verbosity.ToVerbosity(), }); }
public static void ConfigureGitVersion(ICakeContext ctx, TaskConfig cfg) { // Update the GitVersion config GitVersionConfig gitVersion = cfg.Load <GitVersionConfig>(); Common.Tools.GitVersion.GitVersion version = ctx.GitVersion(); gitVersion.Version = version; EnvConfig env = cfg.Load <EnvConfig>(); // Update branch name env.Branch = version.BranchName; // Update primary and full versions env.Version.Primary = version.MajorMinorPatch; env.Version.Full = version.SemVer; // Update build number env.Version.BuildNumber = version.CommitsSinceVersionSource.HasValue ? version.CommitsSinceVersionSource.Value.ToString() : version.BuildMetaData; }
public static void SetDirectoryPublisherOutputs(ICakeContext ctx, TaskConfig cfg) { EnvConfig env = cfg.Load <EnvConfig>(); var directoryPublishers = env.Publishers.OfType <DirectoryPublisher>().ToList(); foreach (DirectoryPublisher publisher in directoryPublishers) { publisher.ValidateDirectory(); string directory = Path.Combine(env.Directories.Working, publisher.Directory); publisher.SetOutput(directory); } }
public static void ConfigureProjectNameFromGitRepoUrl(ICakeContext ctx, TaskConfig cfg) { EnvConfig env = cfg.Load <EnvConfig>(); string gitDir = Path.Combine(env.Directories.Working, ".git"); if (!Directory.Exists(gitDir)) { ctx.LogInfo($"Working directory '{env.Directories.Working}' is not a Git repository. Cannot calculate project name from it."); return; } string fetchHeadFile = Path.Combine(gitDir, "FETCH_HEAD"); if (!File.Exists(fetchHeadFile)) { ctx.LogInfo("Cannot retrieve remote URL for current repo."); return; } using StreamReader reader = File.OpenText(fetchHeadFile); string firstLine = reader.ReadLine(); Match match = RemoteUrlPattern.Match(firstLine); if (!match.Success) { ctx.LogInfo("Cannot retrieve remote URL for current repo."); return; } string matchedRemoteUri = match.Groups[1].Value; if (!Uri.TryCreate(matchedRemoteUri, UriKind.Absolute, out Uri remoteUri)) { ctx.LogInfo("Cannot retrieve remote URL for current repo."); return; } const string ignoreExtension = ".git"; string lastSegment = remoteUri.Segments[remoteUri.Segments.Length - 1]; if (lastSegment.EndsWith(ignoreExtension, StringComparison.OrdinalIgnoreCase)) { lastSegment = lastSegment.Substring(0, lastSegment.Length - ignoreExtension.Length); } ctx.LogInfo($"Setting project name to {lastSegment}."); env.Name = lastSegment; }
public static void ConfigureAppVeyorEnvironment(ICakeContext ctx, TaskConfig cfg) { IAppVeyorProvider appveyor = ctx.AppVeyor(); if (!appveyor.IsRunningOnAppVeyor) { throw new TaskConfigException("Not running in AppVeyor"); } EnvConfig env = cfg.Load <EnvConfig>(); env.IsCi = true; env.Version.BuildNumber = appveyor.Environment.Build.Number.ToString(); env.Version.Build = $"{env.Version.Primary}-build.{env.Version.BuildNumber}"; }
public static void ConfigureTfsEnvironment(ICakeContext ctx, TaskConfig cfg) { IAzurePipelinesProvider azurePipelines = ctx.AzurePipelines(); ctx.LogInfo(azurePipelines.Dump()); //if (!azurePipelines.IsRunningOnAzurePipelines || !azurePipelines.IsRunningOnAzurePipelinesHosted) // throw new TaskConfigException("Not running in Azure Pipelines"); EnvConfig env = cfg.Load <EnvConfig>(); env.IsCi = true; // If the build number is configured as an integer, use it. Otherwise use the build ID. // Basically, we need something unique. env.Version.BuildNumber = azurePipelines.Environment.Build.Number; }
public static void CleanDotNetCoreSolution(ICakeContext context, TaskConfig config) { context.LogInfo("Shutting down .NET Core build server"); context.DotNetCoreBuildServerShutdown(); DotNetCoreConfig cfg = config.Load <DotNetCoreConfig>(); string cleanProjectFile = cfg.Build.ProjectFile.Resolve(); if (cleanProjectFile is null) { throw new TaskConfigException("Build solution or project file not specified."); } context.DotNetCoreClean(cleanProjectFile, new DotNetCoreCleanSettings { Verbosity = context.Log.Verbosity.ToVerbosity(), }); }