Skip to content

Instantly share code, notes, and snippets.

@adamluzsi
Last active October 13, 2019 00:04
Show Gist options
  • Save adamluzsi/996b6d45deac64dc70d5c7c5a1d59369 to your computer and use it in GitHub Desktop.
Save adamluzsi/996b6d45deac64dc70d5c7c5a1d59369 to your computer and use it in GitHub Desktop.
GoLang bash completion
#!/usr/bin/env bash
function _comp_go-subcmd() {
local cmd=${1:?"cmd is required"}
local cur=${COMP_WORDS[COMP_CWORD]}
# try find completion for cmd options
if _comp_go-subcmd-opts "${cmd}"; then
return 0
fi
# checking empty here make sure that file paths don't bloat when opts wanted to be checked
if [[ -n ${cur} ]]; then
_comp_go-subcmd-dirs "${cur}"
return 0
fi
}
function _comp_go-subcmd-opts() {
local cmd=${1:?"cmd is required"}
local cur=${COMP_WORDS[COMP_CWORD]}
local prev=${COMP_WORDS[COMP_CWORD - 1]}
local curRGX=$(CUR="${cur}" perl -e 'print quotemeta($ENV{"CUR"})')
# option completion
case ${prev} in
"-mod")
COMPREPLY+=($(compgen -W "readonly vendor" -- ${cur}))
return 0
;;
"-count")
COMPREPLY+=($(compgen -W "1" -- ${cur}))
return 0
;;
esac
case ${cmd} in
"test" | "build") COMPREPLY+=($(compgen -W "-mod" -- ${cur})) ;;
esac
# option listing
local opts=$(
(
case ${cmd} in
"test") go doc go/internal/test.HelpTestflag | grep -e '^[[:space:]]*-' ;;
*) go help "${cmd}" ;;
esac
) \
| perl -n -l -e 'print $1 if /\s+(-\w+)/;' \
| grep -P -e "^${curRGX}" \
| sort \
| uniq
)
local opt
for opt in ${opts[@]}; do
COMPREPLY+=("${opt}")
done
if [[ ${cur} == -* ]]; then
return 0
fi
return 64
}
function _comp_go-subcmd-dirs() {
local cur=${1:?"current dir path is required"}
if [[ -d ${cur} ]] && [[ ${cur} == */. ]]; then
COMPREPLY+=("${cur%/.}/...")
return 0
fi
local -a dirs
readarray -t dirs < <(compgen -d "${cur}")
local d
for d in ${dirs[@]}; do
COMPREPLY+=("${d}/")
COMPREPLY+=("${d}/...")
done
}
function _comp_go-cmds() {
local cur=${COMP_WORDS[COMP_CWORD]}
local curRGX=$(CUR="${cur}" perl -e 'print quotemeta($ENV{"CUR"})')
local kws=$(
go help \
| grep -B 128 -F -e 'go help <command>' \
| perl -n -l -e 'print $1 if /^\t(\w+)/;' \
| grep -P -e "^${curRGX}"
)
local kw
for kw in ${kws[@]}; do
COMPREPLY+=("${kw}")
done
}
function _comp_go() {
local cur=${COMP_WORDS[COMP_CWORD]}
local subcmd=${COMP_WORDS[1]}
# go help [cur]
if [[ ${subcmd} == "help" ]]; then
_comp_go-cmds
return
fi
if [[ ${COMP_CWORD} -eq 1 ]]; then
_comp_go-cmds
return
fi
_comp_go-subcmd "${subcmd}"
}
complete -F _comp_go go
@adamluzsi
Copy link
Author

adamluzsi commented Sep 12, 2019

gives auto-completion for

  • sub commands
  • sub command options
  • certain sub command option parameters
  • sub command paths
    • directories
    • ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment