Skip to content

Commit

Permalink
Throw an exception if a sub-command name is duplicated
Browse files Browse the repository at this point in the history
  • Loading branch information
mayuki committed Jan 9, 2022
1 parent 36048c5 commit 34be5d2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
18 changes: 13 additions & 5 deletions src/Cocona.Core/Command/CoconaCommandProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,19 @@ private CommandCollection CreateCommandCollectionFromCommandDataSet(IReadOnlyLis
foreach (var (commandMethod, target, metadata) in commandMethods)
{
var command = CreateCommand(commandMethod, !hasMultipleCommand, overloadCommandMethods, target, metadata);
AddCommand(command);
}

// NOTE: For compatibility, add sub-commands to the command set last.
foreach (var subCommand in subCommandEntryPoints)
{
AddCommand(subCommand);
}

return new CommandCollection(commands);

void AddCommand(CommandDescriptor command)
{
if (commandNames.Contains(command.Name))
{
throw new CoconaException($"Command '{command.Name}' has already exists. (Method: {command.Method.Name})");
Expand All @@ -168,11 +181,6 @@ private CommandCollection CreateCommandCollectionFromCommandDataSet(IReadOnlyLis
commands.Add(command);
}

// NOTE: For compatibility, add sub-commands to the command set last.
commands.AddRange(subCommandEntryPoints);

return new CommandCollection(commands);

void ProcessCommandData(ICommandData commandData)
{
switch (commandData)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,13 @@ public void DuplicateSameNameInAliasCommand()
var ex = Assert.Throws<CoconaException>(() => provider.GetCommandCollection());
}

[Fact]
public void DuplicateSameNameSubCommand()
{
var provider = new CoconaCommandProvider(new[] { typeof(CommandTestDuplicateSameNameSubCommand) });
var ex = Assert.Throws<CoconaException>(() => provider.GetCommandCollection());
}

[Fact]
public void DontTreatPublicMethodsAsCommand()
{
Expand Down Expand Up @@ -351,6 +358,19 @@ public void A() { }
public void B() { }
}

[HasSubCommands(typeof(SubCommand), "a")]
public class CommandTestDuplicateSameNameSubCommand
{
[Command("a")]
public void A() { }

public class SubCommand
{
[Command("b")]
public void B() { }
}
}

public class CommandTestDontTreatPublicMethodsAsCommands
{
public void A() { }
Expand Down

0 comments on commit 34be5d2

Please sign in to comment.