Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
28 changes: 1 addition & 27 deletions src/ConsoleAppFramework/ConsoleAppBaseCode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -404,33 +404,7 @@ static bool TryShowHelpOrVersion(ReadOnlySpan<string> args, int requiredParamete

static void ShowVersion()
{
if (Version != null)
{
Log(Version);
return;
}

var asm = Assembly.GetEntryAssembly();
var version = "1.0.0";
var infoVersion = asm!.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
if (infoVersion != null)
{
version = infoVersion.InformationalVersion;
var i = version.IndexOf('+');
if (i != -1)
{
version = version.Substring(0, i);
}
}
else
{
var asmVersion = asm!.GetCustomAttribute<AssemblyVersionAttribute>();
if (asmVersion != null)
{
version = asmVersion.Version;
}
}
Log(version);
Log(Version ?? DefaultVersion);
}

static partial void ShowHelp(int helpId);
Expand Down
45 changes: 45 additions & 0 deletions src/ConsoleAppFramework/ConsoleAppGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,14 @@ public void Initialize(IncrementalGeneratorInitializationContext context)

context.RegisterSourceOutput(hasReferences, EmitConsoleAppConfigure);

// Emit default version(for --version) as literal to avoid runtime reflection(it increases NativeAOT binary size).
// This pipeline is isolated(only string) so version changes do not invalidate other outputs.
var defaultVersion = context.CompilationProvider
.Select((compilation, token) => GetDefaultVersion(compilation))
.WithTrackingName("ConsoleApp.DefaultVersion");

context.RegisterSourceOutput(defaultVersion, EmitDefaultVersion);

// get Options for Combine
var generatorOptions = context.CompilationProvider.Select((compilation, token) =>
{
Expand Down Expand Up @@ -198,6 +206,43 @@ static void EmitConsoleAppTemplateSource(IncrementalGeneratorPostInitializationC
context.AddSource("ConsoleApp.g.cs", ConsoleAppBaseCode.InitializationCode.ReplaceLineEndings());
}

static string GetDefaultVersion(Compilation compilation)
{
string? assemblyVersion = null;
foreach (var attr in compilation.Assembly.GetAttributes())
{
var attrClass = attr.AttributeClass;
if (attrClass == null || attrClass.ContainingNamespace?.ToDisplayString() != "System.Reflection") continue;
if (attr.ConstructorArguments.Length != 1 || attr.ConstructorArguments[0].Value is not string value) continue;

if (attrClass.Name == "AssemblyInformationalVersionAttribute")
{
// Trim SourceRevisionId (SourceLink feature is enabled by default when using .NET SDK 8 or later)
var i = value.IndexOf('+');
return i != -1 ? value.Substring(0, i) : value;
}

if (attrClass.Name == "AssemblyVersionAttribute")
{
assemblyVersion = value;
}
}

return assemblyVersion ?? "1.0.0";
}

static void EmitDefaultVersion(SourceProductionContext sourceProductionContext, string defaultVersion)
{
var sb = new SourceBuilder(0);
sb.AppendLine(ConsoleAppBaseCode.GeneratedCodeHeader);
using (sb.BeginBlock("internal static partial class ConsoleApp"))
{
sb.AppendLine($"const string DefaultVersion = {SymbolDisplay.FormatLiteral(defaultVersion, quote: true)};");
}

sourceProductionContext.AddSource("ConsoleApp.Version.g.cs", sb.ToString().ReplaceLineEndings());
}

static void EmitConsoleAppRun(SourceProductionContext sourceProductionContext, CommandContext commandContext)
{
commandContext.DiagnosticReporter.ReportToContext(sourceProductionContext);
Expand Down
71 changes: 44 additions & 27 deletions tests/ConsoleAppFramework.GeneratorTests/HelpTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,51 @@ public class HelpTest(VerifyHelper verifier)
[Test]
public async Task Version()
{
var version = GetEntryAssemblyVersion();

// no version attributes
await verifier.Execute(code: $$"""
ConsoleApp.Log = x => Console.WriteLine(x);
ConsoleApp.Run(args, (int x, int y) => { });
""",
args: "--version",
expected: $$"""
{{version}}
expected: """
1.0.0

""");
// AssemblyInformationalVersion(trim SourceRevisionId)
await verifier.Execute(code: """
[assembly: System.Reflection.AssemblyInformationalVersion("1.2.3-beta.4+abcdef0123456789")]
[assembly: System.Reflection.AssemblyVersion("1.2.3.0")]

ConsoleApp.Log = x => Console.WriteLine(x);
ConsoleApp.Run(args, (int x, int y) => { });
""",
args: "--version",
expected: """
1.2.3-beta.4

""");
// AssemblyVersion only
await verifier.Execute(code: """
[assembly: System.Reflection.AssemblyVersion("2.3.4.5")]

ConsoleApp.Log = x => Console.WriteLine(x);
ConsoleApp.Run(args, (int x, int y) => { });
""",
args: "--version",
expected: """
2.3.4.5

""");
// escape
await verifier.Execute(code: """
[assembly: System.Reflection.AssemblyInformationalVersion("1.0.0-\"quote\"\\backslash")]

ConsoleApp.Log = x => Console.WriteLine(x);
ConsoleApp.Run(args, (int x, int y) => { });
""",
args: "--version",
expected: """
1.0.0-"quote"\backslash

""");
// custom
Expand All @@ -40,16 +76,16 @@ await verifier.Execute(code: $$"""
[Test]
public async Task VersionOnBuilder()
{
var version = GetEntryAssemblyVersion();

await verifier.Execute(code: """
[assembly: System.Reflection.AssemblyInformationalVersion("3.4.5+abcdef")]

ConsoleApp.Log = x => Console.WriteLine(x);
var app = ConsoleApp.Create();
app.Run(args);
""",
args: "--version",
expected: $$"""
{{version}}
expected: """
3.4.5

""");
}
Expand Down Expand Up @@ -461,25 +497,6 @@ await verifier.Execute(code, args: "a --help", expected: """
""");
}

private static string GetEntryAssemblyVersion()
{
var version = System.Reflection.Assembly.GetEntryAssembly()?.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;

if (version == null)
{
return "1.0.0";
}

// Trim SourceRevisionId (SourceLink feature is enabled by default when using .NET SDK 8 or later)
var i = version.IndexOf('+');
if (i != -1)
{
version = version.Substring(0, i);
}

return version;
}

[Test]
public async Task CommandAlias()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -672,4 +672,51 @@ public void IncrDual()

var reasons = runner.GetIncrementalGeneratorTrackedStepsReasons("ConsoleApp.Builder.", step1, step2);
}

[Test]
public async Task DefaultVersion()
{
var step1 = """
using ConsoleAppFramework;

[assembly: System.Reflection.AssemblyInformationalVersion("1.0.0")]

ConsoleApp.Run(args, int () => 0);
""";

var step2 = """
using ConsoleAppFramework;

[assembly: System.Reflection.AssemblyInformationalVersion("1.0.0")]

ConsoleApp.Run(args, int () => 100); // body change

Console.WriteLine("foo"); // unrelated line
""";

var step3 = """
using ConsoleAppFramework;

[assembly: System.Reflection.AssemblyInformationalVersion("2.0.0")] // version change

ConsoleApp.Run(args, int () => 100);

Console.WriteLine("foo");
""";

var versionReasons = runner.GetIncrementalGeneratorTrackedStepsReasons("ConsoleApp.DefaultVersion", step1, step2, step3);

await Assert.That(versionReasons[0][0].Reasons).IsEqualTo("New");
await Assert.That(versionReasons[1][0].Reasons).IsEqualTo("Unchanged");
await Assert.That(versionReasons[2][0].Reasons).IsEqualTo("Modified");

await VerifySourceOutputReasonIsCached(versionReasons[1]);
await VerifySourceOutputReasonIsNotCached(versionReasons[2]);

// version change should not invalidate ConsoleApp.Run output
var runReasons = runner.GetIncrementalGeneratorTrackedStepsReasons("ConsoleApp.Run.", step1, step2, step3);

await Assert.That(runReasons[2][0].Reasons).IsEqualTo("Unchanged");
await VerifySourceOutputReasonIsCached(runReasons[2]);
}
}