Thread (32 messages) 32 messages, 6 authors, 2025-04-08
STALE446d

[PATCH 1/3] completion: add helper to escape strings for fnmatch

From: David Mandelberg via GitGitGadget <hidden>
Date: 2025-03-02 07:45:29
Subsystem: the rest · Maintainer: Linus Torvalds

From: David Mandelberg <redacted>

A follow-up commit will use this to escape parts of ref names for
for-each-ref.

Signed-off-by: David Mandelberg <redacted>
---
 contrib/completion/git-completion.bash | 12 ++++++++++++
 t/t9902-completion.sh                  |  7 +++++++
 2 files changed, 19 insertions(+)
diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index 413911be3be..cb10f818a81 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -234,6 +234,18 @@ __git_dequote ()
 	done
 }
 
+# Escapes special characters in a string to pass to fnmatch(3)
+# 1: String to escape.
+__git_escape_fnmatch ()
+{
+	local s="$1"
+	s=${s//\\/\\\\}
+	s=${s//\?/\\\?}
+	s=${s//\*/\\\*}
+	s=${s//\[/\\\[}
+	printf '%s\n' "$s"
+}
+
 # The following function is based on code from:
 #
 #   bash_completion - programmable completion functions for bash 3.2+
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index 51bd7508376..c5e91622876 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -455,6 +455,13 @@ test_expect_success '__git_dequote - open double quote' '
 '
 
 
+test_expect_success '__git_escape_fnmatch' '
+	echo '\''foo\\\?\*\['\'' >expected &&
+	__git_escape_fnmatch '\''foo\?*['\'' >"$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
-- 
gitgitgadget
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help