Conversation
louisroyer
left a comment
There was a problem hiding this comment.
Hi,
I see that when you provide the flag m1, m2 is wrongly suggested (they are mutually exclusive, so the only proposed flags should be l1, l2 and m1).
Could you add this test case as well, and adapt the code to make it pass?
|
@louisroyer |
There was a problem hiding this comment.
m1andm2are part of same group and are exclusive with onlyl2.l1is a global flag and will be valid in all cases.
oh, sorry I only tested against the example program from #2209: last 2 commands were not giving expected result, and tried to transpose this to your test scenario that I wrongly read 😅
Here are the test cases I was thinking about:
Co-authored-by: Louis Royer <55180044+louisroyer@users.noreply.github.com>
| if strings.HasPrefix(lastArg, "-") { | ||
| tracef("printing flag suggestion for flag[%v] on command %[1]q", lastArg, cmd.Name) | ||
| printFlagSuggestions(lastArg, cmd.Flags, cmd.Root().Writer) | ||
| printFlagSuggestions(lastArg, cmd.appliedFlags, cmd.Root().Writer) |
There was a problem hiding this comment.
| printFlagSuggestions(lastArg, cmd.appliedFlags, cmd.Root().Writer) | |
| printFlagSuggestions(lastArg, flagSuggestions(cmd, cmd.appliedFlags), cmd.Root().Writer) |
And add the following:
func allMutuallyExclusiveFlags(cmd *Command) [][][]Flag {
var flags [][][]Flag
for pCmd := cmd; pCmd != nil; pCmd = pCmd.parent {
for _, mxflags := range pCmd.MutuallyExclusiveFlags {
flags = append(flags, mxflags.Flags)
}
}
return flags
}
// excludedFlags lists flags that are excluded from flag suggestions because of mutual exclusivity.
func excludedFlags(cmd *Command) []Flag {
mxflags := allMutuallyExclusiveFlags(cmd)
var excluded []Flag
for _, flagsSet := range mxflags {
isExcluded := false
var maybeExcluded []Flag
for _, flags := range flagsSet {
if isExcluded {
excluded = append(excluded, flags...)
} else {
for _, flag := range flags {
if flag.IsSet() {
isExcluded = true
excluded = append(excluded, maybeExcluded...)
break
}
}
maybeExcluded = append(maybeExcluded, flags...)
}
}
}
return excluded
}
func flagSuggestions(cmd *Command, flags []Flag) []Flag {
excludedFlags := excludedFlags(cmd)
var sug []Flag
for _, flag := range flags {
if !flag.IsSet() && !hasFlag(excludedFlags, flag) {
sug = append(sug, flag)
}
}
return sug
}By testing manually, it works on the examples.
What type of PR is this?
(REQUIRED)
What this PR does / why we need it:
(REQUIRED)
Which issue(s) this PR fixes:
(REQUIRED)
Fixes #2209
Special notes for your reviewer:
(fill-in or delete this section)
Testing
(fill-in or delete this section)
go test -run=TestMutuallyExclusiveFlagsCompletion
Release Notes
(REQUIRED)