From 8f1e12bac919c774caad267c0118d7bd753221d1 Mon Sep 17 00:00:00 2001 From: rsxri Date: Tue, 6 Jan 2026 18:04:06 +0000 Subject: [PATCH] feat: add cli flags for input, template & output --- main.py | 59 ++++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 44 insertions(+), 15 deletions(-) diff --git a/main.py b/main.py index f7a61a4..f7f2b5e 100644 --- a/main.py +++ b/main.py @@ -1,3 +1,4 @@ +import argparse import json from pathlib import Path from jinja2 import Environment, FileSystemLoader @@ -5,31 +6,59 @@ from jinja2 import Environment, FileSystemLoader from schema import DocumentInput +def parse_args() -> argparse.Namespace: + # keep cli parsing separate so main stays about workflow + parser = argparse.ArgumentParser(description="Render document from JSON + Jinja2 template") + + parser.add_argument( + "--input", + "-i", + type=Path, + required=True, + help="Path to input JSON file (e.g. examples/input.json)" + ) + parser.add_argument( + "--template", + "-t", + default="doc.md.j2", + help="Template file (e.g. doc.md.j2)" + ) + parser.add_argument( + "--output", + "-o", + type=Path, + required=True, + help="Path to write rendered output (e.g. out.md)" + ) + + return parser.parse_args() + + +def render_template(template_name: str, data: dict) -> str: + # Jinja env points at templates/ + env = Environment(loader=FileSystemLoader("templates"), + trim_blocks=True, + lstrip_blocks=True) + template = env.get_template(template_name) + return template.render(data) + + def main(): + args = parse_args() + # load input data # path() over hardcoding str - data = json.loads(Path("examples/input.json").read_text(encoding="utf-8")) + data = json.loads(args.input.read_text(encoding="utf-8")) # validate + normalise input doc_input = DocumentInput(**data) - # setup template eng - # create jinja2 env for templates - env = Environment( - # look in templates/ - loader=FileSystemLoader("templates"), - # trim whitespaces - trim_blocks=True, - lstrip_blocks=True, - ) # load template to render - # **data spreads dict so keys become template vars - template = env.get_template("doc.md.j2") - out = template.render(**doc_input.model_dump()) + out = render_template(args.template, doc_input.model_dump()) # write output - render md to file - Path("out.md").write_text(out, encoding="utf-8") - print("wrote out.md") + args.output.write_text(out, encoding="utf-8") + print(f"wrote {args.output}") if __name__ == "__main__":