Skip to content

Commit

Permalink
Merge pull request #1676 from MrNaif2018/v2-fix-bash-autocomplete
Browse files Browse the repository at this point in the history
Backport [v2]:  Fix some issues in bash autocompletion
  • Loading branch information
dearchap authored Feb 3, 2023
2 parents 5c8f16b + 341ee8d commit 3d46fd3
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
22 changes: 18 additions & 4 deletions autocomplete/bash_autocomplete
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,31 @@

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

# Macs have bash3 for which the bash-completion package doesn't include
# _init_completion. This is a minimal version of that function.
_cli_init_completion() {
COMPREPLY=()
_get_comp_words_by_ref "$@" cur prev words cword
}

_cli_bash_autocomplete() {
if [[ "${COMP_WORDS[0]}" != "source" ]]; then
local cur opts base
local cur opts base words
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
if declare -F _init_completion >/dev/null 2>&1; then
_init_completion -n "=:" || return
else
_cli_init_completion -n "=:" || return
fi
words=("${words[@]:0:$cword}")
if [[ "$cur" == "-"* ]]; then
opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} ${cur} --generate-bash-completion )
requestComp="${words[*]} ${cur} --generate-bash-completion"
else
opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} --generate-bash-completion )
requestComp="${words[*]} --generate-bash-completion"
fi
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
opts=$(eval "${requestComp}" 2>/dev/null)
COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
return 0
fi
}
Expand Down
22 changes: 22 additions & 0 deletions help_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1194,6 +1194,28 @@ func TestDefaultCompleteWithFlags(t *testing.T) {
argv: []string{"cmd", "--generate-bash-completion"},
expected: "futz\n",
},
{
name: "autocomplete-with-spaces",
c: &Context{App: &App{
Name: "cmd",
Flags: []Flag{
&BoolFlag{Name: "happiness"},
&Int64Flag{Name: "everybody-jump-on"},
},
}},
cmd: &Command{
Name: "putz",
Subcommands: []*Command{
{Name: "help"},
},
Flags: []Flag{
&BoolFlag{Name: "excitement"},
&StringFlag{Name: "hat-shape"},
},
},
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{}
Expand Down

0 comments on commit 3d46fd3

Please sign in to comment.