kolypto / j2cli

Jinja2 Command-Line Tool, reworked
http://pypi.python.org/pypi/j2cli
BSD 2-Clause "Simplified" License
745 stars 82 forks source link

Environment variables only working when executed interactively (`jinja2.exceptions.UndefinedError`) #73

Open jgspratt opened 2 years ago

jgspratt commented 2 years ago

Command

j2 1.txt.j2 -o 1.txt

Fails when executed within a script against this file (jinja2.exceptions.UndefinedError: 'PATH' is undefined):

{{ PATH }}

But works when executed within a script or when executed interactively:

{{ env("PATH") }}

Full script:

#!/usr/bin/env bash
set -o errexit
set -o pipefail
set -o xtrace

echo "This dir: '$(pwd)'"
echo "arg1: ${1}"

if [[ -z "${1}" ]]
then
  _j2_root_dir="$(pwd)"
else
  if [[ -d "${1}" ]]
  then
    _j2_root_dir="${1}"
  else
    echo "WARNING: '${1}' was passed in but is not a directory. Ignoring."
    _j2_root_dir="$(pwd)"
  fi
fi

find "${_j2_root_dir}" -name "*.j2" -print0 | while read -d $'\0' _rel_filepath
do
  _abs_filepath="$(realpath ${_rel_filepath})"
  _abs_filedir="$(dirname ${_rel_filepath})"
  _filename=$(basename -- "${_abs_filepath}")
  _extension_j2="${_filename##*.}"
  _filename_minus_j2="${_filename%.*}"
  echo "_rel_filepath: ${_rel_filepath}"
  echo "_abs_filepath: ${_abs_filepath}"
  echo "> j2 ${_abs_filepath} -o ${_abs_filedir}/${_filename_minus_j2}"
  env | sort -f
  j2 "${_abs_filepath}" -o "${_abs_filedir}/${_filename_minus_j2}"
done

Full error:

Traceback (most recent call last):
  File "/usr/local/bin/j2", line 8, in <module>
    sys.exit(main())
  File "/usr/local/lib/python3.7/dist-packages/j2cli/cli.py", line 206, in main
    sys.argv[1:]
  File "/usr/local/lib/python3.7/dist-packages/j2cli/cli.py", line 186, in render_command
    result = renderer.render(args.template, context)
  File "/usr/local/lib/python3.7/dist-packages/j2cli/cli.py", line 87, in render
    .render(context) \
  File "/usr/local/lib/python3.7/dist-packages/jinja2/environment.py", line 1090, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.7/dist-packages/jinja2/environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "/usr/local/lib/python3.7/dist-packages/jinja2/_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "[redacted]/1.txt.j2", line 1, in top-level template code
    {{ PATH }}
jinja2.exceptions.UndefinedError: 'PATH' is undefined
jgspratt commented 2 years ago

Workaround works:

env | j2 --format=env 1.txt.j2 -o 1.txt