reportist/tools/render.py

91 lines
3.6 KiB
Python

#!/usr/bin/env python3
"""Validate a Reportist v1 YAML/JSON document and render it to PDF with Typst."""
import argparse
import importlib.util
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("reportist_validation", ROOT / "tools" / "validate.py")
validation = importlib.util.module_from_spec(spec)
spec.loader.exec_module(validation)
def stage_asset(report, input_path, staging):
logo = report.get("branding", {}).get("logo")
if not logo:
return
source = input_path.parent
for part in Path(logo).parts:
source = source / part
if source.is_symlink():
raise ValueError(f"/branding/logo: symlinks are not accepted: {logo}")
if not source.resolve().is_relative_to(input_path.parent.resolve()):
raise ValueError(f"/branding/logo: asset escapes the report directory or is a symlink: {logo}")
destination = staging / logo
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, destination)
def render(input_path, output_path, typst, force=False):
input_path = input_path.resolve()
output_path = output_path.resolve()
if input_path == output_path:
raise ValueError("input and output paths must differ")
if output_path.exists() and not force:
raise ValueError(f"{output_path}: output exists; use --force to replace it")
report = validation.load_report(input_path)
errors = validation.validate_document(report)
if errors:
raise ValueError("invalid report:\n" + "\n".join(errors))
output_path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="reportist-") as directory:
staging = Path(directory)
staged_input = staging / ("report.json" if input_path.suffix.lower() == ".json" else "report.yaml")
shutil.copyfile(input_path, staged_input)
shutil.copyfile(ROOT / "templates" / "report.typ", staging / "report.typ")
stage_asset(report, input_path, staging)
staged_pdf = staging / "report.pdf"
command = [typst, "compile", "--root", str(staging), "--input",
f"report={staged_input.name}", "--input",
f"format={input_path.suffix.lower().lstrip('.')}",
str(staging / "report.typ"), str(staged_pdf)]
result = subprocess.run(command, text=True, capture_output=True)
if result.returncode:
raise ValueError("Typst rendering failed:\n" + (result.stderr.strip() or result.stdout.strip()))
if force:
os.replace(staged_pdf, output_path)
else:
os.link(staged_pdf, output_path)
def parser():
result = argparse.ArgumentParser(description=__doc__)
result.add_argument("input", type=Path)
result.add_argument("--output", type=Path, help="PDF path (default: input with .pdf suffix)")
result.add_argument("--typst", default="typst", help="Typst executable (default: typst on PATH)")
result.add_argument("--force", action="store_true", help="Replace an existing output after successful rendering")
return result
def main(argv=None):
args = parser().parse_args(argv)
output = args.output or args.input.with_suffix(".pdf")
try:
render(args.input, output, args.typst, args.force)
except (OSError, ValueError, subprocess.SubprocessError) as error:
print(f"error: {error}", file=sys.stderr)
return 1
print(f"Rendered PDF: {output}")
return 0
if __name__ == "__main__":
sys.exit(main())