tests-always-included / mo

Mustache templates in pure bash
Other
563 stars 67 forks source link

MO_FAIL_ON_UNSET should ignore unrendered variables #70

Closed eherot closed 4 months ago

eherot commented 10 months ago

Prior to 3.0.0, MO_FAIL_ON_UNSET/-u used to ignore unset variables as long as they weren't being rendered:

# 2.4.1
$ unset TESTVAR ; echo 'TESTVAR={{#TESTVAR}}{{TESTVAR}}{{/TESTVAR}}' | mo -u
TESTVAR=

but now that doesn't work anymore:

# 3.0.4
unset TESTVAR ; echo 'TESTVAR={{#TESTVAR}}{{TESTVAR}}{{/TESTVAR}}' | mo -u
ERROR: Environment variable not set: TESTVAR

This was a very handy feature and it would be nice to have it back (or perhaps there is another way of doing this that I'm not seeing?)...

fidian commented 10 months ago

The earlier behavior was buggy. The option is intended to indicate an error whenever a variable is accessed and helps guard against typos. Previously, {{#TESTVAR}}...{{/TESTVAR}} would not use the same mechanism to get the variable. So, if you mistakenly used {{#TEST_VAR}}...{{/TEST_VAR}} it would not realize that the variable was not defined.

image

The erroring is supposed to mirror set -u in Bash, where any usage of an undefined variable would result in an error. It would be extremely handy in user-provided scripts or other untrustworthy sources. In those environments, one can define a set of allowed variables as empty values and the template will work. Perhaps this solution would work for you?

To get similar functionality, you may be able to write a function, but then your template would look quite a bit more ugly. The syntax would likely appear like {{#IF 'TESTVAR'}}...{{/IF 'TESTVAR'}}.

Another option is to modify mo and add a special command to ignore the MO_FAIL_ON_UNSET variable, or another flag could be added to ignore unset on just conditions, though I don't know of any similar approach with Bash scripts.

Maybe you could share more about why you want to use -u to flag undefined variables but you also don't want to care about them in conditions?

fidian commented 4 months ago

Closing due to inactivity. Feel free to reopen with an example of where you would want to error when the variable is used as a variable but not as a condition.