Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Replace ArgumentParser with Spectre.Console.Cli package #4610

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
Copilot wants to merge 9 commits into main
base: main
Choose a base branch
Loading
from copilot/fix-bc2ee707-4523-47a0-ba1a-c6378b8ed425
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
9 commits
Select commit Hold shift + click to select a range
3c06f8e
Initial plan
Copilot Jul 3, 2025
db6b15b
Replace ArgumentParser with SpectreArgumentParser using Spectre.Conso...
Copilot Jul 3, 2025
8863c9f
Complete SpectreArgumentParser implementation with full backward comp...
Copilot Jul 3, 2025
242709c
Replace ArgumentParser delegation with full Spectre.Console.Cli imple...
Copilot Jul 3, 2025
42b74b1
Enhance SpectreArgumentParser with comprehensive CLI argument support...
Copilot Jul 3, 2025
0c05d92
Remove legacy forward slash syntax support from SpectreArgumentParser...
Copilot Jul 3, 2025
d04a748
Use -v for verbosity instead of show variable to follow standard CLI ...
Copilot Jul 3, 2025
22e86b0
Update Spectre.Console.Cli to latest version and split classes into s...
Copilot Jul 3, 2025
2661715
Fix build errors: remove trailing whitespace, suppress obsolete warni...
Copilot Jul 3, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Directory.Packages.props
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
<PackageVersion Include="NUnit.Analyzers" Version="4.9.2" />
<PackageVersion Include="NUnit3TestAdapter" Version="5.0.0" />
<PackageVersion Include="Shouldly" Version="4.3.0" />
<PackageVersion Include="Spectre.Console.Cli" Version="0.50.0" />
<PackageVersion Include="System.Collections.Immutable" Version="9.0.2" />
<PackageVersion Include="System.Drawing.Common" Version="9.0.6" />
<PackageVersion Include="System.IO.Abstractions" Version="22.0.14" />
Expand Down
20 changes: 10 additions & 10 deletions src/GitVersion.App.Tests/ArgumentParserTests.cs
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ public void WrongNumberOfArgumentsShouldThrow()
}

[TestCase("targetDirectoryPath -x logFilePath")]
[TestCase("/invalid-argument")]
[TestCase("--invalid-argument")]
public void UnknownArgumentsShouldThrow(string arguments)
{
var exception = Assert.Throws<WarningException>(() => this.argumentParser.ParseArguments(arguments));
Expand Down Expand Up @@ -370,14 +370,14 @@ public void UpdateAssemblyInfoWithRelativeFilename()
[Test]
public void OverrideconfigWithNoOptions()
{
var arguments = this.argumentParser.ParseArguments("/overrideconfig");
var arguments = this.argumentParser.ParseArguments("--override-config");
arguments.OverrideConfiguration.ShouldBeNull();
}

[TestCaseSource(nameof(OverrideconfigWithInvalidOptionTestData))]
public string OverrideconfigWithInvalidOption(string options)
{
var exception = Assert.Throws<WarningException>(() => this.argumentParser.ParseArguments($"/overrideconfig {options}"));
var exception = Assert.Throws<WarningException>(() => this.argumentParser.ParseArguments($"--override-config {options}"));
exception.ShouldNotBeNull();
return exception.Message;
}
Expand All @@ -386,18 +386,18 @@ private static IEnumerable<TestCaseData> OverrideconfigWithInvalidOptionTestData
{
yield return new TestCaseData("tag-prefix=sample=asdf")
{
ExpectedResult = "Could not parse /overrideconfig option: tag-prefix=sample=asdf. Ensure it is in format 'key=value'."
ExpectedResult = "Could not parse --override-config option: tag-prefix=sample=asdf. Ensure it is in format 'key=value'."
};
yield return new TestCaseData("unknown-option=25")
{
ExpectedResult = "Could not parse /overrideconfig option: unknown-option=25. Unsupported 'key'."
ExpectedResult = "Could not parse --override-config option: unknown-option=25. Unsupported 'key'."
};
}

[TestCaseSource(nameof(OverrideConfigWithSingleOptionTestData))]
public void OverrideConfigWithSingleOptions(string options, IGitVersionConfiguration expected)
{
var arguments = this.argumentParser.ParseArguments($"/overrideconfig {options}");
var arguments = this.argumentParser.ParseArguments($"--override-config {options}");

ConfigurationHelper configurationHelper = new(arguments.OverrideConfiguration);
configurationHelper.Configuration.ShouldBeEquivalentTo(expected);
Expand Down Expand Up @@ -551,23 +551,23 @@ public void OverrideConfigWithMultipleOptions(string options, IGitVersionConfigu
private static IEnumerable<TestCaseData> OverrideConfigWithMultipleOptionsTestData()
{
yield return new TestCaseData(
"/overrideconfig tag-prefix=sample /overrideconfig assembly-versioning-scheme=MajorMinor",
"--override-config tag-prefix=sample --override-config assembly-versioning-scheme=MajorMinor",
new GitVersionConfiguration
{
TagPrefixPattern = "sample",
AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinor
}
);
yield return new TestCaseData(
"/overrideconfig tag-prefix=sample /overrideconfig assembly-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"",
"--override-config tag-prefix=sample --override-config assembly-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\"",
new GitVersionConfiguration
{
TagPrefixPattern = "sample",
AssemblyVersioningFormat = "{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}"
}
);
yield return new TestCaseData(
"/overrideconfig tag-prefix=sample /overrideconfig assembly-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\" /overrideconfig update-build-number=true /overrideconfig assembly-versioning-scheme=MajorMinorPatchTag /overrideconfig mode=ContinuousDelivery /overrideconfig tag-pre-release-weight=4",
"--override-config tag-prefix=sample --override-config assembly-versioning-format=\"{Major}.{Minor}.{Patch}.{env:CI_JOB_ID ?? 0}\" --override-config update-build-number=true --override-config assembly-versioning-scheme=MajorMinorPatchTag --override-config mode=ContinuousDelivery --override-config tag-pre-release-weight=4",
new GitVersionConfiguration
{
TagPrefixPattern = "sample",
Expand Down Expand Up @@ -711,7 +711,7 @@ public void LogPathCanContainForwardSlash()
[Test]
public void BooleanArgumentHandling()
{
var arguments = this.argumentParser.ParseArguments("/nofetch /updateassemblyinfo true");
var arguments = this.argumentParser.ParseArguments("--no-fetch --update-assembly-info true");
arguments.NoFetch.ShouldBe(true);
arguments.UpdateAssemblyInfo.ShouldBe(true);
}
Expand Down
232 changes: 232 additions & 0 deletions src/GitVersion.App/ArgumentInterceptor.cs
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
using System.IO.Abstractions;
using GitVersion.Agents;
using GitVersion.Extensions;
using GitVersion.FileSystemGlobbing;
using GitVersion.Helpers;
using GitVersion.Logging;
using GitVersion.OutputVariables;

Check warning on line 7 in src/GitVersion.App/ArgumentInterceptor.cs

View workflow job for this annotation

GitHub Actions / DotNet Format

Using directive is unnecessary.

Check warning on line 7 in src/GitVersion.App/ArgumentInterceptor.cs

View workflow job for this annotation

GitHub Actions / DotNet Format

Using directive is unnecessary.

Check warning on line 7 in src/GitVersion.App/ArgumentInterceptor.cs

View workflow job for this annotation

GitHub Actions / DotNet Format

Using directive is unnecessary.
using Spectre.Console.Cli;

namespace GitVersion;

/// <summary>
/// Interceptor to capture parsed arguments
/// </summary>
internal class ArgumentInterceptor : ICommandInterceptor
{
private readonly ParseResultStorage storage;
private readonly IEnvironment environment;
private readonly IFileSystem fileSystem;
private readonly ICurrentBuildAgent buildAgent;
private readonly IConsole console;
private readonly IGlobbingResolver globbingResolver;

public ArgumentInterceptor(ParseResultStorage storage, IEnvironment environment, IFileSystem fileSystem, ICurrentBuildAgent buildAgent, IConsole console, IGlobbingResolver globbingResolver)
{
this.storage = storage;
this.environment = environment;
this.fileSystem = fileSystem;
this.buildAgent = buildAgent;
this.console = console;
this.globbingResolver = globbingResolver;
}

public void Intercept(CommandContext context, CommandSettings settings)
{
if (settings is GitVersionSettings gitVersionSettings)
{
var arguments = ConvertToArguments(gitVersionSettings);
AddAuthentication(arguments);
ValidateAndProcessArguments(arguments);
this.storage.SetResult(arguments);
}
}

private void AddAuthentication(Arguments arguments)
{
var username = this.environment.GetEnvironmentVariable("GITVERSION_REMOTE_USERNAME");
if (!username.IsNullOrWhiteSpace())
{
arguments.Authentication.Username = username;
}

var password = this.environment.GetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD");
if (!password.IsNullOrWhiteSpace())
{
arguments.Authentication.Password = password;
}
}

private void ValidateAndProcessArguments(Arguments arguments)
{
// Apply default output if none specified
if (arguments.Output.Count == 0)
{
arguments.Output.Add(OutputType.Json);
}

// Set default output file if file output is specified
if (arguments.Output.Contains(OutputType.File) && arguments.OutputFile == null)
{
arguments.OutputFile = "GitVersion.json";
}

// Apply build agent settings
arguments.NoFetch = arguments.NoFetch || this.buildAgent.PreventFetch();

// Validate configuration file
ValidateConfigurationFile(arguments);

// Process assembly info files
if (!arguments.EnsureAssemblyInfo)
{
arguments.UpdateAssemblyInfoFileName = ResolveFiles(arguments.TargetPath ?? SysEnv.CurrentDirectory, arguments.UpdateAssemblyInfoFileName).ToHashSet();
}
}

private void ValidateConfigurationFile(Arguments arguments)
{
if (arguments.ConfigurationFile.IsNullOrWhiteSpace()) return;

if (FileSystemHelper.Path.IsPathRooted(arguments.ConfigurationFile))
{
if (!this.fileSystem.File.Exists(arguments.ConfigurationFile))
throw new WarningException($"Could not find config file at '{arguments.ConfigurationFile}'");
arguments.ConfigurationFile = FileSystemHelper.Path.GetFullPath(arguments.ConfigurationFile);
}
else
{
var configFilePath = FileSystemHelper.Path.GetFullPath(FileSystemHelper.Path.Combine(arguments.TargetPath, arguments.ConfigurationFile));
if (!this.fileSystem.File.Exists(configFilePath))
throw new WarningException($"Could not find config file at '{configFilePath}'");
arguments.ConfigurationFile = configFilePath;
}
}

private IEnumerable<string> ResolveFiles(string workingDirectory, ISet<string>? assemblyInfoFiles)
{
if (assemblyInfoFiles == null || assemblyInfoFiles.Count == 0)
{
return [];
}

var stringList = new List<string>();

foreach (var filePattern in assemblyInfoFiles)
{
if (FileSystemHelper.Path.IsPathRooted(filePattern))
{
stringList.Add(filePattern);
}
else
{
var searchRoot = FileSystemHelper.Path.GetFullPath(workingDirectory);
var matchingFiles = this.globbingResolver.Resolve(searchRoot, filePattern);
stringList.AddRange(matchingFiles);
}
}

return stringList;
}

private static Arguments ConvertToArguments(GitVersionSettings settings)
{
var arguments = new Arguments();

// Set target path - prioritize explicit targetpath option over positional argument
arguments.TargetPath = settings.TargetPathOption?.TrimEnd('/', '\\')
?? settings.TargetPath?.TrimEnd('/', '\\')
?? SysEnv.CurrentDirectory;

// Configuration options
arguments.ConfigurationFile = settings.ConfigurationFile;
arguments.ShowConfiguration = settings.ShowConfiguration;

// Handle override configuration
if (settings.OverrideConfiguration != null && settings.OverrideConfiguration.Any())
{
var parser = new OverrideConfigurationOptionParser();

foreach (var kvp in settings.OverrideConfiguration)
{
// Validate the key format - Spectre.Console.Cli should have already parsed key=value correctly
// but we still need to validate against supported properties
var keyValueOption = $"{kvp.Key}={kvp.Value}";

var optionKey = kvp.Key.ToLowerInvariant();
if (!OverrideConfigurationOptionParser.SupportedProperties.Contains(optionKey))
{
throw new WarningException($"Could not parse --override-config option: {keyValueOption}. Unsupported 'key'.");
}

parser.SetValue(optionKey, kvp.Value);
}

arguments.OverrideConfiguration = parser.GetOverrideConfiguration();
}
else
{
arguments.OverrideConfiguration = new Dictionary<object, object?>();
}

// Output options
if (settings.Output != null && settings.Output.Any())
{
foreach (var output in settings.Output)
{
if (Enum.TryParse<OutputType>(output, true, out var outputType))
{
arguments.Output.Add(outputType);
}
}
}

arguments.OutputFile = settings.OutputFile;
arguments.Format = settings.Format;
arguments.ShowVariable = settings.ShowVariable;

// Repository options
arguments.TargetUrl = settings.Url;
arguments.TargetBranch = settings.Branch;
arguments.CommitId = settings.Commit;
arguments.ClonePath = settings.DynamicRepoLocation;

// Authentication
if (!string.IsNullOrWhiteSpace(settings.Username))
{
arguments.Authentication.Username = settings.Username;
}
if (!string.IsNullOrWhiteSpace(settings.Password))
{
arguments.Authentication.Password = settings.Password;
}

// Behavioral flags
arguments.NoFetch = settings.NoFetch;
arguments.NoCache = settings.NoCache;
arguments.NoNormalize = settings.NoNormalize;
arguments.AllowShallow = settings.AllowShallow;
arguments.Diag = settings.Diag;

// Assembly info options
arguments.UpdateAssemblyInfo = settings.UpdateAssemblyInfo;
arguments.EnsureAssemblyInfo = settings.EnsureAssemblyInfo;
arguments.UpdateProjectFiles = settings.UpdateProjectFiles;
arguments.UpdateWixVersionFile = settings.UpdateWixVersionFile;

// Handle assembly info file names
if (settings.UpdateAssemblyInfoFileName != null && settings.UpdateAssemblyInfoFileName.Any())
{
arguments.UpdateAssemblyInfoFileName = settings.UpdateAssemblyInfoFileName.ToHashSet();
}

// Logging
arguments.LogFilePath = settings.LogFilePath;
if (Enum.TryParse<Verbosity>(settings.Verbosity, true, out var verbosity))
{
arguments.Verbosity = verbosity;
}

return arguments;
}
}
1 change: 1 addition & 0 deletions src/GitVersion.App/GitVersion.App.csproj
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" />
<PackageReference Include="Microsoft.Extensions.FileSystemGlobbing" />
<PackageReference Include="Spectre.Console.Cli" />
</ItemGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/GitVersion.App/GitVersionAppModule.cs
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ internal class GitVersionAppModule : IGitVersionModule
{
public void RegisterTypes(IServiceCollection services)
{
services.AddSingleton<IArgumentParser, ArgumentParser>();
services.AddSingleton<IArgumentParser, SpectreArgumentParser>();
services.AddSingleton<IGlobbingResolver, GlobbingResolver>();

services.AddSingleton<IHelpWriter, HelpWriter>();
Expand Down
13 changes: 13 additions & 0 deletions src/GitVersion.App/GitVersionCommand.cs
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System.ComponentModel;
using Spectre.Console.Cli;

namespace GitVersion;

/// <summary>
/// Main GitVersion command with POSIX compliant options
/// </summary>
[Description("Generate version information based on Git repository")]
internal class GitVersionCommand : Command<GitVersionSettings>
{
public override int Execute(CommandContext context, GitVersionSettings settings) => 0;
}
Loading
Loading

AltStyle によって変換されたページ (->オリジナル) /