diff mbox series

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

Message ID c8594d311741e884680fab8f9cc15eb881774163.1740901525.git.gitgitgadget@gmail.com (mailing list archive)
State New
Headers show
Series completion: fix bugs with slashes in remote names | expand

Commit Message

David Mandelberg March 2, 2025, 7:45 a.m. UTC
From: David Mandelberg <david@mandelberg.org>

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

Signed-off-by: David Mandelberg <david@mandelberg.org>
---
 contrib/completion/git-completion.bash | 12 ++++++++++++
 t/t9902-completion.sh                  |  7 +++++++
 2 files changed, 19 insertions(+)
diff mbox series

Patch

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