Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Subcommand fallback call to ExitErrHandler, fixing #816 #856

Merged
merged 1 commit into from
Aug 12, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
54 changes: 54 additions & 0 deletions app_test.go
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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