diff options
Diffstat (limited to 'lib/template.sh')
-rw-r--r-- | lib/template.sh | 51 |
1 files changed, 40 insertions, 11 deletions
diff --git a/lib/template.sh b/lib/template.sh index f9fc825..ae1dde5 100644 --- a/lib/template.sh +++ b/lib/template.sh @@ -17,12 +17,15 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # -source ${LIBDIR}/config.sh # # Provides *very* basic templating functionality. Interpolates basic jinja # variable syntax ( "{{ variable }}" ). # +# Template variables are replaced with matching bash environment variabes. This +# means that template variables can only contain upper case, lower case, +# numbers, underscores. All non-conforming variables are ignored. +# # @param src Path to template file to interpolate # @param dest Destination to copy the interpolated template to # @@ -30,17 +33,43 @@ function template { local src=${1:-} local dest=${2:-} - local delim=$'\001' - local tmp=$(mktemp tmp.template.XXXXXXXX) + local _delim # Regex delimiter (use an uncommon character please) + local _tmp # Path to the tmp copy of the original template file + local _oldifs # Old value of IFS (for changing it back) + local _filevars # List of valid variable references found in the template file + local _varstr # Template string calling the variable (eg: {{ varname }}) + local _varname # Name of the actual variable (eg: {{ varname }} == varname) - cp -p ${src} ${tmp} - for key in ${!configs[@]}; do - sed -i "s${delim}{{ ${key} }}${delim}${configs[$key]}${delim}g" ${tmp} - done + # Pick a really weird delimiter to avoid possible regex conflict + _delim=$'\001' + + # Copy the template to a temp location so we don't work on the original + _tmp=$(mktemp tmp.template.XXXXXXXX) + cp -p ${src} ${_tmp} + + # Read all unique template variables specified in the file + _filevars=("$( grep -o '{{ [_[:alnum:]]\+ }}' ${_tmp} | sort | uniq)") - # Create parent directory if it doesn't yet exist - [[ ! -d $(dirname ${dest}) ]] && mkdir -p $(dirname ${dest}) + _oldifs=${IFS} + IFS=$'\n' + for _varstr in ${_filevars[@]}; do + # Strip '{{ ' and ' }}' from varstr to get variable name + _varname="${_varstr:3:-3}" + + # Skip any unset but referenced variables + if [ -z "${!_varname}" ]; then + printf \ + "WARN: Template variable '%s' is referenced but is unset.\n" \ + ${_varname} >&2 + continue + fi + + # If variable is set, then find and replace + sed -i "s${_delim}${_varstr}${_delim}${!_varname}${_delim}g" "${_tmp}" + done + IFS=${_oldifs} - # Move the modified version into place - mv ${tmp} ${dest} + # Move the modified version into place, creating any leading dirs if necessary + install -D "${_tmp}" "${dest}" + rm -f "${_tmp}" } |