Skip to content

Commit

Permalink
feat(_comp_get_fist_arg): support "-o GLOB" to skip optargs
Browse files Browse the repository at this point in the history
  • Loading branch information
akinomyoga committed Sep 2, 2023
1 parent 1e4315a commit 0f14cc0
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 2 deletions.
23 changes: 21 additions & 2 deletions bash_completion
Original file line number Diff line number Diff line change
Expand Up @@ -2157,17 +2157,36 @@ _comp_realcommand()
}

# This function returns the first argument, excluding options
#
# Options:
# -a GLOB Pattern of options that take an option argument
#
# @var[out] ret First argument before current being completed if any, or
# otherwise an empty string
# @return True (0) if any argument is found, False (> 0) otherwise.
# @since 2.12
_comp_get_first_arg()
{
local i
local has_optarg=""
local OPTIND=1 OPTARG="" OPTERR=0 _opt
while getopts ':a:' _opt "$@"; do
case $_opt in
a) has_optarg=$OPTARG ;;
*)
echo "bash_completion: $FUNCNAME: usage error" >&2
return 2
;;
esac
done
shift "$((OPTIND - 1))"

local i
ret=
for ((i = 1; i < cword; i++)); do
if [[ ${words[i]} != -?* ]]; then
# shellcheck disable=SC2053
if [[ $has_optarg && ${words[i]} == $has_optarg ]]; then
((i++))
elif [[ ${words[i]} != -?* ]]; then
ret=${words[i]}
return 0
elif [[ ${words[i]} == -- ]]; then
Expand Down
54 changes: 54 additions & 0 deletions test/t/unit/test_unit_get_first_arg.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,57 @@ def test_8_double_hyphen_2(self, bash, functions):
bash, '_comp__test_unit "(a b -- -c -d e)" 5', want_output=None
).strip()
assert output == "b"

def test_9_skip_optarg_1(self, bash, functions):
output = assert_bash_exec(
bash,
'_comp__test_unit "(a -b -c d e f)" 5 -a "@(-c|--foo)"',
want_output=None,
).strip()
assert output == "e"

def test_9_skip_optarg_2(self, bash, functions):
output = assert_bash_exec(
bash,
'_comp__test_unit "(a -b --foo d e f)" 5 -a "@(-c|--foo)"',
want_output=None,
).strip()
assert output == "e"

def test_9_skip_optarg_3(self, bash):
output = assert_bash_exec(
bash,
'_comp__test_unit "(a -b - c d e)" 5 -a "-b"',
want_output=None,
).strip()
assert output == "c"

def test_9_skip_optarg_4(self, bash):
output = assert_bash_exec(
bash,
'_comp__test_unit "(a -b -c d e f)" 5 -a "-[bc]"',
want_output=None,
).strip()
assert output == "d"

def test_9_skip_optarg_5(self, bash):
output = assert_bash_exec(
bash, '_comp__test_unit "(a +o b c d)" 4 -a "+o"', want_output=None
).strip()
assert output == "c"

def test_9_skip_optarg_6(self, bash):
output = assert_bash_exec(
bash,
'_comp__test_unit "(a -o -o -o -o b c)" 6 -a "-o"',
want_output=None,
).strip()
assert output == "b"

def test_9_skip_optarg_7(self, bash):
output = assert_bash_exec(
bash,
'_comp__test_unit "(a -o -- -b -c d e)" 6 -a "-o"',
want_output=None,
).strip()
assert output == "d"

0 comments on commit 0f14cc0

Please sign in to comment.