Pass arguments to function as environment variable MO_ALLOW_FUNCTION_ARGUMENTS

This commit is contained in:
Andrea Bonomi 2019-08-08 10:36:44 +02:00
parent fcedd32155
commit 5b8cf24068
5 changed files with 41 additions and 8 deletions

29
demo/function-args Executable file
View File

@ -0,0 +1,29 @@
#!/bin/bash
#
# This sources a simple script with the env. variables needed for the template.
cd "$(dirname "$0")" # Go to the script's directory
source ../mo
export NAME="Alex"
export ARRAY=( AAA BBB CCC )
# Include an external template
INCLUDE() {
cat "$MO_FUNCTION_ARGS"
}
# Print section title
TITLE() {
echo "+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+"
echo "$MO_FUNCTION_ARGS"
echo "+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+"
}
cat <<EOF | mo -u
{{TITLE Part 1}}
{{INCLUDE function-args-part1}}
{{TITLE Part 2}}
{{INCLUDE function-args-part2}}
EOF

1
demo/function-args-part1 Normal file
View File

@ -0,0 +1 @@
Hello, my name is {{NAME}}.

3
demo/function-args-part2 Normal file
View File

@ -0,0 +1,3 @@
{{#ARRAY}}
* {{.}}
{{/ARRAY}}

14
mo
View File

@ -62,8 +62,7 @@
# options and arguments. This puts the content from the
# template directly into an eval statement. Use with
# extreme care.
# MO_ARGS - Arguments passed to the function,
# only if MO_ALLOW_FUNCTION_ARGUMENTS is unset
# MO_FUNCTION_ARGS - Arguments passed to the function
# MO_FAIL_ON_UNSET - When set to a non-empty value, expansion of an unset
# env variable will be aborted with an error.
# MO_FALSE_IS_EMPTY - When set to a non-empty value, the string "false"
@ -156,16 +155,17 @@ mo() (
#
# Returns nothing.
moCallFunction() {
local moArgs
local moArgs moFunctionArgs
moArgs=()
moTrimWhitespace moFunctionArgs "$3"
# shellcheck disable=SC2031
if [[ -n "${MO_ALLOW_FUNCTION_ARGUMENTS-}" ]]; then
moArgs=$3
echo -n "$2" | eval "$1" "$moArgs"
else
moTrimWhitespace moArgs "$3"
echo -n "$2" | MO_ARGS="$moArgs" eval "$1"
fi
echo -n "$2" | MO_FUNCTION_ARGS="$moFunctionArgs" eval "$1" "$moArgs"
}

View File

@ -1,3 +1,3 @@
testArgs() {
echo "$MO_ARGS"
echo "$MO_FUNCTION_ARGS"
}