Skip to content

Commit

Permalink
Merge pull request #856 from FaranIdo/master
Browse files Browse the repository at this point in the history
Add Subcommand fallback call to ExitErrHandler, fixing #816
  • Loading branch information
AudriusButkevicius committed Aug 12, 2019
2 parents 7e49cc2 + 08c24e2 commit 6cc7e98
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
54 changes: 54 additions & 0 deletions app_test.go
Expand Up @@ -2166,3 +2166,57 @@ func TestHandleActionActuallyWorksWithActions(t *testing.T) {
t.Errorf("Function was not called")
}
}

func TestWhenExitSubCommandWithCodeThenAppQuitUnexpectedly(t *testing.T) {
testCode := 104

app := NewApp()
app.Commands = []Command{
Command{
Name: "cmd",
Subcommands: []Command{
Command{
Name: "subcmd",
Action: func(c *Context) error {
return NewExitError("exit error", testCode)
},
},
},
},
}

// set user function as ExitErrHandler
var exitCodeFromExitErrHandler int
app.ExitErrHandler = func(c *Context, err error) {
if exitErr, ok := err.(ExitCoder); ok {
t.Log(exitErr)
exitCodeFromExitErrHandler = exitErr.ExitCode()
}
}

// keep and restore original OsExiter
origExiter := OsExiter
defer func() {
OsExiter = origExiter
}()

// set user function as OsExiter
var exitCodeFromOsExiter int
OsExiter = func(exitCode int) {
exitCodeFromOsExiter = exitCode
}

app.Run([]string{
"myapp",
"cmd",
"subcmd",
})

if exitCodeFromOsExiter != 0 {
t.Errorf("exitCodeFromOsExiter should not change, but its value is %v", exitCodeFromOsExiter)
}

if exitCodeFromExitErrHandler != testCode {
t.Errorf("exitCodeFromOsExiter valeu should be %v, but its value is %v", testCode, exitCodeFromExitErrHandler)
}
}
1 change: 1 addition & 0 deletions command.go
Expand Up @@ -268,6 +268,7 @@ func (c Command) HasName(name string) bool {
func (c Command) startApp(ctx *Context) error {
app := NewApp()
app.Metadata = ctx.App.Metadata
app.ExitErrHandler = ctx.App.ExitErrHandler
// set the name and usage
app.Name = fmt.Sprintf("%s %s", ctx.App.Name, c.Name)
if c.HelpName == "" {
Expand Down

0 comments on commit 6cc7e98

Please sign in to comment.