Skip to contentSkip to conversation

support bash completion for add-on commands

PATCH New Joey Hess 1 participant 1 message Jun 15, 2016

lore
Share & tools
lore

Joey Hess

author
#0 lore raw

PATCH 1/1 support bash completion for add-on commands

This makes it possible to implement bash completion for add-on commands, that will work even when the bash completion scripts are being loaded on-demand, as is done by the bash-completion package.

git's bash completion handles subcommands by running a _git_$command function. As well as the many such functions included in git-completion.bash, there can be other functions defined elsewhere to support third-party add-on git commands, and they'll happily be used.

But, bash completion scripts are often loaded on demand, as shown in the completion_loader example in bash's man page, and the bash-completion implementation that is commonly used on many Linux systems. The demand loading will load this very script from some place like /usr/share/bash-completion/completions/git, when the user complete a git command. But, completion scripts for git add-on commands don't get loaded.

For example, when I wrote a git-annex bash completion script, bash was unable to tab complete "git annex foo", until I tab completed a "git-annex" command. Which loaded the git-annex completion, and then that same completion worked to make "git annex foo" tab complete. An inconsistent UI..

So, if the git completion script is unable to find the wanted _git_$command function, have it fall-back to looking for a git-$command completion script, and loading it. The add-on script is looked for in the same directory as the git completion script, which we can find by looking at BASH_SOURCE.

---
 contrib/completion/git-completion.bash | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
contrib/completion/git-completion.bash +10 -1
index c97c648..ba91b2a 100644
@@ -2614,7 +2614,16 @@ __git_main ()
 	if [ -n "$expansion" ]; then
 		words[1]=$expansion
 		completion_func="_git_${expansion//-/_}"
-		declare -f $completion_func >/dev/null && $completion_func
+		declare -f $completion_func >/dev/null && $completion_func && return
+	fi
+
+	# As a fallback, if no completion function is defined for the
+	# command, look for add-on command completion script in same
+	# directory as this completion script, and if found, source it,
+	# and restart completion using it.
+	local compdir="${BASH_SOURCE%/*}"
+	if [ -e "$compdir/git-$command" ]; then
+		source "$compdir/git-$command" && __git_main "$@"
 	fi
 }
 
Signature · 1 line
2.1.4