completion: add helper to count path components

A follow-up commit will use this with for-each-ref to strip the right number of path components from refnames. Signed-off-by: David Mandelberg <david@mandelberg.org> Signed-off-by: Junio C Hamano <gitster@pobox.com>

David Mandelberg committed Mar 23, 2025 at 17:05 UTC 5637bdc352a7763e30290bb37239a61cb9865d1b
2 files changed +37
contrib/completion/git-completion.bash
+11
@@ -234,6 +234,17 @@ __git_dequote ()
234 done
235 }
236
237 +# Prints the number of slash-separated components in a path.
238 +# 1: Path to count components of.
239 +__git_count_path_components ()
240 +{
241 + local path="$1"
242 + local relative="${path#/}"
243 + relative="${relative%/}"
244 + local slashes="/${relative//[^\/]}"
245 + echo "${#slashes}"
246 +}
247 +
248 # The following function is based on code from:
249 #
250 # bash_completion - programmable completion functions for bash 3.2+
t/t9902-completion.sh
+26
@@ -455,6 +455,32 @@ test_expect_success '__git_dequote - open double quote' '
455 '
456
457
458 +test_expect_success '__git_count_path_components - no slashes' '
459 + echo 1 >expected &&
460 + __git_count_path_components a >"$actual" &&
461 + test_cmp expected "$actual"
462 +'
463 +
464 +test_expect_success '__git_count_path_components - relative' '
465 + echo 3 >expected &&
466 + __git_count_path_components a/b/c >"$actual" &&
467 + test_cmp expected "$actual"
468 +
469 +'
470 +
471 +test_expect_success '__git_count_path_components - absolute' '
472 + echo 3 >expected &&
473 + __git_count_path_components /a/b/c >"$actual" &&
474 + test_cmp expected "$actual"
475 +'
476 +
477 +test_expect_success '__git_count_path_components - trailing slash' '
478 + echo 3 >expected &&
479 + __git_count_path_components a/b/c/ >"$actual" &&
480 + test_cmp expected "$actual"
481 +'
482 +
483 +
484 test_expect_success '__gitcomp_direct - puts everything into COMPREPLY as-is' '
485 sed -e "s/Z$//g" >expected <<-EOF &&
486 with-trailing-space Z