Factor out jinja2 template to be generic
This lets us reuse it for many more config setups to avoid duplication.
Change-Id: I9e77e55d460edb3f8037ce164818e45b6ab7a56e
diff --git a/tools/build_rules/BUILD b/tools/build_rules/BUILD
index f96fb3a..8ad7018 100644
--- a/tools/build_rules/BUILD
+++ b/tools/build_rules/BUILD
@@ -3,3 +3,10 @@
srcs = ["quiet_success.sh"],
visibility = ["//visibility:public"],
)
+
+py_binary(
+ name = "jinja2_generator",
+ srcs = ["jinja2_generator.py"],
+ visibility = ["//visibility:public"],
+ deps = ["@python_jinja2"],
+)
diff --git a/tools/build_rules/jinja2_generator.py b/tools/build_rules/jinja2_generator.py
new file mode 100644
index 0000000..34f3354
--- /dev/null
+++ b/tools/build_rules/jinja2_generator.py
@@ -0,0 +1,29 @@
+#!/usr/bin/python3
+
+import argparse
+import json
+import sys
+
+import jinja2
+
+
+def main():
+ # Note: this is a pretty transparent interface to jinja2--there's no reason
+ # this script couldn't be renamed and then used to generate any config from
+ # a template.
+ parser = argparse.ArgumentParser(
+ description="Generates the raspberry pi configs from a template.")
+ parser.add_argument("template", type=str, help="File to use for template.")
+ parser.add_argument("replacements", type=json.loads, help="Dictionary of parameters to replace in the template.")
+ parser.add_argument("output", type=str, help="Output file to create.")
+ args = parser.parse_args(sys.argv[1:])
+
+ with open(args.template, 'r') as input_file:
+ template = jinja2.Template(input_file.read())
+
+ output = template.render(args.replacements)
+ with open(args.output, 'w') as config_file:
+ config_file.write(output)
+
+if __name__ == '__main__':
+ main()
diff --git a/tools/build_rules/template.bzl b/tools/build_rules/template.bzl
new file mode 100644
index 0000000..d4807e8
--- /dev/null
+++ b/tools/build_rules/template.bzl
@@ -0,0 +1,33 @@
+def _jinja2_template_impl(ctx):
+ out = ctx.actions.declare_file(ctx.attr.name)
+
+ ctx.actions.run_shell(
+ inputs = ctx.files.src,
+ tools = [ctx.executable._jinja2],
+ progress_message = "Generating " + out.short_path,
+ outputs = [out],
+ command = ctx.executable._jinja2.path + " " + ctx.files.src[0].path + " '" + str(ctx.attr.parameters) + "' " + out.path,
+ )
+
+ return [DefaultInfo(files = depset([out])), OutputGroupInfo(out = depset([out]))]
+
+jinja2_template = rule(
+ attrs = {
+ "src": attr.label(
+ mandatory = True,
+ allow_single_file = True,
+ doc = """The jinja2 template file to expand.""",
+ ),
+ "parameters": attr.string_dict(
+ mandatory = True,
+ doc = """The parameters to supply to Jinja2.""",
+ ),
+ "_jinja2": attr.label(
+ default = "//tools/build_rules:jinja2_generator",
+ cfg = "host",
+ executable = True,
+ ),
+ },
+ implementation = _jinja2_template_impl,
+ doc = """Expands a jinja2 template given parameters.""",
+)