From 6d60ada502dd3ae5e869831be9cb995b7c34218a Mon Sep 17 00:00:00 2001 From: "rob.spoor" Date: Tue, 16 Jul 2019 15:45:07 +0200 Subject: [PATCH 1/2] Added support for Environment properties --- jinja2cli/cli.py | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/jinja2cli/cli.py b/jinja2cli/cli.py index f76be43..4fd5d59 100644 --- a/jinja2cli/cli.py +++ b/jinja2cli/cli.py @@ -242,7 +242,19 @@ def _load_json5(): } -def render(template_path, data, extensions, strict=False): +def convert_value(value, target_type): + if target_type == bool: + if value.lower() == "true": + return True + if value.lower() == "false": + return False + raise ValueError("not a valid boolean: %s" % value) + if target_type == int: + return int(value) + return value + + +def render(template_path, data, extensions, strict=False, env_opts={}): from jinja2 import ( __version__ as jinja_version, Environment, @@ -268,6 +280,13 @@ def render(template_path, data, extensions, strict=False): ) if strict: env.undefined = StrictUndefined + for key in env_opts: + if hasattr(env, key): + target_type = type(getattr(env, key)) + new_value = convert_value(env_opts[key], target_type) + setattr(env, key, new_value) + else: + raise MalformedEnv("unsupported environment option: %s" % key) # Add environ global env.globals["environ"] = lambda key: force_text(os.environ.get(key)) @@ -352,6 +371,8 @@ def cli(opts, args): data.update(parse_kv_string(opts.D or [])) + env_opts = parse_kv_string(opts.env or []) + if opts.outfile is None: out = sys.stdout else: @@ -362,7 +383,7 @@ def cli(opts, args): out = codecs.getwriter("utf8")(out) - out.write(render(template_path, data, extensions, opts.strict)) + out.write(render(template_path, data, extensions, opts.strict, env_opts)) out.flush() return 0 @@ -456,6 +477,13 @@ def main(): metavar="FILE", action="store", ) + parser.add_option( + "--env-opt", + help="Define jinja2 Environment option in the form of option=value. Available options: %s", + dest="env", + action="append", + metavar="option=value", + ) opts, args = parser.parse_args() # Dedupe list From 5ec0a0292685d04acecc89103da1dfdd41ad0b19 Mon Sep 17 00:00:00 2001 From: "rob.spoor" Date: Tue, 16 Jul 2019 15:52:32 +0200 Subject: [PATCH 2/2] Fixed env-opt documentation --- jinja2cli/cli.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jinja2cli/cli.py b/jinja2cli/cli.py index 4fd5d59..b5c3cbf 100644 --- a/jinja2cli/cli.py +++ b/jinja2cli/cli.py @@ -479,7 +479,7 @@ def main(): ) parser.add_option( "--env-opt", - help="Define jinja2 Environment option in the form of option=value. Available options: %s", + help="Define jinja2 Environment option in the form of option=value", dest="env", action="append", metavar="option=value",