Fix After not run

This commit is contained in:
Dokiy 2022-07-28 19:00:48 +08:00
parent c8147a4845
commit a1c26d5491
2 changed files with 33 additions and 12 deletions

24
app.go
View File

@ -300,6 +300,18 @@ func (a *App) RunContext(ctx context.Context, arguments []string) (err error) {
return err return err
} }
if a.After != nil {
defer func() {
if afterErr := a.After(cCtx); afterErr != nil {
if err != nil {
err = newMultiError(err, afterErr)
} else {
err = afterErr
}
}
}()
}
if !a.HideHelp && checkHelp(cCtx) { if !a.HideHelp && checkHelp(cCtx) {
_ = ShowAppHelp(cCtx) _ = ShowAppHelp(cCtx)
return nil return nil
@ -316,18 +328,6 @@ func (a *App) RunContext(ctx context.Context, arguments []string) (err error) {
return cerr return cerr
} }
if a.After != nil {
defer func() {
if afterErr := a.After(cCtx); afterErr != nil {
if err != nil {
err = newMultiError(err, afterErr)
} else {
err = afterErr
}
}
}()
}
if a.Before != nil { if a.Before != nil {
beforeErr := a.Before(cCtx) beforeErr := a.Before(cCtx)
if beforeErr != nil { if beforeErr != nil {

View File

@ -1309,6 +1309,27 @@ func TestApp_AfterFunc(t *testing.T) {
if counts.SubCommand != 1 { if counts.SubCommand != 1 {
t.Errorf("Subcommand not executed when expected") t.Errorf("Subcommand not executed when expected")
} }
/*
reset
*/
counts = &opCounts{}
// run with none args
err = app.Run([]string{"command"})
// should be the same error produced by the Before func
if err != nil {
t.Fatalf("Run error: %s", err)
}
if counts.After != 1 {
t.Errorf("After() not executed when expected")
}
if counts.SubCommand != 0 {
t.Errorf("Subcommand not executed when expected")
}
} }
func TestAppNoHelpFlag(t *testing.T) { func TestAppNoHelpFlag(t *testing.T) {