From f0f0f02d90df92ec197768a4618341a018ac2c21 Mon Sep 17 00:00:00 2001 From: Torben Nehmer Date: Fri, 4 Dec 2026 03:42:34 +0100 Subject: [PATCH] Add Page and SourcePage with lossless reading and source writing Pages keep their original bytes; fields and sections are views. Source pages are read strictly and written in a fixed field order. Co-Authored-By: Claude Sonnet 5.5 --- src/chemenu/domain/page.py | 73 +++++++++++++ src/chemenu/domain/source_page.py | 155 ++++++++++++++++++++++++++ tests/domain/test_page.py | 69 ++++++++++++ tests/domain/test_source_page.py | 175 ++++++++++++++++++++++++++++++ 4 files changed, 472 insertions(+) create mode 100644 src/chemenu/domain/page.py create mode 100644 src/chemenu/domain/source_page.py create mode 100644 tests/domain/test_page.py create mode 100644 tests/domain/test_source_page.py diff --git a/src/chemenu/domain/page.py b/src/chemenu/domain/page.py new file mode 100644 index 0000000..e89f311 --- /dev/null +++ b/src/chemenu/domain/page.py @@ -0,0 +1,73 @@ +"""A page read losslessly: the original bytes plus views on them.""" + +from collections.abc import Mapping +from dataclasses import dataclass +from types import MappingProxyType + +from chemenu.domain.errors import FrontmatterError, InvalidPageIdError, PageError +from chemenu.domain.frontmatter import Value, parse_frontmatter, split_document +from chemenu.domain.identity import PageId, PageTitle +from chemenu.domain.sections import Section, split_sections +from chemenu.domain.wikilinks import WikiLink, find_wikilinks + +_BOM = b"\xef\xbb\xbf" + + +@dataclass(frozen=True, kw_only=True) +class Page: + """A page. `raw` is authoritative; all other fields are views on it.""" + + title: PageTitle + id: PageId + aliases: tuple[str, ...] + frontmatter: Mapping[str, Value] + body: str + sections: tuple[Section, ...] + links: tuple[WikiLink, ...] + raw: bytes + + def to_bytes(self) -> bytes: + """The original bytes, unchanged.""" + return self.raw + + +def _read_id(fields: Mapping[str, Value]) -> PageId: + value = fields.get("id") + if not isinstance(value, str): + raise InvalidPageIdError(f"page id missing or not text: {value!r}") + return PageId(value) + + +def _read_aliases(fields: Mapping[str, Value]) -> tuple[str, ...]: + if "aliases" not in fields: + return () + value = fields["aliases"] + if not isinstance(value, list): + raise FrontmatterError("aliases must be a list of texts") + aliases: list[str] = [] + for item in value: + if not isinstance(item, str): + raise FrontmatterError("aliases must be a list of texts") + aliases.append(item) + return tuple(aliases) + + +def parse_page(title: PageTitle, data: bytes) -> Page: + """Read a page; `PageError` (or a subclass) for anything unusable.""" + content = data[len(_BOM) :] if data.startswith(_BOM) else data + try: + text = content.decode("utf-8") + except UnicodeDecodeError as exc: + raise PageError(f"page is not valid UTF-8: {exc}") from exc + block, body = split_document(text) + fields = parse_frontmatter(block) + return Page( + title=title, + id=_read_id(fields), + aliases=_read_aliases(fields), + frontmatter=MappingProxyType(fields), + body=body, + sections=split_sections(body), + links=find_wikilinks(body), + raw=data, + ) diff --git a/src/chemenu/domain/source_page.py b/src/chemenu/domain/source_page.py new file mode 100644 index 0000000..41aad14 --- /dev/null +++ b/src/chemenu/domain/source_page.py @@ -0,0 +1,155 @@ +"""Source pages: pages that describe a raw capture, read and written.""" + +import re +import unicodedata +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from datetime import date, datetime +from enum import Enum + +from chemenu.domain.errors import InvalidSourceError +from chemenu.domain.frontmatter import Value, render_frontmatter +from chemenu.domain.identity import PageId, PageTitle +from chemenu.domain.markdown import is_blank, line_content, split_lines +from chemenu.domain.page import Page, parse_page +from chemenu.domain.sections import split_sections +from chemenu.domain.source import ( + Authority, + AuthorityForm, + DatingBasis, + FactTime, + format_point, + parse_point, +) + +_H1_RE = re.compile(r" {0,3}#(?:[ \t]|$)") + + +@dataclass(frozen=True, kw_only=True) +class SourcePage: + """A page of type `source` with its raw files and fact time.""" + + page: Page + raw_files: tuple[str, ...] + fact_time: FactTime + authority: Authority + authority_form: AuthorityForm + + +def _check_raw_file(name: str) -> None: + if not name: + raise InvalidSourceError("raw file path is empty") + if any(unicodedata.category(c) in ("Cc", "Cs") or c == "\\" for c in name): + raise InvalidSourceError(f"raw file path has forbidden characters: {name!r}") + if name.startswith("/") or any(part in ("", ".", "..") for part in name.split("/")): + raise InvalidSourceError(f"raw file path is not a clean relative path: {name!r}") + + +def _check_raw_files(names: Sequence[str]) -> tuple[str, ...]: + if not names: + raise InvalidSourceError("raw_files must not be empty") + for name in names: + _check_raw_file(name) + if len(set(names)) != len(names): + raise InvalidSourceError("raw_files contains duplicates") + return tuple(names) + + +def _text(fields: Mapping[str, Value], key: str) -> str: + value = fields.get(key) + if not isinstance(value, str): + raise InvalidSourceError(f"{key} is missing or not text") + return value + + +def _enum[E: Enum](kind: type[E], fields: Mapping[str, Value], key: str) -> E: + text = _text(fields, key) + try: + return kind(text) + except ValueError as exc: + raise InvalidSourceError(f"invalid {key}: {text!r}") from exc + + +def parse_source_page(title: PageTitle, data: bytes) -> SourcePage: + """Read a source page; errors of `parse_page` pass through.""" + page = parse_page(title, data) + fields = page.frontmatter + if fields.get("type") != "source": + raise InvalidSourceError("page type is not 'source'") + raw_files = fields.get("raw_files") + if not isinstance(raw_files, list) or not all(isinstance(n, str) for n in raw_files): + raise InvalidSourceError("raw_files must be a list of texts") + names = _check_raw_files([n for n in raw_files if isinstance(n, str)]) + earliest: date | datetime | None = None + if "fact_earliest" in fields: + earliest = parse_point(_text(fields, "fact_earliest")) + latest = parse_point(_text(fields, "fact_latest")) + basis = _enum(DatingBasis, fields, "fact_basis") + authority = _enum(Authority, fields, "authority") + form = _enum(AuthorityForm, fields, "authority_form") + return SourcePage( + page=page, + raw_files=names, + fact_time=FactTime(earliest=earliest, latest=latest, basis=basis), + authority=authority, + authority_form=form, + ) + + +def _has_own_title(body: str) -> bool: + for section in split_sections(body): + lines = split_lines(section.text) + if section.key.heading is None: + lines = tuple(line for line in lines if not is_blank(line))[:1] + else: + lines = lines[:1] + if any(_H1_RE.match(line_content(line)) for line in lines): + return True + return False + + +def _clean_body(body: str) -> str: + if any(0xD800 <= ord(c) <= 0xDFFF for c in body): + raise InvalidSourceError("body contains surrogates") + lines = [line_content(line) for line in split_lines(body)] + start, end = 0, len(lines) + while start < end and is_blank(lines[start]): + start += 1 + while start < end and is_blank(lines[end - 1]): + end -= 1 + cleaned = "\n".join(lines[start:end]) + if _has_own_title(cleaned): + raise InvalidSourceError("body must not contain a level-1 heading") + return cleaned + + +def render_source_page( + *, + title: PageTitle, + id: PageId, + aliases: Sequence[str], + raw_files: Sequence[str], + fact_time: FactTime, + authority: Authority, + authority_form: AuthorityForm, + body: str, +) -> bytes: + """Write a new source page: frontmatter, blank line, title line, text, one LF.""" + names = _check_raw_files(raw_files) + text = _clean_body(body) + fields: dict[str, str | Sequence[str]] = { + "id": id.value, + "type": "source", + "aliases": list(aliases), + "raw_files": list(names), + } + if fact_time.earliest is not None: + fields["fact_earliest"] = format_point(fact_time.earliest) + fields["fact_latest"] = format_point(fact_time.latest) + fields["fact_basis"] = fact_time.basis.value + fields["authority"] = authority.value + fields["authority_form"] = authority_form.value + out = render_frontmatter(fields) + f"\n# {title.value}\n" + if text: + out += f"\n{text}\n" + return out.encode("utf-8") diff --git a/tests/domain/test_page.py b/tests/domain/test_page.py new file mode 100644 index 0000000..4b231ed --- /dev/null +++ b/tests/domain/test_page.py @@ -0,0 +1,69 @@ +import codecs + +import pytest + +from chemenu.domain.errors import FrontmatterError, InvalidPageIdError, PageError +from chemenu.domain.identity import PageTitle +from chemenu.domain.page import parse_page + +ID = "01a238ea-2e6d-7157-ba55-5da7405095ff" +TITLE = PageTitle("Note") + + +def test_unchanged_is_byte_equal() -> None: + samples = [ + f'---\nid: "{ID}"\n---\n\n# Note\n\ntext\n'.encode(), + f'---\r\nid: "{ID}"\r\n# comment\r\nunknown: {{a: [b, c]}}\r\n---\r\n# Note\r\n'.encode(), + codecs.BOM_UTF8 + f"---\nid: {ID}\n---\nno trailing newline".encode(), + f"---\nid: {ID}\n---\n".encode(), + codecs.BOM_UTF8 + f"---\r\nid: {ID}\r\n---\r\n\r\n# Note\r\n".encode(), + ] + for data in samples: + page = parse_page(TITLE, data) + assert page.raw == data + assert page.to_bytes() == data + assert "".join(s.text for s in page.sections) == page.body + bom = parse_page(TITLE, samples[2]) + assert bom.body == "no trailing newline" + assert bom.id.value == ID + + +def test_aliases_and_links() -> None: + data = ( + f'---\nid: "{ID}"\naliases: [A, "B c"]\nx: "[[Frontmatter]]"\n---\n' + "# Note\n\nsee [[Other|o]]\n\n## Sec\n[[T#a]]\n" + ).encode() + page = parse_page(TITLE, data) + assert page.aliases == ("A", "B c") + assert [link.target for link in page.links] == ["Other", "T"] + assert [s.key.heading for s in page.sections] == [None, "Sec"] + assert page.frontmatter["x"] == "[[Frontmatter]]" + with pytest.raises(TypeError): + page.frontmatter["new"] = "v" # pyright: ignore[reportIndexIssue] + plain = parse_page(TITLE, f"---\nid: {ID}\n---\n".encode()) + assert plain.aliases == () + for bad in ["aliases: x", "aliases: [[a]]", "aliases: {a: b}"]: + with pytest.raises(FrontmatterError): + parse_page(TITLE, f"---\nid: {ID}\n{bad}\n---\n".encode()) + + +def test_missing_frontmatter_raises() -> None: + for data in [b"", b"# Note\n", b"---\nid: x\n", b"\n---\nid: x\n---\n", b"---\n---\n"]: + with pytest.raises(FrontmatterError): + parse_page(TITLE, data) + + +def test_missing_or_invalid_id_raises() -> None: + for block in ["a: b", "id: nope", f"id: [{ID}]", f"id: {{a: {ID}}}", f"id: {ID.upper()}"]: + with pytest.raises(InvalidPageIdError): + parse_page(TITLE, f"---\n{block}\n---\n".encode()) + + +def test_invalid_utf8_raises() -> None: + for data in [ + b"---\nid: \xff\n---\n", + b"\xef\xbb\xbf\xef\xbb\xbf---\n", + f"---\nid: {ID}\n---\n".encode() + b"\xed\xa0\x80", + ]: + with pytest.raises(PageError): + parse_page(TITLE, data) diff --git a/tests/domain/test_source_page.py b/tests/domain/test_source_page.py new file mode 100644 index 0000000..74ba270 --- /dev/null +++ b/tests/domain/test_source_page.py @@ -0,0 +1,175 @@ +from datetime import date, datetime, timedelta, timezone + +import pytest + +from chemenu.domain.errors import FactTimeError, FrontmatterError, InvalidSourceError +from chemenu.domain.identity import PageId, PageTitle +from chemenu.domain.page import parse_page +from chemenu.domain.source import Authority, AuthorityForm, DatingBasis, FactTime +from chemenu.domain.source_page import parse_source_page, render_source_page + +ID = "01a238ea-2e6d-7157-ba55-5da7405095ff" +TITLE = PageTitle("Note") +FACT = FactTime(earliest=date(2026, 11, 28), latest=date(2026, 11, 29), basis=DatingBasis.CAPTURED) + + +def render( + *, + aliases: list[str] | None = None, + raw_files: list[str] | None = None, + fact_time: FactTime = FACT, + body: str = "text", +) -> bytes: + return render_source_page( + title=TITLE, + id=PageId(ID), + aliases=["A"] if aliases is None else aliases, + raw_files=["raw/notes/a.md"] if raw_files is None else raw_files, + fact_time=fact_time, + authority=Authority.ORGANIZATION, + authority_form=AuthorityForm.ORAL, + body=body, + ) + + +def source(**fields: str | None) -> bytes: + base: dict[str, str | None] = { + "type": '"source"', + "raw_files": '["a.md"]', + "fact_latest": "2026-11-28", + "fact_basis": "captured", + "authority": "official", + "authority_form": "written", + } + base.update(fields) + lines = [f"{k}: {v}" for k, v in base.items() if v is not None] + return "\n".join(["---", f"id: {ID}", *lines, "---", "# Note", ""]).encode() + + +def test_render_then_parse() -> None: + point = datetime(2026, 11, 28, 14, 32, tzinfo=timezone(timedelta(hours=1))) + fact = FactTime(earliest=point, latest=point, basis=DatingBasis.CAPTURED) + data = render( + fact_time=fact, + aliases=[], + raw_files=["raw/notes/2026-11-28-1432.md"], + body="\n \n indented\n\r\nline2\r\n\n\n", + ) + assert data == ( + b'---\nid: "01a238ea-2e6d-7157-ba55-5da7405095ff"\ntype: "source"\naliases: []\n' + b'raw_files: ["raw/notes/2026-11-28-1432.md"]\n' + b'fact_earliest: "2026-11-28T14:32:00+01:00"\n' + b'fact_latest: "2026-11-28T14:32:00+01:00"\nfact_basis: "captured"\n' + b'authority: "organization"\nauthority_form: "oral"\n---\n\n' + b"# Note\n\n indented\n\nline2\n" + ) + sp = parse_source_page(TITLE, data) + assert sp.fact_time == fact + assert sp.page.id == PageId(ID) + assert sp.page.title == TITLE + assert sp.page.body == "\n# Note\n\n indented\n\nline2\n" + assert sp.raw_files == ("raw/notes/2026-11-28-1432.md",) + assert sp.authority is Authority.ORGANIZATION + assert sp.authority_form is AuthorityForm.ORAL + assert parse_page(TITLE, data).raw == sp.page.raw + + assert render(body="").endswith(b"# Note\n") + assert render(body=" \n\n").endswith(b"# Note\n") + for body in ["# H1", "\n # H1\n", "a\n\n# H1\nb", "a\n```\n# x\n```\n# H1", "#"]: + with pytest.raises(InvalidSourceError): + render(body=body) + for body in ["a\n```\n# x\n```\n", "a\n", " # code", "## two", "#hash"]: + assert parse_source_page(TITLE, render(body=body)).page.body.endswith("\n") + with pytest.raises(InvalidSourceError): + render(body="a\ud800") + with pytest.raises(FrontmatterError): + render(aliases=["\ud800"]) + + +def test_fact_times_are_comparable() -> None: + later = FactTime( + earliest=date(2026, 12, 1), latest=date(2026, 12, 1), basis=DatingBasis.RECEIVED + ) + first = parse_source_page(TITLE, render()) + second = parse_source_page(TITLE, render(fact_time=later)) + assert first.fact_time.precedes(second.fact_time) + assert not second.fact_time.precedes(first.fact_time) + + +def test_comma_survives() -> None: + names = ["a,b.md", 'q"uote.md', "x..y/c d.md"] + sp = parse_source_page(TITLE, render(raw_files=names, aliases=["a, b", "c"])) + assert sp.raw_files == tuple(names) + assert sp.page.aliases == ("a, b", "c") + + +def test_missing_field_raises() -> None: + for field in ["type", "raw_files", "fact_latest", "fact_basis", "authority", "authority_form"]: + with pytest.raises(InvalidSourceError): + parse_source_page(TITLE, source(**{field: None})) + assert parse_source_page(TITLE, source(fact_earliest=None)).fact_time.earliest is None + for bad in [ + {"raw_files": "[]"}, + {"raw_files": "a.md"}, + {"raw_files": "[[a]]"}, + {"raw_files": "{a: b}"}, + {"raw_files": "[a.md, a.md]"}, + {"fact_latest": "[2026-01-01]"}, + {"fact_earliest": "{a: b}"}, + {"fact_basis": "nope"}, + {"fact_basis": "[captured]"}, + {"authority": "OFFICIAL"}, + {"authority": "[a, b]"}, + {"authority_form": "{a: b}"}, + {"type": "[source]"}, + ]: + with pytest.raises(InvalidSourceError): + parse_source_page(TITLE, source(**bad)) + for bad in [{"fact_latest": "yesterday"}, {"fact_earliest": "2027-01-01"}]: + with pytest.raises(FactTimeError): + parse_source_page(TITLE, source(**bad)) + + +def test_invalid_raw_file_raises() -> None: + bad = [ + "", + "/a", + "../a", + "a/..", + "a/./b", + "./a", + "a//b", + "a/", + "a\\b", + "a\nb", + "a\x00", + ".", + "..", + ] + for name in bad: + with pytest.raises(InvalidSourceError): + render(raw_files=[name]) + for names in [[], ["a", "a"]]: + with pytest.raises(InvalidSourceError): + render(raw_files=names) + with pytest.raises(InvalidSourceError): + parse_source_page(TITLE, source(raw_files='["a//b"]')) + with pytest.raises(InvalidSourceError): + parse_source_page(TITLE, source(raw_files='["a\\u0007"]')) + assert parse_source_page(TITLE, source(raw_files='["a..b", ".x/..y"]')).raw_files == ( + "a..b", + ".x/..y", + ) + + +def test_unknown_start_is_omitted() -> None: + fact = FactTime(earliest=None, latest=date(2026, 1, 1), basis=DatingBasis.EXIF) + data = render(fact_time=fact) + assert b"fact_earliest" not in data + assert parse_source_page(TITLE, data).fact_time == fact + + +def test_other_type_raises() -> None: + for t in ["note", '""', "Source"]: + with pytest.raises(InvalidSourceError): + parse_source_page(TITLE, source(type=t))