1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
from __future__ import annotations
from pathlib import Path
import tomlkit
def parse_frontmatter(path: Path) -> tuple[dict, str]:
"""Parse TOML frontmatter delimited by +++. Returns (frontmatter_dict, body_str)."""
text = path.read_text(encoding="utf-8")
if not text.startswith("+++"):
raise ValueError(f"No TOML frontmatter found in {path}")
parts = text.split("+++", 2)
if len(parts) < 3:
raise ValueError(f"Malformed frontmatter in {path}")
_, toml_block, body = parts
fm = dict(tomlkit.loads(toml_block))
return fm, body.lstrip("\n")
def write_frontmatter(path: Path, frontmatter: dict, body: str) -> None:
"""Write frontmatter + body back to file, preserving TOML format."""
text = path.read_text(encoding="utf-8")
parts = text.split("+++", 2)
if len(parts) < 3:
raise ValueError(f"Malformed frontmatter in {path}")
_, original_toml, _ = parts
doc = tomlkit.loads(original_toml)
for k, v in frontmatter.items():
doc[k] = v
new_text = f"+++\n{tomlkit.dumps(doc)}+++\n\n{body}"
path.write_text(new_text, encoding="utf-8")
|