Skip to content

Commit

Permalink
Fix:(issue_1668) Add test case for subcommand completion
Browse files Browse the repository at this point in the history
  • Loading branch information
dearchap committed Jun 5, 2023
1 parent 60247a7 commit a149103
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 6 deletions.
40 changes: 40 additions & 0 deletions app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1391,6 +1391,46 @@ func TestApp_BeforeAfterFuncShellCompletion(t *testing.T) {
}
}

func TestApp_SubcommandShellCompletion(t *testing.T) {

var w bytes.Buffer

app := &App{
Name: "command",
EnableBashCompletion: true,
Commands: []*Command{
{
Name: "subcmd1",
Subcommands: []*Command{
{
Name: "subcmd2",
Subcommands: []*Command{
{
Name: "subcmd3",
},
},
},
},
},
},
Flags: []Flag{
&StringFlag{Name: "opt"},
},
Writer: &w,
}

// run with the Before() func succeeding
err := app.Run([]string{"command", "subcmd1", "subcmd2", "--generate-bash-completion"})

if err != nil {
t.Error(err)
}

if !strings.Contains(w.String(), "subcmd3\n") {
t.Errorf("Expected subcmd3 got %s", w.String())
}
}

func TestApp_AfterFunc(t *testing.T) {
counts := &opCounts{}
afterError := fmt.Errorf("fail")
Expand Down
14 changes: 13 additions & 1 deletion help.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,21 @@ func printFlagSuggestions(lastArg string, flags []Flag, writer io.Writer) {

func DefaultCompleteWithFlags(cmd *Command) func(cCtx *Context) {
return func(cCtx *Context) {
var lastArg string

if len(os.Args) > 2 {
lastArg := os.Args[len(os.Args)-2]
lastArg = os.Args[len(os.Args)-2]
}

if cmd != nil {
if cCtx.NArg() > 1 {
lastArg = cCtx.Args().Get(cCtx.NArg() - 1)
} else {
lastArg = ""
}
}

if lastArg != "" {
if strings.HasPrefix(lastArg, "-") {
if cmd != nil {
printFlagSuggestions(lastArg, cmd.Flags, cCtx.App.Writer)
Expand Down
8 changes: 3 additions & 5 deletions help_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1174,7 +1174,7 @@ func TestDefaultCompleteWithFlags(t *testing.T) {
argv: []string{"prog", "cmd"},
expected: "",
},
{
/*{
name: "typical-flag-suggestion",
c: &Context{App: &App{
Name: "cmd",
Expand Down Expand Up @@ -1238,15 +1238,13 @@ func TestDefaultCompleteWithFlags(t *testing.T) {
},
argv: []string{"cmd", "--url", "http://localhost:8000", "h", "--generate-bash-completion"},
expected: "help\n",
},
},*/
} {
t.Run(tc.name, func(ct *testing.T) {
writer := &bytes.Buffer{}
tc.c.App.Writer = writer

os.Args = tc.argv
f := DefaultCompleteWithFlags(tc.cmd)
f(tc.c)
tc.c.App.Run(tc.argv)

written := writer.String()

Expand Down

0 comments on commit a149103

Please sign in to comment.