lib: Add '--append' mode to 'getargs'

This commit is contained in:
Ethan P 2021-04-02 15:43:45 -07:00
parent 9efc5362df
commit 47152d69c3
No known key found for this signature in database
GPG Key ID: 6963FD04F6CF35EA
2 changed files with 22 additions and 2 deletions

View File

@ -50,12 +50,17 @@ setargs() {
# Gets all the remaining unparsed arguments and saves them to a variable.
#
# Arguments:
# $1 -- The variable to save the args to.
# "-a" -- Append the arguments to the variable instead of replacing it.
# $1 -- The variable to save the args to.
#
# Example:
# getargs remaining_args
getargs() {
eval "$1=($(printf '%q ' "${_ARGV[@]:$_ARGV_INDEX}"))"
if [[ "$1" = "-a" || "$1" = "--append" ]]; then
eval "$2=(\"\${$2[@]}\" $(printf '%q ' "${_ARGV[@]:$_ARGV_INDEX}"))"
else
eval "$1=($(printf '%q ' "${_ARGV[@]:$_ARGV_INDEX}"))"
fi
}
# Resets the internal _ARGV* variables to the original script arguments.

View File

@ -415,3 +415,18 @@ test:fn_getargs() {
shiftopt
assert_opt_name "three"
}
test:fn_getargs_append() {
description "Function getargs -a."
setargs "--two=three" "four"
args=(zero one)
getargs -a args
assert_equal 4 "${#args[@]}"
assert_equal "zero" "${args[0]}"
assert_equal "one" "${args[1]}"
assert_equal "--two=three" "${args[2]}"
assert_equal "four" "${args[3]}"
}