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

Fix:(issue_1094) Dont execute Before/After during shell completions #1459

Merged
merged 1 commit into from Aug 29, 2022
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
8 changes: 4 additions & 4 deletions app.go
Expand Up @@ -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 {
Expand All @@ -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)
Expand Down Expand Up @@ -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 {
Expand All @@ -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)
Expand Down
52 changes: 52 additions & 0 deletions app_test.go
Expand Up @@ -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")
Expand Down