Files
mytoolkit/bin/templates_registry.py
T
Zhengshou Lai 3e4cf618a8 refactor: restructure mytoolkit with new subcommands and md-to-pdf improvements
- Add new subcommands: convert, preflight, server, templates, webpage
- Migrate config from bin/config.json to ~/.config/mytoolkit
- Fix expand_bookmarks to modify writer objects instead of reader
- Improve md_to_pdf with CJK bookmark support
- Update README and project metadata
2026-05-04 17:19:32 +08:00

61 lines
1.6 KiB
Python

"""External templates registry for md→pdf / md→docx conversion."""
import json
from pathlib import Path
import click
CONFIG_PATH = Path.home() / ".config" / "mytoolkit" / "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