Skip to content

Commit

Permalink
refactor: use Python's native string.Template formatting
Browse files Browse the repository at this point in the history
Require successfully reading all the QubesDB keys found by string.Template.get_identifiers(), rather than requiring an explicit list of keys via "--key".
  • Loading branch information
cfm committed May 23, 2024
1 parent 23e244e commit 538d8aa
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions files/template-from-qubesdb.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#!/usr/bin/python3
import argparse
import subprocess
from jinja2 import Template
import string

from qubesdb import QubesDB

Expand All @@ -14,6 +13,7 @@ def get_env(args):
value = db.read(f"/vm-config/{key}")
if not value or len(value) == 0:
raise KeyError(f"Could not read from QubesDB: {key}")
env[key] = (value or "").decode()

finally:
db.close()
Expand All @@ -23,17 +23,20 @@ def get_env(args):

if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Use -k/--key one or more times to read the specified key from QubesDB. The input template will be written to the output file with those variables substituted."
description="The input template will be written to the output file, with each variable "
"replaced by its value from QubesDB. If any variable cannot be read from QubesDB, "
"templating will fail. See the documentation on Python's string.Template for details "
"(https://docs.python.org/3/library/string.html#template-strings)",
)
parser.add_argument("-k", "--key", action="append")
parser.add_argument("input")
parser.add_argument("output")
args = parser.parse_args()
env = get_env(args.key)

with open(args.input) as input_f:
template = Template(input_f.read())
template = string.Template(input_f.read())

env = get_env(template.get_identifiers()) # type: ignore[attr-defined]

with open(args.output, "w") as output_f:
rendered = template.render(**env)
rendered = template.substitute(env)
output_f.write(rendered)

0 comments on commit 538d8aa

Please sign in to comment.