completion: Support the DWIM mode for git checkout
Ever since commit 70c9ac2 (DWIM: "git checkout frotz" to "git checkout -b frotz origin/frotz"), git checkout has supported a DWIM mode where it creates a local tracking branch for a remote branch if just the name of the remote branch is specified on the command-line and only one remote has a branch with that name. Teach the bash completion script to understand this DWIM mode and provide such remote-tracking branch names as possible completions. Signed-off-by: Kevin Ballard <kevin@sb.org> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Kevin Ballard committed
Oct 12, 2010 at 14:38 UTC
34a6bbb549095544ad8fc9ec29e2c890ef0c27d1
1 file changed
+27
-3
contrib/completion/git-completion.bash
+27
-3
@@ -380,16 +380,19 @@ __git_tags ()
380
done
381
}
382
383
-# __git_refs accepts 0 or 1 arguments (to pass to __gitdir)
383
+# __git_refs accepts 0, 1 (to pass to __gitdir), or 2 arguments
384
+# presence of 2nd argument means use the guess heuristic employed
385
+# by checkout for tracking branches
386
__git_refs ()
387
{
386
- local i is_hash=y dir="$(__gitdir "${1-}")"
388
+ local i is_hash=y dir="$(__gitdir "${1-}")" track="${2-}"
389
local cur="${COMP_WORDS[COMP_CWORD]}" format refs
390
if [ -d "$dir" ]; then
391
case "$cur" in
392
refs|refs/*)
393
format="refname"
394
refs="${cur%/*}"
395
+ track=""
396
;;
397
*)
398
for i in HEAD FETCH_HEAD ORIG_HEAD MERGE_HEAD; do
@@ -401,6 +404,21 @@ __git_refs ()
404
esac
405
git --git-dir="$dir" for-each-ref --format="%($format)" \
406
$refs
407
+ if [ -n "$track" ]; then
408
+ # employ the heuristic used by git checkout
409
+ # Try to find a remote branch that matches the completion word
410
+ # but only output if the branch name is unique
411
+ local ref entry
412
+ git --git-dir="$dir" for-each-ref --shell --format="ref=%(refname:short)" \
413
+ "refs/remotes/" | \
414
+ while read entry; do
415
+ eval "$entry"
416
+ ref="${ref#*/}"
417
+ if [[ "$ref" == "$cur"* ]]; then
418
+ echo "$ref"
419
+ fi
420
+ done | uniq -u
421
+ fi
422
return
423
fi
424
for i in $(git ls-remote "$dir" 2>/dev/null); do
@@ -988,7 +1006,13 @@ _git_checkout ()
1006
"
1007
;;
1008
*)
991
- __gitcomp "$(__git_refs)"
1009
+ # check if --track, --no-track, or --no-guess was specified
1010
+ # if so, disable DWIM mode
1011
+ local flags="--track --no-track --no-guess" track=1
1012
+ if [ -n "$(__git_find_on_cmdline "$flags")" ]; then
1013
+ track=''
1014
+ fi
1015
+ __gitcomp "$(__git_refs '' $track)"
1016
;;
1017
esac
1018
}