Skip to content

Commit 6d60ada

Browse files
io-aws-labrob-spoor
authored andcommitted
Added support for Environment properties
1 parent c2f028d commit 6d60ada

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
@@ -242,7 +242,19 @@ def _load_json5():
242242
}
243243

244244

245-
def render(template_path, data, extensions, strict=False):
245+
def convert_value(value, target_type):
246+
if target_type == bool:
247+
if value.lower() == "true":
248+
return True
249+
if value.lower() == "false":
250+
return False
251+
raise ValueError("not a valid boolean: %s" % value)
252+
if target_type == int:
253+
return int(value)
254+
return value
255+
256+
257+
def render(template_path, data, extensions, strict=False, env_opts={}):
246258
from jinja2 import (
247259
__version__ as jinja_version,
248260
Environment,
@@ -268,6 +280,13 @@ def render(template_path, data, extensions, strict=False):
268280
)
269281
if strict:
270282
env.undefined = StrictUndefined
283+
for key in env_opts:
284+
if hasattr(env, key):
285+
target_type = type(getattr(env, key))
286+
new_value = convert_value(env_opts[key], target_type)
287+
setattr(env, key, new_value)
288+
else:
289+
raise MalformedEnv("unsupported environment option: %s" % key)
271290

272291
# Add environ global
273292
env.globals["environ"] = lambda key: force_text(os.environ.get(key))
@@ -352,6 +371,8 @@ def cli(opts, args):
352371

353372
data.update(parse_kv_string(opts.D or []))
354373

374+
env_opts = parse_kv_string(opts.env or [])
375+
355376
if opts.outfile is None:
356377
out = sys.stdout
357378
else:
@@ -362,7 +383,7 @@ def cli(opts, args):
362383

363384
out = codecs.getwriter("utf8")(out)
364385

365-
out.write(render(template_path, data, extensions, opts.strict))
386+
out.write(render(template_path, data, extensions, opts.strict, env_opts))
366387
out.flush()
367388
return 0
368389

@@ -456,6 +477,13 @@ def main():
456477
metavar="FILE",
457478
action="store",
458479
)
480+
parser.add_option(
481+
"--env-opt",
482+
help="Define jinja2 Environment option in the form of option=value. Available options: %s",
483+
dest="env",
484+
action="append",
485+
metavar="option=value",
486+
)
459487
opts, args = parser.parse_args()
460488

461489
# Dedupe list

0 commit comments

Comments
 (0)