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

Closed
wants to merge 5 commits into from
Closed
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
2 changes: 2 additions & 0 deletions src/ConsoleAppFramework/Command.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand Down
2 changes: 1 addition & 1 deletion src/ConsoleAppFramework/CommandHelpBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion src/ConsoleAppFramework/ConsoleAppGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand Down
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;
Expand Down Expand Up @@ -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})");
Expand All @@ -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}\":"))
{
Expand Down
31 changes: 29 additions & 2 deletions src/ConsoleAppFramework/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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));

Expand Down Expand Up @@ -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)!;
}
Expand All @@ -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;
})
Expand Down Expand Up @@ -367,6 +392,7 @@ internal class Parser(DiagnosticReporter context, InvocationExpressionSyntax nod
var cmd = new Command
{
Name = commandName,
Aliases = [],
IsAsync = isAsync,
IsVoid = isVoid,
Parameters = parameters,
Expand Down Expand Up @@ -522,6 +548,7 @@ internal class Parser(DiagnosticReporter context, InvocationExpressionSyntax nod
var cmd = new Command
{
Name = commandName,
Aliases = [],
IsAsync = isAsync,
IsVoid = isVoid,
Parameters = parameters,
Expand Down
23 changes: 23 additions & 0 deletions tests/ConsoleAppFramework.GeneratorTests/ConsoleAppBuilderTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
}


Expand Down
Loading