Skip to content

Commit

Permalink
feat: use GitHub.Actions.Core to handle GitHub Actions Inputs
Browse files Browse the repository at this point in the history
  • Loading branch information
github-actions[bot] committed Jan 22, 2025
1 parent 0f47ad3 commit a7de3b2
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 47 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/create-release.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ jobs:
# validate
- name: Validate and normalize tag
id: validate
run: dotnet run --project "./src/CysharpActions/CysharpActions.csproj" --no-launch-profile -- validate-tag --tag "${{ inputs.tag }}" ${{ inputs.require-validation && '--require-validation' || '' }}
run: dotnet run --project "./src/CysharpActions/CysharpActions.csproj" --no-launch-profile -- validate-tag --tag "${{ inputs.tag }}"
env:
GH_REPO: ${{ github.repository }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/update-packagejson.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ jobs:
# validate
- name: Validate and normalize tag
id: validate
run: dotnet run --project "./src/CysharpActions/CysharpActions.csproj" --no-launch-profile -- validate-tag --tag "${{ inputs.tag }}" ${{ inputs.require-validation && '--require-validation' || '' }}
run: dotnet run --project "./src/CysharpActions/CysharpActions.csproj" --no-launch-profile -- validate-tag --tag "${{ inputs.tag }}"
env:
GH_REPO: ${{ github.repository }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Expand All @@ -93,7 +93,7 @@ jobs:
# TIPS: Converting file-oath from \n to ,
- name: Update files to version ${{ steps.validate.outputs.normalized-tag }}
id: update
run: dotnet run --project "./src/CysharpActions/CysharpActions.csproj" --no-launch-profile -- update-version --version "${{ steps.validate.outputs.normalized-tag }}" --path-string "${{ inputs.file-path }}" ${{ inputs.dry-run && '--dry-run' || '' }}
run: dotnet run --project "./src/CysharpActions/CysharpActions.csproj" --no-launch-profile -- update-version --version "${{ steps.validate.outputs.normalized-tag }}" --path-string "${{ inputs.file-path }}"
env:
GITHUB_CONTEXT: ${{ toJson(github) }}

Expand Down
3 changes: 1 addition & 2 deletions src/CysharpActions/Commands/CreateReleaseCommand.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using CysharpActions.Utils;
using static CysharpActions.Utils.ZxHelper;

namespace CysharpActions.Commands;

Expand Down Expand Up @@ -40,7 +39,7 @@ public async Task UploadAssetFiles(string[] assetPaths)
foreach (var file in GlobSearch.EnumerateFiles(assetPath))
{
using var _ = new GitHubActionsGroupLogger($"Uploading asset. tag: {tag}. assetPath: {file}");
await $"gh release upload {tag} \"{EscapeArg(file)}\"";
await $"gh release upload {tag} \"{file.EscapeArg()}\"";
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/CysharpActions/CysharpActions.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="GitHub.Actions.Core" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.1" />
<PackageReference Include="Microsoft.Extensions.FileSystemGlobbing" Version="9.0.1" />
<PackageReference Include="ProcessX" Version="1.5.5" />
</ItemGroup>
Expand Down
69 changes: 30 additions & 39 deletions src/CysharpActions/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,22 @@
using CysharpActions.Contexts;
using CysharpActions.Utils;
using Cysharp.Diagnostics;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.DependencyInjection;
using Actions.Core.Extensions;
using Actions.Core.Services;

await using var serviceProvider = new ServiceCollection()
.AddGitHubActionsCore()
.BuildServiceProvider();
ConsoleApp.ServiceProvider = serviceProvider;

var app = ConsoleApp.Create();
app.Add<ActionsBatch>();
app.Run(args);

namespace CysharpActions
{
public class ActionsBatch
public class ActionsBatch(ICoreService githubactions)
{
#pragma warning disable CA1822 // Mark members as static

Expand Down Expand Up @@ -40,17 +47,18 @@ public void Versioning(string tag, string prefix = "", VersionIncrement versionI
/// <returns></returns>
[ConsoleAppFilter<GitHubCliFilter>]
[Command("validate-tag")]
public async Task ValidateTag(string tag, bool requireValidation)
public async Task ValidateTag(string tag, bool requireValidation = false)
{
requireValidation = githubactions.GetBoolInput("require-validation", new InputOptions(false));
var command = new ValidateTagCommand();
var normalizedTag = command.Normalize(tag);
if (requireValidation)
{
await command.ValidateTagAsync(normalizedTag);
}

GitHubOutput("tag", tag);
GitHubOutput("normalized-tag", normalizedTag);
await githubactions.SetOutputAsync("tag", tag);
await githubactions.SetOutputAsync("normalized-tag", normalizedTag);
}

/// <summary>
Expand All @@ -64,13 +72,19 @@ public async Task ValidateTag(string tag, bool requireValidation)
/// </remarks>
[ConsoleAppFilter<GitHubContextFilter>]
[Command("update-version")]
public async Task UpdateVersion(string version, string pathString, bool dryRun)
public async Task UpdateVersion(string version, string pathString, bool dryRun = false)
{
// update version
dryRun = githubactions.GetBoolInput("dry-run", new InputOptions(false));
var command = new UpdateVersionCommand(version);
var paths = SplitByNewLine(pathString);

// update version
var paths = pathString.SplitByNewLine();
foreach (var path in paths)
{
var fullPath = Path.GetFullPath(path);
if (!File.Exists(path))
throw new ActionCommandException($"Upload target file not found", new FileNotFoundException(path));

WriteLog($"Update begin, {path} ...");
if (string.IsNullOrWhiteSpace(path))
{
Expand All @@ -90,10 +104,10 @@ public async Task UpdateVersion(string version, string pathString, bool dryRun)
{
var (commited, sha, branchName, isBranchCreated) = await GitCommitAsync(dryRun, version);

GitHubOutput("commited", commited ? "1" : "0");
GitHubOutput("sha", sha);
GitHubOutput("branch-name", branchName);
GitHubOutput("is-branch-created", isBranchCreated);
await githubactions.SetOutputAsync("commited", commited ? "1" : "0");
await githubactions.SetOutputAsync("sha", sha);
await githubactions.SetOutputAsync("branch-name", branchName);
await githubactions.SetOutputAsync("is-branch-created", isBranchCreated);
}

WriteLog($"Completed ...");
Expand All @@ -106,7 +120,7 @@ public async Task UpdateVersion(string version, string pathString, bool dryRun)
[Command("validate-file-exists")]
public void ValidateFileExists(string pathPatternString)
{
var pathPatterns = SplitByNewLine(pathPatternString);
var pathPatterns = pathPatternString.SplitByNewLine();
foreach (var pathPattern in pathPatterns)
{
using var _ = new GitHubActionsGroupLogger($"Validating path, {pathPattern}");
Expand All @@ -127,7 +141,7 @@ public void ValidateFileExists(string pathPatternString)
[Command("validate-nupkg-exists")]
public void ValidateNupkgExists(string pathPatternString)
{
var pathPatterns = SplitByNewLine(pathPatternString);
var pathPatterns = pathPatternString.SplitByNewLine();
foreach (var pathPattern in pathPatterns)
{
using var _ = new GitHubActionsGroupLogger($"Validating path, {pathPattern}");
Expand Down Expand Up @@ -164,7 +178,7 @@ public void ValidateNupkgExists(string pathPatternString)
[Command("create-release")]
public async Task CreateRelease(string tag, string releaseTitle, string releaseAssetPathString)
{
var releaseAssets = SplitByNewLine(releaseAssetPathString);
var releaseAssets = releaseAssetPathString.SplitByNewLine();

var command = new CreateReleaseCommand(tag, releaseTitle);

Expand Down Expand Up @@ -238,7 +252,7 @@ public void Debug(string[] foo)
WriteLog("Committing change. Running following.");
await $"git config --local user.email \"{email}\"";
await $"git config --local user.name \"{user}\"";
await $"git commit -a -m \"{EscapeArg($"feat: Update package.json to {tag}")}\" -m \"{EscapeArg($"Commit by [GitHub Actions]({GitHubContext.Current.WorkflowRunUrl})")}\"";
await $"git commit -a -m \"{$"feat: Update package.json to {tag}".EscapeArg()}\" -m \"{$"Commit by [GitHub Actions]({GitHubContext.Current.WorkflowRunUrl})".EscapeArg()}\"";

commited = true;
}
Expand All @@ -255,29 +269,6 @@ public void Debug(string[] foo)
OutputFormatType.GitHubActionsOutput => $"{key}={value}",
_ => throw new NotImplementedException(nameof(format)),
};

private static void WriteLog(string value) => Console.WriteLine($"[{DateTime.Now:s}] {value}");

private static void WriteVerbose(string value)
{
if (ActionsBatchOptions.Verbose)
{
WriteLog(value);
}
}

private static void GitHubOutput(string key, string value, [CallerMemberName] string? callerMemberName = null)
{
var input = $"{key}={value}";
var output = Environment.GetEnvironmentVariable("GITHUB_OUTPUT", EnvironmentVariableTarget.Process) ?? Path.Combine(Directory.GetCurrentDirectory(), $"GitHubOutputs/{callerMemberName}");
if (!Directory.Exists(Path.GetDirectoryName(output)))
{
Directory.CreateDirectory(Path.GetDirectoryName(output)!);
}

WriteLog($"GitHub Output: {input}");
File.AppendAllLines(output, [input]);
}
}

internal class GitHubCliFilter(ConsoleAppFilter next) : ConsoleAppFilter(next)
Expand Down
26 changes: 24 additions & 2 deletions src/CysharpActions/Utils/ZxHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public static class ZxHelper
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
public static string EscapeArg(string command)
public static string EscapeArg(this string command)
{
// Windows don't need escape (Windows escape is differ from Linux/macOS)
if (OperatingSystem.IsWindows())
Expand All @@ -20,6 +20,28 @@ public static string EscapeArg(string command)
return "\"" + command + "\"";
}

public static string[] SplitByNewLine(string stringsValue) => stringsValue.Split(["\r\n", "\n"], StringSplitOptions.RemoveEmptyEntries);
/// <summary>
/// Split string by new line.
/// </summary>
/// <param name="stringsValue"></param>
/// <returns></returns>
public static string[] SplitByNewLine(this string stringsValue) => stringsValue.Split(["\\r\\n", "\\n"], StringSplitOptions.RemoveEmptyEntries);

/// <summary>
/// Write log to console with timestamp.
/// </summary>
/// <param name="value"></param>
public static void WriteLog(string value) => Console.WriteLine($"[{DateTime.Now:s}] {value}");

/// <summary>
/// Write log to console with timestamp if verbose is enabled.
/// </summary>
/// <param name="value"></param>
public static void WriteVerbose(string value)
{
if (ActionsBatchOptions.Verbose)
{
WriteLog(value);
}
}
}
3 changes: 2 additions & 1 deletion src/CysharpActions/global.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
global using ConsoleAppFramework;
global using Actions.Core;
global using ConsoleAppFramework;
global using Zx;
global using static CysharpActions.Utils.ZxHelper;

0 comments on commit a7de3b2

Please sign in to comment.