Skip to content
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

Fixes #124 - Created alias variable by allowing multiple command attributes #125

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
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
2 changes: 2 additions & 0 deletions src/ConsoleAppFramework/Command.cs
Original file line number Diff line number Diff line change
@@ -22,6 +22,8 @@ public record class Command
public bool IsRootCommand => Name == "";
public required string Name { get; init; }

public required string[] Aliases { get; set; }

public required EquatableArray<CommandParameter> Parameters { get; init; }
public required string Description { get; init; }
public required MethodKind MethodKind { get; init; }
2 changes: 1 addition & 1 deletion src/ConsoleAppFramework/CommandHelpBuilder.cs
Original file line number Diff line number Diff line change
@@ -217,7 +217,7 @@ static string BuildMethodListMessage(IEnumerable<Command> commands, out int maxW
var formatted = commands
.Select(x =>
{
return (Command: x.Name, x.Description);
return (Command: string.Join(", ", Array.Empty<string>().Concat([x.Name]).Concat(x.Aliases)), x.Description);
})
.ToArray();
maxWidth = formatted.Max(x => x.Command.Length);
2 changes: 1 addition & 1 deletion src/ConsoleAppFramework/ConsoleAppGenerator.cs
Original file line number Diff line number Diff line change
@@ -144,7 +144,7 @@ internal sealed class ArgumentAttribute : Attribute
{
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
internal sealed class CommandAttribute : Attribute
{
public string Command { get; }
17 changes: 16 additions & 1 deletion src/ConsoleAppFramework/Emitter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.CodeAnalysis;
using System.Linq;
using System.Reflection.Metadata;

namespace ConsoleAppFramework;
@@ -447,6 +448,14 @@ void EmitRunBody(ILookup<string, CommandWithId> groupedCommands, int depth, bool
{
var leafCommand = groupedCommands[""].FirstOrDefault();
IDisposable? ifBlcok = null;
if (leafCommand is not null && !leafCommand.Command.Name.Equals(""))
{
// Add or-ing of aliases
foreach (var alias in leafCommand.Command.Aliases)
{
sb.AppendLine($"case \"{alias}\":");
}
}
if (!(groupedCommands.Count == 1 && leafCommand != null))
{
ifBlcok = sb.BeginBlock($"if (args.Length == {depth})");
@@ -462,9 +471,15 @@ void EmitRunBody(ILookup<string, CommandWithId> groupedCommands, int depth, bool
return;
}

IEnumerable<IGrouping<string, CommandWithId>> aliases = [];
if (leafCommand?.Command.Aliases.Length > 0)
{
aliases = leafCommand.Command.Aliases.SelectMany(lc => commandIds.GroupBy(a => lc));
}

using (sb.BeginBlock($"switch (args[{depth}])"))
{
foreach (var commands in groupedCommands.Where(x => x.Key != ""))
foreach (var commands in groupedCommands.Where(x => x.Key != "").Concat(aliases))
{
using (sb.BeginIndent($"case \"{commands.Key}\":"))
{
31 changes: 29 additions & 2 deletions src/ConsoleAppFramework/Parser.cs
Original file line number Diff line number Diff line change
@@ -104,6 +104,15 @@ internal class Parser(DiagnosticReporter context, InvocationExpressionSyntax nod
return [];
}

List<string> rootAliases = [];
if (type.TypeKind.HasFlag(TypeKind.Class))
{
foreach (var item in type.GetAttributes().Where(x => x.AttributeClass?.Name == "CommandAttribute"))
{
rootAliases.Add((item.ConstructorArguments[0].Value as string)!);
}
}

var hasIDisposable = type.AllInterfaces.Any(x => SymbolEqualityComparer.Default.Equals(x, wellKnownTypes.IDisposable));
var hasIAsyncDisposable = type.AllInterfaces.Any(x => SymbolEqualityComparer.Default.Equals(x, wellKnownTypes.IAsyncDisposable));

@@ -141,8 +150,9 @@ internal class Parser(DiagnosticReporter context, InvocationExpressionSyntax nod
.Select(x =>
{
string commandName;
var commandAttribute = x.GetAttributes().FirstOrDefault(x => x.AttributeClass?.Name == "CommandAttribute");
if (commandAttribute != null)
var commandAttributes = x.GetAttributes().Where(x => x.AttributeClass?.Name == "CommandAttribute");
var firstCommandAttribute = commandAttributes.FirstOrDefault();
if (firstCommandAttribute != null)
{
commandName = (x.GetAttributes()[0].ConstructorArguments[0].Value as string)!;
}
@@ -154,6 +164,21 @@ internal class Parser(DiagnosticReporter context, InvocationExpressionSyntax nod
var command = ParseFromMethodSymbol(x, false, (commandPath == null) ? commandName : $"{commandPath.Trim()} {commandName}", typeFilters);
if (command == null) return null;

List<string> methodAliases = [];
if (commandAttributes.Count() > 0)
{
methodAliases.AddRange(commandAttributes.Select((ca, i) => (x.GetAttributes()[i].ConstructorArguments[0].Value as string)!));
}

if (command.IsRootCommand)
{
command.Aliases = methodAliases.Concat(rootAliases).Select(a => NameConverter.ToKebabCase(a)).Distinct().Where(s => !s.Equals(commandName)).ToArray();
}
else
{
command.Aliases = methodAliases.Select(a => NameConverter.ToKebabCase(a)).Distinct().Where(s => !s.Equals(commandName)).ToArray();
}

command.CommandMethodInfo = methodInfoBase with { MethodName = x.Name };
return command;
})
@@ -367,6 +392,7 @@ internal class Parser(DiagnosticReporter context, InvocationExpressionSyntax nod
var cmd = new Command
{
Name = commandName,
Aliases = [],
IsAsync = isAsync,
IsVoid = isVoid,
Parameters = parameters,
@@ -522,6 +548,7 @@ internal class Parser(DiagnosticReporter context, InvocationExpressionSyntax nod
var cmd = new Command
{
Name = commandName,
Aliases = [],
IsAsync = isAsync,
IsVoid = isVoid,
Parameters = parameters,
23 changes: 23 additions & 0 deletions tests/ConsoleAppFramework.GeneratorTests/ConsoleAppBuilderTest.cs
Original file line number Diff line number Diff line change
@@ -241,6 +241,29 @@ public void Do()

verifier.Execute(code, "nomunomu", "yeah");
}

[Fact]
public void CommandAttrAlias()
{
var code = """
var builder = ConsoleApp.Create();
builder.Add<MyClass>();
builder.Run(args);
public class MyClass()
{
[Command("nomunomu")]
[Command("nomunomu2")]
public void Do()
{
Console.Write("yeah");
}
}
""";

verifier.Execute(code, "nomunomu", "yeah");
verifier.Execute(code, "nomunomu2", "yeah");
}
}


280 changes: 280 additions & 0 deletions tests/ConsoleAppFramework.GeneratorTests/HelpTest.cs
Original file line number Diff line number Diff line change
@@ -305,4 +305,284 @@ hello my world.
""");
}

[Fact]
public void CommandAlias()
{
var code = """
var app = ConsoleApp.Create();
app.Add<MyClass>();
app.Run(args);
public class MyClass
{
/// <summary>
/// hello my world.
/// </summary>
/// <param name="boo">-b, my boo is not boo.</param>
/// <param name="fooBar">-f|-fb, my foo is not bar.</param>
[Command("hello-world")]
[Command("hw")]
public void HelloWorld([Argument]int boo, string fooBar)
{
Console.Write("Hello World! " + fooBar);
}
}
""";


verifier.Execute(code, args: "--help", expected: """
Usage: [command] [-h|--help] [--version]
Commands:
hello-world, hw hello my world.
""");


var expectedCommandHelp = """
Usage: hello-world [arguments...] [options...] [-h|--help] [--version]
hello my world.
Arguments:
[0] <int> my boo is not boo.
Options:
-f|-fb|--foo-bar <string> my foo is not bar. (Required)
""";
verifier.Execute(code, args: "hello-world --help", expected: expectedCommandHelp);
verifier.Execute(code, args: "hw --help", expected: expectedCommandHelp);
}

[Fact]
public void CommandAliasWithRoot()
{
var code = """
var app = ConsoleApp.Create();
app.Add<MyClass>();
app.Run(args);
public class MyClass
{
/// <summary>
/// hello my world.
/// </summary>
/// <param name="boo">-b, my boo is not boo.</param>
/// <param name="fooBar">-f|-fb, my foo is not bar.</param>
[Command("")]
[Command("hello-world")]
[Command("hello-world2")]
[Command("hello-world3")]
public void HelloWorld([Argument]int boo, string fooBar)
{
Console.Write("Hello World! " + fooBar);
}
[Command("hello-our-world")]
public void HelloOurWorld([Argument]int boo, string fooBar)
{
Console.Write("Hello World! " + fooBar);
}
}
""";

var expectedCommandHelp = """
Usage: [command] [arguments...] [options...] [-h|--help] [--version]
hello my world.
Arguments:
[0] <int> my boo is not boo.
Options:
-f|-fb|--foo-bar <string> my foo is not bar. (Required)
Commands:
hello-our-world
""";

var expectedSubCommand = """
Usage: [arguments...] [options...] [-h|--help] [--version]
hello my world.
Arguments:
[0] <int> my boo is not boo.
Options:
-f|-fb|--foo-bar <string> my foo is not bar. (Required)
""";

verifier.Execute(code, args: "--help", expected: expectedCommandHelp);
verifier.Execute(code, args: "", expected: expectedSubCommand);
verifier.Execute(code, args: "hello-world --help", expected: expectedSubCommand);
}

[Fact]
public void CommandAliasClassAttribute()
{
var code = """
var app = ConsoleApp.Create();
app.Add<MyClass>();
app.Run(args);
[Command("hello-world")]
public class MyClass
{
/// <summary>
/// hello my world.
/// </summary>
/// <param name="boo">-b, my boo is not boo.</param>
/// <param name="fooBar">-f|-fb, my foo is not bar.</param>
[Command("hw")]
public void HelloWorld([Argument]int boo, string fooBar)
{
Console.Write("Hello World! " + fooBar);
}
}
""";


verifier.Execute(code, args: "--help", expected: """
Usage: [command] [-h|--help] [--version]
Commands:
hw hello my world.
""");


var expectedCommandHelp = """
Usage: hw [arguments...] [options...] [-h|--help] [--version]
hello my world.
Arguments:
[0] <int> my boo is not boo.
Options:
-f|-fb|--foo-bar <string> my foo is not bar. (Required)
""";
verifier.Execute(code, args: "hw --help", expected: expectedCommandHelp);
}

[Fact]
public void CommandClassAttributeAndRootMethod()
{
var code = """
var app = ConsoleApp.Create();
app.Add<MyClass>();
app.Run(args);
[Command("hello-world")]
public class MyClass
{
/// <summary>
/// hello my world.
/// </summary>
/// <param name="boo">-b, my boo is not boo.</param>
/// <param name="fooBar">-f|-fb, my foo is not bar.</param>
[Command("")]
public void HelloWorld([Argument]int boo, string fooBar)
{
Console.Write("Hello World! " + fooBar);
}
/// <summary>
/// hello our world.
/// </summary>
/// <param name="boo">-b, my boo is not boo.</param>
/// <param name="fooBar">-f|-fb, my foo is not bar.</param>
[Command("hello-our-world")]
public void HelloOurWorld([Argument]int boo, string fooBar)
{
Console.Write("Hello World! " + fooBar);
}
}
""";


verifier.Execute(code, args: "--help", expected: """
Usage: [command] [arguments...] [options...] [-h|--help] [--version]
hello my world.
Arguments:
[0] <int> my boo is not boo.
Options:
-f|-fb|--foo-bar <string> my foo is not bar. (Required)
Commands:
hello-our-world hello our world.
""");
}

[Fact]
public void CommandClassAttributeAndMethodCoalescing()
{
var code = """
var app = ConsoleApp.Create();
app.Add<MyClass>();
app.Run(args);
[Command("hello-world")]
[Command("hw")]
public class MyClass
{
/// <summary>
/// hello my world.
/// </summary>
/// <param name="boo">-b, my boo is not boo.</param>
/// <param name="fooBar">-f|-fb, my foo is not bar.</param>
public void HelloWorld([Argument]int boo, string fooBar)
{
Console.Write("Hello World! " + fooBar);
}
/// <summary>
/// hello our world.
/// </summary>
/// <param name="boo">-b, my boo is not boo.</param>
/// <param name="fooBar">-f|-fb, my foo is not bar.</param>
[Command("hello-our-world")]
public void HelloOurWorld([Argument]int boo, string fooBar)
{
Console.Write("Hello World! " + fooBar);
}
}
""";


verifier.Execute(code, args: "--help", expected: """
Usage: [command] [-h|--help] [--version]
Commands:
hello-our-world hello our world.
hello-world, hw hello my world.
""");


var expectedCommandHelp = """
Usage: hello-world [arguments...] [options...] [-h|--help] [--version]
hello my world.
Arguments:
[0] <int> my boo is not boo.
Options:
-f|-fb|--foo-bar <string> my foo is not bar. (Required)
""";
verifier.Execute(code, args: "hello-world --help", expected: expectedCommandHelp);
verifier.Execute(code, args: "hello-our-world --help", expected: expectedCommandHelp);
}
}