Skip to content

Commit 3d46fd3

Browse files
authored
Merge pull request #1676 from MrNaif2018/v2-fix-bash-autocomplete
Backport [v2]: Fix some issues in bash autocompletion
2 parents 5c8f16b + 341ee8d commit 3d46fd3

File tree

2 files changed

+40
-4
lines changed

2 files changed

+40
-4
lines changed

autocomplete/bash_autocomplete

+18-4
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,31 @@
22

33
: ${PROG:=$(basename ${BASH_SOURCE})}
44

5+
# Macs have bash3 for which the bash-completion package doesn't include
6+
# _init_completion. This is a minimal version of that function.
7+
_cli_init_completion() {
8+
COMPREPLY=()
9+
_get_comp_words_by_ref "$@" cur prev words cword
10+
}
11+
512
_cli_bash_autocomplete() {
613
if [[ "${COMP_WORDS[0]}" != "source" ]]; then
7-
local cur opts base
14+
local cur opts base words
815
COMPREPLY=()
916
cur="${COMP_WORDS[COMP_CWORD]}"
17+
if declare -F _init_completion >/dev/null 2>&1; then
18+
_init_completion -n "=:" || return
19+
else
20+
_cli_init_completion -n "=:" || return
21+
fi
22+
words=("${words[@]:0:$cword}")
1023
if [[ "$cur" == "-"* ]]; then
11-
opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} ${cur} --generate-bash-completion )
24+
requestComp="${words[*]} ${cur} --generate-bash-completion"
1225
else
13-
opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} --generate-bash-completion )
26+
requestComp="${words[*]} --generate-bash-completion"
1427
fi
15-
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
28+
opts=$(eval "${requestComp}" 2>/dev/null)
29+
COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
1630
return 0
1731
fi
1832
}

help_test.go

+22
Original file line numberDiff line numberDiff line change
@@ -1194,6 +1194,28 @@ func TestDefaultCompleteWithFlags(t *testing.T) {
11941194
argv: []string{"cmd", "--generate-bash-completion"},
11951195
expected: "futz\n",
11961196
},
1197+
{
1198+
name: "autocomplete-with-spaces",
1199+
c: &Context{App: &App{
1200+
Name: "cmd",
1201+
Flags: []Flag{
1202+
&BoolFlag{Name: "happiness"},
1203+
&Int64Flag{Name: "everybody-jump-on"},
1204+
},
1205+
}},
1206+
cmd: &Command{
1207+
Name: "putz",
1208+
Subcommands: []*Command{
1209+
{Name: "help"},
1210+
},
1211+
Flags: []Flag{
1212+
&BoolFlag{Name: "excitement"},
1213+
&StringFlag{Name: "hat-shape"},
1214+
},
1215+
},
1216+
argv: []string{"cmd", "--url", "http://localhost:8000", "h", "--generate-bash-completion"},
1217+
expected: "help\n",
1218+
},
11971219
} {
11981220
t.Run(tc.name, func(ct *testing.T) {
11991221
writer := &bytes.Buffer{}

0 commit comments

Comments
 (0)