From 94014b6328f813b674a1126ffd221705d7e315b3 Mon Sep 17 00:00:00 2001
From: Michael Hanselmann <hansmi@google.com>
Date: Tue, 18 Sep 2012 14:56:52 +0200
Subject: [PATCH] bash_completion: Always enable extglob
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

In older versions of GNU Bash extended patterns, such as β€œ@(…)” are only
available with the β€œextglob” shell option. This patch adds a wrapper
function so that extglob is always enabled while doing any completion.
Due to early returns inside the main completion function this seemed
like the best option.

Reported by Sascha Lucas.

Signed-off-by: Michael Hanselmann <hansmi@google.com>
Reviewed-by: Bernardo Dal Seno <bdalseno@google.com>
---
 autotools/build-bash-completion | 26 ++++++++++++++++++++++----
 1 file changed, 22 insertions(+), 4 deletions(-)

diff --git a/autotools/build-bash-completion b/autotools/build-bash-completion
index a5e7acfd7..f7e086819 100755
--- a/autotools/build-bash-completion
+++ b/autotools/build-bash-completion
@@ -520,13 +520,12 @@ def WriteCompletion(sw, scriptname, funcname,
   @param commands: List of all subcommands in this program
 
   """
-  sw.Write("%s() {", funcname)
+  sw.Write("%s_inner() {", funcname)
   sw.IncIndent()
   try:
-    sw.Write("local "
+    sw.Write("local i first_arg_idx choices compgenargs arg_idx optcur"
              ' cur="${COMP_WORDS[COMP_CWORD]}"'
-             ' prev="${COMP_WORDS[COMP_CWORD-1]}"'
-             ' i first_arg_idx choices compgenargs arg_idx optcur')
+             ' prev="${COMP_WORDS[COMP_CWORD-1]}"')
 
     sw.Write("_gnt_log cur=\"$cur\" prev=\"$prev\"")
     sw.Write("[[ -n \"$GANETI_COMPL_LOG\" ]] &&"
@@ -575,6 +574,25 @@ def WriteCompletion(sw, scriptname, funcname,
     sw.DecIndent()
   sw.Write("}")
 
+  # Wrapper function to always enable extglob (needed for advanced pattern
+  # matching)
+  sw.Write("%s() {", funcname)
+  sw.IncIndent()
+  try:
+    # Get current state of extglob
+    sw.Write("local -r eg=$(shopt -p extglob || :)")
+
+    # Enable extglob
+    sw.Write("shopt -s extglob")
+
+    sw.Write("%s_inner \"$@\"", funcname)
+
+    # Reset extglob to original value
+    sw.Write("[[ -n \"$eg\" ]] && $eg")
+  finally:
+    sw.DecIndent()
+  sw.Write("}")
+
   sw.Write("complete -F %s -o filenames %s",
            utils.ShellQuote(funcname),
            utils.ShellQuote(scriptname))
-- 
GitLab