The title isn't great. I'll explain. First, thanks for a great library. 🎉
I have a diff at the bottom of this issue with a fix, but I'm not sure how you want to unit test it so I didn't open a PR. Its a one-line fix.
The Problem
We have a CLI with the following two commands:
nomad job status
nomad status
They each implement their own arg autocompletion func. However, we noticed that only the outer one was ever being called. i.e. when you did nomad job status <tab>
, it was returning the same output for nomad status <tab>
. Further confusing: it seemed to call both autocomplete funcs, but only outputted the outer one.
We expected the behavior to only call the inner one.
A failing structure is shown below (where each Args PredictFucn outputs a different thing):
complete.Command{
Sub: {
"job": {
Sub: {
"status": {
Sub: {},
Flags: {},
GlobalFlags: {},
Args: complete.PredictFunc {...},
},
},
Flags: {},
GlobalFlags: {},
Args: nil,
},
"status": {
Sub: {},
Flags: {},
GlobalFlags: {},
Args: complete.PredictFunc {...},
},
},
Flags: {},
GlobalFlags: {},
Args: nil,
}
The Solution
I found the solution is to set only = true
in c.predict
when there is a subcommand found. This properly short-circuits the search. Otherwise, a parent matching command is found and overwrites any results. We also don't want the results merged, since the parent command does something totally different.
Here is the diff:
diff --git a/command.go b/command.go
index eeeb9e0..42b7f43 100644
--- a/command.go
+++ b/command.go
@@ -87,6 +87,7 @@ func (c *Command) predict(a Args) (options []string, only bool) {
// if a sub command was entered, we won't add the parent command
// completions and we return here.
if subCommandFound {
+ only = true
return
}
We'd love to see this fixed!
Again, thanks for a great library. We're rolling this out to all HashiCorp tooling and its been great so far. This is the first bug we've ran into.
bug