Skip to content

Commit c185573

Browse files
authored
Merge pull request urfave#2161 from MohitPanchariya/issue-#2145
Invoke OnUsageError when missing required flags
2 parents 9cd5d9c + de88ce6 commit c185573

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

command_run.go

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

315315
if err := cmd.checkAllRequiredFlags(); err != nil {
316316
cmd.isInError = true
317-
_ = ShowSubcommandHelp(cmd)
317+
if cmd.OnUsageError != nil {
318+
err = cmd.OnUsageError(ctx, cmd, err, cmd.parent != nil)
319+
} else {
320+
_ = ShowSubcommandHelp(cmd)
321+
}
318322
return ctx, err
319323
}
320324

command_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4096,6 +4096,21 @@ func TestCheckRequiredFlags(t *testing.T) {
40964096
}
40974097
}
40984098

4099+
func TestCheckRequiredFlagsWithOnUsageError(t *testing.T) {
4100+
expectedError := errors.New("OnUsageError")
4101+
cmd := &Command{
4102+
Name: "foo",
4103+
Flags: []Flag{
4104+
&StringFlag{Name: "requiredFlag", Required: true},
4105+
},
4106+
OnUsageError: func(_ context.Context, _ *Command, _ error, _ bool) error {
4107+
return expectedError
4108+
},
4109+
}
4110+
actualError := cmd.Run(buildTestContext(t), []string{"requiredFlag"})
4111+
require.ErrorIs(t, actualError, expectedError)
4112+
}
4113+
40994114
func TestCommand_ParentCommand_Set(t *testing.T) {
41004115
cmd := &Command{
41014116
parent: &Command{

0 commit comments

Comments
 (0)