from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True)
class MarkdownDocument:
path: str
frontmatter: dict[str, str]
body: str
raw: str
def parse_frontmatter(path: str, raw: str) -> MarkdownDocument:
if not raw.startswith("---\n"):
return MarkdownDocument(path=path, frontmatter={}, body=raw, raw=raw)
end = raw.find("\n---\n", 4)
if end == -1:
return MarkdownDocument(path=path, frontmatter={}, body=raw, raw=raw)
metadata_text = raw[4:end]
body = raw[end + 5 :]
frontmatter: dict[str, str] = {}
for line in metadata_text.splitlines():
if not line.strip() or line.lstrip().startswith("#"):
continue
if ":" not in line:
continue
key, value = line.split(":", 1)
frontmatter[key.strip()] = value.strip().strip('"').strip("'")
return MarkdownDocument(path=path, frontmatter=frontmatter, body=body, raw=raw)