validate_template_manifest.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import argparse
  2. import json
  3. import sys
  4. from pathlib import Path
  5. from zipfile import ZipFile
  6. import xml.etree.ElementTree as ET
  7. NS = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
  8. def load_styles(path: Path) -> set[str]:
  9. with ZipFile(path, "r") as archive:
  10. try:
  11. xml_bytes = archive.read("word/styles.xml")
  12. except KeyError:
  13. return set()
  14. root = ET.fromstring(xml_bytes)
  15. style_ids = set()
  16. for style in root.findall(".//w:style", NS):
  17. style_id = style.get("{http://schemas.openxmlformats.org/wordprocessingml/2006/main}styleId") or style.get("styleId")
  18. if style_id:
  19. style_ids.add(style_id)
  20. return style_ids
  21. def validate(template_path: Path, manifest_path: Path) -> dict:
  22. manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
  23. style_ids = load_styles(template_path)
  24. required = manifest.get("style_requirements", {})
  25. missing = []
  26. for _, value in required.items():
  27. if isinstance(value, str) and value not in style_ids:
  28. missing.append(value)
  29. return {
  30. "template": str(template_path),
  31. "manifest": str(manifest_path),
  32. "ok": not missing,
  33. "missingStyleIds": missing,
  34. }
  35. def main() -> int:
  36. parser = argparse.ArgumentParser(description="Validate a DOCX template manifest against the template styles.")
  37. parser.add_argument("template_path")
  38. parser.add_argument("manifest_path")
  39. args = parser.parse_args()
  40. template_path = Path(args.template_path).expanduser().resolve()
  41. manifest_path = Path(args.manifest_path).expanduser().resolve()
  42. result = validate(template_path, manifest_path)
  43. print(json.dumps(result, ensure_ascii=False, indent=2))
  44. return 0
  45. if __name__ == "__main__":
  46. try:
  47. raise SystemExit(main())
  48. except Exception as exc: # pragma: no cover
  49. print(f"validate_template_manifest.py failed: {exc}", file=sys.stderr)
  50. raise SystemExit(1)