]> git.ipfire.org Git - thirdparty/git.git/commitdiff
completion: add helper to count path components
authorDavid Mandelberg <david@mandelberg.org>
Sun, 23 Mar 2025 21:05:46 +0000 (17:05 -0400)
committerJunio C Hamano <gitster@pobox.com>
Mon, 24 Mar 2025 06:03:12 +0000 (23:03 -0700)
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>
contrib/completion/git-completion.bash
t/t9902-completion.sh

index 413911be3be3136acda6f1985a1f48112c818b2e..5fdc71208e549c7c2fba0de4e09dfb78e06af6c7 100644 (file)
@@ -234,6 +234,17 @@ __git_dequote ()
        done
 }
 
+# Prints the number of slash-separated components in a path.
+# 1: Path to count components of.
+__git_count_path_components ()
+{
+       local path="$1"
+       local relative="${path#/}"
+       relative="${relative%/}"
+       local slashes="/${relative//[^\/]}"
+       echo "${#slashes}"
+}
+
 # The following function is based on code from:
 #
 #   bash_completion - programmable completion functions for bash 3.2+
index 51bd7508376ce31d917706af71d41262eb101a6f..015289c776466bbc7c18c708e474c0d2df4b026e 100755 (executable)
@@ -455,6 +455,32 @@ test_expect_success '__git_dequote - open double quote' '
 '
 
 
+test_expect_success '__git_count_path_components - no slashes' '
+       echo 1 >expected &&
+       __git_count_path_components a >"$actual" &&
+       test_cmp expected "$actual"
+'
+
+test_expect_success '__git_count_path_components - relative' '
+       echo 3 >expected &&
+       __git_count_path_components a/b/c >"$actual" &&
+       test_cmp expected "$actual"
+
+'
+
+test_expect_success '__git_count_path_components - absolute' '
+       echo 3 >expected &&
+       __git_count_path_components /a/b/c >"$actual" &&
+       test_cmp expected "$actual"
+'
+
+test_expect_success '__git_count_path_components - trailing slash' '
+       echo 3 >expected &&
+       __git_count_path_components a/b/c/ >"$actual" &&
+       test_cmp expected "$actual"
+'
+
+
 test_expect_success '__gitcomp_direct - puts everything into COMPREPLY as-is' '
        sed -e "s/Z$//g" >expected <<-EOF &&
        with-trailing-space Z