Add Page and SourcePage with lossless reading and source writing
CI / checks (pull_request) Successful in 53s
CI / checks (pull_request) Successful in 53s
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 <noreply@anthropic.com>
This commit is contained in:
1 parent
f5fe9af07a
commit
f0f0f02d90
4 files changed
+472
No files matched your search
@@ -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,
|
||||
)
|
||||
@@ -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")
|
||||
Reference in new issue
Block a user