Files
chemenu/tools/chemenu/export_index.py
T
torbenandClaude Sonnet 5.5 db09e89223
CI / verify (push) Successful in 8m17s
CI / pwsh (push) Successful in 2m54s
Release / converters (push) Successful in 28s
Release / release (push) Successful in 36s
Release / wiki-mirror (push) Skipped
tools: Export - include "all" wählt die ganze KB, index: true schreibt index.md und INDEX.md in den Zielordner (#217); 10.1.0-beta.21
Files changed:
- CHANGES.md
- VERSION
- docs/how-to/export-to-a-synced-folder.md
- docs/reference/commands/exports.md
- docs/reference/configuration.md
- raw/CONTRACT.md
- tools/CONTRACT.md
- tools/README.md
- tools/chemenu/catalog.py
- tools/chemenu/commands/export_cmd.py
- tools/chemenu/commands/index_build.py
- tools/chemenu/config_shapes.py
- tools/chemenu/export_index.py
- tools/chemenu/guideline_export.py
- tools/chemenu/page_export.py
- tools/chemenu/tests/test_config_shapes.py
- tools/chemenu/tests/test_export_run.py
- tools/chemenu/tests/test_index_build.py

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SnAJ7Z3CpVD3PRbN73QtU2
2026-10-16 15:44:21 +02:00

164 lines
7.4 KiB
Python

"""The routing files of a page export, with no CLI attached: `index.md` at the
root of a target and an `INDEX.md` per collection and per large area, listing
the pages the target exports - and only those.
They follow the hierarchy of the catalog under `kb/` (`catalog.group_pages`,
`catalog.SHARD_THRESHOLD`) but are not copies of it. The catalog names pages a
partial selection does not export, so copied files would carry titles out of the
`kb/` and link into nothing; these are built from the selection instead.
What makes them safe to keep in a synced folder:
- **Deterministic.** No date of the day, no hint for an agent, no comment ahead
of the frontmatter. "Last Modified" comes from the page's own frontmatter and
is empty where it has none - never from the file's modification time.
- **Local.** A file's marker carries the newest commit of the pages *it lists*,
so one page's commit rewrites the files above it and no others.
- **Marked like a page.** The frontmatter holds one key, `wikitool_export`, with
`kind=index`, whatever the target's `frontmatter` says, so `is_export` and
`raw accept` treat it as what it is.
"""
from __future__ import annotations
import json
import posixpath
import re
from pathlib import Path
from urllib.parse import quote
from chemenu import guideline_export
from chemenu.catalog import ROOT_COLLECTION, Area, Collection, anchor, group_pages, type_label
from chemenu.kb_scan import GENERATED_INDEX
from chemenu.page import Page
ROOT_FILE = "index.md"
_BREAK = re.compile(r"\s+")
_LINK_TEXT_ESCAPES = re.compile(r"([\\\[\]|])")
_DATE_KEYS = ("modified", "date", "created")
PAGE_HEADER = "| Page | Type | Summary | Last Modified |"
PAGE_SEP = "|------|------|---------|---------------|"
def _cell(text: str) -> str:
return _BREAK.sub(" ", text).strip().replace("|", "\\|")
def _link(label: str, target: str, here: str, fragment: str = "") -> str:
"""A Markdown link to the file `target`, as written in a file in the folder
`here` (both below the target root); the destination is percent-encoded."""
destination = quote(posixpath.relpath(target, here or "."), safe="/")
if fragment:
destination += "#" + quote(fragment, safe="-")
return f"[{label}]({destination})"
def _last_modified(page: Page) -> str:
for key in _DATE_KEYS:
value = page.frontmatter.get(key)
if value:
return str(value)
return ""
class _Builder:
def __init__(self, pages: list[Page], kb_dir: Path, instance: str, commits: dict[Path, str],
rank: dict[str, int]) -> None:
self.pages = pages
self.kb_dir = kb_dir
self.instance = instance
self.commits = commits
self.rank = rank
self.files: dict[str, bytes] = {}
def add(self, rel: str, lines: list[str], pages: list[Page]) -> None:
"""Store `lines` as the file `rel` listing `pages`, with the marker of
the newest commit among them."""
newest = min((self.commits[page.path] for page in pages), key=lambda commit: self.rank[commit])
marker = guideline_export.export_marker(guideline_export.INDEX_KIND, self.instance, newest)
head = f"---\nwikitool_export: {json.dumps(marker, ensure_ascii=False)}\n---\n\n"
self.files[rel] = (head + "\n".join(lines) + "\n").encode("utf-8")
def table(self, pages: list[Page], here: str) -> list[str]:
lines = [PAGE_HEADER, PAGE_SEP]
for page in sorted(pages, key=lambda p: (p.title.casefold(), p.title)):
rel = page.path.relative_to(self.kb_dir).as_posix()
title = _LINK_TEXT_ESCAPES.sub(r"\\\1", page.title)
summary = page.frontmatter.get("summary")
lines.append(
f"| {_link(title, rel, here)} | {_cell(type_label(page))} "
f"| {_cell(str(summary)) if summary else ''} | {_cell(_last_modified(page))} |"
)
return lines
def area_file(self, area: Area, collection: str) -> None:
here = f"{collection}/{area.name}"
self.add(f"{here}/{GENERATED_INDEX}",
[f"# {area.title}", "", f"{area.count} page(s).", "", *self.table(area.pages, here)],
area.pages)
def collection_file(self, collection: Collection, pages: list[Page]) -> None:
name = collection.name
lines = [f"# {name}/ - Index", "", f"{collection.count} page(s).", ""]
for area in collection.areas:
lines += [f"## {area.title}", ""]
if area.own_shard:
shard = f"{name}/{area.name}/{GENERATED_INDEX}"
lines.append(f"{area.count} page(s) - listed in "
f"{_link(f'{area.name}/{GENERATED_INDEX}', shard, name)}.")
else:
lines += self.table(area.pages, name)
lines.append("")
self.add(f"{name}/{GENERATED_INDEX}", lines[:-1], pages)
def root_file(self, collections: list[Collection], strays: list[Page]) -> None:
lines = ["# Index", "", f"{len(self.pages)} page(s).", ""]
if collections:
lines += ["## Collections", "", "| Collection | Pages | Index |", "|------------|------:|-------|"]
for collection in collections:
target = f"{collection.name}/{GENERATED_INDEX}"
lines.append(f"| `{collection.name}/` | {collection.count} | {_link(target, target, '')} |")
lines.append("")
for collection in collections:
named = [area for area in collection.areas if area.name]
if not named:
continue
lines += [f"### {collection.name}/", "", "| Area | Pages | Index |", "|------|------:|-------|"]
for area in named:
if area.own_shard:
target, fragment = f"{collection.name}/{area.name}/{GENERATED_INDEX}", ""
else:
target, fragment = f"{collection.name}/{GENERATED_INDEX}", anchor(area.title)
shown = target + (f"#{fragment}" if fragment else "")
lines.append(f"| {_cell(area.title)} | {area.count} | {_link(shown, target, '', fragment)} |")
lines.append("")
if strays:
lines += ["## Pages outside any collection", "", *self.table(strays, ""), ""]
self.add(ROOT_FILE, lines[:-1], self.pages)
def build(pages: list[Page], kb_dir: Path, instance: str, commits: dict[Path, str],
rank: dict[str, int]) -> dict[str, bytes]:
"""The index files for `pages` - the pages a target exports - by path below
the target, each as the bytes to write. `commits` and `rank` come from
`guideline_export.page_commit_history`. No pages, no files."""
if not pages:
return {}
builder = _Builder(pages, kb_dir, instance, commits, rank)
strays: list[Page] = []
collections: list[Collection] = []
for collection in group_pages(kb_dir, {str(page.path): page for page in pages}):
if not collection.count:
continue
members = [page for area in collection.areas for page in area.pages]
if collection.name == ROOT_COLLECTION:
strays = members
continue
collections.append(collection)
builder.collection_file(collection, members)
for area in collection.areas:
if area.own_shard:
builder.area_file(area, collection.name)
builder.root_file(collections, strays)
return builder.files