Skip to content

Commit

Permalink
Merge pull request #125 from guitarrapc/feature/ConsoleApp5
Browse files Browse the repository at this point in the history
feat: bump ConsoleAppFramework v5
  • Loading branch information
guitarrapc authored Feb 6, 2025
2 parents fb4e7c5 + 930b7d4 commit 9c22c08
Show file tree
Hide file tree
Showing 7 changed files with 69 additions and 47 deletions.
1 change: 1 addition & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<Project>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<LangVersion>Latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<!-- Set this to true to enable faster builds in Visual Studio. https://github.com/dotnet/project-system/blob/main/docs/build-acceleration.md -->
Expand Down
2 changes: 1 addition & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="ConsoleAppFramework" Version="4.2.4" />
<PackageVersion Include="ConsoleAppFramework" Version="5.4.0" />
<PackageVersion Include="Microsoft.Extensions.Logging" Version="9.0.1" />
<!-- Tests -->
<PackageVersion Include="GitHubActionsTestLogger" Version="2.4.1" />
Expand Down
8 changes: 1 addition & 7 deletions src/UnityBuildRunner.Core/DefaultBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,7 @@ Starting Unity Build.
WorkingDirectory = settings.WorkingDirectory,
UseShellExecute = false,
CreateNoWindow = true,
});

