completion: return the index of found word from __git_find_on_cmdline()
When using the __git_find_on_cmdline() helper function so far we've only been interested in which one of a set of words appear on the command line. To complete options for some of 'git worktree's subcommands in the following patches we'll need not only that, but the index of that word on the command line as well. Extend __git_find_on_cmdline() to optionally show the index of the found word on the command line (IOW in the $words array) when the '--show-idx' option is given. Signed-off-by: SZEDER Gábor <szeder.dev@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
SZEDER Gábor committed
Dec 19, 2019 at 16:09 UTC
367efd54b34883889068255c370a4b9f079cec2d
2 files changed
+46
-3
contrib/completion/git-completion.bash
+17
-3
@@ -1069,18 +1069,32 @@ __git_aliased_command ()
1069
done
1070
}
1071
1072
-# __git_find_on_cmdline requires 1 argument
1072
# Check whether one of the given words is present on the command line,
1073
# and print the first word found.
1074
+#
1075
+# Usage: __git_find_on_cmdline [<option>]... "<wordlist>"
1076
+# --show-idx: Optionally show the index of the found word in the $words array.
1077
__git_find_on_cmdline ()
1078
{
1077
- local word c=1
1079
+ local word c=1 show_idx
1080
+
1081
+ while test $# -gt 1; do
1082
+ case "$1" in
1083
+ --show-idx) show_idx=y ;;
1084
+ *) return 1 ;;
1085
+ esac
1086
+ shift
1087
+ done
1088
local wordlist="$1"
1089
1090
while [ $c -lt $cword ]; do
1091
for word in $wordlist; do
1092
if [ "$word" = "${words[c]}" ]; then
1083
- echo "$word"
1093
+ if [ -n "$show_idx" ]; then
1094
+ echo "$c $word"
1095
+ else
1096
+ echo "$word"
1097
+ fi
1098
return
1099
fi
1100
done
t/t9902-completion.sh
+29
@@ -1392,6 +1392,35 @@ test_expect_success '__git_find_on_cmdline - no match' '
1392
test_must_be_empty actual
1393
'
1394
1395
+test_expect_success '__git_find_on_cmdline - single match with index' '
1396
+ echo "3 list" >expect &&
1397
+ (
1398
+ words=(git command --opt list) &&
1399
+ cword=${#words[@]} &&
1400
+ __git_find_on_cmdline --show-idx "add list remove" >actual
1401
+ ) &&
1402
+ test_cmp expect actual
1403
+'
1404
+
1405
+test_expect_success '__git_find_on_cmdline - multiple matches with index' '
1406
+ echo "4 remove" >expect &&
1407
+ (
1408
+ words=(git command -o --opt remove list add) &&
1409
+ cword=${#words[@]} &&
1410
+ __git_find_on_cmdline --show-idx "add list remove" >actual
1411
+ ) &&
1412
+ test_cmp expect actual
1413
+'
1414
+
1415
+test_expect_success '__git_find_on_cmdline - no match with index' '
1416
+ (
1417
+ words=(git command --opt branch) &&
1418
+ cword=${#words[@]} &&
1419
+ __git_find_on_cmdline --show-idx "add list remove" >actual
1420
+ ) &&
1421
+ test_must_be_empty actual
1422
+'
1423
+
1424
test_expect_success '__git_get_config_variables' '
1425
cat >expect <<-EOF &&
1426
name-1