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

Panic on duplicate command names #317

Merged
merged 2 commits into from Jul 17, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions build.go
Expand Up @@ -158,6 +158,20 @@ MAIN:
}
}

// Validate if there are no duplicate names
seenNames := make(map[string]struct{})
for _, node := range node.Children {
if _, ok := seenNames[node.Name]; ok {
name := v.Type().Name()
if name == "" {
name = "<anonymous struct>"
}
return nil, fmt.Errorf("duplicate command name %q in command %q", node.Name, name)
}

seenNames[node.Name] = struct{}{}
}

// "Unsee" flags.
for _, flag := range node.Flags {
delete(seenFlags, "--"+flag.Name)
Expand Down
32 changes: 32 additions & 0 deletions kong_test.go
Expand Up @@ -1662,3 +1662,35 @@ func TestMapDecoderHelpfulErrorMsg(t *testing.T) {
})
}
}

func TestDuplicateName(t *testing.T) {
var cli struct {
DupA struct{} `cmd:"" name:"duplicate"`
DupB struct{} `cmd:"" name:"duplicate"`
}
_, err := kong.New(&cli)
assert.Error(t, err)
}

func TestDuplicateChildName(t *testing.T) {
var cli struct {
A struct {
DupA struct{} `cmd:"" name:"duplicate"`
DupB struct{} `cmd:"" name:"duplicate"`
} `cmd:""`
B struct{} `cmd:""`
}
_, err := kong.New(&cli)
assert.Error(t, err)
}

func TestChildNameCanBeDuplicated(t *testing.T) {
var cli struct {
A struct {
A struct{} `cmd:"" name:"duplicateA"`
B struct{} `cmd:"" name:"duplicateB"`
} `cmd:"" name:"duplicateA"`
B struct{} `cmd:"" name:"duplicateB"`
}
mustNew(t, &cli)
}