if (process is null)
{
throw new OperationCanceledException("Could not start Unity. Somthing blocked creating process.");
}

}) ?? throw new OperationCanceledException("Could not start Unity. Somthing blocked creating process.");
var unityProcessExitCode = 0;
try
{
Expand Down
42 changes: 29 additions & 13 deletions src/UnityBuildRunner.Core/DefaultSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public CancellationTokenSource CreateCancellationTokenSource(CancellationToken?
/// <summary>
/// Parse args and create <see cref="DefaultSettings"/>.
/// </summary>
public static bool TryParse(IReadOnlyList<string> args, string unityPath, TimeSpan timeout, [NotNullWhen(true)] out DefaultSettings? settings)
public static bool TryParse(ReadOnlySpan<string> args, string unityPath, TimeSpan timeout, [NotNullWhen(true)] out DefaultSettings? settings)
{
try
{
Expand All @@ -108,39 +108,55 @@ public static bool TryParse(IReadOnlyList<string> args, string unityPath, TimeSp
/// <summary>
/// Parse args and create <see cref="DefaultSettings"/>.
/// </summary>
public static DefaultSettings Parse(IReadOnlyList<string> args, string unityPath, TimeSpan timeout)
public static DefaultSettings Parse(ReadOnlySpan<string> args, string unityPath, TimeSpan timeout)
{
// Unity Path
var unityPathFixed = !string.IsNullOrWhiteSpace(unityPath) ? unityPath : Environment.GetEnvironmentVariable(ISettings.UNITY_PATH_ENVVAR_KEY) ?? throw new ArgumentNullException($"Unity Path not specified. Please pass Unity Executable path with argument '--unity-path' or environment variable '{ISettings.UNITY_PATH_ENVVAR_KEY}'.");
var unityPathFixed = !string.IsNullOrWhiteSpace(unityPath)
? unityPath
: Environment.GetEnvironmentVariable(ISettings.UNITY_PATH_ENVVAR_KEY) ?? throw new ArgumentNullException($"Unity Path not specified. Please pass Unity Executable path with argument '--unity-path' or environment variable '{ISettings.UNITY_PATH_ENVVAR_KEY}'.");

// parse and fallback logfilePath
var arguments = args.ToArray().ToList(); // muda of muda
var logFilePath = ParseLogFile(args);
if (!IsValidLogFileName(logFilePath))
{
var inputLogFilePath = logFilePath;
logFilePath = "unitybuild.log";

// remove current `-logFile "-"` and replace to `-logFile unitybuild.log`
var tmpArgs = string.IsNullOrEmpty(logFilePath)
? args.Except(new[] { "-logFile" }, StringComparer.OrdinalIgnoreCase).Concat(new[] { "-logFile", logFilePath })
: args.Except(new[] { "-logFile" }, StringComparer.OrdinalIgnoreCase).Except(new[] { inputLogFilePath }).Concat(new[] { "-logFile", logFilePath });
args = tmpArgs.ToArray();
RemoveArgument(arguments, "-logFile");
RemoveArgument(arguments, inputLogFilePath);

// add new logFile argument
arguments.Add("-logFile");
arguments.Add(logFilePath);
}

var arguments = args.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();
var argumentString = string.Join(" ", arguments.Select(s => s.AsSpan()[0] == '-' ? s : QuoteString(s)));
var noEmptyArray = arguments.Where(x => !string.IsNullOrWhiteSpace(x));
var argumentString = string.Join(" ", noEmptyArray.Select(s => s.AsSpan()[0] == '-' ? s : QuoteString(s)));

// WorkingDirectory should be cli launch path.
var workingDirectory = Directory.GetCurrentDirectory();

// Create settings
var settings = new DefaultSettings(arguments, argumentString, unityPathFixed, logFilePath, workingDirectory, timeout, TimeProvider.System);
var settings = new DefaultSettings([.. noEmptyArray], argumentString, unityPathFixed, logFilePath, workingDirectory, timeout, TimeProvider.System);

// Validate settings
settings.Validate();

return settings;
}

private static void RemoveArgument(List<string> args, string argument)
{
var index = args.FindIndex(x => string.Equals(x, argument, StringComparison.OrdinalIgnoreCase));
if (index >= 0)
{
args.RemoveAt(index);
}
}


/// <summary>
/// QuoteString when possible.
/// </summary>
Expand Down Expand Up @@ -196,12 +212,12 @@ internal static string QuoteString(string text)
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
internal static string ParseLogFile(IReadOnlyList<string> args)
internal static string ParseLogFile(ReadOnlySpan<string> args)
{
var logFile = "";
for (var i = 0; i < args.Count; i++)
for (var i = 0; i < args.Length; i++)
{
if (string.Equals(args[i], "-logFile", StringComparison.OrdinalIgnoreCase) && i + 1 < args.Count)
if (string.Equals(args[i], "-logFile", StringComparison.OrdinalIgnoreCase) && i + 1 < args.Length)
{
logFile = args[i + 1];
break;
Expand Down
46 changes: 27 additions & 19 deletions src/UnityBuildRunner/Program.cs
Original file line number Diff line number Diff line change
@@ -1,38 +1,46 @@
using ConsoleAppFramework;
using Microsoft.Extensions.Logging;
using UnityBuildRunner.Core;

var builder = ConsoleApp.CreateBuilder(args);
var app = builder.Build();
app.AddCommands<UnityBuildRunnerCommand>();
app.Run();
var app = ConsoleApp.Create();
app.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddSimpleConsole();
});
app.Add<UnityBuildRunnerCommand>();
await app.RunAsync(args);

public class UnityBuildRunnerCommand(ILogger<UnityBuildRunnerCommand> logger) : ConsoleAppBase
internal class UnityBuildRunnerCommand(ILogger<UnityBuildRunnerCommand> logger)
{
private const string DefaultTimeout = "02:00:00"; // 2 hours

private readonly TimeSpan timeoutDefault = TimeSpan.Parse(DefaultTimeout);

[RootCommand]
public async Task<int> Run([Option("--unity-path", "Full Path to the Unity executable, leave empty when use 'UnityPath' Environment variables instead.")] string unityPath = "", [Option("--timeout", "Timeout for Unity Build.")] string timeout = DefaultTimeout)
/// <summary>
///
/// </summary>
/// <param name="context">Accesing to batch context.</param>
/// <param name="unityPath">Full Path to the Unity executable, leave empty when use 'UnityPath' Environment variables instead.</param>
/// <param name="timeout">Timeout for Unity Build.</param>
/// <param name="cancellationToken">CancellationToken to cancel command when Ctrl+C pressed.</param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
[Command("")]
public async Task<int> Run(ConsoleAppContext context, string unityPath = "", string timeout = DefaultTimeout, CancellationToken cancellationToken = default)
{
var arguments = Context.Arguments
.Except(["--timeout", timeout]);
if (!string.IsNullOrEmpty(unityPath))
var args = context.EscapedArguments;
if (args.Length == 0)
{
arguments = arguments.Except(["--unity-path", unityPath]);
}
var args = arguments?.ToArray();

if (args is null || args.Length == 0)
{
throw new ArgumentOutOfRangeException($"No valid argument found, exiting. You have specified arguments: {string.Join(" ", args ?? [])}");
throw new ArgumentOutOfRangeException($"No valid argument found, exiting. You have specified arguments: {string.Join(" ", context.Arguments)}");
}

// build
var timeoutSpan = TimeSpan.TryParse(timeout, out var r) ? r : timeoutDefault;
var settings = DefaultSettings.Parse(args!, unityPath, timeoutSpan);
using var cts = settings.CreateCancellationTokenSource(Context.CancellationToken);
var settings = DefaultSettings.Parse(args, unityPath, timeoutSpan);
using var cts = settings.CreateCancellationTokenSource(cancellationToken);

// build
var builder = new DefaultBuilder(settings, logger);
await builder.BuildAsync(cts.Token);
return builder.ExitCode;
Expand Down
12 changes: 6 additions & 6 deletions src/UnityBuildRunner/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,30 @@
},
"UnityBuildRunner (unity-path)": {
"commandName": "Project",
"commandLineArgs": "--unity-path \"C:/Program Files/Unity/Hub/Editor/6000.0.12f1/Editor/Unity.exe\" -quit -batchmode -nographics -silent-crashes -logfile log.log -buildTarget StandaloneWindows64 -projectPath ../../../../../sandbox/Sandbox.Unity -executeMethod BuildUnity.BuildGame"
"commandLineArgs": "--unity-path \"C:/Program Files/Unity/Hub/Editor/6000.0.12f1/Editor/Unity.exe\" -- -quit -batchmode -nographics -silent-crashes -logfile log.log -buildTarget StandaloneWindows64 -projectPath ../../../../../sandbox/Sandbox.Unity -executeMethod BuildUnity.BuildGame"
},
"UnityBuildRunner (env)": {
"commandName": "Project",
"commandLineArgs": "-quit -batchmode -nographics -silent-crashes -logfile log.log -buildTarget StandaloneWindows64 -projectPath ../../../../../sandbox/Sandbox.Unity -executeMethod BuildUnity.BuildGame",
"commandLineArgs": "-- -quit -batchmode -nographics -silent-crashes -logfile log.log -buildTarget StandaloneWindows64 -projectPath ../../../../../sandbox/Sandbox.Unity -executeMethod BuildUnity.BuildGame",
"environmentVariables": {
"UnityPath": "C:\\Program Files\\Unity\\Hub\\Editor\\2021.3.17f1\\Editor\\Unity.exe"
}
},
"UnityBuildRunner (-logFile -)": {
"commandName": "Project",
"commandLineArgs": "--unity-path \"C:/Program Files/Unity/Hub/Editor/6000.0.12f1/Editor/Unity.exe\" -quit -batchmode -nographics -silent-crashes -logfile - -buildTarget StandaloneWindows64 -projectPath ../../../../../sandbox/Sandbox.Unity -executeMethod BuildUnity.BuildGame"
"commandLineArgs": "--unity-path \"C:/Program Files/Unity/Hub/Editor/6000.0.12f1/Editor/Unity.exe\" -- -quit -batchmode -nographics -silent-crashes -logfile - -buildTarget StandaloneWindows64 -projectPath ../../../../../sandbox/Sandbox.Unity -executeMethod BuildUnity.BuildGame"
},
"UnityBuildRunner (quote-slash)": {
"commandName": "Project",
"commandLineArgs": "--unity-path \"C:/Program Files/Unity/Hub/Editor/6000.0.12f1/Editor/Unity.exe\" -quit -batchmode -nographics -silent-crashes -logfile - -buildTarget StandaloneWindows64 -projectPath \"../../../../../sandbox/Sandbox.Unity/\" -executeMethod BuildUnity.BuildGame"
"commandLineArgs": "--unity-path \"C:/Program Files/Unity/Hub/Editor/6000.0.12f1/Editor/Unity.exe\" -- -quit -batchmode -nographics -silent-crashes -logfile - -buildTarget StandaloneWindows64 -projectPath \"../../../../../sandbox/Sandbox.Unity/\" -executeMethod BuildUnity.BuildGame"
},
"UnityBuildRunner (quote)": {
"commandName": "Project",
"commandLineArgs": "--unity-path \"C:/Program Files/Unity/Hub/Editor/6000.0.12f1/Editor/Unity.exe\" -quit -batchmode -nographics -silent-crashes -logfile - -buildTarget StandaloneWindows64 -projectPath \"..\\..\\..\\..\\..\\sandbox/Sandbox.Unity\\\\\" -executeMethod BuildUnity.BuildGame"
"commandLineArgs": "--unity-path \"C:/Program Files/Unity/Hub/Editor/6000.0.12f1/Editor/Unity.exe\" -- -quit -batchmode -nographics -silent-crashes -logfile - -buildTarget StandaloneWindows64 -projectPath \"..\\..\\..\\..\\..\\sandbox/Sandbox.Unity\\\\\" -executeMethod BuildUnity.BuildGame"
},
"UnityBuildRunner (quote-bad)": {
"commandName": "Project",
"commandLineArgs": "--unity-path \"C:/Program Files/Unity/Hub/Editor/6000.0.12f1/Editor/Unity.exe\" -quit -batchmode -nographics -silent-crashes -logfile - -buildTarget StandaloneWindows64 -projectPath \"..\\..\\..\\..\\..\\sandbox/Sandbox.Unity\\\" -executeMethod BuildUnity.BuildGame"
"commandLineArgs": "--unity-path \"C:/Program Files/Unity/Hub/Editor/6000.0.12f1/Editor/Unity.exe\" -- -quit -batchmode -nographics -silent-crashes -logfile - -buildTarget StandaloneWindows64 -projectPath \"..\\..\\..\\..\\..\\sandbox/Sandbox.Unity\\\" -executeMethod BuildUnity.BuildGame"
}
}
}
5 changes: 4 additions & 1 deletion src/UnityBuildRunner/UnityBuildRunner.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="ConsoleAppFramework" />
<PackageReference Include="ConsoleAppFramework">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
Expand Down

0 comments on commit 9c22c08

Please sign in to comment.