Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for Environment options #80

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions jinja2cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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))
Expand Down Expand Up @@ -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:
Expand All @@ -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

Expand Down Expand Up @@ -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",
dest="env",
action="append",
metavar="option=value",
)
opts, args = parser.parse_args()

# Dedupe list
Expand Down