Skip to content

Commit fa4fd12

Browse files
authored
Merge pull request #2152 from Ali-Doustkani/fix_usageerrfunc_with_mutuallyexclusiveflags
2 parents 2a8bf1f + f76ffae commit fa4fd12

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed

command_run.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,11 @@ func (cmd *Command) run(ctx context.Context, osArgs []string) (_ context.Context
223223

224224
for _, grp := range cmd.MutuallyExclusiveFlags {
225225
if err := grp.check(cmd); err != nil {
226-
_ = ShowSubcommandHelp(cmd)
226+
if cmd.OnUsageError != nil {
227+
err = cmd.OnUsageError(ctx, cmd, err, cmd.parent != nil)
228+
} else {
229+
_ = ShowSubcommandHelp(cmd)
230+
}
227231
return ctx, err
228232
}
229233
}

command_test.go

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5168,6 +5168,62 @@ func TestJSONExportCommand(t *testing.T) {
51685168
assert.JSONEq(t, expected, string(out))
51695169
}
51705170

5171+
func TestCommand_ExclusiveFlags(t *testing.T) {
5172+
cmd := &Command{
5173+
Name: "bar",
5174+
MutuallyExclusiveFlags: []MutuallyExclusiveFlags{
5175+
{
5176+
Flags: [][]Flag{
5177+
{
5178+
&StringFlag{
5179+
Name: "foo1",
5180+
},
5181+
},
5182+
{
5183+
&StringFlag{
5184+
Name: "foo2",
5185+
},
5186+
},
5187+
},
5188+
},
5189+
},
5190+
}
5191+
5192+
err := cmd.Run(buildTestContext(t), []string{"bar", "--foo1", "var1", "--foo2", "var2"})
5193+
5194+
require.Equal(t, "option foo1 cannot be set along with option foo2", err.Error())
5195+
}
5196+
5197+
func TestCommand_ExclusiveFlagsWithOnUsageError(t *testing.T) {
5198+
expectedErr := errors.New("my custom error")
5199+
cmd := &Command{
5200+
Name: "bar",
5201+
MutuallyExclusiveFlags: []MutuallyExclusiveFlags{
5202+
{
5203+
Flags: [][]Flag{
5204+
{
5205+
&StringFlag{
5206+
Name: "foo1",
5207+
},
5208+
},
5209+
{
5210+
&StringFlag{
5211+
Name: "foo2",
5212+
},
5213+
},
5214+
},
5215+
},
5216+
},
5217+
OnUsageError: func(_ context.Context, _ *Command, _ error, _ bool) error {
5218+
return expectedErr
5219+
},
5220+
}
5221+
5222+
actualErr := cmd.Run(buildTestContext(t), []string{"bar", "--foo1", "v1", "--foo2", "v2"})
5223+
5224+
require.ErrorIs(t, actualErr, expectedErr)
5225+
}
5226+
51715227
func TestCommand_ExclusiveFlagsWithAfter(t *testing.T) {
51725228
var called bool
51735229
cmd := &Command{

0 commit comments

Comments
 (0)