blob: 7bb9c75c53fe9d1dcdbcaaec86cfcc395f21f3a9 [file] [log] [blame]
James Kuszmaul55d9fc72020-05-10 18:58:08 -07001#!/usr/bin/python3
2
3import argparse
James Kuszmaul55d9fc72020-05-10 18:58:08 -07004import json
5import sys
Philipp Schrader75f1c262024-04-03 11:32:58 -07006from pathlib import Path
James Kuszmaul55d9fc72020-05-10 18:58:08 -07007
8import jinja2
9
10
11def main():
Ravago Jones5127ccc2022-07-31 16:32:45 -070012 # Note: this is a pretty transparent interface to jinja2--there's no reason
13 # this script couldn't be renamed and then used to generate any config from
14 # a template.
15 parser = argparse.ArgumentParser(
16 description="Generates the raspberry pi configs from a template.")
Philipp Schrader75f1c262024-04-03 11:32:58 -070017 parser.add_argument("template",
18 type=Path,
19 help="File to use for template.")
Ravago Jones5127ccc2022-07-31 16:32:45 -070020 parser.add_argument(
Philipp Schrader4187e172024-04-03 11:45:19 -070021 "--replacements_file",
22 type=Path,
23 help=("File containing a dictionary of parameters to replace "
24 "in the template. The behaviour is undefined if keys are "
25 "duplicated between this file and the `replacements` argument."),
26 )
27 parser.add_argument(
Ravago Jones5127ccc2022-07-31 16:32:45 -070028 "replacements",
29 type=json.loads,
30 help="Dictionary of parameters to replace in the template.")
James Kuszmaulba43b062024-01-14 17:29:21 -080031 parser.add_argument(
Philipp Schrader75f1c262024-04-03 11:32:58 -070032 "--include_dir",
33 action="append",
34 type=Path,
35 default=[],
36 help="One or more search directories for {% include %} blocks.",
37 )
38 parser.add_argument("output", type=Path, help="Output file to create.")
Ravago Jones5127ccc2022-07-31 16:32:45 -070039 args = parser.parse_args(sys.argv[1:])
James Kuszmaul55d9fc72020-05-10 18:58:08 -070040
Philipp Schrader75f1c262024-04-03 11:32:58 -070041 env = jinja2.Environment(loader=jinja2.FileSystemLoader(args.include_dir))
42 template = env.from_string(args.template.read_text())
James Kuszmaul55d9fc72020-05-10 18:58:08 -070043
Philipp Schrader4187e172024-04-03 11:45:19 -070044 replacements = args.replacements.copy()
45 if args.replacements_file:
46 with args.replacements_file.open() as file:
47 replacements.update(json.load(file))
48
49 args.output.write_text(template.render(replacements))
Ravago Jones5127ccc2022-07-31 16:32:45 -070050
James Kuszmaul55d9fc72020-05-10 18:58:08 -070051
52if __name__ == '__main__':
Ravago Jones5127ccc2022-07-31 16:32:45 -070053 main()