Adding an option to fail upon unset env variables

This commit is contained in:
Alexey Maslennikov 2017-06-15 20:47:51 +02:00
parent 4ccfaf9d79
commit 50aa18e2a6
5 changed files with 46 additions and 18 deletions

1
.gitignore vendored
View File

@ -4,3 +4,4 @@ diagnostic.test
tests/*.diff
spec/
spec-runner/
node_modules/

16
mo
View File

@ -13,6 +13,7 @@
#/
#/ mo [--false] [--help] [--source=FILE] filenames...
#/
#/ --fail-not-set - Fail upon expansion of an unset variable.
#/ --false - Treat the string "false" as empty for conditionals.
#/ --help - This message.
#/ --source=FILE - Load FILE into the environment before processing templates.
@ -28,6 +29,8 @@
# Public: Template parser function. Writes templates to stdout.
#
# $0 - Name of the mo file, used for getting the help message.
# --fail-not-set - Fail upon expansion of an unset variable. Default behavior
# is to silently ignore and expand into empty string.
# --false - Treat "false" as an empty value. You may set the
# MO_FALSE_IS_EMPTY environment variable instead to a non-empty
# value to enable this behavior.
@ -40,6 +43,8 @@
#
# Mo uses the following environment variables:
#
# 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"
# will be treated as an empty value for the purposes
# of conditionals.
@ -69,6 +74,11 @@ mo() (
exit 0
;;
--fail-not-set)
# shellcheck disable=SC2030
MO_FAIL_ON_UNSET=true
;;
--false)
# shellcheck disable=SC2030
MO_FALSE_IS_EMPTY=true
@ -746,7 +756,13 @@ moShow() {
eval moJoin moJoined "," "\${$1[@]}"
echo -n "$moJoined"
else
# shellcheck disable=SC2031
if [[ -z "$MO_FAIL_ON_UNSET" ]] || moTest "$1"; then
echo -n "${!1}"
else
echo "Env variable not set: $1" >&2
exit 1
fi
fi
else
# Further subindexes are disallowed

View File

@ -0,0 +1 @@
This will fail: Env variable not set: __NO_SUCH_VAR

9
tests/fail-not-set.sh Executable file
View File

@ -0,0 +1,9 @@
#!/usr/bin/env bash
cd "${0%/*}"
unset __NO_SUCH_VAR
echo "This will fail: {{__NO_SUCH_VAR}}" | ../mo --fail-not-set 2>&1
if [[ $? -ne 1 ]]; then
echo "Did not return 1"
fi

View File

@ -11,6 +11,7 @@ Simple usage:
mo [--false] [--help] [--source=FILE] filenames...
--fail-not-set - Fail upon expansion of an unset variable.
--false - Treat the string "false" as empty for conditionals.
--help - This message.
--source=FILE - Load FILE into the environment before processing templates.