From c24c9f398d5d925f8c3d990509e8c7b3ae942646 Mon Sep 17 00:00:00 2001 From: dearchap Date: Mon, 29 Aug 2022 07:24:10 -0400 Subject: [PATCH] Fix:(issue_1094) Dont execute Before/After during shell completions (#1459) --- app.go | 8 ++++---- app_test.go | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/app.go b/app.go index 382f238f49..df5a9a91be 100644 --- a/app.go +++ b/app.go @@ -248,7 +248,7 @@ func (a *App) Run(arguments []string) (err error) { return cerr } - if a.After != nil { + if a.After != nil && !context.shellComplete { defer func() { if afterErr := a.After(context); afterErr != nil { if err != nil { @@ -260,7 +260,7 @@ func (a *App) Run(arguments []string) (err error) { }() } - if a.Before != nil { + if a.Before != nil && !context.shellComplete { beforeErr := a.Before(context) if beforeErr != nil { a.handleExitCoder(context, beforeErr) @@ -374,7 +374,7 @@ func (a *App) RunAsSubcommand(ctx *Context) (err error) { return cerr } - if a.After != nil { + if a.After != nil && !context.shellComplete { defer func() { afterErr := a.After(context) if afterErr != nil { @@ -388,7 +388,7 @@ func (a *App) RunAsSubcommand(ctx *Context) (err error) { }() } - if a.Before != nil { + if a.Before != nil && !context.shellComplete { beforeErr := a.Before(context) if beforeErr != nil { a.handleExitCoder(context, beforeErr) diff --git a/app_test.go b/app_test.go index 4dc43ba623..e18a9f074e 100644 --- a/app_test.go +++ b/app_test.go @@ -986,6 +986,58 @@ func TestApp_BeforeFunc(t *testing.T) { } } +func TestApp_BeforeAfterFuncShellCompletion(t *testing.T) { + counts := &opCounts{} + var err error + + app := &App{ + EnableBashCompletion: true, + Before: func(c *Context) error { + counts.Total++ + counts.Before = counts.Total + return nil + }, + After: func(c *Context) error { + counts.Total++ + counts.After = counts.Total + return nil + }, + Commands: []Command{ + { + Name: "sub", + Action: func(c *Context) error { + counts.Total++ + counts.SubCommand = counts.Total + return nil + }, + }, + }, + Flags: []Flag{ + &StringFlag{Name: "opt"}, + }, + Writer: ioutil.Discard, + } + + // run with the Before() func succeeding + err = app.Run([]string{"command", "--opt", "succeed", "sub", "--generate-bash-completion"}) + + if err != nil { + t.Fatalf("Run error: %s", err) + } + + if counts.Before != 0 { + t.Errorf("Before() executed when not expected") + } + + if counts.After != 0 { + t.Errorf("After() executed when not expected") + } + + if counts.SubCommand != 0 { + t.Errorf("Subcommand executed more than expected") + } +} + func TestApp_AfterFunc(t *testing.T) { counts := &opCounts{} afterError := fmt.Errorf("fail")