"""Lossless splitting, strict reading and canonical writing of page frontmatter.""" import re import unicodedata from collections.abc import Mapping, Sequence from typing import Any, cast import yaml from chemenu.domain.errors import FrontmatterError type Value = str | list[Value] | dict[str, Value] _FENCE = "---" _LINE_RE = re.compile(r"([^\r\n]*)(\r\n|\n|\r|$)") _KEY_RE = re.compile(r"[a-z][a-z0-9_]*") # PyYAML breaks lines here, `split_document` does not. _AMBIGUOUS_BREAKS_RE = re.compile("[\x85\u2028\u2029]") _SURROGATE_RE = re.compile("[\ud800-\udfff]") _MAX_DEPTH = 32 _ALWAYS_ESCAPED = frozenset(map(chr, (0x85, 0x2028, 0x2029, 0xFEFF, 0xFFFE, 0xFFFF))) def split_document(text: str) -> tuple[str, str]: """Split text into the YAML block between the fences and the body, losslessly.""" pos = 0 block_start = -1 while pos < len(text): match = _LINE_RE.match(text, pos) if match is None: # unreachable: the pattern matches at any position raise FrontmatterError("cannot read line") line, eol = match.group(1), match.group(2) end = match.end() if block_start < 0: if line != _FENCE or not eol: raise FrontmatterError("document does not start with a '---' line") block_start = end elif line == _FENCE: return text[block_start:pos], text[end:] pos = end raise FrontmatterError("frontmatter is not closed by a '---' line") class _Loader(yaml.BaseLoader): """Composes nodes without anchors and aliases; values stay text.""" _depth = 0 def compose_node(self, parent: Any, index: Any) -> Any: # pyright: ignore[reportIncompatibleMethodOverride] if self.check_event(yaml.AliasEvent): raise FrontmatterError("YAML aliases are not allowed") event = cast("object", self.peek_event()) # pyright: ignore[reportUnknownMemberType] if getattr(event, "anchor", None) is not None: raise FrontmatterError("YAML anchors are not allowed") self._depth += 1 if self._depth > _MAX_DEPTH: raise FrontmatterError("frontmatter is nested too deeply") node = super().compose_node(parent, index) self._depth -= 1 return node def _scalar(node: yaml.ScalarNode) -> str: text = str(node.value) if _SURROGATE_RE.search(text): # from an escape such as "\\ud800" raise FrontmatterError("text contains a lone surrogate") return text def _convert(node: yaml.Node) -> Value: if isinstance(node, yaml.ScalarNode): return _scalar(node) if isinstance(node, yaml.SequenceNode): return [_convert(child) for child in node.value] if isinstance(node, yaml.MappingNode): result: dict[str, Value] = {} for key_node, value_node in node.value: if not isinstance(key_node, yaml.ScalarNode): raise FrontmatterError("mapping keys must be plain text") key = _scalar(key_node) if key in result: raise FrontmatterError(f"duplicate key: {key!r}") result[key] = _convert(value_node) return result raise FrontmatterError("unsupported YAML node") def parse_frontmatter(block: str) -> dict[str, Value]: """Read a YAML block into nested text values; every problem is a FrontmatterError.""" if _AMBIGUOUS_BREAKS_RE.search(block): raise FrontmatterError("frontmatter contains U+0085, U+2028 or U+2029") try: loader = _Loader(block) try: node = loader.get_single_node() finally: loader.dispose() if node is None: raise FrontmatterError("frontmatter is empty") if not isinstance(node, yaml.MappingNode): raise FrontmatterError("frontmatter must be a mapping") value = _convert(node) except FrontmatterError: raise except (yaml.YAMLError, RecursionError, ValueError, TypeError) as exc: raise FrontmatterError(f"invalid frontmatter: {' '.join(str(exc).split())}") from exc if not isinstance(value, dict): raise FrontmatterError("frontmatter must be a mapping") return value def _quote(text: str) -> str: out = ['"'] for char in text: code = ord(char) if 0xD800 <= code <= 0xDFFF: raise FrontmatterError("text contains a lone surrogate") if char == '"' or char == "\\": out.append("\\" + char) elif unicodedata.category(char) == "Cc" or char in _ALWAYS_ESCAPED: out.append(f"\\u{code:04x}") else: out.append(char) out.append('"') return "".join(out) def render_frontmatter(fields: Mapping[str, str | Sequence[str]]) -> str: """Write fields in order between fences; texts quoted, lists on one line.""" lines = [_FENCE] for key, value in fields.items(): if not _KEY_RE.fullmatch(key): raise FrontmatterError(f"invalid key: {key!r}") if isinstance(value, str): rendered = _quote(value) else: rendered = "[" + ", ".join(_quote(item) for item in value) + "]" lines.append(f"{key}: {rendered}") lines.append(_FENCE) return "\n".join(lines) + "\n"