diff --git a/.build/Build.CI.cs b/.build/Build.CI.cs index a44b8ebbb..a4627e56f 100644 --- a/.build/Build.CI.cs +++ b/.build/Build.CI.cs @@ -1,5 +1,6 @@ using Nuke.Common; using Nuke.Common.CI.GitHubActions; + using Rocket.Surgery.Nuke.ContinuousIntegration; using Rocket.Surgery.Nuke.GithubActions; using Rocket.Surgery.Nuke.Jobs; @@ -87,7 +88,7 @@ public static RocketSurgeonGitHubActionsConfiguration CiIgnoreMiddleware(RocketS .ProducesGithubActionsOutput("iSetAThing", "Some output value") .Requires(() => ThisIsAInput) .Executes(() => GitHubActions.Instance?.SetOutput("iSetAThing", "myValue")); - #pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. +#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. [Parameter] public string ThisIsAInput { get; set; } @@ -124,8 +125,8 @@ public static RocketSurgeonGitHubActionsConfiguration CiMiddleware(RocketSurgeon .ExcludeRepositoryConfigurationFiles() .Jobs.OfType() .First(z => z.Name.Equals("Build", StringComparison.OrdinalIgnoreCase)) - .UseDotNetSdks("8.0", "9.0") - // .ConfigureForGitVersion() + .UseDotNetSdks("8.0", "9.0", "10.0") + // .ConfigureForGitVersion() .ConfigureStep(step => step.FetchDepth = 0) .PublishLogs(); @@ -137,7 +138,7 @@ public static RocketSurgeonGitHubActionsConfiguration LintStagedMiddleware(Rocke configuration .Jobs.OfType() .First(z => z.Name.Equals("Build", StringComparison.OrdinalIgnoreCase)) - .UseDotNetSdks("8.0", "9.0"); + .UseDotNetSdks("8.0", "9.0", "10.0"); return configuration; } diff --git a/.build/Build.cs b/.build/Build.cs index 69d857a1c..8df650dff 100644 --- a/.build/Build.cs +++ b/.build/Build.cs @@ -28,7 +28,7 @@ internal partial class Pipeline : NukeBuild, ICanClean, IHaveCommonLintTargets, IRemoveUnusedDependencies, - IHavePublicApis, + // IHavePublicApis, IGenerateCodeCoverageReport, IGenerateCodeCoverageSummary, IGenerateCodeCoverageBadges, diff --git a/.build/Configuration.cs b/.build/Configuration.cs index 45ad73057..c007289ce 100644 --- a/.build/Configuration.cs +++ b/.build/Configuration.cs @@ -1,4 +1,5 @@ using System.ComponentModel; + using Nuke.Common.Tooling; #pragma warning disable CA1050, CA1724, CA2225 @@ -6,8 +7,7 @@ [TypeConverter(typeof(TypeConverter))] public class Configuration : Enumeration { + public static implicit operator string(Configuration configuration) => configuration.Value; public static readonly Configuration Debug = new() { Value = nameof(Debug) }; public static readonly Configuration Release = new() { Value = nameof(Release) }; - - public static implicit operator string(Configuration configuration) => configuration.Value; } diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 6bfe6f5c8..221011053 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -3,12 +3,12 @@ "isRoot": true, "tools": { "gitversion.tool": { - "version": "6.3.0", + "version": "6.4.0", "commands": ["dotnet-gitversion"], "rollForward": false }, "dotnet-reportgenerator-globaltool": { - "version": "5.4.8", + "version": "5.4.12", "commands": ["reportgenerator"], "rollForward": false }, @@ -23,17 +23,17 @@ "rollForward": false }, "jetbrains.resharper.globaltools": { - "version": "2024.3.8", + "version": "2025.2.1", "commands": ["jb"], "rollForward": false }, "jetbrains.dotcover.commandlinetools": { - "version": "2024.3.8", - "commands": ["dotnet-dotCover"], + "version": "2025.2.1", + "commands": ["dotCover"], "rollForward": false }, "jetbrains.dottrace.globaltools": { - "version": "2024.3.8", + "version": "2025.2.1", "commands": ["dottrace"], "rollForward": false }, @@ -58,7 +58,7 @@ "rollForward": false }, "gitreleasemanager.tool": { - "version": "0.18.0", + "version": "0.20.0", "commands": ["dotnet-gitreleasemanager"], "rollForward": false } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a72a82140..07844f664 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -121,6 +121,10 @@ jobs: uses: actions/setup-dotnet@v4.3.1 with: dotnet-version: '9.0.x' + - name: 🔨 Use .NET Core 10.0 SDK + uses: actions/setup-dotnet@v4.3.1 + with: + dotnet-version: '10.0.x' - name: 🚒 dotnet workload restore continue-on-error: true run: | diff --git a/.github/workflows/close-milestone.yml b/.github/workflows/close-milestone.yml index 95f5c7a19..daec4e66a 100644 --- a/.github/workflows/close-milestone.yml +++ b/.github/workflows/close-milestone.yml @@ -78,7 +78,7 @@ jobs: - name: 📲 Install GitReleaseManager uses: gittools/actions/gitreleasemanager/setup@v3.2.1 with: - versionSpec: '0.18.0' + versionSpec: '0.20.0' - name: Get Repo and Owner id: repository if: ${{ !github.event.release.prerelease && steps.gitversion.outputs.preReleaseTag == '' }} diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index f615b7648..3c452ca13 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -67,6 +67,10 @@ jobs: uses: actions/setup-dotnet@v4 with: dotnet-version: '9.0.x' + - name: 🔨 Use .NET Core 10.0 SDK + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' - name: 🚒 dotnet workload restore continue-on-error: true run: | @@ -82,14 +86,6 @@ jobs: id: lintFiles run: | dotnet .build/bin/Debug/.build.dll --target LintFiles --skip Restore --ThisIsAOtherVariable "${{ vars.THIS_IS_A_VARIABLE }}" --ThisIsAnotherVariable "${{ vars.THIS_IS_ANOTHER_VARIABLE }}" --THIS_IS_A_VARIABLE "${{ vars.THIS_IS_A_VARIABLE }}" --ThisIsAEnv "${{ env.THIS_IS_A_ENV || 'test' }}" --ThisIsASecret "${{ secrets.THIS_IS_A_SECRET }}" --GitHubToken "${{ secrets.GITHUB_TOKEN }}" - - name: Lint Public Api Analyzers - id: lintPublicApiAnalyzers - run: | - dotnet .build/bin/Debug/.build.dll --target LintPublicApiAnalyzers --ThisIsAOtherVariable "${{ vars.THIS_IS_A_VARIABLE }}" --ThisIsAnotherVariable "${{ vars.THIS_IS_ANOTHER_VARIABLE }}" --THIS_IS_A_VARIABLE "${{ vars.THIS_IS_A_VARIABLE }}" --ThisIsAEnv "${{ env.THIS_IS_A_ENV || 'test' }}" --ThisIsASecret "${{ secrets.THIS_IS_A_SECRET }}" --GitHubToken "${{ secrets.GITHUB_TOKEN }}" - - name: Move Unshipped to Shipped - id: moveUnshippedToShipped - run: | - dotnet .build/bin/Debug/.build.dll --target MoveUnshippedToShipped --skip LintPublicApiAnalyzers --ThisIsAOtherVariable "${{ vars.THIS_IS_A_VARIABLE }}" --ThisIsAnotherVariable "${{ vars.THIS_IS_ANOTHER_VARIABLE }}" --THIS_IS_A_VARIABLE "${{ vars.THIS_IS_A_VARIABLE }}" --ThisIsAEnv "${{ env.THIS_IS_A_ENV || 'test' }}" --ThisIsASecret "${{ secrets.THIS_IS_A_SECRET }}" --GitHubToken "${{ secrets.GITHUB_TOKEN }}" - name: Remove Unused Dependencies id: removeUnusedDependencies run: | diff --git a/.nuke/build.schema.json b/.nuke/build.schema.json index 1b9ee94d8..2645dbde4 100644 --- a/.nuke/build.schema.json +++ b/.nuke/build.schema.json @@ -46,15 +46,12 @@ "Lint", "LintFiles", "LintGitAdd", - "LintPublicApiAnalyzers", - "MoveUnshippedToShipped", "Pack", "PostLint", "Prettier", "RegenerateBuildConfigurations", "RemoveUnusedDependencies", "Restore", - "ShipPublicApis", "Test", "WithOutputs" ] diff --git a/Directory.Packages.props b/Directory.Packages.props index 89b0fa480..9b0e2dc98 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -10,30 +10,30 @@ - - + + - - - - - + + + + + - + - - + + - - - - - + + + + + - - + + @@ -42,18 +42,18 @@ - + - + - + - + ( argumentFormat = argumentFormat.Replace("{value}", "{0}"); - string Format(T value) - { - return value.ToString().DoubleQuoteIfNeeded(separator, disallowed, Space); - } + string Format(T value) => value.ToString().DoubleQuoteIfNeeded(separator, disallowed, Space); AddInternal( argumentFormat, separator.HasValue ? [FormatMultiple(list, Format, separator.Value, quoteMultiple)] - : list.Select(Format).ToArray() + : [.. list.Select(Format)] ); return this; @@ -77,17 +75,11 @@ public Arguments Add( var keyValueSeparator = itemFormat.Replace("{key}", "").Replace("{value}", ""); Assert.True(keyValueSeparator.Length == 1); - string Format(object value) - { - return value.ToString().DoubleQuoteIfNeeded(separator, keyValueSeparator.Single(), disallowed, Space); - } + string Format(object value) => value.ToString().DoubleQuoteIfNeeded(separator, keyValueSeparator.Single(), disallowed, Space); - string FormatPair(KeyValuePair pair) - { - return itemFormat - .Replace("{key}", Format(pair!.Key)) - .Replace("{value}", Format(pair!.Value)); - } + string FormatPair(KeyValuePair pair) => itemFormat + .Replace("{key}", Format(pair!.Key)) + .Replace("{value}", Format(pair!.Value)); var pairs = dictionary.Where(x => x.Value is { }).ToList(); @@ -95,7 +87,7 @@ string FormatPair(KeyValuePair pair) argumentFormat, separator.HasValue ? [FormatMultiple(pairs, FormatPair, separator.Value, quoteMultiple)] - : pairs.Select(FormatPair).ToArray() + : [.. pairs.Select(FormatPair)] ); return this; @@ -116,17 +108,11 @@ public Arguments Add( var listSeparator = itemFormat.Replace("{key}", "").Replace("{value}", ""); Assert.True(listSeparator.Length == 1); - string Format(object value) - { - return value?.ToString().DoubleQuoteIfNeeded(separator, listSeparator.Single(), disallowed, Space); - } + string Format(object value) => value?.ToString().DoubleQuoteIfNeeded(separator, listSeparator.Single(), disallowed, Space); - string FormatLookup(TKey key, string values) - { - return itemFormat - .Replace("{key}", Format(key!)) - .Replace("{value}", values); - } + string FormatLookup(TKey key, string values) => itemFormat + .Replace("{key}", Format(key!)) + .Replace("{value}", values); foreach (var list in lookup) { @@ -134,7 +120,7 @@ string FormatLookup(TKey key, string values) argumentFormat, separator.HasValue ? [FormatLookup(list.Key, FormatMultiple(list, x => Format(x!), separator.NotNull().Value, quoteMultiple))] - : list.Select(x => FormatLookup(list.Key, Format(x!))).ToArray() + : [.. list.Select(x => FormatLookup(list.Key, Format(x!)))] ); } @@ -187,12 +173,9 @@ private string FormatMultiple(IEnumerable items, Func format, c private string Render(bool forOutput) { - string Format(string argument) - { - return !_secrets.Contains(argument) || !forOutput - ? argument - : Redacted; - } + string Format(string argument) => !_secrets.Contains(argument) || !forOutput + ? argument + : Redacted; var builder = new StringBuilder(); foreach (var argumentPair in _arguments) diff --git a/src/Nuke/Azp/AzurePipelinesParameter.cs b/src/Nuke/Azp/AzurePipelinesParameter.cs index 0ed0373e0..2f8cfeafb 100644 --- a/src/Nuke/Azp/AzurePipelinesParameter.cs +++ b/src/Nuke/Azp/AzurePipelinesParameter.cs @@ -8,6 +8,12 @@ namespace Rocket.Surgery.Nuke.Azp; /// public class AzurePipelinesParameter : ConfigurationEntity { + /// + public override void Write(CustomFileWriter writer) + { + using var a = writer.WriteBlock($"{Name}: '{Default}'"); + } + // ReSharper disable once NullableWarningSuppressionIsUsed /// /// The parameter name @@ -19,10 +25,4 @@ public class AzurePipelinesParameter : ConfigurationEntity /// The default name /// public string Default { get; set; } = null!; - - /// - public override void Write(CustomFileWriter writer) - { - using var a = writer.WriteBlock($"{Name}: '{Default}'"); - } } diff --git a/src/Nuke/Azp/AzurePipelinesStep.cs b/src/Nuke/Azp/AzurePipelinesStep.cs index 35069818a..46d9ea10e 100644 --- a/src/Nuke/Azp/AzurePipelinesStep.cs +++ b/src/Nuke/Azp/AzurePipelinesStep.cs @@ -8,6 +8,21 @@ namespace Rocket.Surgery.Nuke.Azp; /// public class AzurePipelinesStep { + /// + /// Write the pipelines step + /// + /// + /// + public void Write(CustomFileWriter writer, string parameters) + { + using (writer.WriteBlock( + $"- pwsh: {ScriptPath} {InvokedTargets.JoinSpace()} --skip {parameters}".TrimEnd() + )) + { + writer.WriteLine($"displayName: {DisplayName.SingleQuote()}"); + } + } + /// /// The step name /// @@ -27,19 +42,4 @@ public class AzurePipelinesStep /// The targets to invoke /// public IEnumerable InvokedTargets { get; set; } = Array.Empty(); - - /// - /// Write the pipelines step - /// - /// - /// - public void Write(CustomFileWriter writer, string parameters) - { - using (writer.WriteBlock( - $"- pwsh: {ScriptPath} {InvokedTargets.JoinSpace()} --skip {parameters}".TrimEnd() - )) - { - writer.WriteLine($"displayName: {DisplayName.SingleQuote()}"); - } - } } diff --git a/src/Nuke/Azp/AzurePipelinesSteps.cs b/src/Nuke/Azp/AzurePipelinesSteps.cs index a0fc0c3da..c874ae3f8 100644 --- a/src/Nuke/Azp/AzurePipelinesSteps.cs +++ b/src/Nuke/Azp/AzurePipelinesSteps.cs @@ -16,6 +16,7 @@ public override void Write(CustomFileWriter writer) { writer.WriteLine("#"); if (Parameters.Count > 0) + { using (writer.WriteBlock("parameters:")) { foreach (var item in Parameters) @@ -23,15 +24,16 @@ public override void Write(CustomFileWriter writer) item.Write(writer); } } + } using (writer.WriteBlock("steps:")) { - #pragma warning disable CA1308 +#pragma warning disable CA1308 var parameters = Parameters .Select(z => $"--{z.Name.ToLowerInvariant()} '${{{{ parameters.{z.Name} }}}}'") .ToArray() .JoinSpace(); - #pragma warning restore CA1308 +#pragma warning restore CA1308 foreach (var step in Steps) { diff --git a/src/Nuke/AzurePipelinesStepsAttribute.cs b/src/Nuke/AzurePipelinesStepsAttribute.cs index 9116ebda5..5ed86cc64 100644 --- a/src/Nuke/AzurePipelinesStepsAttribute.cs +++ b/src/Nuke/AzurePipelinesStepsAttribute.cs @@ -1,9 +1,11 @@ using System.Reflection; + using Nuke.Common.CI; using Nuke.Common.CI.AzurePipelines; using Nuke.Common.Execution; using Nuke.Common.IO; using Nuke.Common.Utilities.Collections; + using Rocket.Surgery.Nuke.Azp; #pragma warning disable CA1813 @@ -63,7 +65,7 @@ IReadOnlyCollection relevantTargets var lookupTable = new LookupTable(); var steps = relevantTargets - .Select(x => ( ExecutableTarget: x, Job: GetStep(x, relevantTargets, lookupTable) )) + .Select(x => (ExecutableTarget: x, Job: GetStep(x, relevantTargets, lookupTable))) .ForEachLazy(x => lookupTable.Add(x.ExecutableTarget, x.Job)) .Select(x => x.Job) .ToArray(); diff --git a/src/Nuke/ComputedGitVersionAttribute.cs b/src/Nuke/ComputedGitVersionAttribute.cs index 877b55fe3..b7fa33ac7 100644 --- a/src/Nuke/ComputedGitVersionAttribute.cs +++ b/src/Nuke/ComputedGitVersionAttribute.cs @@ -1,7 +1,9 @@ using System.Reflection; + using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; + using Nuke.Common.CI.AppVeyor; using Nuke.Common.CI.AzurePipelines; using Nuke.Common.CI.TeamCity; @@ -9,6 +11,7 @@ using Nuke.Common.Tooling; using Nuke.Common.Tools.GitVersion; using Nuke.Common.ValueInjection; + using Serilog; using static Nuke.Common.EnvironmentInfo; @@ -28,12 +31,6 @@ namespace Rocket.Surgery.Nuke; [ExcludeFromCodeCoverage] public class ComputedGitVersionAttribute(string? frameworkVersion) : ValueInjectionAttributeBase { - /// - /// Computes the GitVersion for the repository. - /// - public ComputedGitVersionAttribute() - : this(null) { } - /// public override object GetValue(MemberInfo member, object instance) { @@ -103,6 +100,12 @@ public override object GetValue(MemberInfo member, object instance) /// public bool UpdateAssemblyInfo { get; set; } + /// + /// Computes the GitVersion for the repository. + /// + public ComputedGitVersionAttribute() + : this(null) { } + private class AllWritableContractResolver : DefaultContractResolver { protected override JsonProperty CreateProperty( @@ -119,6 +122,7 @@ MemberSerialization memberSerialization internal static GitVersion GetGitVersion(string? frameworkVersion, bool updateAssemblyInfo) { if (!HasGitVer()) + { return GitVersionTasks.GitVersion( s => s .SetFramework(frameworkVersion) @@ -133,6 +137,7 @@ internal static GitVersion GetGitVersion(string? frameworkVersion, bool updateAs ) ) .Result; + } var json = Variables .Where(z => z.Key.StartsWith("GITVERSION_", StringComparison.OrdinalIgnoreCase)) diff --git a/src/Nuke/Constants.cs b/src/Nuke/Constants.cs index 588240a7b..f9c619dda 100644 --- a/src/Nuke/Constants.cs +++ b/src/Nuke/Constants.cs @@ -3,30 +3,30 @@ namespace Rocket.Surgery.Nuke; internal static class Constants { public const string ReportGeneratorFramework = - #if NET8_0_OR_GREATER +#if NET8_0_OR_GREATER "net8.0" - #elif NET7_0_OR_GREATER +#elif NET7_0_OR_GREATER "net7.0" - #elif NET6_0_OR_GREATER +#elif NET6_0_OR_GREATER "net6.0" - #elif NET5_0_OR_GREATER +#elif NET5_0_OR_GREATER "net5.0" - #else +#else "netcoreapp3.1" - #endif +#endif ; public const string GitVersionFramework = - #if NET8_0_OR_GREATER +#if NET8_0_OR_GREATER "net8.0" - #elif NET7_0_OR_GREATER +#elif NET7_0_OR_GREATER "net7.0" - #elif NET6_0_OR_GREATER +#elif NET6_0_OR_GREATER "net6.0" - #elif NET5_0_OR_GREATER +#elif NET5_0_OR_GREATER "net5.0" - #else +#else "netcoreapp3.1" - #endif +#endif ; } diff --git a/src/Nuke/ContinuousIntegration/ICIEnvironment.cs b/src/Nuke/ContinuousIntegration/ICIEnvironment.cs index c269b0ab2..3fd37509c 100644 --- a/src/Nuke/ContinuousIntegration/ICIEnvironment.cs +++ b/src/Nuke/ContinuousIntegration/ICIEnvironment.cs @@ -15,7 +15,7 @@ public interface ICIEnvironment : IHaveBuildVersion /// /// Replace default implementation to add values not covered by default /// - public IEnumerable WellKnownEnvironmentVariablePrefixes => new[] + IEnumerable WellKnownEnvironmentVariablePrefixes => new[] { // Azure pipelines "CIRCLE", "GITHUB", "APPVEYOR", "TRAVIS", "BITRISE", "BAMBOO", "GITLAB", "JENKINS", "TEAMCITY", @@ -26,23 +26,23 @@ public interface ICIEnvironment : IHaveBuildVersion /// Prints CI environment state for debug purposes /// [NonEntryTarget] - public Target CIEnvironment => d => d - .Unlisted() - .OnlyWhenStatic(() => NukeBuild.IsServerBuild) - .Executes( - () => - { - Log.Information("CI: {CI}", EnvironmentInfo.GetVariable("CI")); - - foreach (var variable in WellKnownEnvironmentVariablePrefixes - .SelectMany( - prefix => EnvironmentInfo.Variables.Keys.Where( - key => key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) - ) - )) + Target CIEnvironment => d => d + .Unlisted() + .OnlyWhenStatic(() => NukeBuild.IsServerBuild) + .Executes( + () => { - Log.Information("{Key}: {Value}", variable, EnvironmentInfo.Variables[variable]); + Log.Information("CI: {CI}", EnvironmentInfo.GetVariable("CI")); + + foreach (var variable in WellKnownEnvironmentVariablePrefixes + .SelectMany( + prefix => EnvironmentInfo.Variables.Keys.Where( + key => key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) + ) + )) + { + Log.Information("{Key}: {Value}", variable, EnvironmentInfo.Variables[variable]); + } } - } - ); + ); } diff --git a/src/Nuke/ContinuousIntegration/PrintBuildVersionAttribute.cs b/src/Nuke/ContinuousIntegration/PrintBuildVersionAttribute.cs index e0615da5e..614d78b83 100644 --- a/src/Nuke/ContinuousIntegration/PrintBuildVersionAttribute.cs +++ b/src/Nuke/ContinuousIntegration/PrintBuildVersionAttribute.cs @@ -1,4 +1,5 @@ using Nuke.Common.Execution; + using Serilog; // ReSharper disable SuspiciousTypeConversion.Global @@ -19,7 +20,7 @@ public void OnBuildInitialized( IReadOnlyCollection executionPlan ) { - if (Build is not (IHaveGitVersion gitVersion and IHaveSolution solution and IHaveConfiguration configuration)) return; + if (Build is not ( IHaveGitVersion gitVersion and IHaveSolution solution and IHaveConfiguration configuration )) return; Log.Logger.Information( "Building version {InformationalVersion} of {SolutionName} ({Configuration}) using version {NukeVersion} of Nuke", diff --git a/src/Nuke/ContinuousIntegration/PrintCIEnvironmentAttribute.cs b/src/Nuke/ContinuousIntegration/PrintCIEnvironmentAttribute.cs index 27c1e872d..ea0642ca3 100644 --- a/src/Nuke/ContinuousIntegration/PrintCIEnvironmentAttribute.cs +++ b/src/Nuke/ContinuousIntegration/PrintCIEnvironmentAttribute.cs @@ -4,6 +4,7 @@ using Nuke.Common.CI.TeamCity; using Nuke.Common.Execution; using Nuke.Common.Utilities.Collections; + using Serilog; // ReSharper disable InconsistentNaming diff --git a/src/Nuke/DotNetCore/ICanBuildWithDotNetCore.cs b/src/Nuke/DotNetCore/ICanBuildWithDotNetCore.cs index c9243c145..e45280fcc 100644 --- a/src/Nuke/DotNetCore/ICanBuildWithDotNetCore.cs +++ b/src/Nuke/DotNetCore/ICanBuildWithDotNetCore.cs @@ -19,21 +19,21 @@ public interface ICanBuildWithDotNetCore : IHaveRestoreTarget, /// dotnet build /// [NonEntryTarget] - public Target DotnetCoreBuild => d => d - .Description("Builds all the projects.") - .Unlisted() - .TryDependentFor(a => a.Build) - .TryAfter(a => a.Restore) - .Net9MsBuildFix() - .Executes( - () => DotNetTasks.DotNetBuild( - s => s - .SetProcessWorkingDirectory(RootDirectory) - .SetProjectFile(Solution) - .SetDefaultLoggers(LogsDirectory / "build.log") - .SetGitVersionEnvironment(GitVersion) - .SetConfiguration(Configuration) - .EnableNoRestore() - ) - ); + Target DotnetCoreBuild => d => d + .Description("Builds all the projects.") + .Unlisted() + .TryDependentFor(a => a.Build) + .TryAfter(a => a.Restore) + .Net9MsBuildFix() + .Executes( + () => DotNetTasks.DotNetBuild( + s => s + .SetProcessWorkingDirectory(RootDirectory) + .SetProjectFile(Solution) + .SetDefaultLoggers(LogsDirectory / "build.log") + .SetGitVersionEnvironment(GitVersion) + .SetConfiguration(Configuration) + .EnableNoRestore() + ) + ); } diff --git a/src/Nuke/DotNetCore/ICanDotNetFormat.cs b/src/Nuke/DotNetCore/ICanDotNetFormat.cs index d0a6e1d94..758f843d8 100644 --- a/src/Nuke/DotNetCore/ICanDotNetFormat.cs +++ b/src/Nuke/DotNetCore/ICanDotNetFormat.cs @@ -16,7 +16,7 @@ public interface ICanDotNetFormat : IHaveSolution, ICanLint, IHaveOutputLogs /// /// The dotnet format target /// - public Target DotnetFormat => + Target DotnetFormat => d => d .TriggeredBy(Lint) .Before(PostLint) @@ -55,35 +55,37 @@ public interface ICanDotNetFormat : IHaveSolution, ICanLint, IHaveOutputLogs } } else + { DotNetTasks.DotNetFormat(formatSettings); + } } ); /// /// A list of diagnostic ids to exclude from the dotnet format /// - public HashSet DotNetFormatExcludedDiagnostics => _dotNetFormatExcludedDiagnostics; + HashSet DotNetFormatExcludedDiagnostics => _dotNetFormatExcludedDiagnostics; /// /// A list of diagnostic ids to include in the dotnet format /// - public HashSet? DotNetFormatIncludedDiagnostics => _dotNetFormatIncludedDiagnostics; + HashSet? DotNetFormatIncludedDiagnostics => _dotNetFormatIncludedDiagnostics; /// /// The default matcher for jetbrains cleanup code /// - public Matcher DotnetFormatMatcher => dnfMatcher ??= new Matcher(StringComparison.OrdinalIgnoreCase) + Matcher DotnetFormatMatcher => dnfMatcher ??= new Matcher(StringComparison.OrdinalIgnoreCase) .AddInclude("**/*.cs"); /// /// The default severity to use for DotNetFormat /// - public DotNetFormatSeverity DotNetFormatSeverity => DotNetFormatSeverity.info; + DotNetFormatSeverity DotNetFormatSeverity => DotNetFormatSeverity.info; /// /// Use the jetbrains code cleanup tool to format the code if installed /// - public Target JetBrainsCleanupCode => + Target JetBrainsCleanupCode => d => { return d @@ -121,7 +123,9 @@ public interface ICanDotNetFormat : IHaveSolution, ICanLint, IHaveOutputLogs ); } else + { ReSharperTasks.ReSharperCleanupCode(cleanupCodeSettings); + } } ); }; @@ -129,7 +133,7 @@ public interface ICanDotNetFormat : IHaveSolution, ICanLint, IHaveOutputLogs /// /// The default matcher for jetbrains cleanup code /// - public Matcher JetBrainsCleanupCodeMatcher => jbMatcher ??= new Matcher(StringComparison.OrdinalIgnoreCase) + Matcher JetBrainsCleanupCodeMatcher => jbMatcher ??= new Matcher(StringComparison.OrdinalIgnoreCase) .AddInclude("**/*.cs") .AddInclude("**/*.csproj") .AddInclude("**/*.targets") @@ -139,7 +143,7 @@ public interface ICanDotNetFormat : IHaveSolution, ICanLint, IHaveOutputLogs /// /// The default profile to use for JetBrainsCleanupCode /// - public string JetBrainsCleanupCodeProfile => "Full Cleanup"; + string JetBrainsCleanupCodeProfile => "Full Cleanup"; private static readonly HashSet _dotNetFormatExcludedDiagnostics = new(StringComparer.OrdinalIgnoreCase) { diff --git a/src/Nuke/DotNetCore/ICanPackWithDotNetCore.cs b/src/Nuke/DotNetCore/ICanPackWithDotNetCore.cs index 9a5930965..2dbbd659a 100644 --- a/src/Nuke/DotNetCore/ICanPackWithDotNetCore.cs +++ b/src/Nuke/DotNetCore/ICanPackWithDotNetCore.cs @@ -22,25 +22,25 @@ public interface ICanPackWithDotNetCore : IHaveBuildTarget, /// dotnet pack /// [NonEntryTarget] - public Target DotnetCorePack => d => d - .Description("Packs all the NuGet packages.") - .Unlisted() - .After(Clean) - .TryDependentFor(a => a.Pack) - .TryDependsOn(b => b.Build) - .TryAfter(a => a.Restore) - .Net9MsBuildFix() - .Executes( - () => DotNetTasks.DotNetPack( - s => s - .SetProcessWorkingDirectory(RootDirectory) - .SetProject(Solution) - .SetDefaultLoggers(LogsDirectory / "pack.log") - .SetGitVersionEnvironment(GitVersion) - .SetConfiguration(Configuration) - .EnableNoRestore() - .EnableNoBuild() - .AddProperty("PackageOutputPath", NuGetPackageDirectory) - ) - ); + Target DotnetCorePack => d => d + .Description("Packs all the NuGet packages.") + .Unlisted() + .After(Clean) + .TryDependentFor(a => a.Pack) + .TryDependsOn(b => b.Build) + .TryAfter(a => a.Restore) + .Net9MsBuildFix() + .Executes( + () => DotNetTasks.DotNetPack( + s => s + .SetProcessWorkingDirectory(RootDirectory) + .SetProject(Solution) + .SetDefaultLoggers(LogsDirectory / "pack.log") + .SetGitVersionEnvironment(GitVersion) + .SetConfiguration(Configuration) + .EnableNoRestore() + .EnableNoBuild() + .AddProperty("PackageOutputPath", NuGetPackageDirectory) + ) + ); } diff --git a/src/Nuke/DotNetCore/ICanRestoreWithDotNetCore.cs b/src/Nuke/DotNetCore/ICanRestoreWithDotNetCore.cs index 5330d2a42..bf605ac3f 100644 --- a/src/Nuke/DotNetCore/ICanRestoreWithDotNetCore.cs +++ b/src/Nuke/DotNetCore/ICanRestoreWithDotNetCore.cs @@ -20,32 +20,32 @@ public interface ICanRestoreWithDotNetCore : IHaveCleanTarget, /// dotnet restore /// [NonEntryTarget] - public Target DotnetCoreRestore => d => d - .Description("Restores the dependencies.") - .Unlisted() - .TryDependentFor(a => a.Restore) - .After(Clean) - .DependsOn(DotnetToolRestore) - .Net9MsBuildFix() - .Executes( - () => DotNetRestore( - s => s - .SetProcessWorkingDirectory(RootDirectory) - .SetProjectFile(Solution) - .SetDefaultLoggers(LogsDirectory / "restore.log") - .SetGitVersionEnvironment(GitVersion) - ) - ); + Target DotnetCoreRestore => d => d + .Description("Restores the dependencies.") + .Unlisted() + .TryDependentFor(a => a.Restore) + .After(Clean) + .DependsOn(DotnetToolRestore) + .Net9MsBuildFix() + .Executes( + () => DotNetRestore( + s => s + .SetProcessWorkingDirectory(RootDirectory) + .SetProjectFile(Solution) + .SetDefaultLoggers(LogsDirectory / "restore.log") + .SetGitVersionEnvironment(GitVersion) + ) + ); /// /// This will ensure that all local dotnet tools are installed /// [ExcludeTarget] [NonEntryTarget] - public Target DotnetToolRestore => d => d - .Unlisted() - .After(Clean) - .TryDependentFor(a => a.Restore) - .OnlyWhenStatic(() => ( NukeBuild.RootDirectory / ".config" / "dotnet-tools.json" ).FileExists()) - .Executes(() => DotNet("tool restore", RootDirectory)); + Target DotnetToolRestore => d => d + .Unlisted() + .After(Clean) + .TryDependentFor(a => a.Restore) + .OnlyWhenStatic(() => ( NukeBuild.RootDirectory / ".config" / "dotnet-tools.json" ).FileExists()) + .Executes(() => DotNet("tool restore", RootDirectory)); } diff --git a/src/Nuke/DotNetCore/ICanTestWithDotNetCore.cs b/src/Nuke/DotNetCore/ICanTestWithDotNetCore.cs index ac0b54101..21c700305 100644 --- a/src/Nuke/DotNetCore/ICanTestWithDotNetCore.cs +++ b/src/Nuke/DotNetCore/ICanTestWithDotNetCore.cs @@ -15,61 +15,61 @@ public interface ICanTestWithDotNetCore : IHaveBuildTarget, IHaveOutputLogs, ICan { + DotNetTestSettings CustomizeDotNetTestSettings(DotNetTestSettings settings) => settings; + /// /// dotnet test /// [NonEntryTarget] - public Target DotnetCoreTest => d => d - .Description("Executes all the unit tests.") - .Unlisted() - .After(Build) - .TryDependentFor(a => a.Test) - .TryAfter(a => a.Restore) - .WhenSkipped(DependencyBehavior.Execute) - .Net9MsBuildFix() - .Executes( - () => DotNetTasks.DotNetBuild( - s => s - .SetProcessWorkingDirectory(RootDirectory) - .SetProjectFile(Solution) - .SetDefaultLoggers(LogsDirectory / "test.build.log") - .SetGitVersionEnvironment(GitVersion) - .SetConfiguration(TestBuildConfiguration) - .EnableNoRestore() - ) - ) - .CreateOrCleanDirectory(TestResultsDirectory) - .EnsureRunSettingsExists(this) - .Net9MsBuildFix() - .Executes( - () => DotNetTool.GetTool("dotnet-coverage")( - $"{new Arguments() - .Add("collect") - .Add("--settings {value}", RunSettings) - .Add("--output {value}", TestResultsDirectory / "test.cobertura.xml") - .Add("--output-format {value}", "cobertura") - .Add("--") - .Add("dotnet") - .Concatenate( - CustomizeDotNetTestSettings( - new DotNetTestSettings() - .SetProcessWorkingDirectory(RootDirectory) - .SetProjectFile(Solution) - .SetDefaultLoggers(LogsDirectory / "test.log") - .SetGitVersionEnvironment(GitVersion) - .SetConfiguration(TestBuildConfiguration) - .EnableNoRestore() - .EnableNoBuild() - .SetLoggers("trx") - .SetResultsDirectory(TestResultsDirectory) - ) - .RemoveLoggers() - .GetProcessArguments() - ) - .RenderForExecution()}", - RootDirectory + Target DotnetCoreTest => d => d + .Description("Executes all the unit tests.") + .Unlisted() + .After(Build) + .TryDependentFor(a => a.Test) + .TryAfter(a => a.Restore) + .WhenSkipped(DependencyBehavior.Execute) + .Net9MsBuildFix() + .Executes( + () => DotNetTasks.DotNetBuild( + s => s + .SetProcessWorkingDirectory(RootDirectory) + .SetProjectFile(Solution) + .SetDefaultLoggers(LogsDirectory / "test.build.log") + .SetGitVersionEnvironment(GitVersion) + .SetConfiguration(TestBuildConfiguration) + .EnableNoRestore() + ) ) - ); - - public DotNetTestSettings CustomizeDotNetTestSettings(DotNetTestSettings settings) => settings; + .CreateOrCleanDirectory(TestResultsDirectory) + .EnsureRunSettingsExists(this) + .Net9MsBuildFix() + .Executes( + () => DotNetTool.GetTool("dotnet-coverage")( + $"{new Arguments() + .Add("collect") + .Add("--settings {value}", RunSettings) + .Add("--output {value}", TestResultsDirectory / "test.cobertura.xml") + .Add("--output-format {value}", "cobertura") + .Add("--") + .Add("dotnet") + .Concatenate( + CustomizeDotNetTestSettings( + new DotNetTestSettings() + .SetProcessWorkingDirectory(RootDirectory) + .SetProjectFile(Solution) + .SetDefaultLoggers(LogsDirectory / "test.log") + .SetGitVersionEnvironment(GitVersion) + .SetConfiguration(TestBuildConfiguration) + .EnableNoRestore() + .EnableNoBuild() + .SetLoggers("trx") + .SetResultsDirectory(TestResultsDirectory) + ) + .RemoveLoggers() + .GetProcessArguments() + ) + .RenderForExecution()}", + RootDirectory + ) + ); } diff --git a/src/Nuke/DotNetCore/ICanTestWithDotNetCoreBuild.cs b/src/Nuke/DotNetCore/ICanTestWithDotNetCoreBuild.cs index 73ef71e7f..3ce815028 100644 --- a/src/Nuke/DotNetCore/ICanTestWithDotNetCoreBuild.cs +++ b/src/Nuke/DotNetCore/ICanTestWithDotNetCoreBuild.cs @@ -17,60 +17,60 @@ public interface ICanTestWithDotNetCoreBuild : IHaveBuildTarget, IHaveOutputLogs, ICan { - public DotNetTestSettings CustomizeDotNetTestSettings(DotNetTestSettings settings) => settings; + DotNetTestSettings CustomizeDotNetTestSettings(DotNetTestSettings settings) => settings; /// /// dotnet test /// [NonEntryTarget] - public Target DotnetCoreTestBuild => d => d - .Description("Executes all the unit tests.") - .Unlisted() - .After(Build) - .TryDependentFor(a => a.Test) - .TryAfter(a => a.Restore) - .WhenSkipped(DependencyBehavior.Execute) - .Executes( - () => MSBuildTasks.MSBuild( - settings => - settings - .SetProcessWorkingDirectory(RootDirectory) - .SetSolutionFile(Solution) - .SetConfiguration(TestBuildConfiguration) - .SetDefaultLoggers(LogsDirectory / "test.build.log") - .SetGitVersionEnvironment(GitVersion) - .SetAssemblyVersion(GitVersion.AssemblySemVer) - .SetPackageVersion(GitVersion.NuGetVersionV2) + Target DotnetCoreTestBuild => d => d + .Description("Executes all the unit tests.") + .Unlisted() + .After(Build) + .TryDependentFor(a => a.Test) + .TryAfter(a => a.Restore) + .WhenSkipped(DependencyBehavior.Execute) + .Executes( + () => MSBuildTasks.MSBuild( + settings => + settings + .SetProcessWorkingDirectory(RootDirectory) + .SetSolutionFile(Solution) + .SetConfiguration(TestBuildConfiguration) + .SetDefaultLoggers(LogsDirectory / "test.build.log") + .SetGitVersionEnvironment(GitVersion) + .SetAssemblyVersion(GitVersion.AssemblySemVer) + .SetPackageVersion(GitVersion.NuGetVersionV2) + ) ) - ) - .CreateOrCleanDirectory(TestResultsDirectory) - .EnsureRunSettingsExists(this) - .Net9MsBuildFix() - .Executes( - () => DotNetTool.GetTool("dotnet-coverage")( - $"{new Arguments() - .Add("collect") - .Add("--settings {value}", RunSettings) - .Add("--output {value}", TestResultsDirectory / "test.cobertura.xml") - .Add("--output-format {value}", "cobertura") - .Add("--") - .Add("dotnet") - .Concatenate( - CustomizeDotNetTestSettings( - new DotNetTestSettings() - .SetProcessWorkingDirectory(RootDirectory) - .SetProjectFile(Solution) - .SetDefaultLoggers(LogsDirectory / "test.log") - .SetGitVersionEnvironment(GitVersion) - .SetConfiguration(TestBuildConfiguration) - .EnableNoRestore() - .EnableNoBuild() - .SetLoggers("trx") - .SetResultsDirectory(TestResultsDirectory) - ) - .GetProcessArguments() - ).RenderForExecution()}", - RootDirectory - ) - ); + .CreateOrCleanDirectory(TestResultsDirectory) + .EnsureRunSettingsExists(this) + .Net9MsBuildFix() + .Executes( + () => DotNetTool.GetTool("dotnet-coverage")( + $"{new Arguments() + .Add("collect") + .Add("--settings {value}", RunSettings) + .Add("--output {value}", TestResultsDirectory / "test.cobertura.xml") + .Add("--output-format {value}", "cobertura") + .Add("--") + .Add("dotnet") + .Concatenate( + CustomizeDotNetTestSettings( + new DotNetTestSettings() + .SetProcessWorkingDirectory(RootDirectory) + .SetProjectFile(Solution) + .SetDefaultLoggers(LogsDirectory / "test.log") + .SetGitVersionEnvironment(GitVersion) + .SetConfiguration(TestBuildConfiguration) + .EnableNoRestore() + .EnableNoBuild() + .SetLoggers("trx") + .SetResultsDirectory(TestResultsDirectory) + ) + .GetProcessArguments() + ).RenderForExecution()}", + RootDirectory + ) + ); } diff --git a/src/Nuke/DotNetCore/IHaveCollectCoverage.cs b/src/Nuke/DotNetCore/IHaveCollectCoverage.cs index 8b1378917..e69de29bb 100644 --- a/src/Nuke/DotNetCore/IHaveCollectCoverage.cs +++ b/src/Nuke/DotNetCore/IHaveCollectCoverage.cs @@ -1 +0,0 @@ - diff --git a/src/Nuke/DotNetToolAttribute.cs b/src/Nuke/DotNetToolAttribute.cs index 9425ea616..6ec62b420 100644 --- a/src/Nuke/DotNetToolAttribute.cs +++ b/src/Nuke/DotNetToolAttribute.cs @@ -1,4 +1,5 @@ using System.Reflection; + using Nuke.Common.Tooling; namespace Rocket.Surgery.Nuke; @@ -22,6 +23,6 @@ public sealed class DotNetToolAttribute(string command) : ToolInjectionAttribute private readonly string _command = command; - #pragma warning disable CA1019 - #pragma warning restore CA1019 +#pragma warning disable CA1019 +#pragma warning restore CA1019 } diff --git a/src/Nuke/DotnetTool.cs b/src/Nuke/DotnetTool.cs index 6155c1a74..3dd8acb6d 100644 --- a/src/Nuke/DotnetTool.cs +++ b/src/Nuke/DotnetTool.cs @@ -1,5 +1,6 @@ using System.Collections.Immutable; using System.Text.Json; + using Nuke.Common.IO; using Nuke.Common.Tooling; @@ -45,19 +46,21 @@ private static ResolvedToolsManifest ResolveToolsManifest() if (ToolsManifestLocation.Value.FileExists()) { - #pragma warning disable CA1869 +#pragma warning disable CA1869 var manifest = // ReSharper disable once NullableWarningSuppressionIsUsed JsonSerializer.Deserialize( File.ReadAllText(ToolsManifestLocation.Value), new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase } )!; - #pragma warning restore CA1869 +#pragma warning restore CA1869 toolsManifest = ResolvedToolsManifest.Create(manifest); } else { - toolsManifest = new(ImmutableDictionary.Empty, ImmutableDictionary.Empty); + var definitions = ImmutableDictionary.Empty; + var otherDefinitions = ImmutableDictionary.Empty; + toolsManifest = new(definitions, otherDefinitions); } return toolsManifest; diff --git a/src/Nuke/DownloadFileAttribute.cs b/src/Nuke/DownloadFileAttribute.cs index c9b6b5d51..a882addb6 100644 --- a/src/Nuke/DownloadFileAttribute.cs +++ b/src/Nuke/DownloadFileAttribute.cs @@ -1,5 +1,6 @@ using Nuke.Common.Execution; using Nuke.Common.IO; + using Serilog; using static Nuke.Common.IO.HttpTasks; diff --git a/src/Nuke/EnsureGitHooksAttribute.cs b/src/Nuke/EnsureGitHooksAttribute.cs index 70bc46872..6da5c5260 100644 --- a/src/Nuke/EnsureGitHooksAttribute.cs +++ b/src/Nuke/EnsureGitHooksAttribute.cs @@ -1,6 +1,7 @@ using Nuke.Common.Execution; using Nuke.Common.IO; using Nuke.Common.Tooling; + using Serilog; #pragma warning disable CA1019, CA1308 @@ -52,7 +53,7 @@ public void OnBuildInitialized(IReadOnlyCollection executableT /// /// The hooks that were asked for. /// - public string[] HookNames { get; } = hookNames + public string[] HookNames { get; } = [.. hookNames .Select( x => x .ToString() @@ -60,6 +61,5 @@ public void OnBuildInitialized(IReadOnlyCollection executableT .Replace(" ", "_", StringComparison.Ordinal) .Dasherize() .ToLowerInvariant() - ) - .ToArray(); + )]; } diff --git a/src/Nuke/EnsurePackageSourceHasCredentialsAttribute.cs b/src/Nuke/EnsurePackageSourceHasCredentialsAttribute.cs index f4ffb457d..d7a695608 100644 --- a/src/Nuke/EnsurePackageSourceHasCredentialsAttribute.cs +++ b/src/Nuke/EnsurePackageSourceHasCredentialsAttribute.cs @@ -1,5 +1,7 @@ using NuGet.Configuration; + using Nuke.Common.Execution; + using Serilog; #pragma warning disable CA1813, CA2201 diff --git a/src/Nuke/Extensions.cs b/src/Nuke/Extensions.cs index f613a5fb1..0ee502440 100644 --- a/src/Nuke/Extensions.cs +++ b/src/Nuke/Extensions.cs @@ -1,11 +1,14 @@ using System.Collections.ObjectModel; using System.Reflection; + using Microsoft.Extensions.FileSystemGlobbing; + using Nuke.Common.CI.GitHubActions; using Nuke.Common.IO; using Nuke.Common.Tooling; using Nuke.Common.Tools.ReportGenerator; using Nuke.Common.Utilities.Collections; + using Serilog; namespace Rocket.Surgery.Nuke; @@ -183,7 +186,7 @@ public static T MapVerbosity(this Verbosity verbosity, T @default) .GetRuntimeFields() .Single(z => z.Name == "Mappings") .NotNull() - // ReSharper disable once NullableWarningSuppressionIsUsed + // ReSharper disable once NullableWarningSuppressionIsUsed .GetValue(null)!; if (!mappings.Contains(typeof(T))) diff --git a/src/Nuke/FilePathExtensions.cs b/src/Nuke/FilePathExtensions.cs index e02f3347e..a98df4c68 100644 --- a/src/Nuke/FilePathExtensions.cs +++ b/src/Nuke/FilePathExtensions.cs @@ -1,4 +1,5 @@ using System.Collections.Concurrent; + using Nuke.Common.IO; namespace Rocket.Surgery.Nuke; @@ -29,7 +30,7 @@ public static class FilePathExtensions /// public static AbsolutePath PickDirectory(IEnumerable paths) { - var absolutePaths = paths as AbsolutePath[] ?? paths.ToArray(); + var absolutePaths = paths as AbsolutePath[] ?? [.. paths]; foreach (var path in absolutePaths) { if (Cache.ContainsKey(path)) return path; @@ -65,7 +66,7 @@ public static AbsolutePath PickDirectory(IEnumerable paths) /// public static AbsolutePath PickFile(IEnumerable paths) { - var absolutePaths = paths as AbsolutePath[] ?? paths.ToArray(); + var absolutePaths = paths as AbsolutePath[] ?? [.. paths]; foreach (var path in absolutePaths) { if (Cache.ContainsKey(path)) return path; diff --git a/src/Nuke/GithubActions/BaseGitHubActionsStep.cs b/src/Nuke/GithubActions/BaseGitHubActionsStep.cs index 26f455067..0de206ba8 100644 --- a/src/Nuke/GithubActions/BaseGitHubActionsStep.cs +++ b/src/Nuke/GithubActions/BaseGitHubActionsStep.cs @@ -48,15 +48,22 @@ public override void Write(CustomFileWriter writer) /// /// The outputs of this step /// - #pragma warning disable CA1002 +#pragma warning disable CA1002 public List Outputs { get; set; } = []; - #pragma warning restore CA1002 +#pragma warning restore CA1002 /// /// The step name /// public string StepName { get; } + /// + /// Configure the step name + /// + /// + /// + protected virtual string ComputeStepName(string name) => Symbols.StepName(name); + /// /// The default constructor /// @@ -67,11 +74,4 @@ protected BaseGitHubActionsStep(string name) if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name)); StepName = name; } - - /// - /// Configure the step name - /// - /// - /// - protected virtual string ComputeStepName(string name) => Symbols.StepName(name); } diff --git a/src/Nuke/GithubActions/CheckoutStep.cs b/src/Nuke/GithubActions/CheckoutStep.cs index d9aae5125..586200173 100644 --- a/src/Nuke/GithubActions/CheckoutStep.cs +++ b/src/Nuke/GithubActions/CheckoutStep.cs @@ -5,18 +5,12 @@ namespace Rocket.Surgery.Nuke.GithubActions; /// public class CheckoutStep : UsingStep { - /// - /// Uses the checkout resource action - /// - /// - public CheckoutStep(string name) : base(name) => Uses = "actions/checkout@v4"; - /// public override void Write(CustomFileWriter writer) { - #pragma warning disable CA1308 +#pragma warning disable CA1308 WithProperties(x => x.Kebaberize()); - #pragma warning restore CA1308 +#pragma warning restore CA1308 base.Write(writer); } @@ -123,4 +117,10 @@ public override void Write(CustomFileWriter writer) /// /// Default: ${{ github.token }} public string? Token { get; set; } + + /// + /// Uses the checkout resource action + /// + /// + public CheckoutStep(string name) : base(name) => Uses = "actions/checkout@v4"; } diff --git a/src/Nuke/GithubActions/CustomFileWriterExtensions.cs b/src/Nuke/GithubActions/CustomFileWriterExtensions.cs index 688b91f7c..ed8fabefc 100644 --- a/src/Nuke/GithubActions/CustomFileWriterExtensions.cs +++ b/src/Nuke/GithubActions/CustomFileWriterExtensions.cs @@ -1,5 +1,3 @@ -using Nuke.Common.Utilities.Collections; - namespace Rocket.Surgery.Nuke.GithubActions; /// @@ -29,7 +27,7 @@ public static void WriteKeyValues(this CustomFileWriter writer, string key, IDic internal static void WriteValue(this CustomFileWriter writer, KeyValuePair kvp) { - ( var key, var value ) = kvp; + (var key, var value) = kvp; if (value.StartsWith('>') || value.StartsWith('|')) { var values = value.Split('\n'); diff --git a/src/Nuke/GithubActions/DownloadArtifactStep.cs b/src/Nuke/GithubActions/DownloadArtifactStep.cs index 0c56f2113..e9c9d4dce 100644 --- a/src/Nuke/GithubActions/DownloadArtifactStep.cs +++ b/src/Nuke/GithubActions/DownloadArtifactStep.cs @@ -6,18 +6,12 @@ namespace Rocket.Surgery.Nuke.GithubActions; [PublicAPI] public class DownloadArtifactStep : UsingStep { - /// - /// The default constructor - /// - /// - public DownloadArtifactStep(string name) : base(name) => Uses = "actions/download-artifact@v4"; - /// public override void Write(CustomFileWriter writer) { - #pragma warning disable CA1308 +#pragma warning disable CA1308 WithProperties(x => x.Kebaberize()); - #pragma warning restore CA1308 +#pragma warning restore CA1308 base.Write(writer); } @@ -60,6 +54,12 @@ public override void Write(CustomFileWriter writer) /// public string? RunId { get; set; } + /// + /// The default constructor + /// + /// + public DownloadArtifactStep(string name) : base(name) => Uses = "actions/download-artifact@v4"; + /// protected override string ComputeStepName(string name) => $"🚀 {name}"; } diff --git a/src/Nuke/GithubActions/GitHubActionsInputType.cs b/src/Nuke/GithubActions/GitHubActionsInputType.cs index b46804ced..14c0ee5b5 100644 --- a/src/Nuke/GithubActions/GitHubActionsInputType.cs +++ b/src/Nuke/GithubActions/GitHubActionsInputType.cs @@ -10,10 +10,10 @@ public enum GitHubActionsInputType /// /// String input /// - #pragma warning disable CA1720 +#pragma warning disable CA1720 [EnumValue("string")] String, - #pragma warning restore CA1720 +#pragma warning restore CA1720 /// /// Boolean input /// diff --git a/src/Nuke/GithubActions/GitHubActionsLintAttribute.cs b/src/Nuke/GithubActions/GitHubActionsLintAttribute.cs index b98daf7b2..85d42d3ff 100644 --- a/src/Nuke/GithubActions/GitHubActionsLintAttribute.cs +++ b/src/Nuke/GithubActions/GitHubActionsLintAttribute.cs @@ -1,4 +1,5 @@ using System.Reflection; + using Nuke.Common.CI; using Nuke.Common.CI.GitHubActions; using Nuke.Common.Execution; @@ -14,30 +15,6 @@ namespace Rocket.Surgery.Nuke.GithubActions; [AttributeUsage(AttributeTargets.Class)] public sealed class GitHubActionsLintAttribute : GitHubActionsStepsAttribute { - /// - /// The default constructor - /// - /// - /// - /// - public GitHubActionsLintAttribute( - string name, - GitHubActionsImage image, - params GitHubActionsImage[] images - ) : base(name, image, images) => InvokedTargets = [nameof(ICanLint.Lint)]; - - /// - /// The default constructor - /// - /// - /// - /// - public GitHubActionsLintAttribute( - string name, - string image, - params string[] images - ) : base(name, image, images) { } - /// public override ConfigurationEntity GetConfiguration(IReadOnlyCollection relevantTargets) { @@ -123,4 +100,28 @@ public override ConfigurationEntity GetConfiguration(IReadOnlyCollection public string TokenSecret { get; set; } = "RSG_BOT_TOKEN"; + + /// + /// The default constructor + /// + /// + /// + /// + public GitHubActionsLintAttribute( + string name, + GitHubActionsImage image, + params GitHubActionsImage[] images + ) : base(name, image, images) => InvokedTargets = [nameof(ICanLint.Lint)]; + + /// + /// The default constructor + /// + /// + /// + /// + public GitHubActionsLintAttribute( + string name, + string image, + params string[] images + ) : base(name, image, images) { } } diff --git a/src/Nuke/GithubActions/GitHubActionsPermission.cs b/src/Nuke/GithubActions/GitHubActionsPermission.cs index 06fe45dc3..14d7afbbd 100644 --- a/src/Nuke/GithubActions/GitHubActionsPermission.cs +++ b/src/Nuke/GithubActions/GitHubActionsPermission.cs @@ -7,7 +7,7 @@ namespace Rocket.Surgery.Nuke.GithubActions; /// #pragma warning disable CA1711 public enum GitHubActionsPermission - #pragma warning restore CA1711 +#pragma warning restore CA1711 { /// /// None diff --git a/src/Nuke/GithubActions/GitHubActionsPermissions.cs b/src/Nuke/GithubActions/GitHubActionsPermissions.cs index 99795275b..d2567f24d 100644 --- a/src/Nuke/GithubActions/GitHubActionsPermissions.cs +++ b/src/Nuke/GithubActions/GitHubActionsPermissions.cs @@ -7,6 +7,61 @@ namespace Rocket.Surgery.Nuke.GithubActions; /// public record GitHubActionsPermissions { + /// + /// Write the permissions to the given yaml file + /// + /// + public void Write(CustomFileWriter writer) + { + if (this == None) + { + writer.WriteLine("permissions: {}"); + return; + } + + if (this == WriteAll) + { + writer.WriteLine("permissions: write-all"); + return; + } + + if (this == ReadAll) + { + writer.WriteLine("permissions: read-all"); + return; + } + + writer.WriteLine("permissions:"); + using (writer.Indent()) + { + if (Actions is { } actions) writer.WriteLine($"actions: {actions.GetValue()}"); + + if (Checks is { } checks) writer.WriteLine($"checks: {checks.GetValue()}"); + + if (Contents is { } contents) writer.WriteLine($"contents: {contents.GetValue()}"); + + if (Deployments is { } deployments) writer.WriteLine($"deployments: {deployments.GetValue()}"); + + if (IdToken is { } idToken) writer.WriteLine($"id-token: {idToken.GetValue()}"); + + if (Issues is { } issues) writer.WriteLine($"issues: {issues.GetValue()}"); + + if (Discussions is { } discussions) writer.WriteLine($"discussions: {discussions.GetValue()}"); + + if (Packages is { } packages) writer.WriteLine($"packages: {packages.GetValue()}"); + + if (Pages is { } pages) writer.WriteLine($"pages: {pages.GetValue()}"); + + if (PullRequests is { } pullRequests) writer.WriteLine($"pull-requests: {pullRequests.GetValue()}"); + + if (RepositoryProjects is { } repositoryProjects) writer.WriteLine($"repository-projects: {repositoryProjects.GetValue()}"); + + if (SecurityEvents is { } securityEvents) writer.WriteLine($"security-events: {securityEvents.GetValue()}"); + + if (Statuses is { } statuses) writer.WriteLine($"statuses: {statuses.GetValue()}"); + } + } + /// /// No permissions to anything /// @@ -131,59 +186,4 @@ public record GitHubActionsPermissions /// The statuses /// public GitHubActionsPermission Statuses { get; set; } = GitHubActionsPermission.Write; - - /// - /// Write the permissions to the given yaml file - /// - /// - public void Write(CustomFileWriter writer) - { - if (this == None) - { - writer.WriteLine("permissions: {}"); - return; - } - - if (this == WriteAll) - { - writer.WriteLine("permissions: write-all"); - return; - } - - if (this == ReadAll) - { - writer.WriteLine("permissions: read-all"); - return; - } - - writer.WriteLine("permissions:"); - using (writer.Indent()) - { - if (Actions is { } actions) writer.WriteLine($"actions: {actions.GetValue()}"); - - if (Checks is { } checks) writer.WriteLine($"checks: {checks.GetValue()}"); - - if (Contents is { } contents) writer.WriteLine($"contents: {contents.GetValue()}"); - - if (Deployments is { } deployments) writer.WriteLine($"deployments: {deployments.GetValue()}"); - - if (IdToken is { } idToken) writer.WriteLine($"id-token: {idToken.GetValue()}"); - - if (Issues is { } issues) writer.WriteLine($"issues: {issues.GetValue()}"); - - if (Discussions is { } discussions) writer.WriteLine($"discussions: {discussions.GetValue()}"); - - if (Packages is { } packages) writer.WriteLine($"packages: {packages.GetValue()}"); - - if (Pages is { } pages) writer.WriteLine($"pages: {pages.GetValue()}"); - - if (PullRequests is { } pullRequests) writer.WriteLine($"pull-requests: {pullRequests.GetValue()}"); - - if (RepositoryProjects is { } repositoryProjects) writer.WriteLine($"repository-projects: {repositoryProjects.GetValue()}"); - - if (SecurityEvents is { } securityEvents) writer.WriteLine($"security-events: {securityEvents.GetValue()}"); - - if (Statuses is { } statuses) writer.WriteLine($"statuses: {statuses.GetValue()}"); - } - } } diff --git a/src/Nuke/GithubActions/GitHubActionsStepsAttribute.cs b/src/Nuke/GithubActions/GitHubActionsStepsAttribute.cs index f69121c0d..4e6027172 100644 --- a/src/Nuke/GithubActions/GitHubActionsStepsAttribute.cs +++ b/src/Nuke/GithubActions/GitHubActionsStepsAttribute.cs @@ -1,5 +1,6 @@ using System.Collections.Immutable; using System.Reflection; + using Nuke.Common.CI; using Nuke.Common.CI.GitHubActions; using Nuke.Common.CI.GitHubActions.Configuration; @@ -7,6 +8,7 @@ using Nuke.Common.IO; using Nuke.Common.Tooling; using Nuke.Common.Utilities.Collections; + using YamlDotNet.RepresentationModel; #pragma warning disable CA1019, CA1308, CA1721, CA1813 @@ -19,36 +21,6 @@ namespace Rocket.Surgery.Nuke.GithubActions; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class GitHubActionsStepsAttribute : GithubActionsStepsAttributeBase { - /// - /// The default constructor - /// - /// - /// - /// - public GitHubActionsStepsAttribute( - string name, - GitHubActionsImage image, - params GitHubActionsImage[] images - ) : base(name) - { - ImmutableArray actionsImage = [image, .. images]; - Images = [.. actionsImage.Select(z => z.GetValue().Replace(".", "_", StringComparison.Ordinal))]; - IsGithubHosted = true; - } - - /// - /// The default constructor - /// - /// - /// - /// - public GitHubActionsStepsAttribute( - string name, - string image, - params string[] images - ) : base(name) => - Images = [image, .. images]; - /// /// Determine if you always want to build the nuke project during the ci run /// @@ -83,6 +55,36 @@ params string[] images /// public override IEnumerable RelevantTargetNames => InvokedTargets; + /// + /// The default constructor + /// + /// + /// + /// + public GitHubActionsStepsAttribute( + string name, + GitHubActionsImage image, + params GitHubActionsImage[] images + ) : base(name) + { + ImmutableArray actionsImage = [image, .. images]; + Images = [.. actionsImage.Select(z => z.GetValue().Replace(".", "_", StringComparison.Ordinal))]; + IsGithubHosted = true; + } + + /// + /// The default constructor + /// + /// + /// + /// + public GitHubActionsStepsAttribute( + string name, + string image, + params string[] images + ) : base(name) => + Images = [image, .. images]; + // public override IEnumerable IrrelevantTargetNames => new string[0]; /// @@ -155,9 +157,7 @@ .. onePasswordServiceAccountSecrets { Id = secrets.First().OutputId, Uses = "1password/load-secrets-action@v1", - Outputs = secrets - .Select(secret => new GitHubActionsOutput(secret.Name, secret.Description)) - .ToList(), + Outputs = [.. secrets.Select(secret => new GitHubActionsOutput(secret.Name, secret.Description))], With = new() { ["export-env"] = "false" }, Environment = Enumerable .Concat( @@ -216,9 +216,7 @@ .. onePasswordConnectServerSecrets { Id = secrets.First().OutputId, Uses = "1password/load-secrets-action@v1", - Outputs = secrets - .Select(secret => new GitHubActionsOutput(secret.Name, secret.Description)) - .ToList(), + Outputs = [.. secrets.Select(secret => new GitHubActionsOutput(secret.Name, secret.Description))], With = new() { ["export-env"] = "false" }, Environment = Enumerable .Concat( @@ -264,12 +262,14 @@ .. onePasswordConnectServerSecrets ); var dotnetTools = Path.Combine(NukeBuild.RootDirectory, ".config/dotnet-tools.json"); if (File.Exists(dotnetTools)) + { steps.Add( new RunStep("dotnet tool restore") { Run = "dotnet tool restore", } ); + } var localTool = DotNetTool.IsInstalled("nuke"); if (!localTool) steps.Add(globalToolStep); @@ -278,13 +278,13 @@ .. onePasswordConnectServerSecrets Enumerable .Concat( GetAllSecrets(secrets) - // ReSharper disable CoVariantArrayConversion + // ReSharper disable CoVariantArrayConversion .Concat(variables) .Concat(onePasswordConnectServerSecrets) .Concat(onePasswordServiceAccountSecrets), environmentAttributes ) - // ReSharper enable CoVariantArrayConversion + // ReSharper enable CoVariantArrayConversion .SelectMany( z => { @@ -318,10 +318,10 @@ .. onePasswordConnectServerSecrets var requiredInputs = new List(); var lookupTable = new LookupTable(); var initialArguments = localTool ? new Arguments().Add("dotnet").Add("nuke") : new Arguments().Add("nuke"); - foreach (( var execute, var targets ) in relevantTargets + foreach ((var execute, var targets) in relevantTargets .Select( - x => ( ExecutableTarget: x, - Targets: GetInvokedTargets(x, relevantTargets).ToArray() ) + x => (ExecutableTarget: x, + Targets: GetInvokedTargets(x, relevantTargets).ToArray()) ) .ForEachLazy(x => lookupTable.Add(x.ExecutableTarget, [.. x.Targets])) ) @@ -371,6 +371,7 @@ .. onePasswordConnectServerSecrets ); if (!AlwaysBuildNukeProject) + { initialArguments = new Arguments() .Add("dotnet") .Add( @@ -378,6 +379,7 @@ .. onePasswordConnectServerSecrets .RootDirectory.GetRelativePathTo(Assembly.GetEntryAssembly()?.Location) .ToUnixRelativePath() ); + } steps.Add( new RunStep(execute.Name.Humanize(LetterCasing.Title)) @@ -423,19 +425,22 @@ .. onePasswordConnectServerSecrets ApplyEnhancements(config); if (!buildJob.Name.Equals(Settings.DefaultGithubJobName, StringComparison.OrdinalIgnoreCase)) + { // ReSharper disable once PossibleMultipleEnumeration - config.DetailedTriggers = GetTriggers(requiredInputs, outputs, secrets) - .Concat(config.DetailedTriggers.Except(triggers)) - .ToList(); + config.DetailedTriggers = [.. GetTriggers(requiredInputs, outputs, secrets) +, .. config.DetailedTriggers.Except(triggers)]; + } // need a better way to do this more generically if (buildJob.Steps.OfType().Any(z => z.Uses?.StartsWith("codecov/codecov-action", StringComparison.OrdinalIgnoreCase) == true)) + { foreach (var trigger in config.DetailedTriggers.OfType()) { if (trigger.Secrets.Any(s => s.Name == "CODECOV_TOKEN")) continue; trigger.Secrets.Add(new("CODECOV_TOKEN", "The codecov token", Alias: "CodecovToken")); } + } if (IsGithubHosted && Images is { Length: > 1 }) { @@ -493,8 +498,8 @@ protected void NormalizeActionVersions(RocketSurgeonGitHubActionsConfiguration c ) .Select( // ReSharper disable once NullableWarningSuppressionIsUsed - z => ( name: ( (YamlScalarNode)z.Children[key] ).Value!.Split("@")[0], - value: ( (YamlScalarNode)z.Children[key] ).Value ) + z => (name: ( (YamlScalarNode)z.Children[key] ).Value!.Split("@")[0], + value: ( (YamlScalarNode)z.Children[key] ).Value) ) .DistinctBy(z => z.name) .ToDictionary( @@ -513,12 +518,16 @@ protected void NormalizeActionVersions(RocketSurgeonGitHubActionsConfiguration c foreach (var job in config.Jobs) { if (job is RocketSurgeonsGithubWorkflowJob workflowJob) + { workflowJob.Uses = GetValue(workflowJob.Uses); + } else if (job is RocketSurgeonsGithubActionsJob actionsJob) + { foreach (var step in actionsJob.Steps.OfType()) { step.Uses = step.Uses = GetValue(step.Uses); } + } } } diff --git a/src/Nuke/GithubActions/GithubActionsNukeParameter.cs b/src/Nuke/GithubActions/GithubActionsNukeParameter.cs index c95323b4f..35712e65f 100644 --- a/src/Nuke/GithubActions/GithubActionsNukeParameter.cs +++ b/src/Nuke/GithubActions/GithubActionsNukeParameter.cs @@ -8,6 +8,12 @@ namespace Rocket.Surgery.Nuke.GithubActions; /// public class GithubActionsNukeParameter : ConfigurationEntity { + /// + public override void Write(CustomFileWriter writer) + { + using var a = writer.WriteBlock($"{Name}: '{Default}'"); + } + // ReSharper disable once NullableWarningSuppressionIsUsed /// /// The name @@ -19,10 +25,4 @@ public class GithubActionsNukeParameter : ConfigurationEntity /// The default value of the parameter /// public string Default { get; set; } = null!; - - /// - public override void Write(CustomFileWriter writer) - { - using var a = writer.WriteBlock($"{Name}: '{Default}'"); - } } diff --git a/src/Nuke/GithubActions/GithubActionsStepsAttributeBase.cs b/src/Nuke/GithubActions/GithubActionsStepsAttributeBase.cs index a670e9e96..c4420da67 100644 --- a/src/Nuke/GithubActions/GithubActionsStepsAttributeBase.cs +++ b/src/Nuke/GithubActions/GithubActionsStepsAttributeBase.cs @@ -2,6 +2,7 @@ using Nuke.Common.CI.GitHubActions; using Nuke.Common.CI.GitHubActions.Configuration; using Nuke.Common.IO; + using YamlDotNet.RepresentationModel; #pragma warning disable CA1851 @@ -136,17 +137,6 @@ public abstract class GithubActionsStepsAttributeBase : ChainedConfigurationAttr /// public string[] Workflows { get; set; } = []; - /// - /// The default constructor given the file name - /// - /// - protected GithubActionsStepsAttributeBase(string name) - { - Name = name; - ExcludedTargets = []; - NonEntryTargets = []; - } - /// /// Applies the given enhancements to the build /// @@ -154,6 +144,7 @@ protected GithubActionsStepsAttributeBase(string name) protected void ApplyEnhancements(RocketSurgeonGitHubActionsConfiguration config) { if (Enhancements.Length > 0) + { foreach (var method in Enhancements.Join(Build.GetType().GetMethods(), z => z, z => z.Name, (_, e) => e)) { config = method.IsStatic @@ -161,6 +152,7 @@ protected void ApplyEnhancements(RocketSurgeonGitHubActionsConfiguration config) : method.Invoke(Build, [config]) as RocketSurgeonGitHubActionsConfiguration ?? config; } + } // This will normalize the version numbers against the existing file. if (!File.Exists(ConfigurationFile)) return; @@ -181,8 +173,8 @@ protected void ApplyEnhancements(RocketSurgeonGitHubActionsConfiguration config) ) .Select( // ReSharper disable once NullableWarningSuppressionIsUsed - z => ( name: ( (YamlScalarNode)z.Children[key] ).Value!.Split("@")[0], - value: ( (YamlScalarNode)z.Children[key] ).Value ) + z => (name: ( (YamlScalarNode)z.Children[key] ).Value!.Split("@")[0], + value: ( (YamlScalarNode)z.Children[key] ).Value) ) .DistinctBy(z => z.name) .ToDictionary( @@ -201,12 +193,16 @@ protected void ApplyEnhancements(RocketSurgeonGitHubActionsConfiguration config) foreach (var job in config.Jobs) { if (job is RocketSurgeonsGithubWorkflowJob workflowJob) + { workflowJob.Uses = GetValue(workflowJob.Uses); + } else if (job is RocketSurgeonsGithubActionsJob actionsJob) + { foreach (var step in actionsJob.Steps.OfType()) { step.Uses = step.Uses = GetValue(step.Uses); } + } } } @@ -235,13 +231,16 @@ IEnumerable secrets ) { if (On.Any(z => z == RocketSurgeonGitHubActionsTrigger.WorkflowDispatch)) + { yield return new RocketSurgeonGitHubActionsWorkflowTrigger { Kind = RocketSurgeonGitHubActionsTrigger.WorkflowDispatch, Inputs = [.. inputs], }; + } if (On.Any(z => z == RocketSurgeonGitHubActionsTrigger.WorkflowCall)) + { yield return new RocketSurgeonGitHubActionsWorkflowTrigger { Kind = RocketSurgeonGitHubActionsTrigger.WorkflowCall, @@ -249,16 +248,20 @@ IEnumerable secrets Outputs = [.. outputs], Inputs = [.. inputs], }; + } if (On.Any(z => z == RocketSurgeonGitHubActionsTrigger.WorkflowRun)) + { yield return new RocketSurgeonGitHubActionsWorkflowTrigger { Kind = RocketSurgeonGitHubActionsTrigger.WorkflowRun, Types = [.. Types], Workflows = [.. Workflows], }; + } if (OnPushBranches.Length > 0 || OnPushTags.Length > 0 || OnPushIncludePaths.Length > 0 || OnPushExcludePaths.Length > 0) + { yield return new RocketSurgeonGitHubActionsVcsTrigger { Kind = RocketSurgeonGitHubActionsTrigger.Push, @@ -267,8 +270,10 @@ IEnumerable secrets IncludePaths = [.. OnPushIncludePaths], ExcludePaths = [.. OnPushExcludePaths], }; + } if (OnPullRequestBranches.Length > 0 || OnPullRequestTags.Length > 0 || OnPullRequestIncludePaths.Length > 0 || OnPullRequestExcludePaths.Length > 0) + { yield return new RocketSurgeonGitHubActionsVcsTrigger { Kind = RocketSurgeonGitHubActionsTrigger.PullRequest, @@ -277,11 +282,13 @@ IEnumerable secrets IncludePaths = [.. OnPullRequestIncludePaths], ExcludePaths = [.. OnPullRequestExcludePaths], }; + } if (OnPullRequestTargetBranches.Length > 0 || OnPullRequestTargetTags.Length > 0 || OnPullRequestTargetIncludePaths.Length > 0 || OnPullRequestTargetExcludePaths.Length > 0) + { yield return new RocketSurgeonGitHubActionsVcsTrigger { Kind = RocketSurgeonGitHubActionsTrigger.PullRequestTarget, @@ -290,6 +297,7 @@ IEnumerable secrets IncludePaths = [.. OnPullRequestTargetIncludePaths], ExcludePaths = [.. OnPullRequestTargetExcludePaths], }; + } if (OnCronSchedule is null) yield break; @@ -300,4 +308,15 @@ IEnumerable secrets /// The name of the file /// protected string Name { get; } + + /// + /// The default constructor given the file name + /// + /// + protected GithubActionsStepsAttributeBase(string name) + { + Name = name; + ExcludedTargets = []; + NonEntryTargets = []; + } } diff --git a/src/Nuke/GithubActions/HeadlessRunStep.cs b/src/Nuke/GithubActions/HeadlessRunStep.cs index 3344d5b79..c3dede3ae 100644 --- a/src/Nuke/GithubActions/HeadlessRunStep.cs +++ b/src/Nuke/GithubActions/HeadlessRunStep.cs @@ -6,12 +6,6 @@ namespace Rocket.Surgery.Nuke.GithubActions; [PublicAPI] public class HeadlessRunStep : UsingStep { - /// - /// The default constructor - /// - /// - public HeadlessRunStep(string name) : base(name) => Uses = "coactions/setup-xvfb@v1"; - /// public override void Write(CustomFileWriter writer) { @@ -33,4 +27,10 @@ public override void Write(CustomFileWriter writer) /// The working directory where the script is run /// public string? WorkingDirectory { get; set; } + + /// + /// The default constructor + /// + /// + public HeadlessRunStep(string name) : base(name) => Uses = "coactions/setup-xvfb@v1"; } diff --git a/src/Nuke/GithubActions/OnePasswordConnectServerSecret.cs b/src/Nuke/GithubActions/OnePasswordConnectServerSecret.cs index 53f9e4651..75807e018 100644 --- a/src/Nuke/GithubActions/OnePasswordConnectServerSecret.cs +++ b/src/Nuke/GithubActions/OnePasswordConnectServerSecret.cs @@ -23,6 +23,14 @@ public sealed record OnePasswordConnectServerSecret string ConnectHost = "OP_CONNECT_HOST", string ConnectToken = "OP_CONNECT_TOKEN") : ITriggerValue { + /// + public string Prefix => $"steps.{OutputId}.outputs"; + + /// + public string? Default => null; + + internal string OutputId => $"op{HashId(ConnectHost + ConnectToken)}"; + private static string HashId(string value) { var data = SHA256.HashData(Encoding.UTF8.GetBytes(value)); @@ -35,12 +43,4 @@ private static string HashId(string value) return sBuilder.ToString()[..8]; } - - internal string OutputId => $"op{HashId(ConnectHost + ConnectToken)}"; - - /// - public string Prefix => $"steps.{OutputId}.outputs"; - - /// - public string? Default => null; } diff --git a/src/Nuke/GithubActions/OnePasswordConnectServerSecretAttribute.cs b/src/Nuke/GithubActions/OnePasswordConnectServerSecretAttribute.cs index a135161ef..5221b014c 100644 --- a/src/Nuke/GithubActions/OnePasswordConnectServerSecretAttribute.cs +++ b/src/Nuke/GithubActions/OnePasswordConnectServerSecretAttribute.cs @@ -11,15 +11,6 @@ namespace Rocket.Surgery.Nuke.GithubActions; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class OnePasswordConnectServerSecretAttribute(string name, string path) : TriggerValueAttribute(name) { - /// - /// The constructor for the - /// - /// The name of the variable to be output - /// The GitHub variable to item path part for the op reference (eg. op://vault/item) - /// The second half the op reference path - /// param> - public OnePasswordConnectServerSecretAttribute(string name, string variable, string path) : this(name, path) => Variable = variable; - /// /// Convert to a secret /// @@ -67,4 +58,13 @@ public string? ConnectToken /// The github variable that defines the item in the vault /// public string? Variable { get; } + + /// + /// The constructor for the + /// + /// The name of the variable to be output + /// The GitHub variable to item path part for the op reference (eg. op://vault/item) + /// The second half the op reference path + /// param> + public OnePasswordConnectServerSecretAttribute(string name, string variable, string path) : this(name, path) => Variable = variable; } diff --git a/src/Nuke/GithubActions/OnePasswordSecretAttribute.cs b/src/Nuke/GithubActions/OnePasswordSecretAttribute.cs index f7989399a..2c62a23c0 100644 --- a/src/Nuke/GithubActions/OnePasswordSecretAttribute.cs +++ b/src/Nuke/GithubActions/OnePasswordSecretAttribute.cs @@ -11,15 +11,6 @@ namespace Rocket.Surgery.Nuke.GithubActions; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class OnePasswordSecretAttribute(string name, string path) : TriggerValueAttribute(name) { - /// - /// The constructor for the - /// - /// The name of the variable to be output - /// The GitHub variable to item path part for the op reference (eg. op://vault/item) - /// The second half the op reference path - /// param> - public OnePasswordSecretAttribute(string name, string variable, string path) : this(name, path) => Variable = variable; - /// public override ITriggerValue ToTriggerValue() => ToSecret(); @@ -86,6 +77,15 @@ public bool UseConnectServer /// public string? Variable { get; } + /// + /// The constructor for the + /// + /// The name of the variable to be output + /// The GitHub variable to item path part for the op reference (eg. op://vault/item) + /// The second half the op reference path + /// param> + public OnePasswordSecretAttribute(string name, string variable, string path) : this(name, path) => Variable = variable; + /// /// Convert to a secret /// diff --git a/src/Nuke/GithubActions/OnePasswordServiceAccountSecret.cs b/src/Nuke/GithubActions/OnePasswordServiceAccountSecret.cs index 9fac9c893..71f5dcd31 100644 --- a/src/Nuke/GithubActions/OnePasswordServiceAccountSecret.cs +++ b/src/Nuke/GithubActions/OnePasswordServiceAccountSecret.cs @@ -21,6 +21,14 @@ public record OnePasswordServiceAccountSecret string? Variable = null, string Secret = "OP_SERVICE_ACCOUNT_TOKEN") : ITriggerValue { + /// + public string Prefix => $"steps.{OutputId}.outputs"; + + /// + public string? Default => null; + + internal string OutputId => $"op{HashId(Secret)}"; + private static string HashId(string value) { var data = SHA256.HashData(Encoding.UTF8.GetBytes(value)); @@ -33,12 +41,4 @@ private static string HashId(string value) return sBuilder.ToString()[..8]; } - - internal string OutputId => $"op{HashId(Secret)}"; - - /// - public string Prefix => $"steps.{OutputId}.outputs"; - - /// - public string? Default => null; } diff --git a/src/Nuke/GithubActions/OnePasswordServiceAccountSecretAttribute.cs b/src/Nuke/GithubActions/OnePasswordServiceAccountSecretAttribute.cs index 254116154..8ac576b0a 100644 --- a/src/Nuke/GithubActions/OnePasswordServiceAccountSecretAttribute.cs +++ b/src/Nuke/GithubActions/OnePasswordServiceAccountSecretAttribute.cs @@ -11,15 +11,6 @@ namespace Rocket.Surgery.Nuke.GithubActions; [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class OnePasswordServiceAccountSecretAttribute(string name, string path) : TriggerValueAttribute(name) { - /// - /// The constructor for the - /// - /// The name of the variable to be output - /// The GitHub variable to item path part for the op reference (eg. op://vault/item) - /// The second half the op reference path - /// param> - public OnePasswordServiceAccountSecretAttribute(string name, string variable, string path) : this(name, path) => Variable = variable; - /// /// Convert to a secret /// @@ -56,4 +47,13 @@ public string? Secret /// The github variable that defines the item in the vault /// public string? Variable { get; } + + /// + /// The constructor for the + /// + /// The name of the variable to be output + /// The GitHub variable to item path part for the op reference (eg. op://vault/item) + /// The second half the op reference path + /// param> + public OnePasswordServiceAccountSecretAttribute(string name, string variable, string path) : this(name, path) => Variable = variable; } diff --git a/src/Nuke/GithubActions/RocketSurgeonGitHubActionsVcsTrigger.cs b/src/Nuke/GithubActions/RocketSurgeonGitHubActionsVcsTrigger.cs index 7b716a9f5..12b1f7657 100644 --- a/src/Nuke/GithubActions/RocketSurgeonGitHubActionsVcsTrigger.cs +++ b/src/Nuke/GithubActions/RocketSurgeonGitHubActionsVcsTrigger.cs @@ -1,4 +1,5 @@ using System.Collections.Immutable; + using Nuke.Common.CI.GitHubActions.Configuration; using Nuke.Common.Tooling; using Nuke.Common.Utilities.Collections; @@ -19,6 +20,7 @@ public override void Write(CustomFileWriter writer) if (Kind is RocketSurgeonGitHubActionsTrigger.WorkflowDispatch or RocketSurgeonGitHubActionsTrigger.WorkflowCall or RocketSurgeonGitHubActionsTrigger.WorkflowRun) return; if (Kind is RocketSurgeonGitHubActionsTrigger.PullRequest or RocketSurgeonGitHubActionsTrigger.PullRequestTarget) + { using (writer.Indent()) { if (Types.Length > 0) @@ -30,6 +32,7 @@ public override void Write(CustomFileWriter writer) } } } + } using (writer.Indent()) { diff --git a/src/Nuke/GithubActions/RocketSurgeonGitHubActionsWorkflowTrigger.cs b/src/Nuke/GithubActions/RocketSurgeonGitHubActionsWorkflowTrigger.cs index 1d52c0e68..0dca1263f 100644 --- a/src/Nuke/GithubActions/RocketSurgeonGitHubActionsWorkflowTrigger.cs +++ b/src/Nuke/GithubActions/RocketSurgeonGitHubActionsWorkflowTrigger.cs @@ -17,11 +17,14 @@ public override void Write(CustomFileWriter writer) if (Kind is not RocketSurgeonGitHubActionsTrigger.WorkflowDispatch and not RocketSurgeonGitHubActionsTrigger.WorkflowCall and not RocketSurgeonGitHubActionsTrigger.WorkflowRun) + { return; + } using (writer.Indent()) { if (Kind is not RocketSurgeonGitHubActionsTrigger.WorkflowRun) + { if (Inputs.Count > 0) { writer.WriteLine("inputs:"); @@ -42,6 +45,7 @@ and not RocketSurgeonGitHubActionsTrigger.WorkflowCall } } } + } if (Kind is RocketSurgeonGitHubActionsTrigger.WorkflowRun) { diff --git a/src/Nuke/GithubActions/RocketSurgeonsGithubActionsConcurrency.cs b/src/Nuke/GithubActions/RocketSurgeonsGithubActionsConcurrency.cs index 2362aad2f..27f481809 100644 --- a/src/Nuke/GithubActions/RocketSurgeonsGithubActionsConcurrency.cs +++ b/src/Nuke/GithubActions/RocketSurgeonsGithubActionsConcurrency.cs @@ -7,6 +7,15 @@ namespace Rocket.Surgery.Nuke.GithubActions; /// public class RocketSurgeonsGithubActionsConcurrency : ConfigurationEntity { + /// + public override void Write(CustomFileWriter writer) + { + using var _ = writer.Indent(); + if (!string.IsNullOrWhiteSpace(Group)) writer.WriteValue(new("group", Group)); + + if (CancelInProgress.HasValue) writer.WriteLine($"cancel-in-progress: {CancelInProgress.Value.ToString().ToLowerInvariant()}"); + } + /// /// The concurrency group /// @@ -16,13 +25,4 @@ public class RocketSurgeonsGithubActionsConcurrency : ConfigurationEntity /// Cancel existing jobs /// public bool? CancelInProgress { get; set; } - - /// - public override void Write(CustomFileWriter writer) - { - using var _ = writer.Indent(); - if (!string.IsNullOrWhiteSpace(Group)) writer.WriteValue(new("group", Group)); - - if (CancelInProgress.HasValue) writer.WriteLine($"cancel-in-progress: {CancelInProgress.Value.ToString().ToLowerInvariant()}"); - } } diff --git a/src/Nuke/GithubActions/RocketSurgeonsGithubActionsDefaults.cs b/src/Nuke/GithubActions/RocketSurgeonsGithubActionsDefaults.cs index 729817b3b..ed445ade8 100644 --- a/src/Nuke/GithubActions/RocketSurgeonsGithubActionsDefaults.cs +++ b/src/Nuke/GithubActions/RocketSurgeonsGithubActionsDefaults.cs @@ -7,11 +7,6 @@ namespace Rocket.Surgery.Nuke.GithubActions; /// public class RocketSurgeonsGithubActionsDefaults : ConfigurationEntity { - /// - /// The defaults of run - /// - public RocketSurgeonsGithubActionsDefaultsRun? Run { get; set; } - /// public override void Write(CustomFileWriter writer) { @@ -20,4 +15,9 @@ public override void Write(CustomFileWriter writer) writer.WriteLine("run:"); Run.Write(writer); } + + /// + /// The defaults of run + /// + public RocketSurgeonsGithubActionsDefaultsRun? Run { get; set; } } diff --git a/src/Nuke/GithubActions/RocketSurgeonsGithubActionsDefaultsRun.cs b/src/Nuke/GithubActions/RocketSurgeonsGithubActionsDefaultsRun.cs index 6c94268bd..4dacfe57a 100644 --- a/src/Nuke/GithubActions/RocketSurgeonsGithubActionsDefaultsRun.cs +++ b/src/Nuke/GithubActions/RocketSurgeonsGithubActionsDefaultsRun.cs @@ -7,16 +7,6 @@ namespace Rocket.Surgery.Nuke.GithubActions; /// public class RocketSurgeonsGithubActionsDefaultsRun : ConfigurationEntity { - /// - /// The shell - /// - public GithubActionShell? Shell { get; set; } - - /// - /// The working directory where the script is run - /// - public string? WorkingDirectory { get; set; } - /// public override void Write(CustomFileWriter writer) { @@ -26,4 +16,14 @@ public override void Write(CustomFileWriter writer) if (!string.IsNullOrWhiteSpace(Shell?.ToString())) writer.WriteLine($"shell: {Shell}"); } + + /// + /// The shell + /// + public GithubActionShell? Shell { get; set; } + + /// + /// The working directory where the script is run + /// + public string? WorkingDirectory { get; set; } } diff --git a/src/Nuke/GithubActions/SetupDotNetStep.cs b/src/Nuke/GithubActions/SetupDotNetStep.cs index 1536259dc..54f09057c 100644 --- a/src/Nuke/GithubActions/SetupDotNetStep.cs +++ b/src/Nuke/GithubActions/SetupDotNetStep.cs @@ -7,14 +7,6 @@ namespace Rocket.Surgery.Nuke.GithubActions; [PublicAPI] public class SetupDotNetStep : UsingStep { - /// - /// The default constructor - /// - /// - public SetupDotNetStep(string name) : base(name) => - // temporary to deal with sxs issue roll back once https://github.com/actions/setup-dotnet/pull/71 is merged - Uses = "actions/setup-dotnet@v4"; - /// public override void Write(CustomFileWriter writer) { @@ -59,4 +51,12 @@ public override void Write(CustomFileWriter writer) /// NuGet.config using the NUGET_AUTH_TOKEN environment variable as a ClearTextPassword /// public string? SourceUrl { get; set; } + + /// + /// The default constructor + /// + /// + public SetupDotNetStep(string name) : base(name) => + // temporary to deal with sxs issue roll back once https://github.com/actions/setup-dotnet/pull/71 is merged + Uses = "actions/setup-dotnet@v4"; } diff --git a/src/Nuke/GithubActions/StickyPullRequestStep.cs b/src/Nuke/GithubActions/StickyPullRequestStep.cs index f53cd2357..92634a7a8 100644 --- a/src/Nuke/GithubActions/StickyPullRequestStep.cs +++ b/src/Nuke/GithubActions/StickyPullRequestStep.cs @@ -8,12 +8,6 @@ namespace Rocket.Surgery.Nuke.GithubActions; [PublicAPI] public class StickyPullRequestStep : UsingStep { - /// - /// The default constructor - /// - /// - public StickyPullRequestStep(string name) : base(name) => Uses = "marocchino/sticky-pull-request-comment@v2"; - /// public override void Write(CustomFileWriter writer) { @@ -81,4 +75,10 @@ public override void Write(CustomFileWriter writer) /// Only update or recreate if message is different from previous public bool? SkipUnchanged { get; set; } + + /// + /// The default constructor + /// + /// + public StickyPullRequestStep(string name) : base(name) => Uses = "marocchino/sticky-pull-request-comment@v2"; } diff --git a/src/Nuke/GithubActions/UploadArtifactStep.cs b/src/Nuke/GithubActions/UploadArtifactStep.cs index 03369c025..38407dc73 100644 --- a/src/Nuke/GithubActions/UploadArtifactStep.cs +++ b/src/Nuke/GithubActions/UploadArtifactStep.cs @@ -6,18 +6,12 @@ namespace Rocket.Surgery.Nuke.GithubActions; [PublicAPI] public class UploadArtifactStep : UsingStep { - /// - /// The default constructor - /// - /// - public UploadArtifactStep(string name) : base(name) => Uses = "actions/upload-artifact@v4"; - /// public override void Write(CustomFileWriter writer) { - #pragma warning disable CA1308 +#pragma warning disable CA1308 WithProperties(x => x.Kebaberize()); - #pragma warning restore CA1308 +#pragma warning restore CA1308 base.Write(writer); } @@ -51,6 +45,12 @@ public override void Write(CustomFileWriter writer) /// public int? RetentionDays { get; set; } + /// + /// The default constructor + /// + /// + public UploadArtifactStep(string name) : base(name) => Uses = "actions/upload-artifact@v4"; + /// protected override string ComputeStepName(string name) => $"🏺 {name}"; } diff --git a/src/Nuke/HuskyEngine.cs b/src/Nuke/HuskyEngine.cs index 6af37d8a1..ec264fc77 100644 --- a/src/Nuke/HuskyEngine.cs +++ b/src/Nuke/HuskyEngine.cs @@ -17,9 +17,9 @@ public bool AreHooksInstalled(IReadOnlyCollection hooks) return hooksPath.StartsWith(".husky") && AbsolutePath.Create(NukeBuild.RootDirectory / hooksPath / "_" / "husky.sh").FileExists(); } - #pragma warning disable CA1031 +#pragma warning disable CA1031 catch - #pragma warning restore CA1031 +#pragma warning restore CA1031 { return false; } diff --git a/src/Nuke/ICanClean.cs b/src/Nuke/ICanClean.cs index 5cc74e5ad..733abc5b8 100644 --- a/src/Nuke/ICanClean.cs +++ b/src/Nuke/ICanClean.cs @@ -15,51 +15,57 @@ public interface ICanClean : IHaveCleanTarget, IHaveBuildTarget /// clean all artifact directories /// [NonEntryTarget] - public Target CleanWellKnownTemporaryFiles => d => d - .Before(Build) - .TryDependentFor(z => z.Clean) - .Executes( - () => - { - if (this is IHaveArtifacts artifacts) + Target CleanWellKnownTemporaryFiles => d => d + .Before(Build) + .TryDependentFor(z => z.Clean) + .Executes( + () => { - artifacts.ArtifactsDirectory.CreateOrCleanDirectory(); - if (artifacts is IHaveOutputLogs logs) logs.LogsDirectory.CreateDirectory(); + if (this is IHaveArtifacts artifacts) + { + artifacts.ArtifactsDirectory.CreateOrCleanDirectory(); + if (artifacts is IHaveOutputLogs logs) logs.LogsDirectory.CreateDirectory(); - if (artifacts is IHaveTestArtifacts testArtifacts) testArtifacts.TestResultsDirectory.CreateDirectory(); + if (artifacts is IHaveTestArtifacts testArtifacts) testArtifacts.TestResultsDirectory.CreateDirectory(); - if (artifacts is IHaveNuGetPackages nuGetArtifacts) nuGetArtifacts.NuGetPackageDirectory.CreateDirectory(); + if (artifacts is IHaveNuGetPackages nuGetArtifacts) nuGetArtifacts.NuGetPackageDirectory.CreateDirectory(); - if (artifacts is IHavePublishArtifacts publishArtifacts) publishArtifacts.PublishDirectory.CreateDirectory(); + if (artifacts is IHavePublishArtifacts publishArtifacts) publishArtifacts.PublishDirectory.CreateDirectory(); - if (artifacts is IHaveOutputArtifacts outputArtifacts) outputArtifacts.OutputArtifactsDirectory.CreateDirectory(); - } + if (artifacts is IHaveOutputArtifacts outputArtifacts) outputArtifacts.OutputArtifactsDirectory.CreateDirectory(); + } - if (this is IHaveCodeCoverage codeCoverage) codeCoverage.CoverageDirectory.CreateOrCleanDirectory(); + if (this is IHaveCodeCoverage codeCoverage) codeCoverage.CoverageDirectory.CreateOrCleanDirectory(); - // ReSharper disable SuspiciousTypeConversion.Global - if (this is not IMayTheForceBeWithYou forceBeWithYou || !forceBeWithYou.Force) return; + // ReSharper disable SuspiciousTypeConversion.Global + if (this is not IMayTheForceBeWithYou forceBeWithYou || !forceBeWithYou.Force) return; - if (this is IComprehendSamples samples && samples.SampleDirectory.DirectoryExists()) - samples - .SampleDirectory.GlobDirectories("**/bin", "**/obj") - .ForEach(AbsolutePathExtensions.DeleteDirectory); + if (this is IComprehendSamples samples && samples.SampleDirectory.DirectoryExists()) + { + samples + .SampleDirectory.GlobDirectories("**/bin", "**/obj") + .ForEach(AbsolutePathExtensions.DeleteDirectory); + } - if (this is IComprehendSources sources && sources.SourceDirectory.DirectoryExists()) - sources - .SourceDirectory.GlobDirectories("**/bin", "**/obj") - .ForEach(AbsolutePathExtensions.DeleteDirectory); + if (this is IComprehendSources sources && sources.SourceDirectory.DirectoryExists()) + { + sources + .SourceDirectory.GlobDirectories("**/bin", "**/obj") + .ForEach(AbsolutePathExtensions.DeleteDirectory); + } - if (this is IComprehendTemplates templates && templates.TemplatesDirectory.DirectoryExists()) - templates - .TemplatesDirectory.GlobDirectories("**/bin", "**/obj") - .ForEach(AbsolutePathExtensions.DeleteDirectory); + if (this is IComprehendTemplates templates && templates.TemplatesDirectory.DirectoryExists()) + { + templates + .TemplatesDirectory.GlobDirectories("**/bin", "**/obj") + .ForEach(AbsolutePathExtensions.DeleteDirectory); + } - if (this is not IComprehendTests tests || !tests.TestsDirectory.DirectoryExists()) return; + if (this is not IComprehendTests tests || !tests.TestsDirectory.DirectoryExists()) return; - tests - .TestsDirectory.GlobDirectories("**/bin", "**/obj") - .ForEach(AbsolutePathExtensions.DeleteDirectory); - } // ReSharper restore SuspiciousTypeConversion.Global - ); + tests + .TestsDirectory.GlobDirectories("**/bin", "**/obj") + .ForEach(AbsolutePathExtensions.DeleteDirectory); + } // ReSharper restore SuspiciousTypeConversion.Global + ); } diff --git a/src/Nuke/ICanLint.cs b/src/Nuke/ICanLint.cs index 5d3f1e32e..58cbaddfa 100644 --- a/src/Nuke/ICanLint.cs +++ b/src/Nuke/ICanLint.cs @@ -1,10 +1,14 @@ using System.Collections.Immutable; + using LibGit2Sharp; + using Microsoft.Extensions.FileSystemGlobbing; + using Nuke.Common.CI.GitHubActions; using Nuke.Common.IO; using Nuke.Common.Tooling; using Nuke.Common.Tools.Git; + using Serilog; using Serilog.Events; @@ -30,13 +34,13 @@ static IEnumerable FilterFiles(TreeChanges patch) /// /// The default matcher to exclude files from linting /// - public static Matcher DefaultLintMatcher { get; } = ResolveLintMatcher(); + static Matcher DefaultLintMatcher { get; } = ResolveLintMatcher(); /// /// A ensure only the linted files are added to the commit /// [ExcludeTarget] - public Target HuskyLint => + Target HuskyLint => t => t .Unlisted() .OnlyWhenStatic(() => IsLocalBuild) @@ -62,7 +66,7 @@ static IEnumerable FilterFiles(TreeChanges patch) /// /// The lint target /// - public Target LintFiles => t => t + Target LintFiles => t => t .OnlyWhenDynamic(() => LintPaths.Active) .TryDependsOn(a => a.Restore) .TryDependentFor(a => a.Lint) @@ -77,7 +81,7 @@ static IEnumerable FilterFiles(TreeChanges patch) /// /// A ensure only the linted files are added to the commit /// - public Target LintGitAdd => + Target LintGitAdd => t => t .Unlisted() .After(Lint) @@ -103,18 +107,18 @@ static IEnumerable FilterFiles(TreeChanges patch) /// /// The default matcher to exclude files from linting /// - public Matcher LintMatcher => DefaultLintMatcher; + Matcher LintMatcher => DefaultLintMatcher; /// /// The lint paths rooted as an absolute path. /// - public LintPaths LintPaths => lintPaths ??= ResolveLintPathsImpl(); + LintPaths LintPaths => lintPaths ??= ResolveLintPathsImpl(); /// /// A lint target that runs last /// [ExcludeTarget] - public Target PostLint => t => t.Unlisted().After(Lint).TriggeredBy(Lint); + Target PostLint => t => t.Unlisted().After(Lint).TriggeredBy(Lint); private static Matcher ResolveLintMatcher() => new Matcher(StringComparison.OrdinalIgnoreCase) diff --git a/src/Nuke/ICanPrettier.cs b/src/Nuke/ICanPrettier.cs index 4a1663536..c67f2be82 100644 --- a/src/Nuke/ICanPrettier.cs +++ b/src/Nuke/ICanPrettier.cs @@ -19,7 +19,7 @@ public interface ICanPrettier : ICanLint /// /// The prettier target /// - public Target Prettier => + Target Prettier => d => d .TriggeredBy(Lint) .Before(PostLint) @@ -79,7 +79,7 @@ static IEnumerable makeArgsForStagedFiles(ImmutableList /// /// The default matcher for what files prettier supports with the xml plugin /// - public Matcher PrettierMatcher => matcher ??= new Matcher(StringComparison.OrdinalIgnoreCase) + Matcher PrettierMatcher => matcher ??= new Matcher(StringComparison.OrdinalIgnoreCase) .AddInclude("**/*.csproj") .AddInclude("**/*.targets") .AddInclude("**/*.props") diff --git a/src/Nuke/ICanRegenerateBuildConfiguration.cs b/src/Nuke/ICanRegenerateBuildConfiguration.cs index 3e8fade35..2820bc9ad 100644 --- a/src/Nuke/ICanRegenerateBuildConfiguration.cs +++ b/src/Nuke/ICanRegenerateBuildConfiguration.cs @@ -1,7 +1,9 @@ using System.Reflection; + using Nuke.Common.CI; using Nuke.Common.IO; using Nuke.Common.Tools.DotNet; + using Serilog; namespace Rocket.Surgery.Nuke; @@ -15,7 +17,7 @@ public interface ICanRegenerateBuildConfiguration : ICanLint /// /// Regenerate the build configurations /// - public Target RegenerateBuildConfigurations => + Target RegenerateBuildConfigurations => t => t .TriggeredBy(static z => z.Lint) .TryAfter(static z => z.PostLint) diff --git a/src/Nuke/ICanUpdateReadme.cs b/src/Nuke/ICanUpdateReadme.cs index b5e0ed4c8..6365b90dc 100644 --- a/src/Nuke/ICanUpdateReadme.cs +++ b/src/Nuke/ICanUpdateReadme.cs @@ -1,4 +1,5 @@ using Nuke.Common.IO; + using Rocket.Surgery.Nuke.Readme; namespace Rocket.Surgery.Nuke; @@ -13,18 +14,18 @@ public interface ICanUpdateReadme : IHaveSolution /// The readme updater that ensures that all the badges are in sync. /// [Readme] - public ReadmeUpdater Readme => TryGetValue(() => Readme)!; + ReadmeUpdater Readme => TryGetValue(() => Readme)!; /// /// The path to the readme file /// - public AbsolutePath ReadmeFilePath => NukeBuild.RootDirectory / "Readme.md"; + AbsolutePath ReadmeFilePath => NukeBuild.RootDirectory / "Readme.md"; /// /// Loops through the Readme to update sections that are automated to give nuget packages, build histories and more, while /// keeping the rest of the readme correct. /// - public Target GenerateReadme => d => d + Target GenerateReadme => d => d .Unlisted() .TryTriggeredBy(z => z.PostLint) .TryAfter(z => z.PostLint) diff --git a/src/Nuke/ICanUpdateSolution.cs b/src/Nuke/ICanUpdateSolution.cs index 7ba52a273..c5b8a7bce 100644 --- a/src/Nuke/ICanUpdateSolution.cs +++ b/src/Nuke/ICanUpdateSolution.cs @@ -9,11 +9,11 @@ public interface ICanUpdateSolution : IHaveSolution /// /// The solution updater that ensures that all the files are in the solution. /// - public Target GenerateSolutionItems => + Target GenerateSolutionItems => d => d .Unlisted() - // Does not work well on the linting runner - // always seems to produce a commit against the solution + // Does not work well on the linting runner + // always seems to produce a commit against the solution .OnlyWhenStatic(() => IsLocalBuild) .TryTriggeredBy(z => z.PostLint) .TryAfter(z => z.PostLint) @@ -38,5 +38,5 @@ public interface ICanUpdateSolution : IHaveSolution /// /// The name of the folder that contains the solution configuration files in the solution /// - public string SolutionConfigFolderName => "config"; + string SolutionConfigFolderName => "config"; } diff --git a/src/Nuke/IComprehendSamples.cs b/src/Nuke/IComprehendSamples.cs index a6588f158..6aed8ecf7 100644 --- a/src/Nuke/IComprehendSamples.cs +++ b/src/Nuke/IComprehendSamples.cs @@ -10,7 +10,7 @@ public interface IComprehendSamples : IComprehend /// /// The directory where samples will be placed /// - public AbsolutePath SampleDirectory => FilePathExtensions.PickDirectory( + AbsolutePath SampleDirectory => FilePathExtensions.PickDirectory( NukeBuild.RootDirectory / "sample", NukeBuild.RootDirectory / "samples" ); diff --git a/src/Nuke/IComprehendSources.cs b/src/Nuke/IComprehendSources.cs index 8dd32776a..32d311720 100644 --- a/src/Nuke/IComprehendSources.cs +++ b/src/Nuke/IComprehendSources.cs @@ -10,7 +10,7 @@ public interface IComprehendSources : IComprehend /// /// The directory where samples will be placed /// - public AbsolutePath SourceDirectory => FilePathExtensions.PickDirectory( + AbsolutePath SourceDirectory => FilePathExtensions.PickDirectory( NukeBuild.RootDirectory / "src", NukeBuild.RootDirectory / "source", NukeBuild.RootDirectory / "sources" diff --git a/src/Nuke/IComprehendTemplates.cs b/src/Nuke/IComprehendTemplates.cs index cafa48ec3..d17216830 100644 --- a/src/Nuke/IComprehendTemplates.cs +++ b/src/Nuke/IComprehendTemplates.cs @@ -10,7 +10,7 @@ public interface IComprehendTemplates : IComprehend /// /// The directory where templates will be placed /// - public AbsolutePath TemplatesDirectory => FilePathExtensions.PickDirectory( + AbsolutePath TemplatesDirectory => FilePathExtensions.PickDirectory( NukeBuild.RootDirectory / "template", NukeBuild.RootDirectory / "templates" ); diff --git a/src/Nuke/IComprehendTests.cs b/src/Nuke/IComprehendTests.cs index 63ef15102..5b7e0687f 100644 --- a/src/Nuke/IComprehendTests.cs +++ b/src/Nuke/IComprehendTests.cs @@ -34,5 +34,5 @@ public interface IComprehendTests : IComprehend /// /// The coverage data collector /// - public string DataCollector => "Code Coverage"; + string DataCollector => "Code Coverage"; } diff --git a/src/Nuke/IGenerateCodeCoverageBadges.cs b/src/Nuke/IGenerateCodeCoverageBadges.cs index 509a28646..a1e74fd68 100644 --- a/src/Nuke/IGenerateCodeCoverageBadges.cs +++ b/src/Nuke/IGenerateCodeCoverageBadges.cs @@ -12,24 +12,24 @@ public interface IGenerateCodeCoverageBadges : ITriggerCodeCoverageReports, IGen /// /// The directory where the badges will be places /// - public AbsolutePath CoverageBadgeDirectory => CoverageDirectory / "badges"; + AbsolutePath CoverageBadgeDirectory => CoverageDirectory / "badges"; /// /// Generate a code coverage badges for the given reports /// [NonEntryTarget] - public Target GenerateCodeCoverageBadges => d => d - .After(GenerateCodeCoverageReportCobertura) - .TriggeredBy(CollectCodeCoverage) - .Unlisted() - .AssuredAfterFailure() - .ProceedAfterFailure() - .OnlyWhenDynamic(() => InputReports.Any()) - .Executes( - () => ReportGeneratorTasks.ReportGenerator( - s => Defaults(s) - .SetTargetDirectory(CoverageBadgeDirectory) - .SetReportTypes(ReportTypes.Badges) - ) - ); + Target GenerateCodeCoverageBadges => d => d + .After(GenerateCodeCoverageReportCobertura) + .TriggeredBy(CollectCodeCoverage) + .Unlisted() + .AssuredAfterFailure() + .ProceedAfterFailure() + .OnlyWhenDynamic(() => InputReports.Any()) + .Executes( + () => ReportGeneratorTasks.ReportGenerator( + s => Defaults(s) + .SetTargetDirectory(CoverageBadgeDirectory) + .SetReportTypes(ReportTypes.Badges) + ) + ); } diff --git a/src/Nuke/IGenerateCodeCoverageReport.cs b/src/Nuke/IGenerateCodeCoverageReport.cs index 668fd5bcd..a835e0a9d 100644 --- a/src/Nuke/IGenerateCodeCoverageReport.cs +++ b/src/Nuke/IGenerateCodeCoverageReport.cs @@ -12,25 +12,25 @@ public interface IGenerateCodeCoverageReport : ITriggerCodeCoverageReports, IGen /// /// The directory where the report will be placed /// - public AbsolutePath CoverageReportDirectory => CoverageDirectory / "report"; + AbsolutePath CoverageReportDirectory => CoverageDirectory / "report"; /// /// Generates a code coverage report got the given set of input reports /// [NonEntryTarget] - public Target GenerateCodeCoverageReport => d => d - .After(GenerateCodeCoverageReportCobertura) - .TriggeredBy(CollectCodeCoverage) - .Unlisted() - .AssuredAfterFailure() - .ProceedAfterFailure() - .OnlyWhenDynamic(() => InputReports.Any()) - .Executes( - () => ReportGeneratorTasks.ReportGenerator( - s => Defaults(s) - .SetTargetDirectory(CoverageReportDirectory) - // these trample... don't forget next time. - .SetReportTypes( /*ReportTypes.HtmlInline_AzurePipelines_Dark, */ReportTypes.Html_Dark) - ) - ); + Target GenerateCodeCoverageReport => d => d + .After(GenerateCodeCoverageReportCobertura) + .TriggeredBy(CollectCodeCoverage) + .Unlisted() + .AssuredAfterFailure() + .ProceedAfterFailure() + .OnlyWhenDynamic(() => InputReports.Any()) + .Executes( + () => ReportGeneratorTasks.ReportGenerator( + s => Defaults(s) + .SetTargetDirectory(CoverageReportDirectory) + // these trample... don't forget next time. + .SetReportTypes( /*ReportTypes.HtmlInline_AzurePipelines_Dark, */ReportTypes.Html_Dark) + ) + ); } diff --git a/src/Nuke/IGenerateCodeCoverageSummary.cs b/src/Nuke/IGenerateCodeCoverageSummary.cs index ab6865d40..38beb78bb 100644 --- a/src/Nuke/IGenerateCodeCoverageSummary.cs +++ b/src/Nuke/IGenerateCodeCoverageSummary.cs @@ -12,29 +12,29 @@ public interface IGenerateCodeCoverageSummary : ITriggerCodeCoverageReports, IGe /// /// The directory where the summary will be places /// - public AbsolutePath CoverageSummaryDirectory => CoverageDirectory / "summary"; + AbsolutePath CoverageSummaryDirectory => CoverageDirectory / "summary"; /// /// Generate a code coverage summary for the given reports /// [NonEntryTarget] - public Target GenerateCodeCoverageSummary => d => d - .After(GenerateCodeCoverageReportCobertura) - .TriggeredBy(CollectCodeCoverage) - .Unlisted() - .AssuredAfterFailure() - .ProceedAfterFailure() - .OnlyWhenDynamic(() => InputReports.Any()) - .Executes( - () => ReportGeneratorTasks.ReportGenerator( - s => Defaults(s) - .SetTargetDirectory(CoverageSummaryDirectory) - .SetReportTypes( - ReportTypes.HtmlSummary, - ReportTypes.TextSummary, - ReportTypes.MarkdownSummary, - ReportTypes.MarkdownSummaryGithub - ) - ) - ); + Target GenerateCodeCoverageSummary => d => d + .After(GenerateCodeCoverageReportCobertura) + .TriggeredBy(CollectCodeCoverage) + .Unlisted() + .AssuredAfterFailure() + .ProceedAfterFailure() + .OnlyWhenDynamic(() => InputReports.Any()) + .Executes( + () => ReportGeneratorTasks.ReportGenerator( + s => Defaults(s) + .SetTargetDirectory(CoverageSummaryDirectory) + .SetReportTypes( + ReportTypes.HtmlSummary, + ReportTypes.TextSummary, + ReportTypes.MarkdownSummary, + ReportTypes.MarkdownSummaryGithub + ) + ) + ); } diff --git a/src/Nuke/IGenerateDocFx.cs b/src/Nuke/IGenerateDocFx.cs index 1a35cc456..0695cbd54 100644 --- a/src/Nuke/IGenerateDocFx.cs +++ b/src/Nuke/IGenerateDocFx.cs @@ -13,39 +13,39 @@ public interface IGenerateDocFx : IHaveDocs /// Parameter to be used to serve documentation /// [Parameter("serve the docs")] - public bool? Serve => EnvironmentInfo.GetVariable("Serve") - // ?? ValueInjectionUtility.TryGetValue(() => Serve) + bool? Serve => EnvironmentInfo.GetVariable("Serve") + // ?? ValueInjectionUtility.TryGetValue(() => Serve) ?? false; /// /// The docfx tool /// - public Tool Docfx => DotNetTool.GetTool("docfx"); + Tool Docfx => DotNetTool.GetTool("docfx"); /// /// The core docs to generate documentation /// [NonEntryTarget] - public Target GenerateDocFx => d => d - .TryDependentFor(z => z.Docs) - .OnlyWhenStatic(() => DocumentationDirectory.DirectoryExists()) - .OnlyWhenStatic(() => ( DocumentationDirectory / "docfx.json" ).FileExists()) - .Executes( - () => - { - if (Serve == true) + Target GenerateDocFx => d => d + .TryDependentFor(z => z.Docs) + .OnlyWhenStatic(() => DocumentationDirectory.DirectoryExists()) + .OnlyWhenStatic(() => ( DocumentationDirectory / "docfx.json" ).FileExists()) + .Executes( + () => { - Task.Run(() => Docfx($"{DocumentationDirectory / "docfx.json"} --serve")); - - var watcher = new FileSystemWatcher(DocumentationDirectory) { EnableRaisingEvents = true }; - while (true) + if (Serve == true) { - watcher.WaitForChanged(WatcherChangeTypes.All); - Docfx($"{DocumentationDirectory / "docfx.json"}"); + Task.Run(() => Docfx($"{DocumentationDirectory / "docfx.json"} --serve")); + + var watcher = new FileSystemWatcher(DocumentationDirectory) { EnableRaisingEvents = true }; + while (true) + { + watcher.WaitForChanged(WatcherChangeTypes.All); + Docfx($"{DocumentationDirectory / "docfx.json"}"); + } } - } - Docfx($"{DocumentationDirectory / "docfx.json"}"); - } - ); + Docfx($"{DocumentationDirectory / "docfx.json"}"); + } + ); } diff --git a/src/Nuke/IHaveArtifacts.cs b/src/Nuke/IHaveArtifacts.cs index b238ec860..26822a305 100644 --- a/src/Nuke/IHaveArtifacts.cs +++ b/src/Nuke/IHaveArtifacts.cs @@ -11,7 +11,7 @@ public interface IHaveArtifacts : IHave /// The directory where artifacts are to be dropped /// [Parameter("The directory where artifacts are to be dropped", Name = "Artifacts")] - public AbsolutePath ArtifactsDirectory => EnvironmentInfo.GetVariable("Artifacts") + AbsolutePath ArtifactsDirectory => EnvironmentInfo.GetVariable("Artifacts") ?? TryGetValue(() => ArtifactsDirectory) ?? NukeBuild.RootDirectory / "artifacts"; } diff --git a/src/Nuke/IHaveBuildVersion.cs b/src/Nuke/IHaveBuildVersion.cs index 74daa1789..93d4b5c6c 100644 --- a/src/Nuke/IHaveBuildVersion.cs +++ b/src/Nuke/IHaveBuildVersion.cs @@ -11,7 +11,7 @@ public interface IHaveBuildVersion : IHaveGitVersion, IHaveSolution, IHaveConfig /// /// prints the build information. /// - public Target BuildVersion => d => d + Target BuildVersion => d => d .Executes( () => { diff --git a/src/Nuke/IHaveCodeCoverage.cs b/src/Nuke/IHaveCodeCoverage.cs index 95bbe9ca7..ee845f34d 100644 --- a/src/Nuke/IHaveCodeCoverage.cs +++ b/src/Nuke/IHaveCodeCoverage.cs @@ -1,4 +1,5 @@ using System.Xml.Linq; + using Nuke.Common.IO; namespace Rocket.Surgery.Nuke; @@ -12,13 +13,14 @@ namespace Rocket.Surgery.Nuke; /// public interface IHaveCodeCoverage : IHaveArtifacts { - public static IEnumerable DefaultIncludeModulePaths => []; - public static IEnumerable DefaultExcludeModulePaths => []; - public static IEnumerable DefaultIncludeSources => []; - public static IEnumerable DefaultExcludeSources => []; - public static IEnumerable DefaultIncludeAttributes => []; + XDocument CustomizeCoverageRunSettings(XDocument document) => document; + static IEnumerable DefaultIncludeModulePaths => []; + static IEnumerable DefaultExcludeModulePaths => []; + static IEnumerable DefaultIncludeSources => []; + static IEnumerable DefaultExcludeSources => []; + static IEnumerable DefaultIncludeAttributes => []; - public static IEnumerable DefaultExcludeAttributes => + static IEnumerable DefaultExcludeAttributes => [ "System.Diagnostics.DebuggerHiddenAttribute", "System.Diagnostics.DebuggerNonUserCodeAttribute", @@ -27,9 +29,9 @@ public interface IHaveCodeCoverage : IHaveArtifacts "System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute", ]; - public static IEnumerable DefaultIncludeNamespaces => []; + static IEnumerable DefaultIncludeNamespaces => []; - public static IEnumerable DefaultExcludeNamespaces => + static IEnumerable DefaultExcludeNamespaces => [ "Bogus", "FakeItEasy", @@ -51,19 +53,17 @@ public interface IHaveCodeCoverage : IHaveArtifacts /// The directory where coverage artifacts are to be dropped /// [Parameter("The directory where coverage artifacts are to be dropped", Name = "Coverage")] - public AbsolutePath CoverageDirectory => + AbsolutePath CoverageDirectory => EnvironmentInfo.GetVariable("Coverage") ?? TryGetValue(() => CoverageDirectory) ?? NukeBuild.RootDirectory / "coverage"; - public IEnumerable IncludeNamespaces => DefaultIncludeNamespaces; - public IEnumerable ExcludeNamespaces => DefaultExcludeNamespaces; - public IEnumerable IncludeAttributes => DefaultIncludeAttributes; - public IEnumerable ExcludeAttributes => DefaultExcludeAttributes; - public IEnumerable IncludeSources => DefaultIncludeSources; - public IEnumerable ExcludeSources => DefaultExcludeSources; - public IEnumerable IncludeModulePaths => DefaultIncludeModulePaths; - public IEnumerable ExcludeModulePaths => DefaultExcludeModulePaths; - - public XDocument CustomizeCoverageRunSettings(XDocument document) => document; + IEnumerable IncludeNamespaces => DefaultIncludeNamespaces; + IEnumerable ExcludeNamespaces => DefaultExcludeNamespaces; + IEnumerable IncludeAttributes => DefaultIncludeAttributes; + IEnumerable ExcludeAttributes => DefaultExcludeAttributes; + IEnumerable IncludeSources => DefaultIncludeSources; + IEnumerable ExcludeSources => DefaultExcludeSources; + IEnumerable IncludeModulePaths => DefaultIncludeModulePaths; + IEnumerable ExcludeModulePaths => DefaultExcludeModulePaths; } diff --git a/src/Nuke/IHaveConfiguration.cs b/src/Nuke/IHaveConfiguration.cs index f5dbabae8..4ce5b0a98 100644 --- a/src/Nuke/IHaveConfiguration.cs +++ b/src/Nuke/IHaveConfiguration.cs @@ -23,7 +23,7 @@ public interface IHaveConfiguration : IHaveConfiguration /// /// The build configuration /// - public new T Configuration { get; } + new T Configuration { get; } string IHaveConfiguration.Configuration => Configuration.ToString(); } diff --git a/src/Nuke/IHaveDocs.cs b/src/Nuke/IHaveDocs.cs index 8602a1da2..05feec8fe 100644 --- a/src/Nuke/IHaveDocs.cs +++ b/src/Nuke/IHaveDocs.cs @@ -16,10 +16,10 @@ public interface IHaveDocs : IHaveArtifacts /// /// Where the docs are stored /// - public AbsolutePath DocumentationDirectory => NukeBuild.RootDirectory / "docs"; + AbsolutePath DocumentationDirectory => NukeBuild.RootDirectory / "docs"; /// /// Where the docs are output /// - public AbsolutePath DocumentationsOutputDirectory => ArtifactsDirectory / "docs"; + AbsolutePath DocumentationsOutputDirectory => ArtifactsDirectory / "docs"; } diff --git a/src/Nuke/IHaveEnableRestore.cs b/src/Nuke/IHaveEnableRestore.cs index 5f0f86a5e..aa8a625bc 100644 --- a/src/Nuke/IHaveEnableRestore.cs +++ b/src/Nuke/IHaveEnableRestore.cs @@ -9,7 +9,7 @@ public interface IHaveEnableRestore : IHave /// A value indicating whether to enable restoring for a given target /// [Parameter("A value indicating whether to enable restoring for a given target", Name = "EnableRestore")] - public bool EnableRestore => EnvironmentInfo.GetVariable("EnableRestore") + bool EnableRestore => EnvironmentInfo.GetVariable("EnableRestore") ?? TryGetValue(() => EnableRestore) ?? false; } diff --git a/src/Nuke/IHaveNuGetPackages.cs b/src/Nuke/IHaveNuGetPackages.cs index 7669d8a3f..f363ba120 100644 --- a/src/Nuke/IHaveNuGetPackages.cs +++ b/src/Nuke/IHaveNuGetPackages.cs @@ -10,5 +10,5 @@ public interface IHaveNuGetPackages : IHaveArtifacts /// /// The directory where nuget packages will be placed /// - public AbsolutePath NuGetPackageDirectory => ArtifactsDirectory / "nuget"; + AbsolutePath NuGetPackageDirectory => ArtifactsDirectory / "nuget"; } diff --git a/src/Nuke/IHaveOutputArtifacts.cs b/src/Nuke/IHaveOutputArtifacts.cs index ef9119f55..5e4348b0f 100644 --- a/src/Nuke/IHaveOutputArtifacts.cs +++ b/src/Nuke/IHaveOutputArtifacts.cs @@ -10,5 +10,5 @@ public interface IHaveOutputArtifacts : IHaveArtifacts /// /// The directory where packaged output should be placed (zip, webdeploy, etc) /// - public AbsolutePath OutputArtifactsDirectory => ArtifactsDirectory / "output"; + AbsolutePath OutputArtifactsDirectory => ArtifactsDirectory / "output"; } diff --git a/src/Nuke/IHaveOutputLogs.cs b/src/Nuke/IHaveOutputLogs.cs index c3a38e85a..79dd29744 100644 --- a/src/Nuke/IHaveOutputLogs.cs +++ b/src/Nuke/IHaveOutputLogs.cs @@ -10,5 +10,5 @@ public interface IHaveOutputLogs : IHaveArtifacts /// /// The directory where logs will be placed /// - public AbsolutePath LogsDirectory => ArtifactsDirectory / "logs"; + AbsolutePath LogsDirectory => ArtifactsDirectory / "logs"; } diff --git a/src/Nuke/IHavePublicApis.cs b/src/Nuke/IHavePublicApis.cs index 54af22426..537c30079 100644 --- a/src/Nuke/IHavePublicApis.cs +++ b/src/Nuke/IHavePublicApis.cs @@ -3,7 +3,9 @@ using Nuke.Common.Tooling; using Nuke.Common.Tools.DotNet; using Nuke.Common.Tools.MSBuild; + using Rocket.Surgery.Nuke.ProjectModel; + using Serilog; using Serilog.Events; @@ -18,7 +20,7 @@ public interface IHavePublicApis : IHaveSolution, ICanLint, IHaveOutputLogs /// /// Setup to lint the public api projects /// - public Target LintPublicApiAnalyzers => d => + Target LintPublicApiAnalyzers => d => d .TriggeredBy(Lint) .Before(PostLint) @@ -69,7 +71,7 @@ public interface IHavePublicApis : IHaveSolution, ICanLint, IHaveOutputLogs /// /// Ensure the shipped file is up to date /// - public Target MoveUnshippedToShipped => d => + Target MoveUnshippedToShipped => d => d .DependsOn(LintPublicApiAnalyzers) .TriggeredBy(LintPublicApiAnalyzers) @@ -98,26 +100,21 @@ public interface IHavePublicApis : IHaveSolution, ICanLint, IHaveOutputLogs await File.WriteAllTextAsync(unshippedFilePath, "#nullable enable"); } - static async Task> GetLines(AbsolutePath path) - { - return path.FileExists() - ? ( await File.ReadAllLinesAsync(path) ) - .Where(z => z != "#nullable enable") - .ToList() - : []; - } + static async Task> GetLines(AbsolutePath path) => path.FileExists() + ? [.. ( await File.ReadAllLinesAsync(path) ).Where(z => z != "#nullable enable")] + : []; } ); /// /// Setup to lint the public api projects /// - public Target ShipPublicApis => d => d.Triggers(LintPublicApiAnalyzers); + Target ShipPublicApis => d => d.Triggers(LintPublicApiAnalyzers); /// /// Determine if Unshipped apis should always be pushed the Shipped file used in lint-staged to automatically update the shipped file /// - public bool ShouldMoveUnshippedToShipped => true; + bool ShouldMoveUnshippedToShipped => true; /// /// All the projects that depend on the Microsoft.CodeAnalysis.PublicApiAnalyzers package diff --git a/src/Nuke/IHavePublishArtifacts.cs b/src/Nuke/IHavePublishArtifacts.cs index 8108a76ef..232199aac 100644 --- a/src/Nuke/IHavePublishArtifacts.cs +++ b/src/Nuke/IHavePublishArtifacts.cs @@ -10,5 +10,5 @@ public interface IHavePublishArtifacts : IHaveArtifacts /// /// The directory where publish output should be placed /// - public AbsolutePath PublishDirectory => ArtifactsDirectory / "publish"; + AbsolutePath PublishDirectory => ArtifactsDirectory / "publish"; } diff --git a/src/Nuke/IHaveSolution.cs b/src/Nuke/IHaveSolution.cs index cf7ae4f5a..8163a2686 100644 --- a/src/Nuke/IHaveSolution.cs +++ b/src/Nuke/IHaveSolution.cs @@ -11,6 +11,5 @@ public interface IHaveSolution : IHave /// The solution currently being build /// [Solution] - // ReSharper disable once NullableWarningSuppressionIsUsed - public Solution Solution => TryGetValue(() => Solution)!; + Solution Solution => TryGetValue(() => Solution)!; } diff --git a/src/Nuke/IHaveTestArtifacts.cs b/src/Nuke/IHaveTestArtifacts.cs index e2fc2b9ca..aba16dc1b 100644 --- a/src/Nuke/IHaveTestArtifacts.cs +++ b/src/Nuke/IHaveTestArtifacts.cs @@ -13,5 +13,5 @@ public interface IHaveTestArtifacts : IHaveArtifacts /// /// The directory where test results will be placed /// - public AbsolutePath TestResultsDirectory => ArtifactsDirectory / "test"; + AbsolutePath TestResultsDirectory => ArtifactsDirectory / "test"; } diff --git a/src/Nuke/IMayTheForceBeWithYou.cs b/src/Nuke/IMayTheForceBeWithYou.cs index a71fddcb2..9b9a21db8 100644 --- a/src/Nuke/IMayTheForceBeWithYou.cs +++ b/src/Nuke/IMayTheForceBeWithYou.cs @@ -9,5 +9,5 @@ public interface IMayTheForceBeWithYou : INukeBuild /// Force a clean build, otherwise leave some incremental build pieces /// [Parameter("Force a clean build")] - public bool Force { get; } + bool Force { get; } } diff --git a/src/Nuke/IRemoveUnusedDependencies.cs b/src/Nuke/IRemoveUnusedDependencies.cs index a8c17316e..3f2d4441d 100644 --- a/src/Nuke/IRemoveUnusedDependencies.cs +++ b/src/Nuke/IRemoveUnusedDependencies.cs @@ -1,22 +1,25 @@ using System.Collections.Immutable; using System.Xml.Linq; + using Microsoft.Extensions.FileSystemGlobbing; + using Nuke.Common.IO; using Nuke.Common.Tools.Git; + using Serilog; namespace Rocket.Surgery.Nuke; /// -/// Looks at project, props, and target files and removes unused dependencies +/// Looks at project, props, and target files and removes unused dependencies /// public interface IRemoveUnusedDependencies : INukeBuild { /// - /// Looks at project, props, and target files and removes unused dependencies + /// Looks at project, props, and target files and removes unused dependencies /// - public Target RemoveUnusedDependencies - => _ => _ + Target RemoveUnusedDependencies => + _ => _ .TriggeredBy(x => x.Lint) .Executes( async () => @@ -31,17 +34,7 @@ public Target RemoveUnusedDependencies .Select(AbsolutePath.Create) .Match(matcher) .ToAsyncEnumerable() - .SelectAwait( - x => ValueTask.FromResult( - ( Path: x, - Document: XDocument.Load( - x, - LoadOptions.PreserveWhitespace - | LoadOptions.SetBaseUri - | LoadOptions.SetLineInfo - ) ) - ) - ) + .Select(x => (Path: x, Document: XDocument.Load(x, LoadOptions.PreserveWhitespace | LoadOptions.SetBaseUri | LoadOptions.SetLineInfo))) .ToListAsync(); var xmlDocs = documents.ToImmutableDictionary( diff --git a/src/Nuke/ITriggerCodeCoverageReports.cs b/src/Nuke/ITriggerCodeCoverageReports.cs index 0b0571d9d..53d52adb3 100644 --- a/src/Nuke/ITriggerCodeCoverageReports.cs +++ b/src/Nuke/ITriggerCodeCoverageReports.cs @@ -1,6 +1,7 @@ using Nuke.Common.IO; using Nuke.Common.Tooling; using Nuke.Common.Tools.ReportGenerator; + using Rocket.Surgery.Nuke.ProjectModel; // ReSharper disable SuspiciousTypeConversion.Global @@ -20,60 +21,60 @@ public interface ITriggerCodeCoverageReports : IHaveCodeCoverage, IHaveTestTarge /// This will generate code coverage reports from emitted coverage data /// [NonEntryTarget] - public Target CollectCodeCoverage => d => d - .TriggeredBy(Test) - .After(Test) - .Description("Collects code coverage results") - .AssuredAfterFailure() - .Executes( - () => - { - var files = TestResultsDirectory.GlobFiles("**/*.xml", "**/*.json", "**/*.coverage"); - if (!files.Any()) return; + Target CollectCodeCoverage => d => d + .TriggeredBy(Test) + .After(Test) + .Description("Collects code coverage results") + .AssuredAfterFailure() + .Executes( + () => + { + var files = TestResultsDirectory.GlobFiles("**/*.xml", "**/*.json", "**/*.coverage"); + if (!files.Any()) return; - ReportGeneratorTasks.ReportGenerator( - settings => settings - .SetReports(files) - .SetSourceDirectories(NukeBuild.RootDirectory) - .SetProcessWorkingDirectory(RootDirectory) - .SetTargetDirectory(CoverageDirectory) - .AddReportTypes( - ReportTypes.Cobertura, - ReportTypes.Xml, - ReportTypes.lcov, - ReportTypes.Latex, - ReportTypes.OpenCover - ) - ); + ReportGeneratorTasks.ReportGenerator( + settings => settings + .SetReports(files) + .SetSourceDirectories(NukeBuild.RootDirectory) + .SetProcessWorkingDirectory(RootDirectory) + .SetTargetDirectory(CoverageDirectory) + .AddReportTypes( + ReportTypes.Cobertura, + ReportTypes.Xml, + ReportTypes.lcov, + ReportTypes.Latex, + ReportTypes.OpenCover + ) + ); - ( CoverageDirectory / "Cobertura.xml" ).Move( - CoverageDirectory / "test.cobertura.xml", - ExistsPolicy.FileOverwriteIfNewer - ); - } - ); + ( CoverageDirectory / "Cobertura.xml" ).Move( + CoverageDirectory / "test.cobertura.xml", + ExistsPolicy.FileOverwriteIfNewer + ); + } + ); /// /// This will generate code coverage reports from emitted coverage data /// [NonEntryTarget] - public Target GenerateCodeCoverageReportCobertura => d => d - .TriggeredBy(CollectCodeCoverage) - .Unlisted() - .AssuredAfterFailure() - .ProceedAfterFailure() - .OnlyWhenDynamic(() => InputReports.Any()) - .Executes( - () => - { - // var toolPath = ToolPathResolver.GetPackageExecutable("ReportGenerator", "ReportGenerator.dll", framework: "netcoreapp3.0"); - ReportGeneratorTasks.ReportGenerator( - s => Defaults(s) - .SetTargetDirectory(CoverageDirectory) - .SetReportTypes(ReportTypes.Cobertura) - ); - } - ); + Target GenerateCodeCoverageReportCobertura => d => d + .TriggeredBy(CollectCodeCoverage) + .Unlisted() + .AssuredAfterFailure() + .ProceedAfterFailure() + .OnlyWhenDynamic(() => InputReports.Any()) + .Executes( + () => + { + // var toolPath = ToolPathResolver.GetPackageExecutable("ReportGenerator", "ReportGenerator.dll", framework: "netcoreapp3.0"); + ReportGeneratorTasks.ReportGenerator( + s => Defaults(s) + .SetTargetDirectory(CoverageDirectory) + .SetReportTypes(ReportTypes.Cobertura) + ); + } + ); /// /// The input reports @@ -81,7 +82,7 @@ public interface ITriggerCodeCoverageReports : IHaveCodeCoverage, IHaveTestTarge /// /// used to determine if any coverage was emitted, if not the tasks will skip to avoid errors /// - public IEnumerable InputReports => CoverageDirectory.GlobFiles("**/*.cobertura.xml"); + IEnumerable InputReports => CoverageDirectory.GlobFiles("**/*.cobertura.xml"); /// /// ensures that ReportGenerator is called with the appropriate settings given the current state. @@ -90,17 +91,17 @@ public interface ITriggerCodeCoverageReports : IHaveCodeCoverage, IHaveTestTarge /// protected ReportGeneratorSettings Defaults(ReportGeneratorSettings settings) => ( this switch - { - IHaveGitVersion gitVersion => settings.SetTag(gitVersion.GitVersion.InformationalVersion), - IHaveGitRepository { GitRepository: { } } gitRepository => settings.SetTag(gitRepository.GitRepository.Head), - _ => settings, - } + { + IHaveGitVersion gitVersion => settings.SetTag(gitVersion.GitVersion.InformationalVersion), + IHaveGitRepository { GitRepository: { } } gitRepository => settings.SetTag(gitRepository.GitRepository.Head), + _ => settings, + } ) .SetReports(InputReports) .SetSourceDirectories(NukeBuild.RootDirectory) .SetFramework(Constants.ReportGeneratorFramework) - // this is more or less a hack / compromise because - // I was unable to coverage to exclude everything in a given assembly by default. + // this is more or less a hack / compromise because + // I was unable to coverage to exclude everything in a given assembly by default. .AddAssemblyFilters( Solution .AnalyzeAllProjects() diff --git a/src/Nuke/Jobs/CloseMilestoneJobAttribute.cs b/src/Nuke/Jobs/CloseMilestoneJobAttribute.cs index 0f36a97a7..ab9cb7100 100644 --- a/src/Nuke/Jobs/CloseMilestoneJobAttribute.cs +++ b/src/Nuke/Jobs/CloseMilestoneJobAttribute.cs @@ -13,21 +13,6 @@ namespace Rocket.Surgery.Nuke.Jobs; [AttributeUsage(AttributeTargets.Class)] public sealed class CloseMilestoneJobAttribute : GitHubActionsStepsAttribute { - /// - /// Adds draft release support to the build - /// - public CloseMilestoneJobAttribute() : base("close-milestone", GitHubActionsImage.UbuntuLatest) => AutoGenerate = false; - - /// - /// Adds draft release support to the build - /// - public CloseMilestoneJobAttribute(string image, params string[] images) : base("close-milestone", image, images) => AutoGenerate = false; - - /// - /// Adds draft release support to the build - /// - public CloseMilestoneJobAttribute(GitHubActionsImage image) : base("close-milestone", image) => AutoGenerate = false; - /// public override ConfigurationEntity GetConfiguration(IReadOnlyCollection relevantTargets) { @@ -87,4 +72,19 @@ dotnet gitreleasemanager close ` return build; } + + /// + /// Adds draft release support to the build + /// + public CloseMilestoneJobAttribute() : base("close-milestone", GitHubActionsImage.UbuntuLatest) => AutoGenerate = false; + + /// + /// Adds draft release support to the build + /// + public CloseMilestoneJobAttribute(string image, params string[] images) : base("close-milestone", image, images) => AutoGenerate = false; + + /// + /// Adds draft release support to the build + /// + public CloseMilestoneJobAttribute(GitHubActionsImage image) : base("close-milestone", image) => AutoGenerate = false; } diff --git a/src/Nuke/Jobs/DraftReleaseJobAttribute.cs b/src/Nuke/Jobs/DraftReleaseJobAttribute.cs index f7be5ed08..5d3097ea2 100644 --- a/src/Nuke/Jobs/DraftReleaseJobAttribute.cs +++ b/src/Nuke/Jobs/DraftReleaseJobAttribute.cs @@ -14,21 +14,6 @@ namespace Rocket.Surgery.Nuke.Jobs; [AttributeUsage(AttributeTargets.Class)] public sealed class DraftReleaseJobAttribute : GitHubActionsStepsAttribute { - /// - /// Adds draft release support to the build - /// - public DraftReleaseJobAttribute() : base("draft-release", GitHubActionsImage.UbuntuLatest) => AutoGenerate = false; - - /// - /// Adds draft release support to the build - /// - public DraftReleaseJobAttribute(string image, params string[] images) : base("draft-release", image, images) => AutoGenerate = false; - - /// - /// Adds draft release support to the build - /// - public DraftReleaseJobAttribute(GitHubActionsImage image) : base("draft-release", image) => AutoGenerate = false; - /// public override ConfigurationEntity GetConfiguration(IReadOnlyCollection relevantTargets) { @@ -84,4 +69,19 @@ public override ConfigurationEntity GetConfiguration(IReadOnlyCollection + /// Adds draft release support to the build + /// + public DraftReleaseJobAttribute() : base("draft-release", GitHubActionsImage.UbuntuLatest) => AutoGenerate = false; + + /// + /// Adds draft release support to the build + /// + public DraftReleaseJobAttribute(string image, params string[] images) : base("draft-release", image, images) => AutoGenerate = false; + + /// + /// Adds draft release support to the build + /// + public DraftReleaseJobAttribute(GitHubActionsImage image) : base("draft-release", image) => AutoGenerate = false; } diff --git a/src/Nuke/Jobs/PublishNugetPackagesJobAttribute.cs b/src/Nuke/Jobs/PublishNugetPackagesJobAttribute.cs index 86422f23d..e33ad031e 100644 --- a/src/Nuke/Jobs/PublishNugetPackagesJobAttribute.cs +++ b/src/Nuke/Jobs/PublishNugetPackagesJobAttribute.cs @@ -1,7 +1,9 @@ using System.Collections.Immutable; + using Nuke.Common.CI; using Nuke.Common.CI.GitHubActions; using Nuke.Common.Execution; + using Rocket.Surgery.Nuke.GithubActions; #pragma warning disable RS0026, RS0027 @@ -15,52 +17,6 @@ namespace Rocket.Surgery.Nuke.Jobs; [AttributeUsage(AttributeTargets.Class)] public sealed class PublishNugetPackagesJobAttribute : GitHubActionsStepsAttribute { - /// - /// Adds draft release support to the build - /// - public PublishNugetPackagesJobAttribute(string secretKey, string triggeringWorkflow, string[]? includeBranches = null, string? nugetOrgCondition = null) : base( - "publish-nuget", - GitHubActionsImage.UbuntuLatest - ) - { - _secretKey = secretKey; - _triggeringWorkflow = triggeringWorkflow; - _nugetOrgCondition = nugetOrgCondition ?? _nugetOrgCondition; - _includeBranches = [.. includeBranches ?? []]; - AutoGenerate = false; - } - - /// - /// Adds draft release support to the build - /// - public PublishNugetPackagesJobAttribute(string secretKey, string triggeringWorkflow, string[] includeBranches, string? nugetOrgCondition, string image, params string[] images) : base( - "publish-nuget", - image, - images - ) - { - _secretKey = secretKey; - _triggeringWorkflow = triggeringWorkflow; - _nugetOrgCondition = nugetOrgCondition ?? _nugetOrgCondition; - _includeBranches = [.. includeBranches]; - AutoGenerate = false; - } - - /// - /// Adds draft release support to the build - /// - public PublishNugetPackagesJobAttribute(string secretKey, string triggeringWorkflow, GitHubActionsImage image, string[]? includeBranches = null, string? nugetOrgCondition = null) : base( - "publish-nuget", - image - ) - { - _secretKey = secretKey; - _triggeringWorkflow = triggeringWorkflow; - _nugetOrgCondition = nugetOrgCondition ?? _nugetOrgCondition; - _includeBranches = [.. includeBranches ?? []]; - AutoGenerate = false; - } - /// public override ConfigurationEntity GetConfiguration(IReadOnlyCollection relevantTargets) { @@ -117,6 +73,52 @@ public override ConfigurationEntity GetConfiguration(IReadOnlyCollection + /// Adds draft release support to the build + /// + public PublishNugetPackagesJobAttribute(string secretKey, string triggeringWorkflow, string[]? includeBranches = null, string? nugetOrgCondition = null) : base( + "publish-nuget", + GitHubActionsImage.UbuntuLatest + ) + { + _secretKey = secretKey; + _triggeringWorkflow = triggeringWorkflow; + _nugetOrgCondition = nugetOrgCondition ?? _nugetOrgCondition; + _includeBranches = [.. includeBranches ?? []]; + AutoGenerate = false; + } + + /// + /// Adds draft release support to the build + /// + public PublishNugetPackagesJobAttribute(string secretKey, string triggeringWorkflow, string[] includeBranches, string? nugetOrgCondition, string image, params string[] images) : base( + "publish-nuget", + image, + images + ) + { + _secretKey = secretKey; + _triggeringWorkflow = triggeringWorkflow; + _nugetOrgCondition = nugetOrgCondition ?? _nugetOrgCondition; + _includeBranches = [.. includeBranches]; + AutoGenerate = false; + } + + /// + /// Adds draft release support to the build + /// + public PublishNugetPackagesJobAttribute(string secretKey, string triggeringWorkflow, GitHubActionsImage image, string[]? includeBranches = null, string? nugetOrgCondition = null) : base( + "publish-nuget", + image + ) + { + _secretKey = secretKey; + _triggeringWorkflow = triggeringWorkflow; + _nugetOrgCondition = nugetOrgCondition ?? _nugetOrgCondition; + _includeBranches = [.. includeBranches ?? []]; + AutoGenerate = false; + } + private readonly ImmutableArray _includeBranches; private readonly GithubActionCondition _nugetOrgCondition = diff --git a/src/Nuke/Jobs/UpdateMilestoneJobAttribute.cs b/src/Nuke/Jobs/UpdateMilestoneJobAttribute.cs index 7ee523423..b3a5c7616 100644 --- a/src/Nuke/Jobs/UpdateMilestoneJobAttribute.cs +++ b/src/Nuke/Jobs/UpdateMilestoneJobAttribute.cs @@ -13,21 +13,6 @@ namespace Rocket.Surgery.Nuke.Jobs; [AttributeUsage(AttributeTargets.Class)] public sealed class UpdateMilestoneJobAttribute : GitHubActionsStepsAttribute { - /// - /// Adds update milestone support to the build - /// - public UpdateMilestoneJobAttribute() : base("update-milestone", GitHubActionsImage.UbuntuLatest) => AutoGenerate = false; - - /// - /// Adds update milestone support to the build - /// - public UpdateMilestoneJobAttribute(string image, params string[] images) : base("update-milestone", image, images) => AutoGenerate = false; - - /// - /// Adds update milestone support to the build - /// - public UpdateMilestoneJobAttribute(GitHubActionsImage image) : base("update-milestone", image) => AutoGenerate = false; - /// public override ConfigurationEntity GetConfiguration(IReadOnlyCollection relevantTargets) { @@ -57,4 +42,19 @@ public override ConfigurationEntity GetConfiguration(IReadOnlyCollection + /// Adds update milestone support to the build + /// + public UpdateMilestoneJobAttribute() : base("update-milestone", GitHubActionsImage.UbuntuLatest) => AutoGenerate = false; + + /// + /// Adds update milestone support to the build + /// + public UpdateMilestoneJobAttribute(string image, params string[] images) : base("update-milestone", image, images) => AutoGenerate = false; + + /// + /// Adds update milestone support to the build + /// + public UpdateMilestoneJobAttribute(GitHubActionsImage image) : base("update-milestone", image) => AutoGenerate = false; } diff --git a/src/Nuke/LintPaths.cs b/src/Nuke/LintPaths.cs index 31e5993dd..7239f3783 100644 --- a/src/Nuke/LintPaths.cs +++ b/src/Nuke/LintPaths.cs @@ -24,14 +24,13 @@ public sealed class LintPaths trigger, message, new( - () => ( trigger is LintTrigger.None + () => [.. ( trigger is LintTrigger.None ? GitTasks .Git("ls-files", NukeBuild.RootDirectory, logOutput: false, logInvocation: false) .Select(z => z.Text.Trim()) : paths ) .Select(z => Path.IsPathRooted(z) ? (AbsolutePath)z : NukeBuild.RootDirectory / z) - .Match(matcher) - .ToImmutableList() + .Match(matcher)] ) ); @@ -44,7 +43,7 @@ public sealed class LintPaths /// /// public static LintPaths Create(Matcher matcher, LintTrigger trigger, string message, IEnumerable paths) => - new(trigger, message, new(() => paths.Match(matcher).ToImmutableList())); + new(trigger, message, new(() => [.. paths.Match(matcher)])); /// /// Glob against a given matcher to included / exclude files diff --git a/src/Nuke/LocalBuildConventionsAttribute.cs b/src/Nuke/LocalBuildConventionsAttribute.cs index 0ab2c7e8b..0036351d8 100644 --- a/src/Nuke/LocalBuildConventionsAttribute.cs +++ b/src/Nuke/LocalBuildConventionsAttribute.cs @@ -1,4 +1,5 @@ using Nuke.Common.Execution; + using Serilog; namespace Rocket.Surgery.Nuke; diff --git a/src/Nuke/MsBuild/ICanBuildWithMsBuild.cs b/src/Nuke/MsBuild/ICanBuildWithMsBuild.cs index 24978462e..b370b8dbc 100644 --- a/src/Nuke/MsBuild/ICanBuildWithMsBuild.cs +++ b/src/Nuke/MsBuild/ICanBuildWithMsBuild.cs @@ -16,7 +16,7 @@ public interface ICanBuildWithMsBuild : IHaveBuildTarget, /// /// msbuild /// - public Target NetBuild => d => d + Target NetBuild => d => d .DependsOn(Restore) .Unlisted() .Executes( diff --git a/src/Nuke/MsBuild/ICanPackWithMsBuild.cs b/src/Nuke/MsBuild/ICanPackWithMsBuild.cs index 28d8fe2dc..47b164fdd 100644 --- a/src/Nuke/MsBuild/ICanPackWithMsBuild.cs +++ b/src/Nuke/MsBuild/ICanPackWithMsBuild.cs @@ -17,12 +17,12 @@ public interface ICanPackWithMsBuild : IHavePackTarget, /// /// The directory where templates will be placed /// - public static AbsolutePath NuspecDirectory => NukeBuild.RootDirectory / ".nuspec"; + static AbsolutePath NuspecDirectory => NukeBuild.RootDirectory / ".nuspec"; /// /// nuget pack /// - public Target NetPack => d => d + Target NetPack => d => d .DependsOn(Build) .Unlisted() .After(Test) diff --git a/src/Nuke/MsBuild/ICanRestoreWithMsBuild.cs b/src/Nuke/MsBuild/ICanRestoreWithMsBuild.cs index 76ff678d3..c7e49bde2 100644 --- a/src/Nuke/MsBuild/ICanRestoreWithMsBuild.cs +++ b/src/Nuke/MsBuild/ICanRestoreWithMsBuild.cs @@ -10,7 +10,7 @@ public interface ICanRestoreWithMsBuild : IHaveRestoreTarget, IHaveCleanTarget, /// /// nuget restore /// - public Target NetRestore => d => d + Target NetRestore => d => d .DependsOn(Clean) .Unlisted() .Executes( diff --git a/src/Nuke/MsBuild/ICanTestWithXUnit.cs b/src/Nuke/MsBuild/ICanTestWithXUnit.cs index bc0b28d35..0670347f4 100644 --- a/src/Nuke/MsBuild/ICanTestWithXUnit.cs +++ b/src/Nuke/MsBuild/ICanTestWithXUnit.cs @@ -17,7 +17,7 @@ public interface ICanTestWithXUnit : IHaveTestTarget, /// /// xunit test /// - public Target NetTest => d => d + Target NetTest => d => d .DependsOn(Build) .Unlisted() .Executes( diff --git a/src/Nuke/OptionalGitRepositoryAttribute.cs b/src/Nuke/OptionalGitRepositoryAttribute.cs index fbcc7ff86..8b7233c4b 100644 --- a/src/Nuke/OptionalGitRepositoryAttribute.cs +++ b/src/Nuke/OptionalGitRepositoryAttribute.cs @@ -1,6 +1,8 @@ using System.Reflection; + using Nuke.Common.Git; using Nuke.Common.IO; + using Serilog; namespace Rocket.Surgery.Nuke; diff --git a/src/Nuke/PathGrouper.cs b/src/Nuke/PathGrouper.cs index 6fbdb7d2c..3db7e6408 100644 --- a/src/Nuke/PathGrouper.cs +++ b/src/Nuke/PathGrouper.cs @@ -1,5 +1,6 @@ using System.Collections.Immutable; using System.Runtime.InteropServices; + using Nuke.Common.IO; namespace Rocket.Surgery.Nuke; diff --git a/src/Nuke/ProjectModel/NukeSolutionExtensions.cs b/src/Nuke/ProjectModel/NukeSolutionExtensions.cs index 71f8a216e..3dcca7892 100644 --- a/src/Nuke/ProjectModel/NukeSolutionExtensions.cs +++ b/src/Nuke/ProjectModel/NukeSolutionExtensions.cs @@ -1,10 +1,13 @@ using System.Collections.Concurrent; using System.Diagnostics; using System.Runtime.CompilerServices; + using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Microsoft.Build.Locator; + using Nuke.Common.ProjectModel; + using Serilog; using Project = Nuke.Common.ProjectModel.Project; @@ -42,10 +45,7 @@ public static void Initialize() return; - static void triggerAssemblyResolution() - { - new ProjectCollection(); - } + static void triggerAssemblyResolution() => new ProjectCollection(); } internal static Microsoft.Build.Evaluation.Project ParseProject(string projectFile, string? configuration = null, string? targetFramework = null) diff --git a/src/Nuke/Readme/AppVeyorHistory.cs b/src/Nuke/Readme/AppVeyorHistory.cs index 31eeff88f..21e147008 100644 --- a/src/Nuke/Readme/AppVeyorHistory.cs +++ b/src/Nuke/Readme/AppVeyorHistory.cs @@ -2,10 +2,6 @@ namespace Rocket.Surgery.Nuke.Readme; internal class AppVeyorHistory : IHistorySection { - public string Name { get; } = "AppVeyor"; - - public string ConfigKey { get; } = "appveyor"; - public (string badge, string history) Process( IDictionary config, IMarkdownReferences references, @@ -31,6 +27,10 @@ IHaveSolution build "AppVeyor History" ); - return ( $"[!{badge}]{url}", $"[!{historyBadge}]{historyUrl}" ); + return ($"[!{badge}]{url}", $"[!{historyBadge}]{historyUrl}"); } + + public string Name { get; } = "AppVeyor"; + + public string ConfigKey { get; } = "appveyor"; } diff --git a/src/Nuke/Readme/AzurePipelinesHistory.cs b/src/Nuke/Readme/AzurePipelinesHistory.cs index 8eb6bcf83..309c8dbd0 100644 --- a/src/Nuke/Readme/AzurePipelinesHistory.cs +++ b/src/Nuke/Readme/AzurePipelinesHistory.cs @@ -2,10 +2,6 @@ namespace Rocket.Surgery.Nuke.Readme; internal class AzurePipelinesHistory : IHistorySection { - public string Name { get; } = "Azure Pipelines"; - - public string ConfigKey { get; } = "azurepipelines"; - public (string badge, string history) Process( IDictionary config, IMarkdownReferences references, @@ -31,6 +27,10 @@ IHaveSolution build "Azure Pipelines History" ); - return ( $"[!{badge}]{url}", $"[!{historyBadge}]{historyUrl}" ); + return ($"[!{badge}]{url}", $"[!{historyBadge}]{historyUrl}"); } + + public string Name { get; } = "Azure Pipelines"; + + public string ConfigKey { get; } = "azurepipelines"; } diff --git a/src/Nuke/Readme/Badges.cs b/src/Nuke/Readme/Badges.cs index f9c0c67c6..28ea4eecd 100644 --- a/src/Nuke/Readme/Badges.cs +++ b/src/Nuke/Readme/Badges.cs @@ -29,7 +29,7 @@ IHaveSolution build foreach (var section in _sections) { var subConfig = string.IsNullOrEmpty(section.ConfigKey) ? config.ToDictionary(x => (object)x.Key, x => x.Value) : - config.TryGetValue(section.ConfigKey, out var o) ? o as IDictionary : null; + config.TryGetValue(section.ConfigKey, out var o) ? o as IDictionary : null; // Assume if not configured, it will never be able to be rendered if (subConfig is null) continue; diff --git a/src/Nuke/Readme/CodecovSection.cs b/src/Nuke/Readme/CodecovSection.cs index 6bbcb5fc5..8d4fcc0e6 100644 --- a/src/Nuke/Readme/CodecovSection.cs +++ b/src/Nuke/Readme/CodecovSection.cs @@ -2,10 +2,6 @@ namespace Rocket.Surgery.Nuke.Readme; internal class CodecovSection : IBadgeSection { - public string Name => "Codecov"; - - public string ConfigKey => "github"; - public string Process( IDictionary config, IMarkdownReferences references, @@ -23,4 +19,8 @@ IHaveSolution build ); return $"[!{badge}]{url}"; } + + public string Name => "Codecov"; + + public string ConfigKey => "github"; } diff --git a/src/Nuke/Readme/GitHubActionsHistory.cs b/src/Nuke/Readme/GitHubActionsHistory.cs index bc8ef024c..977b3ca0d 100644 --- a/src/Nuke/Readme/GitHubActionsHistory.cs +++ b/src/Nuke/Readme/GitHubActionsHistory.cs @@ -2,10 +2,6 @@ namespace Rocket.Surgery.Nuke.Readme; internal class GitHubActionsHistory : IHistorySection { - public string Name { get; } = "GitHub Actions"; - - public string ConfigKey { get; } = "github"; - public (string badge, string history) Process( IDictionary config, IMarkdownReferences references, @@ -27,6 +23,10 @@ IHaveSolution build "GitHub Actions History" ); - return ( $"[!{badge}]{url}", $"[!{historyBadge}]{url}" ); + return ($"[!{badge}]{url}", $"[!{historyBadge}]{url}"); } + + public string Name { get; } = "GitHub Actions"; + + public string ConfigKey { get; } = "github"; } diff --git a/src/Nuke/Readme/GithubLicenseSection.cs b/src/Nuke/Readme/GithubLicenseSection.cs index 62b9dfcc9..b433b5306 100644 --- a/src/Nuke/Readme/GithubLicenseSection.cs +++ b/src/Nuke/Readme/GithubLicenseSection.cs @@ -2,10 +2,6 @@ namespace Rocket.Surgery.Nuke.Readme; internal class GithubLicenseSection : IBadgeSection { - public string Name => "Github Release"; - - public string ConfigKey => "github"; - public string Process( IDictionary config, IMarkdownReferences references, @@ -23,4 +19,8 @@ IHaveSolution build ); return $"[!{badge}]{url}"; } + + public string Name => "Github Release"; + + public string ConfigKey => "github"; } diff --git a/src/Nuke/Readme/GithubReleaseSection.cs b/src/Nuke/Readme/GithubReleaseSection.cs index ec2b102db..7fff06874 100644 --- a/src/Nuke/Readme/GithubReleaseSection.cs +++ b/src/Nuke/Readme/GithubReleaseSection.cs @@ -2,10 +2,6 @@ namespace Rocket.Surgery.Nuke.Readme; internal class GithubReleaseSection : IBadgeSection { - public string Name => "Github Release"; - - public string ConfigKey => "github"; - public string Process( IDictionary config, IMarkdownReferences references, @@ -23,4 +19,8 @@ IHaveSolution build ); return $"[!{badge}]{url}"; } + + public string Name => "Github Release"; + + public string ConfigKey => "github"; } diff --git a/src/Nuke/Readme/Histories.cs b/src/Nuke/Readme/Histories.cs index ae1fd9c9e..e0ebcc37f 100644 --- a/src/Nuke/Readme/Histories.cs +++ b/src/Nuke/Readme/Histories.cs @@ -30,12 +30,12 @@ IHaveSolution build foreach (var section in _sections) { var subConfig = string.IsNullOrEmpty(section.ConfigKey) ? config.ToDictionary(x => (object)x.Key, x => x.Value) : - config.TryGetValue(section.ConfigKey, out var o) ? o as IDictionary : null; + config.TryGetValue(section.ConfigKey, out var o) ? o as IDictionary : null; // Assume if not configured, it will never be able to be rendered if (subConfig is null) continue; - ( var badge, var history ) = section.Process(subConfig, references, build); - results.Add(( section.Name, badge, history )); + (var badge, var history) = section.Process(subConfig, references, build); + results.Add((section.Name, badge, history)); } var sb = new StringBuilder(); diff --git a/src/Nuke/Readme/IBadgeSection.cs b/src/Nuke/Readme/IBadgeSection.cs index c13b5a711..aef381547 100644 --- a/src/Nuke/Readme/IBadgeSection.cs +++ b/src/Nuke/Readme/IBadgeSection.cs @@ -5,6 +5,15 @@ namespace Rocket.Surgery.Nuke.Readme; /// public interface IBadgeSection { + /// + /// Returns the markdown that will produce the badge + /// + /// + /// + /// + /// + string Process(IDictionary config, IMarkdownReferences references, IHaveSolution build); + /// /// The name of the section /// @@ -14,13 +23,4 @@ public interface IBadgeSection /// The configuration key, if you expect to get configuration from the yaml block. /// string ConfigKey { get; } - - /// - /// Returns the markdown that will produce the badge - /// - /// - /// - /// - /// - string Process(IDictionary config, IMarkdownReferences references, IHaveSolution build); } diff --git a/src/Nuke/Readme/IHistorySection.cs b/src/Nuke/Readme/IHistorySection.cs index e9b7c26db..a44768809 100644 --- a/src/Nuke/Readme/IHistorySection.cs +++ b/src/Nuke/Readme/IHistorySection.cs @@ -5,16 +5,6 @@ namespace Rocket.Surgery.Nuke.Readme; /// public interface IHistorySection { - /// - /// The name of the section - /// - string Name { get; } - - /// - /// The configuration key, if you expect to get configuration from the yaml block. - /// - string ConfigKey { get; } - /// /// Returns the markdown that will produce the badge /// @@ -27,4 +17,14 @@ public interface IHistorySection IMarkdownReferences references, IHaveSolution build ); + + /// + /// The name of the section + /// + string Name { get; } + + /// + /// The configuration key, if you expect to get configuration from the yaml block. + /// + string ConfigKey { get; } } diff --git a/src/Nuke/Readme/IReadmeSection.cs b/src/Nuke/Readme/IReadmeSection.cs index fd5b8ca2f..69c394246 100644 --- a/src/Nuke/Readme/IReadmeSection.cs +++ b/src/Nuke/Readme/IReadmeSection.cs @@ -5,6 +5,15 @@ namespace Rocket.Surgery.Nuke.Readme; /// public interface IReadmeSection { + /// + /// Returns the markdown that will produce the badge + /// + /// + /// + /// + /// + Task Process(IDictionary config, IMarkdownReferences references, IHaveSolution build); + /// /// The name of the section /// @@ -14,13 +23,4 @@ public interface IReadmeSection /// The configuration key, if you expect to get configuration from the yaml block. /// string ConfigKey { get; } - - /// - /// Returns the markdown that will produce the badge - /// - /// - /// - /// - /// - Task Process(IDictionary config, IMarkdownReferences references, IHaveSolution build); } diff --git a/src/Nuke/Readme/NugetPackagesSection.cs b/src/Nuke/Readme/NugetPackagesSection.cs index ec7b7668d..f0f39cf49 100644 --- a/src/Nuke/Readme/NugetPackagesSection.cs +++ b/src/Nuke/Readme/NugetPackagesSection.cs @@ -14,13 +14,13 @@ internal class NugetPackagesSection : IReadmeSection /// public static string GetResult(IDictionary config, IMarkdownReferences references, string packageName) { - #pragma warning disable CA1307, CA1308, CA5351 +#pragma warning disable CA1307, CA1308, CA5351 var hash = Convert .ToBase64String(MD5.HashData(Encoding.ASCII.GetBytes(packageName))) .Replace("=", "") [10..] .ToLowerInvariant(); - #pragma warning restore CA5351, CA1308, CA1307 +#pragma warning restore CA5351, CA1308, CA1307 var nugetUrlReference = references.AddReference($"nuget-{hash}", NugetUrl(packageName)); var nugetVersionBadge = references.AddReference( $"nuget-version-{hash}-badge", diff --git a/src/Nuke/Readme/ReadmeAttribute.cs b/src/Nuke/Readme/ReadmeAttribute.cs index 8035d00a4..65641f025 100644 --- a/src/Nuke/Readme/ReadmeAttribute.cs +++ b/src/Nuke/Readme/ReadmeAttribute.cs @@ -1,4 +1,5 @@ using System.Reflection; + using Nuke.Common.ValueInjection; namespace Rocket.Surgery.Nuke.Readme; diff --git a/src/Nuke/Readme/ReadmeUpdater.cs b/src/Nuke/Readme/ReadmeUpdater.cs index ee1ef5971..7fd4da039 100644 --- a/src/Nuke/Readme/ReadmeUpdater.cs +++ b/src/Nuke/Readme/ReadmeUpdater.cs @@ -1,5 +1,6 @@ using System.Dynamic; using System.Text.RegularExpressions; + using YamlDotNet.Serialization; namespace Rocket.Surgery.Nuke.Readme; @@ -10,34 +11,6 @@ namespace Rocket.Surgery.Nuke.Readme; [PublicAPI] public partial class ReadmeUpdater { - /// - /// Default constructor - /// - public ReadmeUpdater() - { - Sections = new(); - Badges = new(); - History = new(); - References = new(); - Sections - .Add(Badges) - .Add(History) - .Add(References) - ; - Sections.Add(new NugetPackagesSection()); - History - .Add(new AzurePipelinesHistory()) - .Add(new GitHubActionsHistory()) - .Add(new AppVeyorHistory()) - ; - Badges - .Add(new GithubReleaseSection()) - .Add(new GithubLicenseSection()) - .Add(new CodecovSection()) - .Add(new CodacySection()) - ; - } - /// /// Updates the given markdown content with all the sections replaced. /// @@ -54,7 +27,7 @@ public async Task Process(string content, IHaveSolution build) var match = nukeDataRegex.Match(content); var yaml = string.Join(Environment.NewLine, match.Groups.Cast().Skip(1).Select(x => x.Value)); var d = new DeserializerBuilder() - // .WithNamingConvention(new CamelCaseNamingConvention()) + // .WithNamingConvention(new CamelCaseNamingConvention()) .Build(); using var reader = new StringReader(yaml.Trim('\n', '\r')); var config = d.Deserialize(reader); @@ -77,8 +50,8 @@ public async Task Process(string content, IHaveSolution build) var sectionEnd = sectionMatch.Last().Captures[0]; var newSectionContent = await section.Process(config, References, build); ranges.Add( - ( sectionStart.Index + sectionStart.Length, - sectionEnd.Index - ( sectionStart.Index + sectionStart.Length ), newSectionContent ) + (sectionStart.Index + sectionStart.Length, + sectionEnd.Index - ( sectionStart.Index + sectionStart.Length ), newSectionContent) ); } @@ -115,6 +88,34 @@ public async Task Process(string content, IHaveSolution build) /// public Sections Sections { get; } + /// + /// Default constructor + /// + public ReadmeUpdater() + { + Sections = new(); + Badges = new(); + History = new(); + References = new(); + Sections + .Add(Badges) + .Add(History) + .Add(References) + ; + Sections.Add(new NugetPackagesSection()); + History + .Add(new AzurePipelinesHistory()) + .Add(new GitHubActionsHistory()) + .Add(new AppVeyorHistory()) + ; + Badges + .Add(new GithubReleaseSection()) + .Add(new GithubLicenseSection()) + .Add(new CodecovSection()) + .Add(new CodacySection()) + ; + } + [GeneratedRegex("", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline, "en-US")] private static partial Regex MyRegex(); diff --git a/src/Nuke/Readme/Sections.cs b/src/Nuke/Readme/Sections.cs index 3fc6ebb49..8a18efe9e 100644 --- a/src/Nuke/Readme/Sections.cs +++ b/src/Nuke/Readme/Sections.cs @@ -8,13 +8,6 @@ namespace Rocket.Surgery.Nuke.Readme; [PublicAPI] public class Sections { - private readonly Dictionary _sections = new(StringComparer.OrdinalIgnoreCase); - - /// - /// Gets a list of all the sections for markdown use - /// - internal IReadOnlyDictionary AllSections => new ReadOnlyDictionary(_sections); - /// /// Adds a new section. /// @@ -25,4 +18,11 @@ public Sections Add(IReadmeSection section) _sections.Add(section.Name, section); return this; } + + /// + /// Gets a list of all the sections for markdown use + /// + internal IReadOnlyDictionary AllSections => new ReadOnlyDictionary(_sections); + + private readonly Dictionary _sections = new(StringComparer.OrdinalIgnoreCase); } diff --git a/src/Nuke/ResolvedToolsManifest.cs b/src/Nuke/ResolvedToolsManifest.cs index 2af731f01..042e63a5a 100644 --- a/src/Nuke/ResolvedToolsManifest.cs +++ b/src/Nuke/ResolvedToolsManifest.cs @@ -1,6 +1,8 @@ using System.Collections.Immutable; + using Nuke.Common.Tooling; using Nuke.Common.Tools.DotNet; + using Serilog; namespace Rocket.Surgery.Nuke; @@ -26,17 +28,27 @@ public static ResolvedToolsManifest Create(ToolsManifset source) return new(source.Tools.ToImmutableDictionary(z => z.Key, z => z.Value, StringComparer.OrdinalIgnoreCase), commandBuilder.ToImmutable()); } + public bool IsInstalled(string commandName) => commandDefinitions.ContainsKey(commandName) || toolDefinitions.ContainsKey(commandName); + + public ToolDefinition GetToolDefinition(string nugetPackageName) => toolDefinitions.TryGetValue(nugetPackageName, out var tool) + ? tool + : throw new InvalidOperationException($"Tool {nugetPackageName} is not installed"); + + public Tool GetTool(string nugetPackageName) => toolDefinitions.TryGetValue(nugetPackageName, out var tool) + ? CreateHandler(tool.Commands.First()) + : commandDefinitions.TryGetValue(nugetPackageName, out var command) + ? CreateHandler(command.Command) + : throw new InvalidOperationException($"Tool {nugetPackageName} is not installed"); + + public Tool GetProperTool(string nugetPackageName) => GetTool(nugetPackageName); + private static void DefaultLogger(OutputType kind, string message) { // ReSharper disable TemplateIsNotCompileTimeConstantProblem if (kind == OutputType.Std) - { Log.Information(message); - } else - { Log.Warning(message); - } // ReSharper restore TemplateIsNotCompileTimeConstantProblem } @@ -60,28 +72,11 @@ private static Tool CreateHandler(string command) => (arguments, directory, vari logger ?? DefaultLogger, process => { - if (handler is null) - { - return process.AssertZeroExitCode(); - } + if (handler is null) return process.AssertZeroExitCode(); handler.Invoke(process); return process; } ); }; - - public bool IsInstalled(string commandName) => commandDefinitions.ContainsKey(commandName) || toolDefinitions.ContainsKey(commandName); - - public ToolDefinition GetToolDefinition(string nugetPackageName) => toolDefinitions.TryGetValue(nugetPackageName, out var tool) - ? tool - : throw new InvalidOperationException($"Tool {nugetPackageName} is not installed"); - - public Tool GetTool(string nugetPackageName) => toolDefinitions.TryGetValue(nugetPackageName, out var tool) - ? CreateHandler(tool.Commands.First()) - : commandDefinitions.TryGetValue(nugetPackageName, out var command) - ? CreateHandler(command.Command) - : throw new InvalidOperationException($"Tool {nugetPackageName} is not installed"); - - public Tool GetProperTool(string nugetPackageName) => GetTool(nugetPackageName); } diff --git a/src/Nuke/Rocket.Surgery.Nuke.csproj b/src/Nuke/Rocket.Surgery.Nuke.csproj index 72e12cf59..d0e10f357 100644 --- a/src/Nuke/Rocket.Surgery.Nuke.csproj +++ b/src/Nuke/Rocket.Surgery.Nuke.csproj @@ -1,6 +1,6 @@  - net8.0;net9.0 + net8.0;net9.0;net10.0 $(NoWarn);CS0436 true @@ -11,12 +11,12 @@ - - + + - + diff --git a/src/Nuke/SolutionExtensions.cs b/src/Nuke/SolutionExtensions.cs index 712785c5b..337adcda9 100644 --- a/src/Nuke/SolutionExtensions.cs +++ b/src/Nuke/SolutionExtensions.cs @@ -1,4 +1,5 @@ using Nuke.Common.ProjectModel; + using Rocket.Surgery.Nuke.ProjectModel; namespace Rocket.Surgery.Nuke; diff --git a/src/Nuke/SolutionUpdater.cs b/src/Nuke/SolutionUpdater.cs index fff1f4452..31ecdfbc2 100644 --- a/src/Nuke/SolutionUpdater.cs +++ b/src/Nuke/SolutionUpdater.cs @@ -1,7 +1,9 @@ using GlobExpressions; + using Nuke.Common.IO; using Nuke.Common.ProjectModel; using Nuke.Common.Utilities.Collections; + using Serilog; namespace Rocket.Surgery.Nuke; @@ -91,10 +93,10 @@ private static void AddNukeBuilds(Solution solution, SolutionFolder configFolder .Where(z => z.Configurations.Count > 0) .SelectMany( project => project.Configurations.Where(z => z.Key.Contains(".Build.", StringComparison.OrdinalIgnoreCase)), - (project, pair) => ( Project: project, pair.Key ) + (project, pair) => (Project: project, pair.Key) ) .ToArray(); - foreach (( var project, var key ) in projects) + foreach ((var project, var key) in projects) { Log.Logger.Information("Removing {Key} from {Project} configuration", key, project.Name); project.Configurations.Remove(key); @@ -133,10 +135,10 @@ private static bool CleanupSolution(Solution solution) var done = false; var itemValuesToRemove = solution .AllSolutionFolders - .SelectMany(z => z.Items, (folder, pair) => ( Folder: folder, ItemPath: pair.Key, FilePath: solution.Directory / pair.Value )) + .SelectMany(z => z.Items, (folder, pair) => (Folder: folder, ItemPath: pair.Key, FilePath: solution.Directory / pair.Value)) .Where(z => !z.FilePath.FileExists() && !implicitConfigItems.Contains(z.FilePath)) .ToArray(); - foreach (( var folder, var itemPath, _ ) in itemValuesToRemove) + foreach ((var folder, var itemPath, _) in itemValuesToRemove) { done = true; Log.Logger.Information("Removing {ItemPath} from {Folder}", GetItemRelativePath(folder, itemPath), GetSolutionFolderPath(folder)); @@ -147,13 +149,13 @@ private static bool CleanupSolution(Solution solution) .AllSolutionFolders .SelectMany( z => z.Items, - (folder, pair) => ( Folder: folder, ItemPath: pair.Key, + (folder, pair) => (Folder: folder, ItemPath: pair.Key, FilePath: GetItemPath(solution, GetItemRelativeFilePath(folder, pair.Key)), - RealFilePath: solution.Directory / pair.Value ) + RealFilePath: solution.Directory / pair.Value) ) .Where(z => !z.FilePath.FileExists() && !implicitConfigItems.Contains(z.RealFilePath)) .ToArray(); - foreach (( var folder, var itemPath, _, _ ) in itemKeysToRemove) + foreach ((var folder, var itemPath, _, _) in itemKeysToRemove) { done = true; Log.Logger.Information("Removing {ItemPath} from {Folder}", GetItemRelativePath(folder, itemPath), GetSolutionFolderPath(folder)); @@ -220,15 +222,9 @@ private static void NormalizePaths(Solution solution) } } - static string toSolutionPath(string path) - { - return path.Replace('/', '\\'); - } + static string toSolutionPath(string path) => path.Replace('/', '\\'); - static bool isUsingSolutionPath(KeyValuePair item) - { - return item.Value.Contains('\\'); - } + static bool isUsingSolutionPath(KeyValuePair item) => item.Value.Contains('\\'); } private static SolutionFolder _configFolder = null!; diff --git a/src/Nuke/TargetAttributeCache.cs b/src/Nuke/TargetAttributeCache.cs index b0b78b4d9..0dadb2c07 100644 --- a/src/Nuke/TargetAttributeCache.cs +++ b/src/Nuke/TargetAttributeCache.cs @@ -2,6 +2,7 @@ using System.Collections.Immutable; using System.Reflection; using System.Text.Json; + using Nuke.Common.IO; namespace Rocket.Surgery.Nuke; @@ -63,7 +64,7 @@ private static ImmutableSortedDictionary> Populat return items .GroupBy(z => z.Key) - .Select(z => ( z.Key, Targets: z.SelectMany(x => x.GetTargets()).Distinct().Order().ToImmutableArray() )) + .Select(z => (z.Key, Targets: z.SelectMany(x => x.GetTargets()).Distinct().Order().ToImmutableArray())) .OrderBy(z => z.Key) .ToImmutableSortedDictionary(z => z.Key, z => z.Targets); } diff --git a/src/Nuke/TestMethodExtensions.cs b/src/Nuke/TestMethodExtensions.cs index 3e60ba592..33e4f27a1 100644 --- a/src/Nuke/TestMethodExtensions.cs +++ b/src/Nuke/TestMethodExtensions.cs @@ -1,6 +1,8 @@ using System.Collections.Immutable; using System.Xml.Linq; + using Nuke.Common.IO; + using Rocket.Surgery.Nuke.DotNetCore; using Rocket.Surgery.Nuke.ProjectModel; @@ -34,7 +36,7 @@ public static ITargetDefinition EnsureRunSettingsExists(this ITargetDefinitio await using var tempFile = File.Open(runsettings, runsettings.FileExists() ? FileMode.Truncate : FileMode.CreateNew); await typeof(ICanTestWithDotNetCore) .Assembly - // ReSharper disable once NullableWarningSuppressionIsUsed + // ReSharper disable once NullableWarningSuppressionIsUsed .GetManifestResourceStream("Rocket.Surgery.Nuke.default.runsettings")!.CopyToAsync(tempFile); } @@ -60,9 +62,9 @@ await typeof(ICanTestWithDotNetCore) build.IncludeModulePaths.Union(includeNames), build.ExcludeModulePaths.Union(excludePackages) ), - ( build.IncludeAttributes, build.ExcludeAttributes ), - ( build.IncludeNamespaces, build.ExcludeNamespaces ), - ( build.IncludeSources, build.ExcludeSources ) + (build.IncludeAttributes, build.ExcludeAttributes), + (build.IncludeNamespaces, build.ExcludeNamespaces), + (build.IncludeSources, build.ExcludeSources) ); } ); @@ -163,24 +165,12 @@ private static void ManageRunSettings( static (IEnumerable include, IEnumerable exclude) transform( (IEnumerable include, IEnumerable exclude) attributes, Func> transformer - ) - { - return ( attributes.include.SelectMany(transformer), attributes.exclude.SelectMany(transformer) ); - } + ) => (attributes.include.SelectMany(transformer), attributes.exclude.SelectMany(transformer)); - static IEnumerable transformAttribute(string attr) - { - return [$"^{attr.Replace(".", "\\.")}$"]; - } + static IEnumerable transformAttribute(string attr) => [$"^{attr.Replace(".", "\\.")}$"]; - static IEnumerable transformModulePath(string ns) - { - return [$".*{ns}"]; - } + static IEnumerable transformModulePath(string ns) => [$".*{ns}"]; - static IEnumerable transformNamespace(string ns) - { - return [$"^{ns.Replace(".", "\\.")}.*"]; - } + static IEnumerable transformNamespace(string ns) => [$"^{ns.Replace(".", "\\.")}.*"]; } } diff --git a/src/Nuke/TitleEventsAttribute.cs b/src/Nuke/TitleEventsAttribute.cs index 517003273..dae9709dd 100644 --- a/src/Nuke/TitleEventsAttribute.cs +++ b/src/Nuke/TitleEventsAttribute.cs @@ -1,4 +1,5 @@ using Nuke.Common.Execution; + using Serilog; namespace Rocket.Surgery.Nuke; @@ -89,7 +90,7 @@ private static short ProgressPercent(IReadOnlyCollection plan, After: Convert.ToInt16(NukeBuild.IsServerBuild ? 0 : Math.Round((double)step++ / ( (short)plan.Count + 1 ) * 100)); */ - Convert.ToInt16(NukeBuild.IsServerBuild ? 0 : Math.Round(( (double)step++ / ( (short)plan.Count + 1 ) ) * 100)); + Convert.ToInt16(NukeBuild.IsServerBuild ? 0 : Math.Round((double)step++ / ( (short)plan.Count + 1 ) * 100)); private IReadOnlyCollection _plan = []; private int step; diff --git a/src/Nuke/ToolSettingsExtensions.cs b/src/Nuke/ToolSettingsExtensions.cs index a81a7db7d..7b736de46 100644 --- a/src/Nuke/ToolSettingsExtensions.cs +++ b/src/Nuke/ToolSettingsExtensions.cs @@ -1,5 +1,7 @@ using System.Runtime.CompilerServices; + using Newtonsoft.Json.Linq; + using Nuke.Common.IO; using Nuke.Common.Tooling; using Nuke.Common.Tools.GitVersion; diff --git a/src/Nuke/Xamarin/ICanBuildXamarin.cs b/src/Nuke/Xamarin/ICanBuildXamarin.cs index 088a6c1fa..1207c8bfd 100644 --- a/src/Nuke/Xamarin/ICanBuildXamarin.cs +++ b/src/Nuke/Xamarin/ICanBuildXamarin.cs @@ -16,19 +16,19 @@ public interface ICanBuildXamarin : IHaveRestoreTarget, /// /// msbuild /// - public Target Build => d => d - .DependsOn(Restore) - .Executes( - () => MSBuild( - settings => - settings - .SetSolutionFile(Solution) - .SetTargetPlatform(MSBuildTargetPlatform.x64) - .SetConfiguration(Configuration) - .SetDefaultLoggers(LogsDirectory / "build.log") - .SetGitVersionEnvironment(GitVersion) - .SetAssemblyVersion(GitVersion.AssemblyVersion()) - .SetPackageVersion(GitVersion.PackageVersion()) - ) - ); + Target Build => d => d + .DependsOn(Restore) + .Executes( + () => MSBuild( + settings => + settings + .SetSolutionFile(Solution) + .SetTargetPlatform(MSBuildTargetPlatform.x64) + .SetConfiguration(Configuration) + .SetDefaultLoggers(LogsDirectory / "build.log") + .SetGitVersionEnvironment(GitVersion) + .SetAssemblyVersion(GitVersion.AssemblyVersion()) + .SetPackageVersion(GitVersion.PackageVersion()) + ) + ); } diff --git a/src/Nuke/Xamarin/ICanRestoreXamarin.cs b/src/Nuke/Xamarin/ICanRestoreXamarin.cs index cd7834f1a..5a7c6805e 100644 --- a/src/Nuke/Xamarin/ICanRestoreXamarin.cs +++ b/src/Nuke/Xamarin/ICanRestoreXamarin.cs @@ -12,7 +12,7 @@ public interface ICanRestoreXamarin : IHaveGitVersion, IHaveSolution, IHaveClean /// nuget restore /// /// https://developercommunity.visualstudio.com/content/problem/20550/cant-run-dotnet-restore.html - public new Target Restore => d => d + new Target Restore => d => d .DependsOn(Clean) .Executes( () => NuGetRestore( diff --git a/src/Nuke/Xamarin/ICanTestXamarin.cs b/src/Nuke/Xamarin/ICanTestXamarin.cs index 116a4f7fc..bcc7f9ac8 100644 --- a/src/Nuke/Xamarin/ICanTestXamarin.cs +++ b/src/Nuke/Xamarin/ICanTestXamarin.cs @@ -20,7 +20,7 @@ public interface ICanTestXamarin : IHaveTestTarget, /// /// test /// - public new Target Test => d => d + new Target Test => d => d .DependsOn(Build) .OnlyWhenStatic(() => TestsDirectory.DirectoryExists()) .CreateOrCleanDirectory(TestResultsDirectory) diff --git a/src/Nuke/Xamarin/XamarinConfiguration.cs b/src/Nuke/Xamarin/XamarinConfiguration.cs index 86e7009fe..f7508e04e 100644 --- a/src/Nuke/Xamarin/XamarinConfiguration.cs +++ b/src/Nuke/Xamarin/XamarinConfiguration.cs @@ -1,4 +1,5 @@ using System.ComponentModel; + using Nuke.Common.Tooling; #pragma warning disable CA2211 // Non-constant fields should not be visible diff --git a/src/Nuke/Xamarin/apple/IHaveBundleIdentifier.cs b/src/Nuke/Xamarin/apple/IHaveBundleIdentifier.cs index 9ef1783eb..98a961db6 100644 --- a/src/Nuke/Xamarin/apple/IHaveBundleIdentifier.cs +++ b/src/Nuke/Xamarin/apple/IHaveBundleIdentifier.cs @@ -11,7 +11,7 @@ public interface IHaveBundleIdentifier : IHave /// Gets the path for the info plist. /// [Parameter("The application bundle identifier.", Name = "BundleIdentifier")] - public string BundleIdentifier => EnvironmentInfo.GetVariable("BundleIdentifier") + string BundleIdentifier => EnvironmentInfo.GetVariable("BundleIdentifier") ?? TryGetValue(() => BundleIdentifier) ?? "com.surgery.rocket.nuke"; @@ -19,5 +19,5 @@ public interface IHaveBundleIdentifier : IHave /// Gets the suffix for the bundle identifier. /// [Parameter("The identifier suffix.")] - public string Suffix { get; set; } + string Suffix { get; set; } } diff --git a/src/Nuke/Xamarin/apple/IHaveInfoPlist.cs b/src/Nuke/Xamarin/apple/IHaveInfoPlist.cs index 91e0c4c15..33cf01818 100644 --- a/src/Nuke/Xamarin/apple/IHaveInfoPlist.cs +++ b/src/Nuke/Xamarin/apple/IHaveInfoPlist.cs @@ -12,5 +12,5 @@ public interface IHaveInfoPlist : IHave /// Gets the path for the info plist. /// [Parameter("The path to the info.plist.")] - public AbsolutePath InfoPlist { get; } + AbsolutePath InfoPlist { get; } } diff --git a/src/Nuke/Xamarin/apple/IXamarinAppleTarget.cs b/src/Nuke/Xamarin/apple/IXamarinAppleTarget.cs index cace06757..c32f308b8 100644 --- a/src/Nuke/Xamarin/apple/IXamarinAppleTarget.cs +++ b/src/Nuke/Xamarin/apple/IXamarinAppleTarget.cs @@ -11,16 +11,16 @@ public partial interface IXamarinAppleTarget : IHaveBundleIdentifier, IHaveGitVe /// /// modify info.plist /// - public Target ModifyInfoPlist => d => d + Target ModifyInfoPlist => d => d .Executes( () => { Log.Verbose("Info.plist Path: {InfoPlist}", InfoPlist); var plist = Plist.Deserialize(InfoPlist); - #pragma warning disable CA1304, CA1308 +#pragma warning disable CA1304, CA1308 plist["CFBundleIdentifier"] = $"{BundleIdentifier}.{Suffix.ToLowerInvariant()}".TrimEnd('.'); - #pragma warning restore CA1304, CA1308 +#pragma warning restore CA1304, CA1308 Log.Information("CFBundleIdentifier: {CFBundleIdentifier}", plist["CFBundleIdentifier"]); plist["CFBundleShortVersionString"] = GitVersion.MajorMinorPatch(); diff --git a/src/Nuke/Xamarin/apple/Plist.cs b/src/Nuke/Xamarin/apple/Plist.cs index a532d6016..304ea2820 100644 --- a/src/Nuke/Xamarin/apple/Plist.cs +++ b/src/Nuke/Xamarin/apple/Plist.cs @@ -1,7 +1,9 @@ using System.Collections; using System.Globalization; using System.Xml.Linq; + using Nuke.Common.IO; + using Serilog; // ReSharper disable once CheckNamespace @@ -80,9 +82,9 @@ private static dynamic DeserializeXml(XElement element) var key = inner[idx]; if (key.Name.LocalName != "key") { - #pragma warning disable CA2201 +#pragma warning disable CA2201 throw new("Even items need to be keys"); - #pragma warning restore CA2201 +#pragma warning restore CA2201 } idx++; diff --git a/src/Nuke/Xamarin/apple/ios/ICanArchiveiOS.cs b/src/Nuke/Xamarin/apple/ios/ICanArchiveiOS.cs index 8f9d01e9c..3a3cebc9b 100644 --- a/src/Nuke/Xamarin/apple/ios/ICanArchiveiOS.cs +++ b/src/Nuke/Xamarin/apple/ios/ICanArchiveiOS.cs @@ -22,7 +22,7 @@ public interface ICanArchiveiOS : IHavePackTarget, /// /// packages a binary for distribution. /// - public Target ArchiveIpa => d => d + Target ArchiveIpa => d => d .OnlyWhenStatic(() => EnvironmentInfo.Platform == PlatformFamily.OSX) .Executes( () => diff --git a/src/Nuke/Xamarin/apple/ios/ICanBuildXamariniOS.cs b/src/Nuke/Xamarin/apple/ios/ICanBuildXamariniOS.cs index a6b0533a0..338ea97b5 100644 --- a/src/Nuke/Xamarin/apple/ios/ICanBuildXamariniOS.cs +++ b/src/Nuke/Xamarin/apple/ios/ICanBuildXamariniOS.cs @@ -22,7 +22,7 @@ public interface ICanBuildXamariniOS : IXamarinAppleTarget, /// /// msbuild /// - public Target BuildiPhone => d => d + Target BuildiPhone => d => d .DependsOn(Restore) .Executes( () => MSBuild( diff --git a/src/Nuke/Xamarin/apple/ios/ICanPackXamariniOS.cs b/src/Nuke/Xamarin/apple/ios/ICanPackXamariniOS.cs index 5519ea226..98b0593b7 100644 --- a/src/Nuke/Xamarin/apple/ios/ICanPackXamariniOS.cs +++ b/src/Nuke/Xamarin/apple/ios/ICanPackXamariniOS.cs @@ -20,7 +20,7 @@ public interface ICanPackXamariniOS : IHavePackTarget, /// /// packages a binary for distribution. /// - public Target PackiPhone => d => d + Target PackiPhone => d => d .DependsOn(Test) .OnlyWhenStatic(() => EnvironmentInfo.Platform == PlatformFamily.OSX) .Executes( diff --git a/src/Nuke/Xamarin/apple/ios/IHaveIpa.cs b/src/Nuke/Xamarin/apple/ios/IHaveIpa.cs index fff4ce23c..30abb1c19 100644 --- a/src/Nuke/Xamarin/apple/ios/IHaveIpa.cs +++ b/src/Nuke/Xamarin/apple/ios/IHaveIpa.cs @@ -12,7 +12,7 @@ public interface IHaveIpa : IHaveArtifacts /// The directory where the ipa is to be dropped. /// [Parameter("The directory where artifacts are to be dropped", Name = "Ipa")] - public AbsolutePath IpaDirectory => EnvironmentInfo.GetVariable("Ipa") + AbsolutePath IpaDirectory => EnvironmentInfo.GetVariable("Ipa") ?? TryGetValue(() => IpaDirectory) ?? NukeBuild.RootDirectory / "artifacts" / "ios"; } diff --git a/src/Nuke/Xamarin/apple/ios/IHaveiOSTargetPlatform.cs b/src/Nuke/Xamarin/apple/ios/IHaveiOSTargetPlatform.cs index 8a1b7b588..7a08194c7 100644 --- a/src/Nuke/Xamarin/apple/ios/IHaveiOSTargetPlatform.cs +++ b/src/Nuke/Xamarin/apple/ios/IHaveiOSTargetPlatform.cs @@ -13,5 +13,5 @@ public interface IHaveiOSTargetPlatform : IHave /// /// The target platform. [Parameter("The target platform for iOS")] - public TargetPlatform iOSTargetPlatform { get; } + TargetPlatform iOSTargetPlatform { get; } } diff --git a/src/Nuke/Xamarin/apple/ios/TargetPlatform.cs b/src/Nuke/Xamarin/apple/ios/TargetPlatform.cs index 96b6270ad..9091b9490 100644 --- a/src/Nuke/Xamarin/apple/ios/TargetPlatform.cs +++ b/src/Nuke/Xamarin/apple/ios/TargetPlatform.cs @@ -1,4 +1,5 @@ using System.ComponentModel; + using Nuke.Common.Tooling; // ReSharper disable InconsistentNaming diff --git a/src/Nuke/Xamarin/apple/mac/ICanBuildXamarinMac.cs b/src/Nuke/Xamarin/apple/mac/ICanBuildXamarinMac.cs index 1962d1a81..b835e3c79 100644 --- a/src/Nuke/Xamarin/apple/mac/ICanBuildXamarinMac.cs +++ b/src/Nuke/Xamarin/apple/mac/ICanBuildXamarinMac.cs @@ -19,7 +19,7 @@ public interface ICanBuildXamarinMac : IXamarinAppleTarget, /// /// msbuild /// - public new Target Build => d => d + new Target Build => d => d .DependsOn(Restore) .Executes( () => MSBuild( diff --git a/src/Nuke/Xamarin/apple/mac/ICanPackXamarinMac.cs b/src/Nuke/Xamarin/apple/mac/ICanPackXamarinMac.cs index 22742a89d..c9dc3d7e9 100644 --- a/src/Nuke/Xamarin/apple/mac/ICanPackXamarinMac.cs +++ b/src/Nuke/Xamarin/apple/mac/ICanPackXamarinMac.cs @@ -18,7 +18,7 @@ public interface IHavePackXamarinMac : IHavePackTarget, /// /// packages a binary for distribution. /// - public Target Package => d => d + Target Package => d => d .DependsOn(Test) .OnlyWhenStatic(() => EnvironmentInfo.Platform == PlatformFamily.OSX) .Executes( diff --git a/test/Nuke.Tests/Rocket.Surgery.Nuke.Tests.csproj b/test/Nuke.Tests/Rocket.Surgery.Nuke.Tests.csproj index c61ea21f0..3239fd7a5 100644 --- a/test/Nuke.Tests/Rocket.Surgery.Nuke.Tests.csproj +++ b/test/Nuke.Tests/Rocket.Surgery.Nuke.Tests.csproj @@ -1,6 +1,6 @@  - net8.0;net9.0 + net8.0;net9.0;net10.0 diff --git a/test/coverage.runsettings b/test/coverage.runsettings index 1dada981e..e5d650e7e 100644 --- a/test/coverage.runsettings +++ b/test/coverage.runsettings @@ -46,8 +46,6 @@ .*Buildalyzer\.dll .*FakeItEasy\.Analyzer\.CSharp\.dll .*FakeItEasy\.dll - .*FluentAssertions\.Analyzers\.dll - .*FluentAssertions\.dll .*GitVersion\.Tool\.dll .*Humanizer\.Core\.dll .*JetBrains\.Annotations\.dll @@ -73,15 +71,17 @@ .*Rocket\.Surgery\.Extensions\.Testing\.XUnit\.dll .*Rocket\.Surgery\.MSBuild\.CI\.dll .*Rocket\.Surgery\.MSBuild\.GitVersion\.dll + .*Rocket\.Surgery\.MSBuild\.GlobalAnalyzerConfig\.dll .*Rocket\.Surgery\.MSBuild\.SourceLink\.dll + .*Rocket\.Surgery\.MyAssembly\.dll .*Roslynator\.Analyzers\.dll .*Roslynator\.CodeAnalysis\.Analyzers\.dll .*Roslynator\.CodeFixes\.dll .*Roslynator\.Formatting\.Analyzers\.dll .*Roslynator\.Refactorings\.dll .*Serilog\.Extensions\.Logging\.dll + .*Shouldly\.dll .*System\.Collections\.Immutable\.dll - .*System\.Interactive\.Async\.dll .*xunit\.analyzers\.dll .*xunit\.dll .*xunit\.runner\.visualstudio\.dll