Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be103e1aa0 | ||
|
|
c4c388c036 | ||
|
|
ea91034d84 | ||
|
|
cc893be3d5 | ||
|
|
b6a00ed972 | ||
|
|
a639e5240e |
No files matched your search
@@ -32,6 +32,7 @@ Chemenu ist ein Dienst, der LLMs für eng umrissene Urteile aufruft: Code führt
|
|||||||
| [0024](decisions/0024-schritt-bausteine-und-evals.md) | Schritt-Bausteine statt `instructions/`, Bewerter nach Vorrang, Testkorpus | Ort des Testkorpus: #21 |
|
| [0024](decisions/0024-schritt-bausteine-und-evals.md) | Schritt-Bausteine statt `instructions/`, Bewerter nach Vorrang, Testkorpus | Ort des Testkorpus: #21 |
|
||||||
| [0025](decisions/0025-prozessor-plugins.md) | Plugin mit Manifest (M1–M13), Exemplar als Definition der Instanz, kein Fremdcode im Dienst | |
|
| [0025](decisions/0025-prozessor-plugins.md) | Plugin mit Manifest (M1–M13), Exemplar als Definition der Instanz, kein Fremdcode im Dienst | |
|
||||||
| [0026](decisions/0026-lage-der-schritt-bausteine.md) | Schritt-Bausteine im Stack-Paket `steps`, `string.Template`, Nummer und Fingerabdruck | |
|
| [0026](decisions/0026-lage-der-schritt-bausteine.md) | Schritt-Bausteine im Stack-Paket `steps`, `string.Template`, Nummer und Fingerabdruck | |
|
||||||
|
| [0027](decisions/0027-seitenformat.md) | Seite verlustfrei als Originalbytes, Titel gleich Dateiname, Abschnitte mit Hash, Quellseite mit flachen Feldern, Faktenzeit aus Daten und Zeitpunkten | |
|
||||||
|
|
||||||
## Abläufe
|
## Abläufe
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
status: accepted
|
status: accepted
|
||||||
date: 2026-12-02
|
date: 2026-12-03
|
||||||
---
|
---
|
||||||
# Markdown mit Titel-Wikilinks bleibt kanonisch, mit stabiler `id` und dem Abschnitt als Einheit
|
# Markdown mit Titel-Wikilinks bleibt kanonisch, mit stabiler `id` und dem Abschnitt als Einheit
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@ Zwei Punkte der Skalierungsliste „Von Anfang an ins Design, weil später nur m
|
|||||||
* **Umbenennen:** Der Dienst schreibt alle Links in einem Commit um, mechanisch und auch bei 10^4 Seiten in Sekunden.
|
* **Umbenennen:** Der Dienst schreibt alle Links in einem Commit um, mechanisch und auch bei 10^4 Seiten in Sekunden.
|
||||||
* **Kollisionen:** Eindeutigkeit wird beim Anlegen erzwungen. Mehrdeutige Namen bekommen einen Zusatz nach Konvention, etwa „X (Organisation)“.
|
* **Kollisionen:** Eindeutigkeit wird beim Anlegen erzwungen. Mehrdeutige Namen bekommen einen Zusatz nach Konvention, etwa „X (Organisation)“.
|
||||||
* **Stabiler Anker:** `id:` im Frontmatter. Obsidian ignoriert unbekannte Felder.
|
* **Stabiler Anker:** `id:` im Frontmatter. Obsidian ignoriert unbekannte Felder.
|
||||||
* **`aliases:` ist ein natives Obsidian-Feld** und dient doppelt: Linkauflösung in Obsidian und Synonyme für die Wiedererkennung von Entitäten.
|
* **`aliases:` ist ein natives Obsidian-Feld** und dient doppelt: Vorschlag beim Tippen eines Links in Obsidian (der Dienst schreibt Links als `[[Titel|Alias]]`) und Synonyme für die Wiedererkennung von Entitäten. Einzelheiten in [ADR 0027](0027-seitenformat.md).
|
||||||
|
|
||||||
### Abschnitt als Einheit
|
### Abschnitt als Einheit
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
status: accepted
|
status: accepted
|
||||||
date: 2026-12-02
|
date: 2026-12-03
|
||||||
---
|
---
|
||||||
# Faktenzeit als Intervall mit Datierungsgrundlage, Halbordnung und Autoritätsskala von Anfang an
|
# Faktenzeit als Intervall mit Datierungsgrundlage, Halbordnung und Autoritätsskala von Anfang an
|
||||||
|
|
||||||
@@ -25,7 +25,7 @@ Gewählte Option: „Intervall mit Datierungsgrundlage, Halbordnung und grobe Au
|
|||||||
|
|
||||||
### Faktenzeit
|
### Faktenzeit
|
||||||
|
|
||||||
* **Felder je Quelle:** frühestens, spätestens, Datierungsgrundlage (worauf sich die Zeitangabe stützt). Ein Transkript ohne Datum hat damit [?, Eingangsdatum].
|
* **Felder je Quelle:** frühestens, spätestens, Datierungsgrundlage (worauf sich die Zeitangabe stützt). Die Schreibweise der Felder steht in [ADR 0027](0027-seitenformat.md). Ein Transkript ohne Datum hat damit [?, Eingangsdatum].
|
||||||
* **Halbordnung:** Zwei Quellen sind geordnet, wenn sich ihre Intervalle nicht überlappen.
|
* **Halbordnung:** Zwei Quellen sind geordnet, wenn sich ihre Intervalle nicht überlappen.
|
||||||
* **Rückfrage nur bei echter Überlappung,** am besten im Eingangsformular mit vorausgefülltem Vorschlag. „Unbekannt“ ist eine legitime Antwort.
|
* **Rückfrage nur bei echter Überlappung,** am besten im Eingangsformular mit vorausgefülltem Vorschlag. „Unbekannt“ ist eine legitime Antwort.
|
||||||
* **Automatisch, nach Verlässlichkeit:** E-Mail-Date-Header, git-Commit, HTML-Metadaten, EXIF; dann Dateinamensmuster und „Stand:“ im Inhalt; PDF- und Office-Metadaten nur bedingt. Datei-mtime ist praktisch wertlos.
|
* **Automatisch, nach Verlässlichkeit:** E-Mail-Date-Header, git-Commit, HTML-Metadaten, EXIF; dann Dateinamensmuster und „Stand:“ im Inhalt; PDF- und Office-Metadaten nur bedingt. Datei-mtime ist praktisch wertlos.
|
||||||
@@ -45,7 +45,7 @@ Wie die Klasse aus Signalen entsteht und wie Fragen behandelt werden, steht in [
|
|||||||
|
|
||||||
### Autorität als zweite Achse, von Anfang an
|
### Autorität als zweite Achse, von Anfang an
|
||||||
|
|
||||||
Eine grobe Skala reicht: amtlich > Organisation selbst > Dritte > Hörensagen, dazu die Form (schriftlich, mündlich). Ein Telefonat mit der Geschäftsführung ist „Organisation selbst, mündlich“. Begründung: Ohne Autorität funktioniert die Ampel nicht. Eine neuere Telefonnotiz gegen einen älteren Registerauszug ist keine reine Frage der Reihenfolge.
|
Eine grobe Skala reicht: amtlich > Organisation selbst > Dritte > Hörensagen, dazu die Form (schriftlich, mündlich). Die Felder je Quelle stehen in [ADR 0027](0027-seitenformat.md). Ein Telefonat mit der Geschäftsführung ist „Organisation selbst, mündlich“. Begründung: Ohne Autorität funktioniert die Ampel nicht. Eine neuere Telefonnotiz gegen einen älteren Registerauszug ist keine reine Frage der Reihenfolge.
|
||||||
|
|
||||||
### Quellenversionen
|
### Quellenversionen
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,198 @@
|
|||||||
|
---
|
||||||
|
status: accepted
|
||||||
|
date: 2026-12-03
|
||||||
|
---
|
||||||
|
# Seitenformat: verlustfrei gelesen, Titel gleich Dateiname, Abschnitte mit Hash, Quellseite mit flachen Feldern
|
||||||
|
|
||||||
|
## Kontext und Problemstellung
|
||||||
|
|
||||||
|
[ADR 0014](0014-speicherformat-und-identitaet.md) legt Markdown mit `id`, `aliases` und dem Abschnitt als Einheit fest, [ADR 0015](0015-faktenzeit-und-autoritaet.md) Faktenzeit und Autorität je Quelle. Beide lassen offen, wie eine Seite im Einzelnen aufgebaut ist und wie die Domäne sie liest und schreibt. Dieses ADR füllt sie aus und präzisiert sie. Bezüge: Operationen in [ADR 0008](0008-schreiben-als-operationen.md), sicheres YAML in [ADR 0019](0019-sicherheitsgrenzen.md).
|
||||||
|
|
||||||
|
Der Dienst ist der einzige Schreiber, Obsidian liest dieselben Dateien. Das Format muss deshalb unveränderte Teile byte-gleich durchreichen, Titel und Links so abbilden, wie Obsidian sie auflöst, und den Abschnitt als Einheit der Basisversion eindeutig bestimmen.
|
||||||
|
|
||||||
|
## Betrachtete Optionen
|
||||||
|
|
||||||
|
Lesen und Schreiben:
|
||||||
|
|
||||||
|
1. Die Seite hält die Originalbytes, Felder und Abschnitte sind Sichten darauf.
|
||||||
|
2. `ruamel.yaml`.
|
||||||
|
3. Dict mit eigenem Schreibstil.
|
||||||
|
|
||||||
|
Titel:
|
||||||
|
|
||||||
|
1. Dateiname ohne `.md`, zusätzlich als einzige `#`-Zeile.
|
||||||
|
2. Nur der Dateiname.
|
||||||
|
3. `title:` im Frontmatter.
|
||||||
|
4. `#` in freier Schreibweise.
|
||||||
|
|
||||||
|
Abschnitte:
|
||||||
|
|
||||||
|
1. ATX-Überschriften der Ebenen 1 und 2 trennen, eigener Scanner.
|
||||||
|
2. Jede Überschrift trennt.
|
||||||
|
3. `markdown-it-py`.
|
||||||
|
|
||||||
|
Hash:
|
||||||
|
|
||||||
|
1. Text unter der Überschrift, Zeilenenden und Ränder normalisiert.
|
||||||
|
2. Rohe Bytes samt Überschrift.
|
||||||
|
3. Leerraum im Text normalisieren.
|
||||||
|
|
||||||
|
`id`:
|
||||||
|
|
||||||
|
1. UUIDv7.
|
||||||
|
2. ULID.
|
||||||
|
3. Kurze Zufalls-ID.
|
||||||
|
|
||||||
|
Quellseite:
|
||||||
|
|
||||||
|
1. Flache Felder, Autorität samt Form als Pflicht.
|
||||||
|
2. Verschachtelte Felder.
|
||||||
|
3. Datierungsgrundlage als Freitext.
|
||||||
|
4. Autorität weglassen oder optional.
|
||||||
|
|
||||||
|
Faktenzeit:
|
||||||
|
|
||||||
|
1. Intervall aus Daten und Zeitpunkten.
|
||||||
|
2. Nur Daten.
|
||||||
|
3. Nur Zeitpunkte.
|
||||||
|
|
||||||
|
## Entscheidung
|
||||||
|
|
||||||
|
### Verlustfrei
|
||||||
|
|
||||||
|
Gewählte Option: „Die Seite hält die Originalbytes“. Felder und Abschnitte sind Sichten darauf. Lesen und unverändert Schreiben ist byte-gleich, auch mit CRLF, BOM, YAML-Kommentaren und unbekannten Feldern. UTF-8 wird strikt gelesen, Zeilenenden werden nicht übersetzt; ein BOM bleibt in den Bytes und fehlt in den Sichten. Verworfen:
|
||||||
|
|
||||||
|
* `ruamel.yaml`: eine Abhängigkeit, und nach Kenntnisstand nicht in jedem Fall byte-gleich.
|
||||||
|
* Dict mit eigenem Schreibstil: nur für selbst geschriebene Dateien byte-gleich. Daran hing torben/chemenu#239.
|
||||||
|
|
||||||
|
Preis: Spätere Änderungen müssen gezielt Textstücke ersetzen.
|
||||||
|
|
||||||
|
### Frontmatter lesen
|
||||||
|
|
||||||
|
Ein eigener Loader auf Basis von `yaml.BaseLoader`: Jeder Wert bleibt Text (`1.10`, `no`, `2026-11-28`). Er erzeugt nur Texte, Listen und Mappings und erfüllt damit den Zweck von [ADR 0019](0019-sicherheitsgrenzen.md). Fehler sind:
|
||||||
|
|
||||||
|
* ein fehlender oder leerer Block,
|
||||||
|
* ungültiges YAML,
|
||||||
|
* ein Wert, der kein Mapping ist,
|
||||||
|
* doppelte Schlüssel auf jeder Ebene (PyYAML nähme still den letzten),
|
||||||
|
* Anker oder Aliase (Alias-Bombe),
|
||||||
|
* mehr als 32 Ebenen Schachtelung,
|
||||||
|
* U+0085, U+2028 oder U+2029 (PyYAML trennt dort Zeilen, die Domäne nicht) und einzelne Surrogate aus Escapes.
|
||||||
|
|
||||||
|
`aliases` fehlt oder ist eine Liste von Texten.
|
||||||
|
|
||||||
|
### Frontmatter schreiben
|
||||||
|
|
||||||
|
Texte stehen immer in doppelten Anführungszeichen, Listen in einer Zeile; ein Titel mit Komma kann so nicht zerfallen. Nicht druckbare Zeichen werden als `\uXXXX` geschrieben, alles andere wörtlich. `json.dumps` allein genügt nicht: Je nach `ensure_ascii` scheitert der Rundlauf über PyYAML an U+0085 oder an Emojis.
|
||||||
|
|
||||||
|
### `id`
|
||||||
|
|
||||||
|
Gewählte Option: „UUIDv7“, klein, mit Bindestrichen. Sie ist nach Zeit sortierbar, in Python 3.14 eingebaut und Standard für Datenbank und OpenAPI. Die Domäne prüft die `id`, die Anwendung erzeugt sie. Verworfen:
|
||||||
|
|
||||||
|
* ULID: eine Abhängigkeit oder ein Eigenbau.
|
||||||
|
* Kurze Zufalls-ID: Kollisionen.
|
||||||
|
|
||||||
|
Preis: 36 Zeichen. Die `id` ist sehr schwer änderbar.
|
||||||
|
|
||||||
|
### Titel
|
||||||
|
|
||||||
|
Gewählte Option: „Dateiname ohne `.md`, zusätzlich als einzige `#`-Zeile“. Verboten sind:
|
||||||
|
|
||||||
|
* `< > : " / \ | ? * [ ] # ^`,
|
||||||
|
* die Folge `%%`,
|
||||||
|
* Steuerzeichen sowie U+2028 und U+2029,
|
||||||
|
* unsichtbare Formatzeichen (Unicode-Kategorie Cf, etwa U+200B, U+FEFF, Richtungszeichen); erlaubt bleiben die Verbinder U+200C und U+200D, die manche Schriften und Emojis brauchen, und die Tag-Zeichen von Regionalflaggen,
|
||||||
|
* die Endung `.md`, auch in anderer Schreibweise,
|
||||||
|
* Punkt oder Leerraum am Rand,
|
||||||
|
* Windows-Gerätenamen,
|
||||||
|
* ein leerer oder nicht NFC-normalisierter Titel,
|
||||||
|
* mehr als 252 Bytes UTF-8 (der Dateiname mit `.md` darf 255 Bytes haben).
|
||||||
|
|
||||||
|
Das Komma ist erlaubt. Unsichtbare Zeichen sind verboten, weil zwei Titel sonst gleich aussehen und doch verschieden sind. Die Endung `.md` ist verboten, weil Obsidian `[[README.md]]` als Link auf die Datei `README.md` liest, eine Seite dieses Titels aber `README.md.md` hieße ([Links](https://obsidian.md/help/links)); die Originalform steht dann in `aliases`. Neue Seiten tragen den Titel wörtlich als einzige `#`-Zeile; der Code erzeugt sie aus dem Dateinamen. Die Originalform („Was ist X?“) steht in `aliases`. Gelesen wird tolerant: Eine fehlende oder abweichende `#`-Zeile ist kein Fehler, das meldet später der Lint. Verworfen:
|
||||||
|
|
||||||
|
* Nur der Dateiname: Außerhalb von Obsidian ist die Seite titellos, und es widerspricht dem [Google-Style-Guide](https://google.github.io/styleguide/docguide/style.html) und [markdownlint MD041](https://github.com/DavidAnson/markdownlint/blob/main/doc/md041.md).
|
||||||
|
* `title:` im Frontmatter: Obsidian nutzt es weder als Linkziel noch zur Anzeige ([Links](https://obsidian.md/help/links), [Eigenschaften](https://obsidian.md/help/properties)).
|
||||||
|
* `#` in freier Schreibweise: zwei Titel je Seite und Kollisionen, siehe auch [markdownlint MD025](https://github.com/DavidAnson/markdownlint/blob/main/doc/md025.md).
|
||||||
|
|
||||||
|
Preis: In Obsidian muss „Show inline title“ aus sein, sonst steht der Titel doppelt. Umbenennen ändert eine Zeile mehr.
|
||||||
|
|
||||||
|
### Abschnitte
|
||||||
|
|
||||||
|
Gewählte Option: „ATX-Überschriften der Ebenen 1 und 2 trennen“. Der Kopf reicht bis zur ersten trennenden Überschrift und hat eine feste Adresse. Trennend sind ATX-Überschriften der Ebenen 1 und 2, außer einer `#`-Zeile, die die erste nichtleere Zeile ist. `###` und tiefer gehören zum Abschnitt, denn die Einheit ist die, über die der Type-Spec spricht. Unterstrichene Überschriften trennen nicht. In Codeblöcken und in HTML-Kommentaren am Zeilenanfang trennt nichts. Codeblöcke gelten auch in Listen und Zitaten und enden mit ihnen. Die Adresse ist die Überschrift, bei Wiederholung mit laufender Nummer. Verworfen:
|
||||||
|
|
||||||
|
* Jede Überschrift trennt: Der Type-Spec kennt die Unterabschnitte nicht.
|
||||||
|
* `markdown-it-py`: eine Abhängigkeit im Kern.
|
||||||
|
|
||||||
|
Preis: Die Einheiten sind größer; dagegen wirkt das Größenbudget aus [ADR 0014](0014-speicherformat-und-identitaet.md).
|
||||||
|
|
||||||
|
### Hash
|
||||||
|
|
||||||
|
Gewählte Option: „Text unter der Überschrift“. Beim Kopf zählt er ohne die `#`-Titelzeile. Zeilenenden werden auf LF gesetzt, Leerzeilen am Rand und das letzte Zeilenende entfallen; der Hash ist SHA-256 über UTF-8. Die Überschrift ist die Adresse, der Hash die Version. Das Umbenennen einer Seite macht keinen wartenden Job ungültig. Wird eine Überschrift umbenannt, findet der Job den Abschnitt nicht und prüft neu. Verworfen:
|
||||||
|
|
||||||
|
* Rohe Bytes samt Überschrift: Ein angefügter Abschnitt ändert den vorigen.
|
||||||
|
* Leerraum im Text normalisieren: Das verdeckt Änderungen in Listen, Tabellen und Code.
|
||||||
|
|
||||||
|
### Links
|
||||||
|
|
||||||
|
Als Link zählt nichts in Codeblöcken, Inline-Code und HTML-Kommentaren. Inline-Code und Kommentare mitten in der Zeile gelten nur innerhalb der Zeile, damit ein vergessenes Zeichen nicht alle folgenden Links verschluckt. Eingerückter Code ohne Zaun wird nicht erkannt, weil er sich von einer Listenfortsetzung kaum unterscheiden lässt. `\|` gilt als `|`, weil es in Tabellen so geschrieben wird ([Erweiterte Syntax](https://obsidian.md/help/advanced-syntax)). Der Anker ist alles ab dem ersten `#`. `[[#X]]` ist kein Link auf eine Seite.
|
||||||
|
|
||||||
|
### Quellseite
|
||||||
|
|
||||||
|
Gewählte Option: „Flache Felder, Autorität samt Form als Pflicht“. Beispiel:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
---
|
||||||
|
id: "01a238ea-2e6d-7157-ba55-5da7405095ff"
|
||||||
|
type: "source"
|
||||||
|
aliases: []
|
||||||
|
raw_files: ["raw/notes/2026-11-28-1432.md"]
|
||||||
|
fact_earliest: "2026-11-28T14:32:00+01:00"
|
||||||
|
fact_latest: "2026-11-28T14:32:00+01:00"
|
||||||
|
fact_basis: "captured"
|
||||||
|
authority: "organization"
|
||||||
|
authority_form: "oral"
|
||||||
|
---
|
||||||
|
```
|
||||||
|
|
||||||
|
* `type` muss `source` sein; andere Werte deutet die Domäne vor den Type-Specs nicht.
|
||||||
|
* `raw_files` nennt mindestens einen relativen POSIX-Pfad ohne `..`, `.`, leere Teile, `\` und Steuerzeichen, keinen doppelt.
|
||||||
|
* `authority` (`official`, `organization`, `third_party`, `hearsay`) und `authority_form` (`written`, `oral`) sind Pflicht, ohne „unbekannt“. `fidelity` des Altstacks kommt nicht zurück, die Form ersetzt es.
|
||||||
|
* `fact_basis` ist die Datierungsgrundlage aus einer festen Liste: `captured`, `received`, `email_header`, `git_commit`, `html_metadata`, `exif`, `filename`, `content`, `document_metadata`, `operator`. Neue Prozessoren erweitern sie.
|
||||||
|
|
||||||
|
Verworfen:
|
||||||
|
|
||||||
|
* Verschachtelte Felder: Obsidian zeigt sie nur im Quellmodus.
|
||||||
|
* Datierungsgrundlage als Freitext: nicht auswertbar.
|
||||||
|
* Autorität weglassen: widerspricht [ADR 0015](0015-faktenzeit-und-autoritaet.md).
|
||||||
|
* Autorität optional: Es gäbe Seiten ohne Autorität, und die Ampel müsste fragen.
|
||||||
|
|
||||||
|
Beim Schreiben entfallen Leerzeilen am Rand des Textes, Zeilenenden werden LF, und eine eigene `#`-Überschrift im Text ist ein Fehler.
|
||||||
|
|
||||||
|
Preis: Autorität und Form müssen beim Einreichen angegeben werden.
|
||||||
|
|
||||||
|
### Faktenzeit
|
||||||
|
|
||||||
|
Gewählte Option: „Intervall aus Daten und Zeitpunkten“. Ein Punkt ist ein Datum `YYYY-MM-DD` oder ein ISO-Zeitpunkt mit `T` und Zeitzone; andere Formen sind ein Fehler. Ist der Anfang unbekannt, fehlt `fact_earliest`; `fact_latest` ist Pflicht. Ein Datum meint den ganzen Tag in UTC („2023“ wird `2023-01-01` bis `2023-12-31`). Der Anfang darf nicht nach dem Ende liegen. Eine Quelle liegt vor einer anderen, wenn ihr Ende echt vor deren Anfang liegt; hat die andere keinen Anfang, nie. Verworfen:
|
||||||
|
|
||||||
|
* Nur Daten: Notizen eines Tages wären nie geordnet.
|
||||||
|
* Nur Zeitpunkte: erfundene Genauigkeit.
|
||||||
|
|
||||||
|
Preis: Nahe Mitternacht ist die Zuordnung bis zu Stunden ungenau. Ein Datum als Anfang und ein Zeitpunkt kurz nach örtlicher Mitternacht als Ende gelten als verdreht; dann gehören beide als Datum oder beide als Zeitpunkt angegeben.
|
||||||
|
|
||||||
|
### Schreibregeln für spätere Operationen
|
||||||
|
|
||||||
|
* Auf einer Seite steht keine Überschrift zweimal.
|
||||||
|
* Aliase stehen immer als `[[Titel|Alias]]`. Obsidian schreibt es selbst so ([Aliase](https://obsidian.md/help/aliases)); dass ein nacktes `[[Alias]]` aufgelöst wird, ist dort nicht dokumentiert.
|
||||||
|
* Fußnoten-Definitionen stehen in einem eigenen Abschnitt am Ende, sonst ändert jedes neue Zitat den Hash des letzten Abschnitts.
|
||||||
|
|
||||||
|
### Konsequenzen
|
||||||
|
|
||||||
|
* Gut, weil Lesen und unverändert Schreiben byte-gleich ist und keine Abhängigkeit nötig wird.
|
||||||
|
* Gut, weil Titel, Dateiname und Linkziel in Obsidian übereinstimmen und die Datei auch außerhalb ihren Titel trägt.
|
||||||
|
* Gut, weil die Überschrift Adresse und der Hash Version ist; das Umbenennen einer Seite macht keinen Job ungültig.
|
||||||
|
* Gut, weil flache Felder in Obsidian sichtbar sind.
|
||||||
|
* Gut, weil jede Quelle eine geordnete oder ausdrücklich unvergleichbare Faktenzeit trägt.
|
||||||
|
* Schlecht, weil spätere Änderungen gezielt Textstücke ersetzen müssen.
|
||||||
|
* Schlecht, weil die Abschnitte größer sind als bei jeder Überschrift als Trenner.
|
||||||
|
* Schlecht, weil Autorität und Form beim Einreichen angegeben werden müssen.
|
||||||
|
* Schlecht, weil die `id` mit 36 Zeichen lang und sehr schwer änderbar ist.
|
||||||
+5
-1
@@ -5,9 +5,10 @@ Feste Begriffspaare Deutsch–Englisch. In der Doku steht das deutsche Wort, im
|
|||||||
| Deutsch | Englisch (Code) | Bedeutung |
|
| Deutsch | Englisch (Code) | Bedeutung |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Abkühlzeit | cooldown | Wartezeit, bevor eine neue Paketversion verwendet wird |
|
| Abkühlzeit | cooldown | Wartezeit, bevor eine neue Paketversion verwendet wird |
|
||||||
|
| Abschnitt | section | Teil einer Seite von einer Überschrift der Ebene 1 oder 2 bis zur nächsten; Einheit der Bearbeitung, adressiert über die Überschrift |
|
||||||
| Adapter | adapter | Implementierung eines Ports für ein konkretes System |
|
| Adapter | adapter | Implementierung eines Ports für ein konkretes System |
|
||||||
| Akzeptanzkriterium | acceptance criterion | prüfbare Bedingung, unter der ein Issue erfüllt ist |
|
| Akzeptanzkriterium | acceptance criterion | prüfbare Bedingung, unter der ein Issue erfüllt ist |
|
||||||
| Alias | alias | Synonym im Frontmatter (`aliases`) für Linkauflösung und Wiedererkennung von Entitäten |
|
| Alias | alias | Synonym im Frontmatter (`aliases`) für Linkvorschläge in Obsidian und Wiedererkennung von Entitäten |
|
||||||
| Altstack | legacy stack | das eingefrorene Repo `torben/chemenu` |
|
| Altstack | legacy stack | das eingefrorene Repo `torben/chemenu` |
|
||||||
| Ampel | traffic light | Klasse (grün, gelb, rot oder Frage) je Operation, die der Code aus Signalen berechnet |
|
| Ampel | traffic light | Klasse (grün, gelb, rot oder Frage) je Operation, die der Code aus Signalen berechnet |
|
||||||
| Änderungsbericht | change report | Bericht eines Jobs über seine Änderungen, auch über strukturelle Ereignisse (angelegt, umbenannt, zusammengeführt, Alias ergänzt) |
|
| Änderungsbericht | change report | Bericht eines Jobs über seine Änderungen, auch über strukturelle Ereignisse (angelegt, umbenannt, zusammengeführt, Alias ergänzt) |
|
||||||
@@ -32,6 +33,7 @@ Feste Begriffspaare Deutsch–Englisch. In der Doku steht das deutsche Wort, im
|
|||||||
| Faktenzeit | fact time | Zeitintervall mit Datierungsgrundlage, das jede Quelle trägt |
|
| Faktenzeit | fact time | Zeitintervall mit Datierungsgrundlage, das jede Quelle trägt |
|
||||||
| Fall (Eval) | eval case | einzelne Eingabe mit erwartetem Ergebnis |
|
| Fall (Eval) | eval case | einzelne Eingabe mit erwartetem Ergebnis |
|
||||||
| Fingerabdruck | fingerprint | Hash über Vorlage und Schemas eines Bausteins |
|
| Fingerabdruck | fingerprint | Hash über Vorlage und Schemas eines Bausteins |
|
||||||
|
| Form (Autorität) | authority form | schriftlich oder mündlich; Pflichtfeld `authority_form` der Quellseite |
|
||||||
| Freigabe | approval | Zustimmung des Betreibers |
|
| Freigabe | approval | Zustimmung des Betreibers |
|
||||||
| Fundstelle | locator | Stelle in der Quelle, die einen Eintrag oder eine Aussage belegt |
|
| Fundstelle | locator | Stelle in der Quelle, die einen Eintrag oder eine Aussage belegt |
|
||||||
| Gesprächspartner | conversation partner | Rolle mit Lesezugriff (search, read), die im Chat mit Zitaten auf Seiten antwortet |
|
| Gesprächspartner | conversation partner | Rolle mit Lesezugriff (search, read), die im Chat mit Zitaten auf Seiten antwortet |
|
||||||
@@ -41,6 +43,7 @@ Feste Begriffspaare Deutsch–Englisch. In der Doku steht das deutsche Wort, im
|
|||||||
| Instanz | instance | eine Wissensbasis als git-Repo samt laufendem Dienst |
|
| Instanz | instance | eine Wissensbasis als git-Repo samt laufendem Dienst |
|
||||||
| Inventar | inventory | Aussagen, Begründungen, Abläufe, Zahlen, Entitäten und Konzepte einer Quelle, je mit Fundstelle |
|
| Inventar | inventory | Aussagen, Begründungen, Abläufe, Zahlen, Entitäten und Konzepte einer Quelle, je mit Fundstelle |
|
||||||
| Job | job | Arbeitsauftrag, den ein Anwendungsfall abarbeitet |
|
| Job | job | Arbeitsauftrag, den ein Anwendungsfall abarbeitet |
|
||||||
|
| Kopf (Seite) | head | Abschnitt ohne Überschrift bis zur ersten trennenden Überschrift, mit fester Adresse; die `#`-Titelzeile gehört dazu, zählt aber nicht in den Hash |
|
||||||
| Korrektur | correction | Notiz mit Ziel (Seite oder Aussage): „Das stimmt nicht, richtig ist …“ |
|
| Korrektur | correction | Notiz mit Ziel (Seite oder Aussage): „Das stimmt nicht, richtig ist …“ |
|
||||||
| Manifest | manifest | Deklaration eines Plugins (M1–M13) |
|
| Manifest | manifest | Deklaration eines Plugins (M1–M13) |
|
||||||
| Nachtrag | addendum | Kommentar zu einer Quelle, als neue Datei in ihr Bundle gelegt |
|
| Nachtrag | addendum | Kommentar zu einer Quelle, als neue Datei in ihr Bundle gelegt |
|
||||||
@@ -71,6 +74,7 @@ Feste Begriffspaare Deutsch–Englisch. In der Doku steht das deutsche Wort, im
|
|||||||
| Tagesnotiz | daily note | Sammlung der Notizen eines Tages, die gebündelt integriert wird |
|
| Tagesnotiz | daily note | Sammlung der Notizen eines Tages, die gebündelt integriert wird |
|
||||||
| Teilanwendung | partial application | grüne Teile eines Jobs laufen sofort, offene warten auf ihre Antwort |
|
| Teilanwendung | partial application | grüne Teile eines Jobs laufen sofort, offene warten auf ihre Antwort |
|
||||||
| Testkorpus | test corpus | kuratierter Korpus von 20–30 Quellen mit erwarteten Eigenschaften, zugleich erster Eval-Satz |
|
| Testkorpus | test corpus | kuratierter Korpus von 20–30 Quellen mit erwarteten Eigenschaften, zugleich erster Eval-Satz |
|
||||||
|
| Titel | title | Dateiname einer Seite ohne `.md`; der Dienst schreibt ihn wörtlich als einzige `#`-Zeile |
|
||||||
| Type-Spec | type spec | legt pro Abschnitt fest, ob er fortgeschrieben oder integriert wird |
|
| Type-Spec | type spec | legt pro Abschnitt fest, ob er fortgeschrieben oder integriert wird |
|
||||||
| Verbleib | disposition | Ort (Seite und Abschnitt) eines Inventar-Eintrags oder Grund, warum er übersprungen wird |
|
| Verbleib | disposition | Ort (Seite und Abschnitt) eines Inventar-Eintrags oder Grund, warum er übersprungen wird |
|
||||||
| Wissensbasis | knowledge base | Gesamtheit der Seiten |
|
| Wissensbasis | knowledge base | Gesamtheit der Seiten |
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""Errors raised by the page domain."""
|
||||||
|
|
||||||
|
|
||||||
|
class PageError(ValueError):
|
||||||
|
"""Base class for all page domain errors."""
|
||||||
|
|
||||||
|
|
||||||
|
class FrontmatterError(PageError):
|
||||||
|
"""Frontmatter is missing, ambiguous or malformed."""
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidPageIdError(PageError):
|
||||||
|
"""A page id is not a lowercase UUIDv7."""
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidTitleError(PageError):
|
||||||
|
"""A page title is not usable as a file name and title line."""
|
||||||
|
|
||||||
|
|
||||||
|
class FactTimeError(PageError):
|
||||||
|
"""A fact time is invalid."""
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidSourceError(PageError):
|
||||||
|
"""A source reference is invalid."""
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""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"
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"""Page identity: id (UUIDv7) and title."""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import unicodedata
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from chemenu.domain.errors import InvalidPageIdError, InvalidTitleError
|
||||||
|
|
||||||
|
_ID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}")
|
||||||
|
_FORBIDDEN_CHARS = frozenset('<>:"/\\|?*[]#^')
|
||||||
|
_LINE_BREAKS = frozenset("\u2028\u2029")
|
||||||
|
_MAX_TITLE_BYTES = 252
|
||||||
|
# Invisible format characters (Cf) are forbidden, except the joiners that some
|
||||||
|
# scripts and emoji sequences need and the tag characters of subdivision flags.
|
||||||
|
_ALLOWED_FORMAT = frozenset("\u200c\u200d")
|
||||||
|
_TAGS = range(0xE0020, 0xE0080)
|
||||||
|
_DEVICE_NAMES = frozenset(
|
||||||
|
{"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"}
|
||||||
|
| {f"{name}{digit}" for name in ("COM", "LPT") for digit in "123456789¹²³"}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class PageId:
|
||||||
|
"""A lowercase UUIDv7 with hyphens."""
|
||||||
|
|
||||||
|
value: str
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if not _ID_RE.fullmatch(self.value):
|
||||||
|
raise InvalidPageIdError(f"invalid page id: {self.value!r}")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class PageTitle:
|
||||||
|
"""A page title that is safe as a file name and as a single title line."""
|
||||||
|
|
||||||
|
value: str
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
reason = _title_problem(self.value)
|
||||||
|
if reason:
|
||||||
|
raise InvalidTitleError(f"invalid title {self.value!r}: {reason}")
|
||||||
|
|
||||||
|
|
||||||
|
def _invisible(char: str) -> bool:
|
||||||
|
return (
|
||||||
|
unicodedata.category(char) == "Cf"
|
||||||
|
and char not in _ALLOWED_FORMAT
|
||||||
|
and ord(char) not in _TAGS
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _title_problem(title: str) -> str | None:
|
||||||
|
if not title:
|
||||||
|
return "empty"
|
||||||
|
if any(0xD800 <= ord(c) <= 0xDFFF for c in title):
|
||||||
|
return "contains surrogates"
|
||||||
|
if any(c in _FORBIDDEN_CHARS for c in title) or "%%" in title:
|
||||||
|
return "contains a forbidden character"
|
||||||
|
if any(unicodedata.category(c) == "Cc" or c in _LINE_BREAKS for c in title):
|
||||||
|
return "contains a control character or line break"
|
||||||
|
if any(_invisible(c) for c in title):
|
||||||
|
return "contains an invisible character"
|
||||||
|
if title.casefold().endswith(".md"):
|
||||||
|
return "ends with .md, which Obsidian reads as the file extension"
|
||||||
|
if title != title.strip() or title.startswith(".") or title.endswith("."):
|
||||||
|
return "starts or ends with whitespace or a dot"
|
||||||
|
if title.split(".", 1)[0].rstrip(" ").upper() in _DEVICE_NAMES:
|
||||||
|
return "is a reserved device name"
|
||||||
|
if not unicodedata.is_normalized("NFC", title):
|
||||||
|
return "is not NFC"
|
||||||
|
if len(title.encode("utf-8")) > _MAX_TITLE_BYTES:
|
||||||
|
return f"longer than {_MAX_TITLE_BYTES} bytes"
|
||||||
|
return None
|
||||||
@@ -0,0 +1,328 @@
|
|||||||
|
"""Length-preserving masking of Markdown code and comments.
|
||||||
|
|
||||||
|
Lines end only at LF, CRLF and CR. ``str.splitlines`` is not used: U+2028,
|
||||||
|
form feed and the like do not separate lines here.
|
||||||
|
|
||||||
|
Blocks (fenced code, HTML comments starting a line) hide everything inside
|
||||||
|
them from heading detection. Whoever opens first wins: a fence inside a comment
|
||||||
|
opens nothing and vice versa. Fences are tracked inside list items and block
|
||||||
|
quotes. Indented code blocks are deliberately not recognised. Inline code spans
|
||||||
|
and comments inside a line are matched within that line only, so that a missing
|
||||||
|
backtick or ``-->`` cannot swallow the rest of the page.
|
||||||
|
|
||||||
|
Masked text has the same length and the same line endings as the input, so
|
||||||
|
offsets stay valid.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
_LINE_RE = re.compile(r"[^\r\n]*(?:\r\n|\r|\n)|[^\r\n]+")
|
||||||
|
_NOT_EOL_RE = re.compile(r"[^\r\n]")
|
||||||
|
_BACKTICKS_RE = re.compile(r"`+")
|
||||||
|
_OPENER_RE = re.compile(r"`+|<!--")
|
||||||
|
_MAX_DEPTH = 32 # open containers; bounds the work per line
|
||||||
|
_QUOTE = -1 # stack entry of a block quote; list entries hold their content column
|
||||||
|
|
||||||
|
|
||||||
|
def split_lines(text: str) -> tuple[str, ...]:
|
||||||
|
"""Split into lines, each keeping its ending (LF, CRLF or CR)."""
|
||||||
|
return tuple(_LINE_RE.findall(text))
|
||||||
|
|
||||||
|
|
||||||
|
def line_content(line: str) -> str:
|
||||||
|
"""The line without its ending."""
|
||||||
|
return line.rstrip("\r\n")
|
||||||
|
|
||||||
|
|
||||||
|
def is_blank(line: str) -> bool:
|
||||||
|
"""Whether the line holds only spaces and tabs (and its ending)."""
|
||||||
|
return not line.strip(" \t\r\n")
|
||||||
|
|
||||||
|
|
||||||
|
def _blank(text: str) -> str:
|
||||||
|
return _NOT_EOL_RE.sub(" ", text)
|
||||||
|
|
||||||
|
|
||||||
|
def _fence_opener(rest: str) -> tuple[str, int] | None:
|
||||||
|
"""Fence character and length if ``rest`` (indent stripped) opens a fence."""
|
||||||
|
if not rest or rest[0] not in "`~":
|
||||||
|
return None
|
||||||
|
char = rest[0]
|
||||||
|
count = len(rest) - len(rest.lstrip(char))
|
||||||
|
if count < 3:
|
||||||
|
return None
|
||||||
|
if char == "`" and "`" in rest[count:]:
|
||||||
|
return None
|
||||||
|
return char, count
|
||||||
|
|
||||||
|
|
||||||
|
def _fence_closes(rest: str, char: str, count: int) -> bool:
|
||||||
|
rest = rest.rstrip(" \t")
|
||||||
|
return len(rest) >= count and rest == char * len(rest)
|
||||||
|
|
||||||
|
|
||||||
|
def _skip_ws(content: str, pos: int, col: int, virt: int) -> tuple[int, int]:
|
||||||
|
"""Skip spaces and tabs (4-column tab stops); return position and column.
|
||||||
|
|
||||||
|
``col`` is the column of the first unconsumed cell and ``virt`` the number
|
||||||
|
of cells of a partly consumed tab that still precede ``content[pos]``.
|
||||||
|
"""
|
||||||
|
cell = col + virt
|
||||||
|
while pos < len(content):
|
||||||
|
char = content[pos]
|
||||||
|
if char == " ":
|
||||||
|
cell += 1
|
||||||
|
elif char == "\t":
|
||||||
|
cell += 4 - cell % 4
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
pos += 1
|
||||||
|
return pos, cell
|
||||||
|
|
||||||
|
|
||||||
|
def _advance(content: str, pos: int, col: int, virt: int, target: int) -> tuple[int, int, int]:
|
||||||
|
"""Consume whitespace cells up to column ``target`` (at least that much exists)."""
|
||||||
|
take = min(virt, target - col)
|
||||||
|
col += take
|
||||||
|
virt -= take
|
||||||
|
while col < target:
|
||||||
|
width = 1 if content[pos] == " " else 4 - col % 4
|
||||||
|
pos += 1
|
||||||
|
if col + width > target:
|
||||||
|
return pos, target, col + width - target
|
||||||
|
col += width
|
||||||
|
return pos, col, virt
|
||||||
|
|
||||||
|
|
||||||
|
def _after_marker(content: str, pos: int, col: int) -> tuple[int, int, int]:
|
||||||
|
"""Cursor after the one optional space or tab that follows a marker."""
|
||||||
|
if pos < len(content) and content[pos] == " ":
|
||||||
|
return pos + 1, col + 1, 0
|
||||||
|
if pos < len(content) and content[pos] == "\t":
|
||||||
|
return pos + 1, col + 1, 3 - col % 4
|
||||||
|
return pos, col, 0
|
||||||
|
|
||||||
|
|
||||||
|
def _list_marker_end(content: str, pos: int) -> int:
|
||||||
|
"""End index of a list marker at ``pos`` (followed by blank or end), else -1."""
|
||||||
|
char = content[pos]
|
||||||
|
end = pos + 1
|
||||||
|
if char in "0123456789":
|
||||||
|
while end < len(content) and content[end] in "0123456789":
|
||||||
|
end += 1
|
||||||
|
if end - pos > 9 or end >= len(content) or content[end] not in ".)":
|
||||||
|
return -1
|
||||||
|
end += 1
|
||||||
|
elif char not in "-*+":
|
||||||
|
return -1
|
||||||
|
if end < len(content) and content[end] not in " \t":
|
||||||
|
return -1
|
||||||
|
return end
|
||||||
|
|
||||||
|
|
||||||
|
def _thematic_tail(content: str) -> tuple[str, int] | None:
|
||||||
|
"""Character and start of a trailing run of ``-`` or ``*`` and blanks."""
|
||||||
|
stripped = content.rstrip(" \t")
|
||||||
|
if not stripped or stripped[-1] not in "-*":
|
||||||
|
return None
|
||||||
|
char = stripped[-1]
|
||||||
|
i = len(stripped)
|
||||||
|
while i > 0 and stripped[i - 1] in (char, " ", "\t"):
|
||||||
|
i -= 1
|
||||||
|
return char, i
|
||||||
|
|
||||||
|
|
||||||
|
class _Scanner:
|
||||||
|
"""Line-by-line tracking of fences and comment blocks in their containers.
|
||||||
|
|
||||||
|
Containers are block quotes and list items (CommonMark, simplified: no
|
||||||
|
lazy continuation, so an unindented line always ends open lists and
|
||||||
|
quotes). A fence ends when its container ends.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.stack: list[int] = []
|
||||||
|
self.fence: tuple[str, int, int] | None = None # char, length, container depth
|
||||||
|
self.in_comment = False
|
||||||
|
|
||||||
|
def _match(self, content: str) -> tuple[int, int, int, int]:
|
||||||
|
"""Number of open containers this line continues, and the cursor."""
|
||||||
|
pos = col = virt = matched = 0
|
||||||
|
for item in self.stack:
|
||||||
|
start, cell = _skip_ws(content, pos, col, virt)
|
||||||
|
if item == _QUOTE:
|
||||||
|
if cell - col > 3 or start >= len(content) or content[start] != ">":
|
||||||
|
break
|
||||||
|
pos, col, virt = _after_marker(content, start + 1, cell + 1)
|
||||||
|
elif start >= len(content):
|
||||||
|
pass # a blank line continues a list item
|
||||||
|
elif cell >= item:
|
||||||
|
pos, col, virt = _advance(content, pos, col, virt, item)
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
matched += 1
|
||||||
|
return matched, pos, col, virt
|
||||||
|
|
||||||
|
def _open(self, content: str, pos: int, col: int, virt: int) -> tuple[int, int, int]:
|
||||||
|
"""Open new containers at the cursor; return the cursor behind them."""
|
||||||
|
tail: tuple[str, int] | bool | None = False
|
||||||
|
while True:
|
||||||
|
start, cell = _skip_ws(content, pos, col, virt)
|
||||||
|
if start >= len(content) or cell - col > 3 or len(self.stack) >= _MAX_DEPTH:
|
||||||
|
return pos, col, virt
|
||||||
|
if content[start] == ">":
|
||||||
|
self.stack.append(_QUOTE)
|
||||||
|
pos, col, virt = _after_marker(content, start + 1, cell + 1)
|
||||||
|
continue
|
||||||
|
end = _list_marker_end(content, start)
|
||||||
|
if end < 0:
|
||||||
|
return pos, col, virt
|
||||||
|
if content[start] in "-*":
|
||||||
|
if tail is False:
|
||||||
|
tail = _thematic_tail(content)
|
||||||
|
if (
|
||||||
|
tail is not None
|
||||||
|
and tail[0] == content[start]
|
||||||
|
and start >= tail[1]
|
||||||
|
and content.count(tail[0], start) >= 3
|
||||||
|
):
|
||||||
|
return pos, col, virt # thematic break
|
||||||
|
mark = cell + end - start
|
||||||
|
after, after_col = _skip_ws(content, end, mark, 0)
|
||||||
|
if after >= len(content) or after_col - mark >= 5:
|
||||||
|
self.stack.append(mark + 1)
|
||||||
|
if end < len(content) and content[end] == "\t":
|
||||||
|
pos, col, virt = end + 1, mark + 1, 3 - mark % 4
|
||||||
|
else:
|
||||||
|
pos, col, virt = min(end + 1, len(content)), mark + 1, 0
|
||||||
|
else:
|
||||||
|
self.stack.append(after_col)
|
||||||
|
pos, col, virt = after, after_col, 0
|
||||||
|
|
||||||
|
def line(self, content: str) -> int | None:
|
||||||
|
"""None for a normal line; else how many leading characters to mask."""
|
||||||
|
size = len(content)
|
||||||
|
if self.in_comment:
|
||||||
|
end = content.find("-->")
|
||||||
|
if end < 0:
|
||||||
|
return size
|
||||||
|
self.in_comment = False
|
||||||
|
return end + 3
|
||||||
|
matched, pos, col, virt = self._match(content)
|
||||||
|
if self.fence is not None:
|
||||||
|
char, count, depth = self.fence
|
||||||
|
if matched >= depth:
|
||||||
|
start, cell = _skip_ws(content, pos, col, virt)
|
||||||
|
if cell - col <= 3 and _fence_closes(content[start:], char, count):
|
||||||
|
self.fence = None
|
||||||
|
return size
|
||||||
|
self.fence = None # the container ended, so does the fence
|
||||||
|
del self.stack[matched:]
|
||||||
|
pos, col, virt = self._open(content, pos, col, virt)
|
||||||
|
start, cell = _skip_ws(content, pos, col, virt)
|
||||||
|
if start >= size or cell - col > 3:
|
||||||
|
return None
|
||||||
|
rest = content[start:]
|
||||||
|
opener = _fence_opener(rest)
|
||||||
|
if opener is not None:
|
||||||
|
self.fence = (opener[0], opener[1], len(self.stack))
|
||||||
|
return size
|
||||||
|
if not self.stack and rest.startswith("<!--"):
|
||||||
|
end = content.find("-->", start + 2)
|
||||||
|
if end < 0:
|
||||||
|
self.in_comment = True
|
||||||
|
return size
|
||||||
|
return end + 3
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def block_lines(lines: tuple[str, ...]) -> tuple[bool, ...]:
|
||||||
|
"""Flag the lines inside fenced code blocks and line-initial HTML comments.
|
||||||
|
|
||||||
|
A fence block runs from its opener to its closer, both inclusive, to the
|
||||||
|
end of its container (list item or block quote) or to the end of the text.
|
||||||
|
A comment block starts on a top-level line with at most three spaces of
|
||||||
|
indent before ``<!--`` and ends with the first line containing ``-->``.
|
||||||
|
Lines with a comment end still count as comment lines as a whole.
|
||||||
|
|
||||||
|
Limits: indented code (four or more columns relative to the container) is
|
||||||
|
not recognised and opens no fence; lazy continuation lines are simplified
|
||||||
|
(a line with less indent than a list item or without ``>`` ends it); comment
|
||||||
|
blocks are recognised only outside containers; containers count up to a
|
||||||
|
depth of 32.
|
||||||
|
"""
|
||||||
|
scanner = _Scanner()
|
||||||
|
return tuple(scanner.line(line_content(line)) is not None for line in lines)
|
||||||
|
|
||||||
|
|
||||||
|
def _escaped(content: str, index: int, low: int) -> bool:
|
||||||
|
"""Whether an odd number of backslashes precedes ``index``."""
|
||||||
|
start = index
|
||||||
|
while start > low and content[start - 1] == "\\":
|
||||||
|
start -= 1
|
||||||
|
return (index - start) % 2 == 1
|
||||||
|
|
||||||
|
|
||||||
|
def _mask_line(content: str, begin: int = 0) -> str:
|
||||||
|
"""Mask inline code spans and complete HTML comments from ``begin`` on.
|
||||||
|
|
||||||
|
A backslash escapes a backtick or ``<!--`` outside code spans only.
|
||||||
|
"""
|
||||||
|
runs: list[tuple[int, int, int]] = [] # opener start, run end, run start
|
||||||
|
for m in _BACKTICKS_RE.finditer(content, begin):
|
||||||
|
opener = m.start() + 1 if _escaped(content, m.start(), begin) else m.start()
|
||||||
|
runs.append((opener, m.end(), m.start()))
|
||||||
|
# For each run the end of the next run of the length it opens, -1 without one.
|
||||||
|
closing = [-1] * len(runs)
|
||||||
|
seen: dict[int, int] = {}
|
||||||
|
for i in range(len(runs) - 1, -1, -1):
|
||||||
|
opener, end, start = runs[i]
|
||||||
|
closing[i] = seen.get(end - opener, -1) if end > opener else -1
|
||||||
|
seen[end - start] = end
|
||||||
|
spans = {
|
||||||
|
opener: close for (opener, _, _), close in zip(runs, closing, strict=True) if close >= 0
|
||||||
|
}
|
||||||
|
out: list[str] = [" " * begin]
|
||||||
|
pos = begin
|
||||||
|
last_comment_end = content.rfind("-->")
|
||||||
|
for match in _OPENER_RE.finditer(content, begin):
|
||||||
|
start = match.start()
|
||||||
|
if match[0] == "<!--":
|
||||||
|
if _escaped(content, start, begin) or last_comment_end < start + 2:
|
||||||
|
continue
|
||||||
|
end = content.index("-->", start + 2) + 3
|
||||||
|
else:
|
||||||
|
if _escaped(content, start, begin):
|
||||||
|
start += 1
|
||||||
|
end = spans.get(start, -1)
|
||||||
|
if end < 0:
|
||||||
|
continue
|
||||||
|
if start < pos:
|
||||||
|
continue
|
||||||
|
out.append(content[pos:start] + " " * (end - start))
|
||||||
|
pos = end
|
||||||
|
return "".join(out) + content[pos:]
|
||||||
|
|
||||||
|
|
||||||
|
def mask_code(body: str) -> str:
|
||||||
|
"""Replace code and comments by spaces, keeping length and line endings.
|
||||||
|
|
||||||
|
Masks fenced blocks, line-initial HTML comments (up to and including their
|
||||||
|
``-->``; the rest of the line counts normally), inline code spans (per
|
||||||
|
line, equal-length backtick runs) and HTML comments within a line.
|
||||||
|
"""
|
||||||
|
scanner = _Scanner()
|
||||||
|
out: list[str] = []
|
||||||
|
for line in split_lines(body):
|
||||||
|
content = line_content(line)
|
||||||
|
masked = scanner.line(content)
|
||||||
|
if masked is None:
|
||||||
|
out.append(_mask_line(content))
|
||||||
|
elif masked >= len(content):
|
||||||
|
out.append(_blank(content))
|
||||||
|
else:
|
||||||
|
out.append(_mask_line(content, masked))
|
||||||
|
out.append(line[len(content) :])
|
||||||
|
return "".join(out)
|
||||||
@@ -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,94 @@
|
|||||||
|
"""Split a page body into sections, each with a content hash."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from chemenu.domain.markdown import block_lines, is_blank, line_content, split_lines
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class SectionKey:
|
||||||
|
"""Identifies a section: heading text and its n-th occurrence on the page."""
|
||||||
|
|
||||||
|
heading: str | None # None: head of the page
|
||||||
|
occurrence: int = 1
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Section:
|
||||||
|
"""A section: raw text (heading included) and a hash of its content."""
|
||||||
|
|
||||||
|
key: SectionKey
|
||||||
|
text: str # raw, incl. heading; all texts joined == body
|
||||||
|
version: str # SHA-256, hex
|
||||||
|
|
||||||
|
|
||||||
|
def _heading(content: str) -> tuple[int, str] | None:
|
||||||
|
"""Level and text of an ATX heading line, else None."""
|
||||||
|
indent = len(content) - len(content.lstrip(" "))
|
||||||
|
if indent > 3:
|
||||||
|
return None
|
||||||
|
rest = content[indent:]
|
||||||
|
level = len(rest) - len(rest.lstrip("#"))
|
||||||
|
if not 1 <= level <= 6:
|
||||||
|
return None
|
||||||
|
after = rest[level:]
|
||||||
|
if after and after[0] not in " \t":
|
||||||
|
return None
|
||||||
|
text = after.strip(" \t")
|
||||||
|
j = len(text)
|
||||||
|
while j > 0 and text[j - 1] == "#":
|
||||||
|
j -= 1
|
||||||
|
if j == 0:
|
||||||
|
text = ""
|
||||||
|
elif text[j - 1] in " \t":
|
||||||
|
text = text[:j].rstrip(" \t")
|
||||||
|
return level, text
|
||||||
|
|
||||||
|
|
||||||
|
def _version(lines: list[str]) -> str:
|
||||||
|
"""Hash lines: LF endings, blank edge lines and the last ending dropped."""
|
||||||
|
contents = [line_content(line) for line in lines]
|
||||||
|
start, end = 0, len(contents)
|
||||||
|
while start < end and is_blank(contents[start]):
|
||||||
|
start += 1
|
||||||
|
while start < end and is_blank(contents[end - 1]):
|
||||||
|
end -= 1
|
||||||
|
return hashlib.sha256("\n".join(contents[start:end]).encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def split_sections(body: str) -> tuple[Section, ...]:
|
||||||
|
"""Split into sections; the first one is always the head.
|
||||||
|
|
||||||
|
Separating are ATX headings of level 1 and 2 outside code blocks and HTML
|
||||||
|
comments, except a level-1 line that is the first non-blank line (page
|
||||||
|
title, part of the head). Deeper and setext headings do not separate.
|
||||||
|
"""
|
||||||
|
lines = split_lines(body)
|
||||||
|
flags = block_lines(lines)
|
||||||
|
first = next((i for i, line in enumerate(lines) if not is_blank(line)), None)
|
||||||
|
# (start index, heading text, index of first hashed line)
|
||||||
|
starts: list[tuple[int, str | None, int]] = [(0, None, 0)]
|
||||||
|
for i, line in enumerate(lines):
|
||||||
|
if flags[i]:
|
||||||
|
continue
|
||||||
|
found = _heading(line_content(line))
|
||||||
|
if found is None or found[0] > 2:
|
||||||
|
continue
|
||||||
|
if i == first and found[0] == 1:
|
||||||
|
starts[0] = (0, None, i + 1)
|
||||||
|
continue
|
||||||
|
starts.append((i, found[1], i + 1))
|
||||||
|
counts: dict[str, int] = {}
|
||||||
|
sections: list[Section] = []
|
||||||
|
for n, (start, heading, hashed) in enumerate(starts):
|
||||||
|
end = starts[n + 1][0] if n + 1 < len(starts) else len(lines)
|
||||||
|
if heading is None:
|
||||||
|
key = SectionKey(None)
|
||||||
|
else:
|
||||||
|
counts[heading] = counts.get(heading, 0) + 1
|
||||||
|
key = SectionKey(heading, counts[heading])
|
||||||
|
sections.append(Section(key, "".join(lines[start:end]), _version(list(lines[hashed:end]))))
|
||||||
|
return tuple(sections)
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
"""Sources: dating basis, authority and fact time."""
|
||||||
|
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import UTC, date, datetime, time, timedelta
|
||||||
|
from enum import StrEnum
|
||||||
|
|
||||||
|
from chemenu.domain.errors import FactTimeError
|
||||||
|
|
||||||
|
|
||||||
|
class DatingBasis(StrEnum):
|
||||||
|
"""Where the fact time of a source comes from."""
|
||||||
|
|
||||||
|
CAPTURED = "captured"
|
||||||
|
RECEIVED = "received"
|
||||||
|
EMAIL_HEADER = "email_header"
|
||||||
|
GIT_COMMIT = "git_commit"
|
||||||
|
HTML_METADATA = "html_metadata"
|
||||||
|
EXIF = "exif"
|
||||||
|
FILENAME = "filename"
|
||||||
|
CONTENT = "content"
|
||||||
|
DOCUMENT_METADATA = "document_metadata"
|
||||||
|
OPERATOR = "operator"
|
||||||
|
|
||||||
|
|
||||||
|
class Authority(StrEnum):
|
||||||
|
"""How authoritative a source is. Enum order is the scale; no comparisons."""
|
||||||
|
|
||||||
|
OFFICIAL = "official"
|
||||||
|
ORGANIZATION = "organization"
|
||||||
|
THIRD_PARTY = "third_party"
|
||||||
|
HEARSAY = "hearsay"
|
||||||
|
|
||||||
|
|
||||||
|
class AuthorityForm(StrEnum):
|
||||||
|
"""Whether the source was written or spoken."""
|
||||||
|
|
||||||
|
WRITTEN = "written"
|
||||||
|
ORAL = "oral"
|
||||||
|
|
||||||
|
|
||||||
|
_DATE = r"[0-9]{4}-[0-9]{2}-[0-9]{2}"
|
||||||
|
_POINT_RE = re.compile(
|
||||||
|
rf"{_DATE}(?:T(?:[01][0-9]|2[0-3]):[0-9]{{2}}(?::[0-9]{{2}}(?:\.[0-9]{{1,6}})?)?"
|
||||||
|
r"(?:Z|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9]))?"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_point(text: str) -> date | datetime:
|
||||||
|
"""Parse a date (`YYYY-MM-DD`) or an ISO datetime with `T` and time zone."""
|
||||||
|
if _POINT_RE.fullmatch(text) is None:
|
||||||
|
raise FactTimeError(f"invalid point in time: {text!r}")
|
||||||
|
try:
|
||||||
|
if "T" not in text:
|
||||||
|
return date.fromisoformat(text)
|
||||||
|
return datetime.fromisoformat(text)
|
||||||
|
except (ValueError, OverflowError) as exc:
|
||||||
|
raise FactTimeError(f"invalid point in time: {text!r}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def format_point(point: date | datetime) -> str:
|
||||||
|
"""Inverse of `parse_point`."""
|
||||||
|
if not isinstance(point, datetime):
|
||||||
|
return point.isoformat()
|
||||||
|
offset = _offset(point)
|
||||||
|
if offset.total_seconds() % 60 != 0:
|
||||||
|
raise FactTimeError(f"unsupported UTC offset: {offset}")
|
||||||
|
return point.isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def _offset(point: datetime) -> timedelta:
|
||||||
|
offset = point.utcoffset()
|
||||||
|
if offset is None:
|
||||||
|
raise FactTimeError("naive datetime is not allowed")
|
||||||
|
return offset
|
||||||
|
|
||||||
|
|
||||||
|
def _to_utc(point: date | datetime, *, end: bool) -> datetime:
|
||||||
|
"""Bound of a point in UTC; a date covers the whole UTC day."""
|
||||||
|
if isinstance(point, datetime):
|
||||||
|
_offset(point)
|
||||||
|
try:
|
||||||
|
return point.astimezone(UTC)
|
||||||
|
except OverflowError as exc:
|
||||||
|
raise FactTimeError("point in time not representable in UTC") from exc
|
||||||
|
return datetime.combine(point, time.max if end else time.min, tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||||
|
class FactTime:
|
||||||
|
"""Interval in which a source's facts hold; `earliest` may be unknown."""
|
||||||
|
|
||||||
|
earliest: date | datetime | None
|
||||||
|
latest: date | datetime
|
||||||
|
basis: DatingBasis
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
end = _to_utc(self.latest, end=True)
|
||||||
|
if self.earliest is not None and _to_utc(self.earliest, end=False) > end:
|
||||||
|
raise FactTimeError("fact time starts after it ends")
|
||||||
|
|
||||||
|
def precedes(self, other: FactTime) -> bool:
|
||||||
|
"""True if this ends strictly before `other` starts."""
|
||||||
|
if other.earliest is None:
|
||||||
|
return False
|
||||||
|
return _to_utc(self.latest, end=True) < _to_utc(other.earliest, end=False)
|
||||||
@@ -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")
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
"""Find wiki links in a page body."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from chemenu.domain.markdown import line_content, mask_code, split_lines
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class WikiLink:
|
||||||
|
"""A link ``[[target#anchor|text]]``; ``embed`` for ``![[...]]``."""
|
||||||
|
|
||||||
|
target: str
|
||||||
|
anchor: str | None = None
|
||||||
|
text: str | None = None
|
||||||
|
embed: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
def _parse(raw: str, masked: str, embed: bool) -> WikiLink | None:
|
||||||
|
"""Parse the inside of a link; ``masked`` locates the separators in ``raw``."""
|
||||||
|
bar = masked.find("|")
|
||||||
|
text: str | None
|
||||||
|
if bar >= 0:
|
||||||
|
head_end = bar - 1 if bar > 0 and masked[bar - 1] == "\\" else bar
|
||||||
|
text = raw[bar + 1 :].replace("\\|", "|")
|
||||||
|
else:
|
||||||
|
head_end = len(raw)
|
||||||
|
text = None
|
||||||
|
head = raw[:head_end]
|
||||||
|
hash_ = masked.find("#", 0, head_end)
|
||||||
|
target = (head[:hash_] if hash_ >= 0 else head).strip()
|
||||||
|
if not target:
|
||||||
|
return None
|
||||||
|
anchor = head[hash_ + 1 :].strip() if hash_ >= 0 else ""
|
||||||
|
return WikiLink(
|
||||||
|
target,
|
||||||
|
anchor or None,
|
||||||
|
(text.strip() or None) if text is not None else None,
|
||||||
|
embed,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _escaped(line: str, index: int) -> bool:
|
||||||
|
start = index
|
||||||
|
while start > 0 and line[start - 1] == "\\":
|
||||||
|
start -= 1
|
||||||
|
return (index - start) % 2 == 1
|
||||||
|
|
||||||
|
|
||||||
|
def _links_in_line(raw: str, line: str) -> list[WikiLink]:
|
||||||
|
"""Links of one line; ``line`` is ``raw`` with code and comments masked."""
|
||||||
|
links: list[WikiLink] = []
|
||||||
|
pos = 0
|
||||||
|
close = -2
|
||||||
|
while True:
|
||||||
|
i = line.find("[[", pos)
|
||||||
|
if i < 0:
|
||||||
|
return links
|
||||||
|
# In "[[[x]]" the link opens at the last of the leading brackets.
|
||||||
|
while line.startswith("[", i + 2):
|
||||||
|
i += 1
|
||||||
|
if _escaped(line, i):
|
||||||
|
pos = i + 1
|
||||||
|
continue
|
||||||
|
if close < i + 2:
|
||||||
|
close = line.find("]]", i + 2)
|
||||||
|
if close < 0:
|
||||||
|
return links
|
||||||
|
nested = line.find("[[", i + 2, close)
|
||||||
|
if nested >= 0:
|
||||||
|
pos = nested
|
||||||
|
continue
|
||||||
|
link = _parse(raw[i + 2 : close], line[i + 2 : close], embed=i > 0 and line[i - 1] == "!")
|
||||||
|
if link is not None:
|
||||||
|
links.append(link)
|
||||||
|
pos = close + 2
|
||||||
|
|
||||||
|
|
||||||
|
def find_wikilinks(body: str) -> tuple[WikiLink, ...]:
|
||||||
|
"""All wiki links in order, duplicates kept.
|
||||||
|
|
||||||
|
Forms: ``[[T]]``, ``[[T|text]]``, ``[[T\\|text]]`` (escaped bar counts as
|
||||||
|
``|``), ``[[T#anchor]]``, ``![[T]]`` (embed). The anchor is everything after
|
||||||
|
the first ``#``; ``[[#X]]`` has no target and is no link. Target, anchor and
|
||||||
|
text are trimmed; an empty anchor or text is None. A link stays within one
|
||||||
|
line and contains no ``[[`` or ``]]``; it ends at the first ``]]``, so text
|
||||||
|
may hold single brackets (``[[T|a [b] c]]``) but not end in ``]``.
|
||||||
|
|
||||||
|
A backslash before the first bracket (``\\[[A]]``) makes it no link; two
|
||||||
|
backslashes cancel out. Code blocks (also in lists and quotes), inline code
|
||||||
|
and HTML comments are ignored as link markup; inside a link they are part of
|
||||||
|
target, anchor and text (``[[Use `x` now]]``). Indented code is not
|
||||||
|
recognised; lazy continuation lines are simplified (see ``block_lines``).
|
||||||
|
"""
|
||||||
|
links: list[WikiLink] = []
|
||||||
|
for raw, masked in zip(split_lines(body), split_lines(mask_code(body)), strict=True):
|
||||||
|
links.extend(_links_in_line(line_content(raw), line_content(masked)))
|
||||||
|
return tuple(links)
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
from datetime import UTC, date, datetime, timedelta, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from chemenu.domain.errors import FactTimeError
|
||||||
|
from chemenu.domain.source import (
|
||||||
|
Authority,
|
||||||
|
AuthorityForm,
|
||||||
|
DatingBasis,
|
||||||
|
FactTime,
|
||||||
|
format_point,
|
||||||
|
parse_point,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _ft(earliest: date | datetime | None, latest: date | datetime) -> FactTime:
|
||||||
|
return FactTime(earliest=earliest, latest=latest, basis=DatingBasis.CAPTURED)
|
||||||
|
|
||||||
|
|
||||||
|
def test_enum_values() -> None:
|
||||||
|
assert DatingBasis.EMAIL_HEADER == "email_header"
|
||||||
|
assert Authority.THIRD_PARTY == "third_party"
|
||||||
|
assert AuthorityForm.ORAL == "oral"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"text",
|
||||||
|
[
|
||||||
|
"2026-11-28",
|
||||||
|
"2026-11-28T14:32:00+01:00",
|
||||||
|
"2026-11-28T14:32:00+00:00",
|
||||||
|
"2026-11-28T14:32:00.123456-05:30",
|
||||||
|
"2026-11-28T14:32:00.5+01:00",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_points_round_trip(text: str) -> None:
|
||||||
|
point = parse_point(text)
|
||||||
|
again = parse_point(format_point(point))
|
||||||
|
assert again == point
|
||||||
|
assert type(again) is type(point)
|
||||||
|
if isinstance(point, datetime):
|
||||||
|
assert isinstance(again, datetime)
|
||||||
|
assert again.utcoffset() == point.utcoffset()
|
||||||
|
|
||||||
|
|
||||||
|
def test_points_z_and_missing_seconds() -> None:
|
||||||
|
z = parse_point("2026-11-28T14:32:00Z")
|
||||||
|
assert isinstance(z, datetime)
|
||||||
|
assert z.utcoffset() == timedelta(0)
|
||||||
|
short = parse_point("2026-11-28T14:32+01:00")
|
||||||
|
assert isinstance(short, datetime)
|
||||||
|
assert short.second == 0
|
||||||
|
assert parse_point("2026-11-28") == date(2026, 11, 28)
|
||||||
|
assert not isinstance(parse_point("2026-11-28"), datetime)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"text",
|
||||||
|
[
|
||||||
|
"",
|
||||||
|
"20261128",
|
||||||
|
"2026-W48-6",
|
||||||
|
"2026-11-28 14:32:00+01:00",
|
||||||
|
" 2026-11-28",
|
||||||
|
"2026-11-28 ",
|
||||||
|
"2026-11-28T14:32:00+01:00\n",
|
||||||
|
"2026-11-28t14:32:00+01:00",
|
||||||
|
"2026-11-28T14:32:00z",
|
||||||
|
chr(0xFF12) + "026-11-28",
|
||||||
|
"2026-02-30",
|
||||||
|
"2026-13-01",
|
||||||
|
"2026-11-28T24:00:00+01:00",
|
||||||
|
"2026-11-28T14:32:00",
|
||||||
|
"2026-11-28T14:32:00.1234567+01:00",
|
||||||
|
"2026-11-28T14:32:00+01:00:30",
|
||||||
|
"2026-11-28T14:32:00+0100",
|
||||||
|
"2026-11-28T14:32:00+01:99",
|
||||||
|
"2026-11-28T14:32:00+24:00",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_invalid_point_raises(text: str) -> None:
|
||||||
|
with pytest.raises(FactTimeError):
|
||||||
|
parse_point(text)
|
||||||
|
|
||||||
|
|
||||||
|
def test_naive_datetime_raises() -> None:
|
||||||
|
naive = datetime(2026, 11, 28, 14, 32)
|
||||||
|
with pytest.raises(FactTimeError):
|
||||||
|
format_point(naive)
|
||||||
|
with pytest.raises(FactTimeError):
|
||||||
|
_ft(naive, date(2026, 12, 1))
|
||||||
|
with pytest.raises(FactTimeError):
|
||||||
|
_ft(None, naive)
|
||||||
|
|
||||||
|
|
||||||
|
def test_exotic_offset_raises() -> None:
|
||||||
|
tz = timezone(timedelta(hours=1, seconds=30))
|
||||||
|
with pytest.raises(FactTimeError):
|
||||||
|
format_point(datetime(2026, 1, 1, tzinfo=tz))
|
||||||
|
|
||||||
|
|
||||||
|
def test_utc_overflow_raises() -> None:
|
||||||
|
tz = timezone(timedelta(hours=1))
|
||||||
|
with pytest.raises(FactTimeError):
|
||||||
|
_ft(None, datetime.min.replace(tzinfo=tz))
|
||||||
|
with pytest.raises(FactTimeError):
|
||||||
|
_ft(None, datetime.max.replace(tzinfo=timezone(-timedelta(hours=1))))
|
||||||
|
|
||||||
|
|
||||||
|
def test_reversed_interval_raises() -> None:
|
||||||
|
with pytest.raises(FactTimeError):
|
||||||
|
_ft(date(2026, 12, 2), date(2026, 12, 1))
|
||||||
|
a = datetime(2026, 11, 28, 14, 0, tzinfo=UTC)
|
||||||
|
with pytest.raises(FactTimeError):
|
||||||
|
_ft(a, a - timedelta(microseconds=1))
|
||||||
|
# same instant in different zones is valid
|
||||||
|
_ft(a, a.astimezone(timezone(timedelta(hours=2))))
|
||||||
|
# equal dates, and date start with datetime end on same UTC day
|
||||||
|
_ft(date(2026, 12, 1), date(2026, 12, 1))
|
||||||
|
_ft(date(2026, 12, 1), datetime(2026, 12, 1, 0, 0, tzinfo=UTC))
|
||||||
|
# a date means its UTC day: 00:30 in Berlin still belongs to the day before
|
||||||
|
with pytest.raises(FactTimeError):
|
||||||
|
_ft(date(2026, 11, 28), datetime(2026, 11, 28, 0, 30, tzinfo=timezone(timedelta(hours=1))))
|
||||||
|
# stored as given
|
||||||
|
tz = timezone(timedelta(hours=1))
|
||||||
|
end = datetime(2026, 12, 1, 10, tzinfo=tz)
|
||||||
|
kept = _ft(None, end).latest
|
||||||
|
assert isinstance(kept, datetime)
|
||||||
|
assert kept.utcoffset() == timedelta(hours=1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_precedes() -> None:
|
||||||
|
a = _ft(None, date(2026, 11, 28))
|
||||||
|
b = _ft(date(2026, 11, 29), date(2026, 12, 1))
|
||||||
|
assert a.precedes(b)
|
||||||
|
assert not b.precedes(a)
|
||||||
|
# touching: end 23:59:59.999999 vs start next day 00:00 is strictly before
|
||||||
|
assert a.precedes(_ft(date(2026, 11, 29), date(2026, 11, 29)))
|
||||||
|
# same day: not strictly before
|
||||||
|
assert not a.precedes(_ft(date(2026, 11, 28), date(2026, 11, 28)))
|
||||||
|
t = datetime(2026, 11, 28, 12, tzinfo=UTC)
|
||||||
|
assert _ft(None, t).precedes(_ft(t + timedelta(seconds=1), t + timedelta(days=1)))
|
||||||
|
assert not _ft(None, t).precedes(_ft(t, t))
|
||||||
|
# date.max / date.min do not overflow
|
||||||
|
assert not _ft(None, date.max).precedes(_ft(date.max, date.max))
|
||||||
|
assert _ft(date.min, date.min).precedes(_ft(date.max, date.max))
|
||||||
|
|
||||||
|
|
||||||
|
def test_overlap_is_unordered() -> None:
|
||||||
|
a = _ft(date(2026, 11, 1), date(2026, 11, 20))
|
||||||
|
b = _ft(date(2026, 11, 10), date(2026, 11, 30))
|
||||||
|
assert not a.precedes(b)
|
||||||
|
assert not b.precedes(a)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_start_never_follows() -> None:
|
||||||
|
a = _ft(date(2020, 1, 1), date(2020, 1, 2))
|
||||||
|
b = _ft(None, date(2030, 1, 1))
|
||||||
|
assert not a.precedes(b)
|
||||||
|
assert not b.precedes(b)
|
||||||
|
|
||||||
|
|
||||||
|
def test_date_covers_utc_day() -> None:
|
||||||
|
day = date(2026, 11, 28)
|
||||||
|
first = datetime(2026, 11, 28, 0, 0, tzinfo=UTC)
|
||||||
|
last = datetime(2026, 11, 28, 23, 59, 59, 999999, tzinfo=UTC)
|
||||||
|
before = _ft(None, first - timedelta(microseconds=1))
|
||||||
|
after = _ft(last + timedelta(microseconds=1), last + timedelta(days=1))
|
||||||
|
# as start: 00:00 UTC
|
||||||
|
assert before.precedes(_ft(day, day))
|
||||||
|
assert not _ft(None, first).precedes(_ft(day, day))
|
||||||
|
# as end: 23:59:59.999999 UTC
|
||||||
|
assert _ft(day, day).precedes(after)
|
||||||
|
assert not _ft(day, day).precedes(_ft(last, last + timedelta(days=1)))
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import sys
|
||||||
|
import unicodedata
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from chemenu.domain.errors import FrontmatterError
|
||||||
|
from chemenu.domain.frontmatter import parse_frontmatter, render_frontmatter, split_document
|
||||||
|
|
||||||
|
|
||||||
|
def test_split_keeps_line_endings() -> None:
|
||||||
|
assert split_document("---\na: b\n---\nbody\n") == ("a: b\n", "body\n")
|
||||||
|
assert split_document("---\r\na: b\r\n---\r\nx\r\ny") == ("a: b\r\n", "x\r\ny")
|
||||||
|
assert split_document("---\ra: b\r---\rx") == ("a: b\r", "x")
|
||||||
|
assert split_document("---\na: b\n---") == ("a: b\n", "")
|
||||||
|
assert split_document("---\n---\n") == ("", "")
|
||||||
|
body = "l1\u2028l2\x0cl3\r\nl4\rl5\n"
|
||||||
|
assert split_document("---\na: b\u2028c\x0c\n---\r\n" + body) == ("a: b\u2028c\x0c\n", body)
|
||||||
|
for bad in [
|
||||||
|
"",
|
||||||
|
"a\n",
|
||||||
|
"--- \na\n---\n",
|
||||||
|
"---\na: b\n",
|
||||||
|
"\n---\na\n---\n",
|
||||||
|
"---",
|
||||||
|
"---\na\n----\n",
|
||||||
|
]:
|
||||||
|
with pytest.raises(FrontmatterError):
|
||||||
|
split_document(bad)
|
||||||
|
|
||||||
|
|
||||||
|
def test_values_stay_text() -> None:
|
||||||
|
parsed = parse_frontmatter(
|
||||||
|
"version: 1.10\nflag: no\nday: 2026-11-28\nn: null\nempty:\n"
|
||||||
|
"tags: [a, 1, true]\nnested:\n k: 0x10\n l:\n - 1e3\n"
|
||||||
|
)
|
||||||
|
assert parsed == {
|
||||||
|
"version": "1.10",
|
||||||
|
"flag": "no",
|
||||||
|
"day": "2026-11-28",
|
||||||
|
"n": "null",
|
||||||
|
"empty": "",
|
||||||
|
"tags": ["a", "1", "true"],
|
||||||
|
"nested": {"k": "0x10", "l": ["1e3"]},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"block",
|
||||||
|
[
|
||||||
|
"",
|
||||||
|
"\n",
|
||||||
|
"# only a comment\n",
|
||||||
|
"a: [\n",
|
||||||
|
"a: b: c\n",
|
||||||
|
"- a\n- b\n",
|
||||||
|
"just text\n",
|
||||||
|
"~\n",
|
||||||
|
"a: 1\n---\nb: 2\n",
|
||||||
|
"a: 1\n...\n---\nb: 2\n",
|
||||||
|
"? [a, b]\n: c\n",
|
||||||
|
"? {a: b}\n: c\n",
|
||||||
|
"a: \x01\n",
|
||||||
|
"a: \ud800\n",
|
||||||
|
"a: \ufffe\n",
|
||||||
|
'a: "\\ud800"\n',
|
||||||
|
'"\\ud800": a\n',
|
||||||
|
f"# comment{chr(0x2028)}type: source\n",
|
||||||
|
f"a: b{chr(0x85)}c\n",
|
||||||
|
"[" * 100000 + "\n",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_invalid_frontmatter_raises(block: str) -> None:
|
||||||
|
with pytest.raises(FrontmatterError):
|
||||||
|
parse_frontmatter(block)
|
||||||
|
|
||||||
|
|
||||||
|
def test_deep_nesting_raises() -> None:
|
||||||
|
block = "a: " + "[" * 5000 + "]" * 5000 + "\n"
|
||||||
|
with pytest.raises(FrontmatterError):
|
||||||
|
parse_frontmatter(block)
|
||||||
|
# The limit is fixed, not the interpreter's recursion limit.
|
||||||
|
parse_frontmatter("a: " + "[" * 30 + "]" * 30 + "\n")
|
||||||
|
with pytest.raises(FrontmatterError, match="nested too deeply"):
|
||||||
|
parse_frontmatter("a: " + "[" * 40 + "]" * 40 + "\n")
|
||||||
|
|
||||||
|
|
||||||
|
def test_duplicate_key_raises() -> None:
|
||||||
|
for block in [
|
||||||
|
"a: 1\na: 2\n",
|
||||||
|
"x:\n a: 1\n a: 2\n",
|
||||||
|
"x: {a: 1, a: 2}\n",
|
||||||
|
"l:\n - a: 1\n a: 2\n",
|
||||||
|
]:
|
||||||
|
with pytest.raises(FrontmatterError):
|
||||||
|
parse_frontmatter(block)
|
||||||
|
|
||||||
|
|
||||||
|
def test_yaml_alias_raises() -> None:
|
||||||
|
for block in ["a: &x 1\nb: *x\n", "a: &x 1\n", "a: *x\n", "a: [&x 1, *x]\n", "a: &x\n b: c\n"]:
|
||||||
|
with pytest.raises(FrontmatterError):
|
||||||
|
parse_frontmatter(block)
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_format() -> None:
|
||||||
|
assert (
|
||||||
|
render_frontmatter({"id": "x", "tags": ["a", "b"], "none": []})
|
||||||
|
== '---\nid: "x"\ntags: ["a", "b"]\nnone: []\n---\n'
|
||||||
|
)
|
||||||
|
assert render_frontmatter({"t": 'a"b\\c\u0085\u00e4\U0001f600'}) == (
|
||||||
|
'---\nt: "a\\"b\\\\c\\u0085\u00e4\U0001f600"\n---\n'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_invalid_input_raises() -> None:
|
||||||
|
for fields in [{"Bad": "x"}, {"1a": "x"}, {"a-b": "x"}, {"": "x"}, {"a\n": "x"}]:
|
||||||
|
with pytest.raises(FrontmatterError):
|
||||||
|
render_frontmatter(fields)
|
||||||
|
with pytest.raises(FrontmatterError):
|
||||||
|
render_frontmatter({"a": "x\ud800"})
|
||||||
|
with pytest.raises(FrontmatterError):
|
||||||
|
render_frontmatter({"a": ["x\udfff"]})
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_round_trips_any_text() -> None:
|
||||||
|
step = 2048
|
||||||
|
for start in range(0, sys.maxunicode + 1, step):
|
||||||
|
chars = [chr(c) for c in range(start, min(start + step, sys.maxunicode + 1))]
|
||||||
|
text = "".join(c for c in chars if unicodedata.category(c) != "Cs")
|
||||||
|
rendered = render_frontmatter({"k": text, "l": [text, "x"]})
|
||||||
|
block, body = split_document(rendered + "body")
|
||||||
|
assert body == "body"
|
||||||
|
assert parse_frontmatter(block) == {"k": text, "l": [text, "x"]}
|
||||||
|
for text in ["", " ", "---", "a\r\nb", "\ufeffx", "\ufffe\uffff", "#c", "\t"]:
|
||||||
|
block, _ = split_document(render_frontmatter({"k": text}))
|
||||||
|
assert parse_frontmatter(block) == {"k": text}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
|
from chemenu.domain.errors import InvalidPageIdError, InvalidTitleError
|
||||||
|
from chemenu.domain.identity import PageId, PageTitle
|
||||||
|
|
||||||
|
VALID_ID = "01a238ea-2e6d-7157-ba55-5da7405095ff"
|
||||||
|
|
||||||
|
|
||||||
|
def test_valid_id() -> None:
|
||||||
|
assert PageId(VALID_ID).value == VALID_ID
|
||||||
|
assert PageId(VALID_ID.replace("ba55", "8a55")).value.startswith("01a2")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"value",
|
||||||
|
[
|
||||||
|
"",
|
||||||
|
VALID_ID + "\n",
|
||||||
|
VALID_ID.upper(),
|
||||||
|
VALID_ID.replace("-7157", "-4157"),
|
||||||
|
VALID_ID.replace("ba55", "ca55"),
|
||||||
|
VALID_ID.replace("-", ""),
|
||||||
|
VALID_ID[:-1],
|
||||||
|
VALID_ID[:-1] + "g",
|
||||||
|
VALID_ID[:-1] + chr(0xFF10),
|
||||||
|
" " + VALID_ID,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_invalid_id_raises(value: str) -> None:
|
||||||
|
with pytest.raises(InvalidPageIdError):
|
||||||
|
PageId(value)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"value",
|
||||||
|
[
|
||||||
|
"Ordnungs-, Wisch- und Sanitätsdienst",
|
||||||
|
"Äpfel 🍎",
|
||||||
|
"a" * 252,
|
||||||
|
"CONSOLE",
|
||||||
|
"Aux-Plan",
|
||||||
|
"a.b",
|
||||||
|
"x%y",
|
||||||
|
"md",
|
||||||
|
"notes.mdx",
|
||||||
|
"a.md b",
|
||||||
|
"Familie 👨" + chr(0x200D) + "👩",
|
||||||
|
"Mi" + chr(0x200C) + "zan",
|
||||||
|
"🏴" + "".join(chr(0xE0000 + ord(c)) for c in "gbeng") + chr(0xE007F),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_title_with_comma(value: str) -> None:
|
||||||
|
assert PageTitle(value).value == value
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"value",
|
||||||
|
[
|
||||||
|
"",
|
||||||
|
" ",
|
||||||
|
"a<b",
|
||||||
|
"a>b",
|
||||||
|
"a:b",
|
||||||
|
'a"b',
|
||||||
|
"a/b",
|
||||||
|
"a\\b",
|
||||||
|
"a|b",
|
||||||
|
"a?b",
|
||||||
|
"a*b",
|
||||||
|
"a[b",
|
||||||
|
"a]b",
|
||||||
|
"a#b",
|
||||||
|
"a^b",
|
||||||
|
"a%%b",
|
||||||
|
"a\tb",
|
||||||
|
"a\nb",
|
||||||
|
"a\x7fb",
|
||||||
|
"a\x85b",
|
||||||
|
f"a{chr(0x2028)}b",
|
||||||
|
f"a{chr(0x2029)}b",
|
||||||
|
".a",
|
||||||
|
"a.",
|
||||||
|
" a",
|
||||||
|
"a ",
|
||||||
|
f"a{chr(0xA0)}",
|
||||||
|
f"{chr(0x3000)}a",
|
||||||
|
"con",
|
||||||
|
"CON",
|
||||||
|
"Con.txt",
|
||||||
|
"con .txt",
|
||||||
|
"NUL",
|
||||||
|
"prn",
|
||||||
|
"conin$",
|
||||||
|
"CONOUT$",
|
||||||
|
"aux",
|
||||||
|
"COM1",
|
||||||
|
"lpt9.x",
|
||||||
|
"COM¹",
|
||||||
|
"LPT²",
|
||||||
|
"COM³.a",
|
||||||
|
"e\u0301",
|
||||||
|
"a" * 253,
|
||||||
|
"ä" * 127,
|
||||||
|
"a\ud800b",
|
||||||
|
"README.md",
|
||||||
|
"notes.MD",
|
||||||
|
"x.Md",
|
||||||
|
"a" + chr(0x200B) + "b",
|
||||||
|
chr(0xFEFF) + "a",
|
||||||
|
"a" + chr(0x202E) + "b",
|
||||||
|
"a" + chr(0x00AD) + "b",
|
||||||
|
"a" + chr(0x2060) + "b",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_invalid_title_raises(value: str) -> None:
|
||||||
|
with pytest.raises(InvalidTitleError):
|
||||||
|
PageTitle(value)
|
||||||
@@ -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)
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
from chemenu.domain.sections import SectionKey, split_sections
|
||||||
|
|
||||||
|
BODY = "# Title\nintro\n\n## A\nalpha\n\n## B\nbeta\n"
|
||||||
|
|
||||||
|
|
||||||
|
def versions(body: str) -> dict[SectionKey, str]:
|
||||||
|
return {s.key: s.version for s in split_sections(body)}
|
||||||
|
|
||||||
|
|
||||||
|
def test_texts_join_to_body() -> None:
|
||||||
|
for body in ["", "x", BODY, "a\r\n## b\rc\n```\n## no", "\n\n## A", "## A\n## A\n"]:
|
||||||
|
assert "".join(s.text for s in split_sections(body)) == body
|
||||||
|
assert split_sections("")[0].key == SectionKey(None)
|
||||||
|
|
||||||
|
|
||||||
|
def test_change_affects_one_version() -> None:
|
||||||
|
before = versions(BODY)
|
||||||
|
after = versions(BODY.replace("alpha", "ALPHA"))
|
||||||
|
changed = [k for k in before if before[k] != after[k]]
|
||||||
|
assert changed == [SectionKey("A")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_append_keeps_versions() -> None:
|
||||||
|
before = versions(BODY)
|
||||||
|
after = versions(BODY + "\n## C\ngamma\n")
|
||||||
|
assert all(after[k] == v for k, v in before.items())
|
||||||
|
assert SectionKey("C") in after
|
||||||
|
|
||||||
|
|
||||||
|
def test_title_line_not_hashed() -> None:
|
||||||
|
a = split_sections("# One\n\ntext\n")[0]
|
||||||
|
b = split_sections("# Two\n\ntext\n")[0]
|
||||||
|
assert a.key == SectionKey(None)
|
||||||
|
assert a.version == b.version
|
||||||
|
assert len(split_sections("# One\ntext\n")) == 1
|
||||||
|
# a second level-1 heading separates
|
||||||
|
assert [s.key.heading for s in split_sections("# One\n# Two\n")] == [None, "Two"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_subheadings_belong_to_section() -> None:
|
||||||
|
body = "## A\n### sub\ntext\nSetext\n======\n ## indented\n#tag\n"
|
||||||
|
assert [s.key.heading for s in split_sections(body)] == [None, "A"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_code_and_comments_do_not_split() -> None:
|
||||||
|
body = (
|
||||||
|
"intro\n```\n## no\n```\n## yes\n~~~\n## no\n~~~\n"
|
||||||
|
"<!--\n## no\n-->\n## also\n <!-- ```\n## no\n-->\n## last\n"
|
||||||
|
"```\n## open\n"
|
||||||
|
)
|
||||||
|
assert [s.key.heading for s in split_sections(body)] == [None, "yes", "also", "last"]
|
||||||
|
# "<!-->" is a complete comment, a tab-indented fence does not close
|
||||||
|
tricky = "<!-->\n## A\n```\n\t```\n## no\n```\n## B\n"
|
||||||
|
assert [s.key.heading for s in split_sections(tricky)] == [None, "A", "B"]
|
||||||
|
inner = "## A\n<!--\n```\n-->\n## B\n"
|
||||||
|
assert [s.key.heading for s in split_sections(inner)] == [None, "A", "B"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_duplicate_headings() -> None:
|
||||||
|
keys = [s.key for s in split_sections("## A\n# A\n## B\n## A\n")]
|
||||||
|
assert keys == [
|
||||||
|
SectionKey(None),
|
||||||
|
SectionKey("A", 1),
|
||||||
|
SectionKey("A", 2),
|
||||||
|
SectionKey("B", 1),
|
||||||
|
SectionKey("A", 3),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_crlf_same_version() -> None:
|
||||||
|
assert versions(BODY) == versions(BODY.replace("\n", "\r\n"))
|
||||||
|
assert versions(BODY) == versions(BODY.replace("\n", "\r"))
|
||||||
|
assert split_sections("## A ## \nx")[1].key == SectionKey("A")
|
||||||
|
|
||||||
|
|
||||||
|
def test_inner_whitespace_changes_version() -> None:
|
||||||
|
plain, blank_edges, indented, gap = (
|
||||||
|
split_sections(f"## A\n{text}")[1].version
|
||||||
|
for text in ("a\nb\n", " \n\na\nb\n\t\n\n", " a\nb\n", "a\n\nb\n")
|
||||||
|
)
|
||||||
|
assert plain == blank_edges
|
||||||
|
assert len({plain, indented, gap}) == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_container_fences_do_not_hide_headings() -> None:
|
||||||
|
def headings(body: str) -> list[str | None]:
|
||||||
|
return [s.key.heading for s in split_sections(body)]
|
||||||
|
|
||||||
|
assert headings("- ```bash\n ls\n ```\n## Next\n[[L]]\n") == [None, "Next"]
|
||||||
|
# unclosed fence in a list ends with the list
|
||||||
|
assert headings("- ```\n ## no\n## Next\n") == [None, "Next"]
|
||||||
|
assert headings("1. a\n ```\n ## no\n ```\n## B\n") == [None, "B"]
|
||||||
|
# unclosed fence in a quote ends with the quote
|
||||||
|
assert headings("> ```\n> ## no\n## Next\n") == [None, "Next"]
|
||||||
|
assert headings("> ```\n> ## no\n\n## Next\n") == [None, "Next"]
|
||||||
|
# at top level an unclosed fence runs to the end
|
||||||
|
assert headings("```\n## no\n- x\n## no\n") == [None]
|
||||||
|
# indented code is not recognised and opens no fence
|
||||||
|
assert headings(" ```\n## A\n") == [None, "A"]
|
||||||
|
# thematic breaks are not list items
|
||||||
|
assert headings("---\n```\n## no\n```\n## A\n* * *\n## B\n") == [None, "A", "B"]
|
||||||
@@ -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<!--\n# x\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))
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import time
|
||||||
|
|
||||||
|
from chemenu.domain.wikilinks import WikiLink, find_wikilinks
|
||||||
|
|
||||||
|
|
||||||
|
def test_targets() -> None:
|
||||||
|
body = "[[Foo]] and [[Bar, Baz]] again [[Foo]]\n[[ ]] [[#X]] [[a\n b]]"
|
||||||
|
assert find_wikilinks(body) == (
|
||||||
|
WikiLink("Foo"),
|
||||||
|
WikiLink("Bar, Baz"),
|
||||||
|
WikiLink("Foo"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_anchor_text_and_embed() -> None:
|
||||||
|
body = "[[T#A#b]] [[T#^blk|Txt]] ![[E]] [[ T # | ]] [[a [b] c|x [y]]]"
|
||||||
|
assert find_wikilinks(body) == (
|
||||||
|
WikiLink("T", "A#b"),
|
||||||
|
WikiLink("T", "^blk", "Txt"),
|
||||||
|
WikiLink("E", embed=True),
|
||||||
|
WikiLink("T"),
|
||||||
|
WikiLink("a [b] c", None, "x [y"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_escaped_pipe() -> None:
|
||||||
|
assert find_wikilinks("| [[T\\|Text]] |") == (WikiLink("T", None, "Text"),)
|
||||||
|
|
||||||
|
|
||||||
|
def test_code_is_ignored() -> None:
|
||||||
|
body = (
|
||||||
|
"```\n[[a]]\n```\n`[[b]]` ``[[c]]`` `x` [[d]]\n<!--\n[[e]]\n-->\nx <!-- [[f]] --> [[g]]\n"
|
||||||
|
)
|
||||||
|
assert [link.target for link in find_wikilinks(body)] == ["d", "g"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_unclosed_code_or_comment_hides_nothing() -> None:
|
||||||
|
body = "x <!-- [[a]]\n`[[b]]\n``[[c]]`\n[[d]]\n"
|
||||||
|
assert [link.target for link in find_wikilinks(body)] == ["a", "b", "c", "d"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_first_opener_wins() -> None:
|
||||||
|
body = "`<!--` [[a]] `-->`\nx <!-- ` --> [[b]] `\n"
|
||||||
|
assert [link.target for link in find_wikilinks(body)] == ["a", "b"]
|
||||||
|
|
||||||
|
|
||||||
|
def targets(body: str) -> list[str]:
|
||||||
|
return [link.target for link in find_wikilinks(body)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_anchor_with_escaped_pipe() -> None:
|
||||||
|
assert find_wikilinks("[[T#A\\|Text]]") == (WikiLink("T", "A", "Text"),)
|
||||||
|
|
||||||
|
|
||||||
|
def test_link_text_keeps_inline_code() -> None:
|
||||||
|
assert find_wikilinks("[[Use `x` now]]") == (WikiLink("Use `x` now"),)
|
||||||
|
assert find_wikilinks("[[T|`code`]]") == (WikiLink("T", None, "`code`"),)
|
||||||
|
assert find_wikilinks("[[T#A <!-- c --> b|x]]") == (WikiLink("T", "A <!-- c --> b", "x"),)
|
||||||
|
assert find_wikilinks("[[T#`a#b`|x]]") == (WikiLink("T", "`a#b`", "x"),)
|
||||||
|
assert find_wikilinks("[[T|`a|b`]]") == (WikiLink("T", None, "`a|b`"),)
|
||||||
|
|
||||||
|
|
||||||
|
def test_text_after_comment_counts() -> None:
|
||||||
|
assert targets("<!-- a --> [[B]]") == ["B"]
|
||||||
|
assert targets("<!--\nx [[a]]\n--> [[g]] `[[h]]` [[i]]\n") == ["g", "i"]
|
||||||
|
assert targets("<!-- c --> [[g]] <!-- [[h]] --> [[i]]") == ["g", "i"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_escapes() -> None:
|
||||||
|
assert targets("\\`[[A]]\\`") == ["A"]
|
||||||
|
assert targets("\\[[A]]") == []
|
||||||
|
assert targets("\\\\[[A]]") == ["A"]
|
||||||
|
assert targets("\\\\\\[[A]]") == []
|
||||||
|
assert targets("\\<!-- [[A]] -->") == ["A"]
|
||||||
|
assert targets("`a\\` [[A]] `b`") == ["A"]
|
||||||
|
assert find_wikilinks("[[T\\|x]]") == (WikiLink("T", None, "x"),)
|
||||||
|
|
||||||
|
|
||||||
|
def test_fences_in_lists_and_quotes() -> None:
|
||||||
|
assert targets("- ```bash\n [[a]]\n ```\n[[b]]\n") == ["b"]
|
||||||
|
assert targets("- x\n ```\n [[a]]\n ```\n[[b]]\n") == ["b"]
|
||||||
|
assert targets("- a\n\t```\n\t[[a]]\n\t```\n[[b]]\n") == ["b"]
|
||||||
|
assert targets("> ```\n> [[a]]\n> ```\n[[b]]\n") == ["b"]
|
||||||
|
assert targets("> - ```\n> [[a]]\n") == []
|
||||||
|
assert targets("1. ```\n [[a]]\n## H\n[[b]]\n") == ["b"]
|
||||||
|
assert targets("> ```\n> [[a]]\n\nparagraph [[b]]\n") == ["b"]
|
||||||
|
assert targets("```\n[[a]]\n- x\n[[b]]\n") == []
|
||||||
|
assert targets(" ```\n[[a]]\n") == ["a"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_large_input_is_fast() -> None:
|
||||||
|
units = ["[", "`", "<!--", "> ", "- ", "\\", "\n", "[[", "]]", "> - ", "- > "]
|
||||||
|
texts = [unit * (50_000 // len(unit)) + "\n[[a]]" for unit in units]
|
||||||
|
texts.append("- " * 5_000 + "\n" * 50_000)
|
||||||
|
texts.append("\n".join(" " * n + "- x" for n in range(500)))
|
||||||
|
start = time.perf_counter()
|
||||||
|
for text in texts:
|
||||||
|
find_wikilinks(text)
|
||||||
|
# Takes about a second; quadratic behaviour would take minutes.
|
||||||
|
assert time.perf_counter() - start < 30
|
||||||
Reference in new issue
Block a user