Merge pull request #32 from andreax79/master

Pass arguments to function as environment variable MO_ALLOW_FUNCTION_ARGUMENTS
This commit is contained in:
Tyler Akins 2019-08-08 07:47:44 -05:00 committed by GitHub
commit 929ffc5b88
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 48 additions and 2 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}}

6
mo
View File

@ -62,6 +62,7 @@
# options and arguments. This puts the content from the
# template directly into an eval statement. Use with
# extreme care.
# 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"
@ -154,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
fi
echo -n "$2" | eval "$1" "$moArgs"
echo -n "$2" | MO_FUNCTION_ARGS="$moFunctionArgs" eval "$1" "$moArgs"
}

View File

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

View File

@ -0,0 +1,4 @@
No args: [] - done
One arg: [one] - done
Multiple arguments: [aa bb cc 'x' " ! {[_.|] - done
Evil: [bla; cat /etc/issue] - done

View File

@ -0,0 +1,4 @@
No args: [{{testArgs}}] - done
One arg: [{{testArgs one}}] - done
Multiple arguments: [{{testArgs aa bb cc 'x' " ! {[_.| }}] - done
Evil: [{{testArgs bla; cat /etc/issue}}] - done