Skip to content

Commit

Permalink
Fix/update apis (#1002)
Browse files Browse the repository at this point in the history
* use ci for build server

* Automatically linting code

---------

Co-authored-by: david-driscoll <david-driscoll@users.noreply.github.com>
  • Loading branch information
david-driscoll and david-driscoll authored Nov 21, 2023
1 parent d9d9531 commit 34e03e3
Show file tree
Hide file tree
Showing 16 changed files with 153 additions and 94 deletions.
2 changes: 1 addition & 1 deletion .build/Build.CI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ public static RocketSurgeonGitHubActionsConfiguration CiMiddleware(RocketSurgeon
.First(z => z.Name.Equals("Build", StringComparison.OrdinalIgnoreCase))
.UseDotNetSdks("6.0", "8.0")
.AddNuGetCache()
// .ConfigureForGitVersion()
// .ConfigureForGitVersion()
.ConfigureStep<CheckoutStep>(step => step.FetchDepth = 0)
.PublishLogs<Pipeline>();

Expand Down
3 changes: 3 additions & 0 deletions .build/Build.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@
[NuGetVerbosityMapping]
[ShutdownDotNetAfterServerBuild]
[LocalBuildConventions]
#pragma warning disable CA1050
public partial class Pipeline : NukeBuild,
#pragma warning restore CA1050
ICanRestoreWithDotNetCore,
ICanBuildWithDotNetCore,
ICanTestWithDotNetCore,
Expand All @@ -35,6 +37,7 @@ public partial class Pipeline : NukeBuild,
IGenerateCodeCoverageReport,
IGenerateCodeCoverageSummary,
IGenerateCodeCoverageBadges,
ICanRegenerateBuildConfiguration,
IHaveConfiguration<Configuration>
{
/// <summary>
Expand Down
1 change: 0 additions & 1 deletion .lintstagedrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ if (!process.env.NUKE_BUILD_ASSEMBLY) {

module.exports = {
'!(*verified|*received).cs': filenames => [`dotnet ${process.env.NUKE_BUILD_ASSEMBLY} lint --lint-files ${filenames.join(' ')}`],
'*.{Shipped.txt,Unshipped.txt}': filenames => [`dotnet ${process.env.NUKE_BUILD_ASSEMBLY} move-unshipped-to-shipped --lint-files ${filenames.join(' ')}`],
'*.{csproj,targets,props,xml}': filenames => [`prettier --write '${filenames.join(`' '`)}`],
'*.{js,ts,jsx,tsx,json,yml,yaml}': filenames => [`prettier --write '${filenames.join(`' '`)}`],
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"prettier": "^3.0.0"
},
"scripts": {
"prepare": "husky install"
"husky": "husky install"
},
"dependencies": {
"which": "^4.0.0"
Expand Down
2 changes: 1 addition & 1 deletion src/Nuke/DotNetCore/ICanDotNetFormat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public interface ICanDotNetFormat : IHaveSolution, ICanLint
d
.TriggeredBy(PostLint)
.After(Lint)
.OnlyWhenStatic(() => IsLocalBuild)
.OnlyWhenStatic(() => IsLocalBuild || LintPaths.Any())
.Executes(
() => LintPaths.Any()
? DotNetTasks.DotNet($"format --severity {DotNetFormatSeverity} --include {string.Join(",", LintPaths)}")
Expand Down
12 changes: 7 additions & 5 deletions src/Nuke/EnsureGitHooksAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,18 +61,17 @@ public void OnBuildInitialized(IReadOnlyCollection<ExecutableTarget> executableT
if (( NukeBuild.RootDirectory / "package.json" ).FileExists() && !NukeBuild.RootDirectory.ContainsDirectory("node_modules"))
{
Log.Information("package.json found running npm install to see if that installs any hooks");
ProcessTasks.StartProcess(ToolPathResolver.GetPathExecutable("npm"), "install", workingDirectory: NukeBuild.RootDirectory)
ProcessTasks.StartProcess(ToolPathResolver.GetPathExecutable("npm"), NukeBuild.IsLocalBuild ? "install" : "ci", workingDirectory: NukeBuild.RootDirectory)
.AssertWaitForExit()
.AssertZeroExitCode();
ProcessTasks.StartProcess(ToolPathResolver.GetPathExecutable("npm"), "run prepare", workingDirectory: NukeBuild.RootDirectory)
.AssertWaitForExit();
}
}

private class HuskyEngine : IGitHooksEngine
{
public bool AreHooksInstalled(IReadOnlyCollection<string> hooks)
{
if (NukeBuild.IsServerBuild) return true;
try
{
var hooksOutput = GitTasks.Git($"config --get core.hookspath", logOutput: false, logInvocation: false);
Expand All @@ -96,8 +95,11 @@ public void InstallHooks(IReadOnlyCollection<string> hooks)
ProcessTasks.StartProcess(ToolPathResolver.GetPathExecutable("npm"), "install", workingDirectory: NukeBuild.RootDirectory)
.AssertWaitForExit()
.AssertZeroExitCode();
ProcessTasks.StartProcess(ToolPathResolver.GetPathExecutable("npm"), "run prepare", workingDirectory: NukeBuild.RootDirectory)
.AssertWaitForExit();
if (NukeBuild.IsLocalBuild)
{
ProcessTasks.StartProcess(ToolPathResolver.GetPathExecutable("npm"), "run husky", workingDirectory: NukeBuild.RootDirectory)
.AssertWaitForExit();
}
}

if (!AreHooksInstalled(hooks))
Expand Down
8 changes: 8 additions & 0 deletions src/Nuke/Extensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.ObjectModel;
using Nuke.Common.CI.GitHubActions;
using Nuke.Common.IO;
using Nuke.Common.Tools.ReportGenerator;
using Nuke.Common.Utilities.Collections;
Expand Down Expand Up @@ -57,6 +58,13 @@ public static T SetReports<T>(this T toolSettings, IEnumerable<AbsolutePath> rep
return toolSettings.SetReports(reports.Select(z => z.ToString()).ToArray());
}

/// <summary>
/// Determine if there is a pullrequest happening or not.
/// </summary>
/// <param name="actions"></param>
/// <returns></returns>
public static bool IsPullRequest(this GitHubActions? actions) => actions?.EventName is "pull_request" or "pull_request_target";

/// <summary>
/// Add a value to the dictionary if it's missing
/// </summary>
Expand Down
5 changes: 3 additions & 2 deletions src/Nuke/GithubActions/GitHubActionsLintAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,16 @@ public override ConfigurationEntity GetConfiguration(IReadOnlyCollection<Executa
.ConfigureStep<CheckoutStep>(
step =>
{
step.FetchDepth = 0;
step.Repository = "${{ github.event.pull_request.head.repo.full_name }}";
step.Ref = "${{ github.event.pull_request.head.ref }}";
}
)
.AddStep(
new UsingStep("Add & Commit")
{
Uses = "EndBug/add-and-commit@v9",
With = { ["message"] = "Automatically linting code", }
Uses = "stefanzweifel/git-auto-commit-action@v5",
With = { ["commit_message"] = "Automatically linting code", }
}
);

Expand Down
8 changes: 4 additions & 4 deletions src/Nuke/GithubActions/GitHubActionsStepsAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,9 @@ public override ConfigurationEntity GetConfiguration(IReadOnlyCollection<Executa

var environmentVariables =
GetAllSecrets(secrets)
// ReSharper disable once CoVariantArrayConversion
// ReSharper disable once CoVariantArrayConversion
.Concat<ITriggerValue>(variables)
// ReSharper disable once CoVariantArrayConversion
// ReSharper disable once CoVariantArrayConversion
.Concat(environmentAttributes)
.SelectMany(
z =>
Expand Down Expand Up @@ -183,8 +183,8 @@ public override ConfigurationEntity GetConfiguration(IReadOnlyCollection<Executa
var lookupTable = new LookupTable<ExecutableTarget, ExecutableTarget[]>();
foreach (var (execute, 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.ToArray()))
)
Expand Down
2 changes: 1 addition & 1 deletion src/Nuke/GithubActions/UsingStep.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ protected void WithProperties(Func<string, string> transformName)
With?.Add(
transformName(property.Name), value switch
{
null => "",
null => string.Empty,
bool b => b.ToString().ToLowerInvariant(),
string s => s,
_ => value.ToString() ?? ""
Expand Down
62 changes: 0 additions & 62 deletions src/Nuke/ICanLint.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
using System.Reflection;
using Nuke.Common.CI.GitHubActions;
using Nuke.Common.IO;
using Nuke.Common.Tooling;
using Nuke.Common.Tools.Git;
using Nuke.Common.Utilities.Collections;
using Serilog;

namespace Rocket.Surgery.Nuke;

Expand Down Expand Up @@ -36,60 +31,3 @@ public interface ICanLint : INukeBuild
/// </summary>
protected internal IEnumerable<AbsolutePath> LintPaths => PrivateLintFiles.Select(z => Path.IsPathRooted(z) ? (AbsolutePath)z : RootDirectory / z);
}

/// <summary>
/// Allows the build to lint staged files, as well as lint files from a given pull request.
/// </summary>
/// <remarks>
/// uses the lint-staged npm package under the covers, with dotnet nuke lint-staged as the entry point.
/// </remarks>
public interface ICanLintStagedFiles : ICanRegenerateBuildConfiguration, INukeBuild
{
/// <summary>
/// Run staged lint tasks
/// </summary>
public Target LintStaged => t =>
t
.DependsOn(RegenerateBuildConfigurations)
.OnlyWhenDynamic(() => LintStagedIsPullRequest || IsLocalBuild)
.Executes(
() => ProcessTasks.StartProcess(
ToolPathResolver.GetPathExecutable("npx"),
$"lint-staged -r {( LintStagedIsPullRequest ? $"""--diff="origin/{GitHubActions.Instance.BaseRef}...origin/{GitHubActions.Instance.HeadRef}" """ : "" )}",
environmentVariables: EnvironmentInfo.Variables
.AddIfMissing("NUKE_INTERNAL_INTERCEPTOR", "1")
// ReSharper disable once NullableWarningSuppressionIsUsed
.AddIfMissing("NUKE_BUILD_ASSEMBLY", RootDirectory.GetRelativePathTo(Assembly.GetEntryAssembly()!.Location)),
logOutput: true,
logger: (type, s) =>
{
if (type == OutputType.Std)
{
// ReSharper disable once TemplateIsNotCompileTimeConstantProblem
Log.Information(s);
}
else
{
// ReSharper disable once TemplateIsNotCompileTimeConstantProblem
Log.Error(s);
}
}
).AssertWaitForExit().AssertZeroExitCode()
)
.Executes(
() =>
{
GitTasks.Git("add .nuke/build.schema.json");
GitTasks.Git("add .github/workflows/*.yml");
if (this is IHavePublicApis)
{
GitTasks.Git("add *PublicAPI.Shipped.txt *PublicAPI.Unshipped.txt");
}
}
);

/// <summary>
/// Defines if the current environment is a pull request
/// </summary>
public bool LintStagedIsPullRequest => GitHubActions.Instance?.IsPullRequest == true;
}
59 changes: 59 additions & 0 deletions src/Nuke/ICanLintStagedFiles.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using System.Reflection;
using Nuke.Common.CI.GitHubActions;
using Nuke.Common.IO;
using Nuke.Common.Tooling;
using Nuke.Common.Tools.Git;
using Rocket.Surgery.Nuke.DotNetCore;
using Serilog;

namespace Rocket.Surgery.Nuke;

/// <summary>
/// Allows the build to lint staged files, as well as lint files from a given pull request.
/// </summary>
/// <remarks>
/// uses the lint-staged npm package under the covers, with dotnet nuke lint-staged as the entry point.
/// </remarks>
public interface ICanLintStagedFiles : INukeBuild
{
/// <summary>
/// Run staged lint tasks
/// </summary>
public Target LintStaged => t =>
t
.Executes(
() => ProcessTasks.StartProcess(
ToolPathResolver.GetPathExecutable("npx"),
GitHubActions.Instance.IsPullRequest() ? $"lint-staged -r --diff=\"origin/{GitHubActions.Instance.BaseRef}...origin/{GitHubActions.Instance.HeadRef}\"" : "lint-staged -r",
environmentVariables: EnvironmentInfo.Variables
.AddIfMissing("NUKE_INTERNAL_INTERCEPTOR", "1")
// ReSharper disable once NullableWarningSuppressionIsUsed
.AddIfMissing("NUKE_BUILD_ASSEMBLY", RootDirectory.GetRelativePathTo(Assembly.GetEntryAssembly()!.Location)),
logOutput: true,
logger: (type, s) =>
{
if (type == OutputType.Std)
{
// ReSharper disable once TemplateIsNotCompileTimeConstantProblem
Log.Information(s);
}
else
{
// ReSharper disable once TemplateIsNotCompileTimeConstantProblem
Log.Error(s);
}
}
).AssertWaitForExit().AssertZeroExitCode()
)
.Executes(
() =>
{
GitTasks.Git("add .nuke/build.schema.json");
GitTasks.Git("add .github/workflows/*.yml");
if (this is IHavePublicApis)
{
GitTasks.Git("add *PublicAPI.Shipped.txt *PublicAPI.Unshipped.txt");
}
}
);
}
6 changes: 4 additions & 2 deletions src/Nuke/ICanRegenerateBuildConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,18 @@ public interface ICanRegenerateBuildConfiguration
{
internal Target RegenerateBuildConfigurations => t =>
t
.TryDependentFor<ICanLintStagedFiles>(static z => z.LintStaged)
.TryTriggeredBy<ICanLint>(static z => z.Lint)
.Unlisted()
.Executes(
() =>
{
var allHosts = this.GetType()
var allHosts = GetType()
.GetCustomAttributes<ConfigurationAttributeBase>()
.OfType<IConfigurationGenerator>();

allHosts
// ReSharper disable once NullableWarningSuppressionIsUsed
// ReSharper disable once NullableWarningSuppressionIsUsed
.Select(z => $"""{Assembly.GetEntryAssembly()!.Location} --{BuildServerConfigurationGeneration.ConfigurationParameterName} {z.Id} --host {z.HostName}""")
.ForEach(
command => DotNetTasks.DotNet(
Expand Down
2 changes: 1 addition & 1 deletion src/Nuke/ICanUpdateReadme.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public interface ICanUpdateReadme : IHaveSolution
/// </summary>
public Target GenerateReadme => d => d
.Unlisted()
.OnlyWhenStatic(() => NukeBuild.IsLocalBuild)
.OnlyWhenStatic(() => IsLocalBuild)
.Executes(
() =>
{
Expand Down
16 changes: 3 additions & 13 deletions src/Nuke/IHavePublicApis.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public interface IHavePublicApis : IHaveSolution, ICanLint
/// <summary>
/// Determine if Unshipped apis should always be pushed the Shipped file used in lint-staged to automatically update the shipped file
/// </summary>
public bool ShouldMoveUnshippedToShipped => IsLocalBuild;
public bool ShouldMoveUnshippedToShipped => true;

/// <summary>
/// All the projects that depend on the Microsoft.CodeAnalysis.PublicApiAnalyzers package
Expand Down Expand Up @@ -49,7 +49,6 @@ private static AbsolutePath GetUnshippedFilePath(AbsolutePath directory)
public Target LintPublicApiAnalyzers => d =>
d
.TriggeredBy(Lint)
.OnlyWhenDynamic(() => IsLocalBuild)
.Unlisted()
.Executes(
async () =>
Expand All @@ -68,16 +67,7 @@ private static AbsolutePath GetUnshippedFilePath(AbsolutePath directory)
await File.WriteAllTextAsync(unshippedFilePath, "#nullable enable");
}

#pragma warning disable CA1860
if (LintPaths.Any())
#pragma warning restore CA1860
{
DotNetTasks.DotNet($"format {project.Path} --diagnostics=RS0016 --include {string.Join(",", LintPaths)}");
}
else
{
DotNetTasks.DotNet($"format {project.Path} --diagnostics=RS0016");
}
DotNetTasks.DotNet($"format {project.Path} --diagnostics=RS0016");
}
}
);
Expand All @@ -88,7 +78,7 @@ private static AbsolutePath GetUnshippedFilePath(AbsolutePath directory)
[UsedImplicitly]
public Target MoveUnshippedToShipped => d =>
d
.After(LintPublicApiAnalyzers)
.DependsOn(LintPublicApiAnalyzers)
.TriggeredBy(LintPublicApiAnalyzers)
.OnlyWhenDynamic(() => ShouldMoveUnshippedToShipped)
.Executes(
Expand Down
Loading

0 comments on commit 34e03e3

Please sign in to comment.