Skip to content

Commit b59daf9

Browse files
io-aws-labrob-spoor
authored andcommitted
Added support for Environment properties
1 parent 679be53 commit b59daf9

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

jinja2cli/cli.py

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,19 @@ def _load_json5():
246246
}
247247

248248

249-
def render(template_path, data, extensions, strict=False):
249+
def convert_value(value, target_type):
250+
if target_type == bool:
251+
if value.lower() == "true":
252+
return True
253+
if value.lower() == "false":
254+
return False
255+
raise ValueError("not a valid boolean: %s" % value)
256+
if target_type == int:
257+
return int(value)
258+
return value
259+
260+
261+
def render(template_path, data, extensions, strict=False, env_opts={}):
250262
from jinja2 import (
251263
__version__ as jinja_version,
252264
Environment,
@@ -272,6 +284,13 @@ def render(template_path, data, extensions, strict=False):
272284
)
273285
if strict:
274286
env.undefined = StrictUndefined
287+
for key in env_opts:
288+
if hasattr(env, key):
289+
target_type = type(getattr(env, key))
290+
new_value = convert_value(env_opts[key], target_type)
291+
setattr(env, key, new_value)
292+
else:
293+
raise MalformedEnv("unsupported environment option: %s" % key)
275294

276295
# Add environ global
277296
env.globals["environ"] = lambda key: force_text(os.environ.get(key))
@@ -356,6 +375,8 @@ def cli(opts, args):
356375

357376
data.update(parse_kv_string(opts.D or []))
358377

378+
env_opts = parse_kv_string(opts.env or [])
379+
359380
if opts.outfile is None:
360381
out = sys.stdout
361382
else:
@@ -366,7 +387,7 @@ def cli(opts, args):
366387

367388
out = codecs.getwriter("utf8")(out)
368389

369-
out.write(render(template_path, data, extensions, opts.strict))
390+
out.write(render(template_path, data, extensions, opts.strict, env_opts))
370391
out.flush()
371392
return 0
372393

@@ -465,6 +486,13 @@ def main():
465486
metavar="FILE",
466487
action="store",
467488
)
489+
parser.add_option(
490+
"--env-opt",
491+
help="Define jinja2 Environment option in the form of option=value. Available options: %s",
492+
dest="env",
493+
action="append",
494+
metavar="option=value",
495+
)
468496
opts, args = parser.parse_args()
469497

470498
# Dedupe list

0 commit comments

Comments
 (0)