Skip to content

Instantly share code, notes, and snippets.

@davesque
Last active December 14, 2017 20:13
Show Gist options
  • Save davesque/80670c86138ea81444c4544a37cd2c75 to your computer and use it in GitHub Desktop.
Save davesque/80670c86138ea81444c4544a37cd2c75 to your computer and use it in GitHub Desktop.
Simple git completion (branches only, no context)
__simple_upsearch() {
if [[ -e $1 ]]; then
[[ $PWD == / ]] \
&& printf '/%s' "$1" \
|| printf '%s/%s' "$PWD" "$1"
return 0
fi
[[ $PWD == / ]] && return 1
cd ..
__simple_upsearch "$1"
}
__simple_git_complete_options() {
(
gitloc=$(__simple_upsearch .git)
options=()
# Add local branch names
cd "$gitloc/refs/heads"
options+=(*)
# Get remote names
cd "$gitloc/refs/remotes"
for r in *; do
# Add bare remote branch names
cd "$r"
options+=(*)
# Add prefixed remote branch names
cd ..
options+=("$r"/*)
done
printf '%s\n' "${options[@]}" | sort | uniq
)
}
__simple_git_complete() {
cur="${COMP_WORDS[COMP_CWORD]}";
IFS=$'\n'
options=($(__simple_git_complete_options))
unset IFS
# Handle leading colon
if [[ ${cur:0:1} == : ]]; then
cur="${cur:1}"
fi
# Handle leading caret
if [[ ${cur:0:1} == ^ ]]; then
IFS=$'\n'
options=($(printf '^%s\n' "${options[@]}"))
unset IFS
fi
# Determine if the current word is a revision range (e.g. master...feature,
# master..feature)
symmetric=$(grep -o '\.\.\(\.\)\?' <<< "$cur")
if [[ -n $symmetric ]]; then
IFS="$symmetric" read -ra bs <<< "$cur"
IFS=$'\n'
options=($(printf "${bs[0]}${symmetric}"'%s\n' "${options[@]}"))
unset IFS
fi
COMPREPLY=($(compgen -W "${options[*]}" "$cur"))
}
complete -o bashdefault -o default -o nospace -F __simple_git_complete git
@davesque
Copy link
Author

davesque commented Dec 13, 2017

Why?

The full git completion file is kind of overkill and adds to bash's boot time. I only ever really want branch name completion so I wanted a light-weight script just for that.

Drawbacks

  • Was designed primarily with completion of branch names in mind. As such, completion options do not depend on context.
  • Assumes branch/remote names have no spaces in them (I believe this must be true anyway so maybe it's not actually a drawback)

Advantages

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