File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11"""Command-line interface to Kajiki to render a single template."""
22
33import argparse
4+ import json
45import os
6+ import pathlib
57import site
68import sys
79
@@ -51,6 +53,13 @@ def main(argv=None):
5153 metavar = "KEY=VALUE" ,
5254 help = "Template variables, passed as KEY=VALUE pairs." ,
5355 )
56+ parser .add_argument (
57+ "--json" ,
58+ action = "append" ,
59+ default = [],
60+ type = pathlib .Path ,
61+ help = "Load template variables from a JSON file." ,
62+ )
5463 parser .add_argument (
5564 "-p" ,
5665 "--package" ,
@@ -82,9 +91,16 @@ def main(argv=None):
8291 opts .paths .append (os .path .dirname (opts .file_or_package ) or "." )
8392 loader_kwargs ["path" ] = opts .paths
8493
94+ template_variables = {}
95+ for json_file in opts .json :
96+ with json_file .open ("r" , encoding = "utf-8" ) as f :
97+ template_variables .update (json .load (f ))
98+
99+ template_variables .update (dict (opts .template_variables ))
100+
85101 loader = opts .loader_type (force_mode = opts .force_mode , ** loader_kwargs )
86102 template = loader .import_ (opts .file_or_package )
87- result = template (dict ( opts . template_variables ) ).render ()
103+ result = template (template_variables ).render ()
88104 opts .output_file .write (result )
89105
90106 # Close the output file to avoid a ResourceWarning during unit
Original file line number Diff line number Diff line change @@ -133,3 +133,19 @@ def test_template_variables_bad(capsys):
133133 captured = capsys .readouterr ()
134134 assert captured .out == ""
135135 assert captured .err .endswith ("error: argument -v/--var: Expected a KEY=VALUE pair, got BADBADBAD\n " )
136+
137+
138+ def test_json_template_variables (tmp_path , main_mocks ):
139+ json_file = tmp_path / "json_file.json"
140+ json_file .write_text ('{"foo": "bar", "baz": "bip"}' )
141+ main (["--json" , str (json_file ), "infile.txt" ])
142+
143+ main_mocks .file_loader_type .assert_called_once_with (path = ["." ], force_mode = None )
144+ main_mocks .import_ .assert_called_once_with ("infile.txt" )
145+ main_mocks .template_type .assert_called_once_with (
146+ {
147+ "foo" : "bar" ,
148+ "baz" : "bip" ,
149+ }
150+ )
151+ main_mocks .render .assert_called_once_with ()
You can’t perform that action at this time.
0 commit comments