Skip to content
Open
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
40 changes: 28 additions & 12 deletions flag_mutex.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,38 @@ type MutuallyExclusiveFlags struct {
}

func (grp MutuallyExclusiveFlags) check(_ *Command) error {
oneSet := false
e := &mutuallyExclusiveGroup{}

for _, grpf := range grp.Flags {
for _, f := range grpf {
if f.IsSet() {
if oneSet {
e.flag2Name = f.Names()[0]
return e
}
e.flag1Name = f.Names()[0]
// First, find the index of the group were the flag was set
// (if it exists.)
var i int
var oneSet bool

flagGroupLoop:
for ; i < len(grp.Flags); i++ {
group := grp.Flags[i]

// For each flag inside this group, check if it's set.
for _, flg := range group {
if flg.IsSet() {
e.flag1Name = flg.Names()[0]
oneSet = true
break
break flagGroupLoop
}
if oneSet {
break
}
}

// Next, continue from the flag group just after the one we
// stopped at above, to see if another flag is set. If so,
// return an error.
i++
for ; i < len(grp.Flags); i++ {
group := grp.Flags[i]

for _, flg := range group {
if flg.IsSet() {
e.flag2Name = flg.Names()[0]
return e
}
}
}
Expand Down
9 changes: 9 additions & 0 deletions flag_mutex_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ func newCommand() *Command {
Aliases: []string{"ai"},
Sources: EnvVars("T_VAR"),
},
&BoolFlag{
Name: "q",
},
},
},
},
Expand Down Expand Up @@ -73,6 +76,12 @@ func TestFlagMutuallyExclusiveFlags(t *testing.T) {
errStr: "option i cannot be set along with option ai",
required: true,
},
{
name: "required both set second member",
args: []string{"--i", "11", "--q"},
errStr: "option i cannot be set along with option q",
required: true,
},
{
name: "set env var",
required: true,
Expand Down