Files
mytoolkit/bin/templates_registry.py
T

63 lines
1.7 KiB
Python

"""External templates registry for md→pdf / md→docx conversion."""
import json
import os
from pathlib import Path
import click
_HOME = Path(os.environ.get("MYTOOLKIT_HOME", Path.home() / ".mytoolkit"))
CONFIG_PATH = _HOME / "templates.json"
def _read() -> dict:
if not CONFIG_PATH.exists():
return {}
with open(CONFIG_PATH, encoding="utf-8") as f:
return json.load(f)
def _write(data: dict) -> None:
CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
with open(CONFIG_PATH, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
f.write("\n")
def set_root(path: Path) -> Path:
"""Register the templates root directory. Returns the resolved path."""
resolved = Path(path).expanduser().resolve()
_write({"dir": str(resolved)})
return resolved
def get_root() -> Path:
"""Return the registered templates root, or raise UsageError if missing."""
data = _read()
raw = data.get("dir")
if not raw:
raise click.UsageError(
"Templates not registered. Run: mytoolkit templates register <path>"
)
root = Path(raw)
if not root.is_dir():
raise click.UsageError(
f"Registered templates dir does not exist: {root}\n"
"Re-run: mytoolkit templates register <path>"
)
return root
def get_md_to_pdf_root() -> Path:
sub = get_root() / "md-to-pdf"
if not sub.is_dir():
raise click.UsageError(f"Subdirectory missing: {sub}")
return sub
def get_md_to_docx_root() -> Path:
sub = get_root() / "md-to-docx"
if not sub.is_dir():
raise click.UsageError(f"Subdirectory missing: {sub}")
return sub