Skip to content

Instantly share code, notes, and snippets.

@APIUM
Created August 21, 2018 02:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save APIUM/f611b31bd5b833340aeb95c29c0f4308 to your computer and use it in GitHub Desktop.
Save APIUM/f611b31bd5b833340aeb95c29c0f4308 to your computer and use it in GitHub Desktop.
output of which
-antigen-parse-args () {
local spec="$1"
shift
spec="$(echo "$spec" | tr '\n' ' ' | sed 's/[[:space:]]//g')"
local code=''
--add-var () {
test -z "$code" || code="$code\n"
code="${code}local $1='$2'"
}
local positional_args="$(echo "$spec" | cut -d\; -f1)"
local positional_args_count="$(echo $positional_args |
awk -F, '{print NF}')"
local i=1
while [[ -n $1 && $1 != --* ]]
do
if (( $i > $positional_args_count ))
then
echo "Only $positional_args_count positional arguments allowed." >&2
echo "Found at least one more: '$1'" >&2
return
fi
local name_spec="$(echo "$positional_args" | cut -d, -f$i)"
local name="${${name_spec%\?}%:}"
local value="$1"
if echo "$code" | grep -l "^local $name=" &> /dev/null
then
echo "Argument '$name' repeated with the value '$value'". >&2
return
fi
--add-var $name "$value"
shift
i=$(($i + 1))
done
local keyword_args="$(
# Positional arguments can double up as keyword arguments too.
echo "$positional_args" | tr , '\n' |
while read line; do
if [[ $line == *\? ]]; then
echo "${line%?}:?"
else
echo "$line:"
fi
done
# Specified keyword arguments.
echo "$spec" | cut -d\; -f2 | tr , '\n'
)"
local keyword_args_count="$(echo $keyword_args | awk -F, '{print NF}')"
while [[ $1 == --* ]]
do
local arg="${1#--}"
if [[ $arg != *=* ]]
then
local name="$arg"
local value=''
else
local name="${arg%\=*}"
local value="${arg#*=}"
fi
if echo "$code" | grep -l "^local $name=" &> /dev/null
then
echo "Argument '$name' repeated with the value '$value'". >&2
return
fi
local arg_line="$(echo "$keyword_args" |
egrep "^$name:?\??" | head -n1)"
if [[ -z $arg_line ]]
then
echo "Unknown argument '$name'." >&2
return
elif (
echo "$arg_line" | grep -l ':' &> /dev/null
) && [[ -z $value ]]
then
echo "Required argument for '$name' not provided." >&2
return
elif (
echo "$arg_line" | grep -vl ':' &> /dev/null
) && [[ -n $value ]]
then
echo "No argument required for '$name', but provided '$value'." >&2
return
fi
if [[ -z $value ]]
then
value=true
fi
--add-var "${name//-/_}" "$value"
shift
done
echo "$code"
unfunction -- --add-var
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment