versions.py

clew/wiki/versions.py

Version-keyed sites and the diff between two of them (1.4.0 W11, #67's fifth consumer).

_maybe_snapshot

dict[str, Any] | None clew.wiki.versions._maybe_snapshot(Path out, str key)

A recorded snapshot, or None when its file is gone.

clew/wiki/versions.py:141

Show on the map →

Called by series

Calls none

Source · 6 lines
def _maybe_snapshot(out: Path, key: str) -> dict[str, Any] | None:
    """@brief Read if present. @return Snapshot or None."""
    path = out / key / "site.json"
    return json.loads(path.read_text(encoding="utf-8")) if path.is_file() else None

Activity · 2 steps
lines 143–143path = out / key / "site.json"lines 144–144return json.loads(path.read_text(encoding="utf-8")) if path.is_file() else None

Flows

_versions

list[dict[str, str]] clew.wiki.versions._versions(Path out)

The recorded version list.

clew/wiki/versions.py:226

Source · 6 lines
def _versions(out: Path) -> list[dict[str, str]]:
    """@brief Read versions.json. @return Entries."""
    path = out / "versions.json"
    return json.loads(path.read_text(encoding="utf-8")) if path.is_file() else []

Activity · 2 steps
lines 228–228path = out / "versions.json"lines 229–229return json.loads(path.read_text(encoding="utf-8")) if path.is_file() else []

Flows

diff_versions

dict[str, Any] clew.wiki.versions.diff_versions(Path out, str old, str new)

Compare two recorded versions and write the diff page.

clew/wiki/versions.py:154

Show on the map →

Called by _diff

Tested by

1 teststest_versioned_builds_and_a_diff_between_them

Calls _diff_body, _page, _snapshot

Source · 23 lines
def diff_versions(out: Path, old: str, new: str) -> dict[str, Any]:
    """@brief Diff two snapshots. @return Diff."""
    out = Path(out)
    a, b = _snapshot(out, old), _snapshot(out, new)
    ra, rb = a.get("requirements", {}), b.get("requirements", {})
    na, nb = set(a.get("nodes", [])), set(b.get("nodes", []))
    diff = {
        "from": old,
        "to": new,
        "nodes_added": sorted(nb - na),
        "nodes_removed": sorted(na - nb),
        "requirements_added": sorted(set(rb) - set(ra)),
        "requirements_removed": sorted(set(ra) - set(rb)),
        "requirements_changed": [
            {"id": i, "from": ra[i], "to": rb[i]}
            for i in sorted(set(ra) & set(rb))
            if ra[i] != rb[i]
        ],
    }
    _page(out / f"diff-{old}-{new}.html", f"Changes {old} → {new}", _diff_body(diff))
    return diff

Activity · 7 steps
lines 156–156out = Path(out)lines 157–157a, b = _snapshot(out, old), _snapshot(out, new)lines 158–158ra, rb = a.get("requirements", {}), b.get("requirements", {})lines 159–159na, nb = set(a.get("nodes", [])), set(b.get("nodes", []))lines 160–172diff = { "from": old, "to": new, "nodes_added": sorted(nb - na), "nodes_removed": sorted(na - nb), "requirements_added": sorted(set(rb) - set(ra)), "requirements_removed": sorted(set(ra) - set(rb)), "requirements_changed": [ {"id": i, "from": ra[i], "to": rb[i]} for i in sorted(set(ra) & set(rb)) if ra[i] != rb[i] ], }lines 173–173_page(out / f"diff-{old}-{new}.html", f"Changes {old} → {new}", _diff_body(diff))lines 174–174return diff

Requirements

REQ-DDB-WIKI-007

record_version

Path clew.wiki.versions.record_version(Path out, str key, dict[str, Any] snapshot, str title, list[tuple[str, str]]|tuple milestones=())

Record one versioned build: its snapshot, the version list and the index page.

clew/wiki/versions.py:71

Source · 35 lines
def record_version(
    out: Path,
    key: str,
    snapshot: dict[str, Any],
    title: str,
    milestones: list[tuple[str, str]] | tuple = (),
) -> Path:
    """REBUILDING A KEY REPLACES ITS ENTRY in place; a new key is appended.

    @brief Record a version.
    @return Snapshot path.
    """
    from .charts import burndown

    out = Path(out)
    path = out / valid_key(key) / "site.json"
    path.write_text(json.dumps(snapshot, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    listing = _versions(out)
    entry = {"key": key, "commit": snapshot.get("commit", "")}
    keys = [v["key"] for v in listing]
    if key in keys:
        listing[keys.index(key)] = entry
    else:
        listing.append(entry)
    (out / "versions.json").write_text(json.dumps(listing, indent=1) + "\n", encoding="utf-8")
    rows = "".join(
        f'<li><a href="{html.escape(v["key"])}/html/index.html">{html.escape(v["key"])}</a>'
        f" <code>{html.escape(v['commit'][:12])}</code></li>"
        for v in listing
    )
    chart = burndown(series(out, key, snapshot), list(milestones))
    _page(out / "index.html", f"{title} — versions", f"<ul>{rows}</ul><h2>Burndown</h2>{chart}")
    return path

Activity · 16 steps
lines 83–83from .charts import burndownlines 85–85out = Path(out)lines 86–86path = out / valid_key(key) / "site.json"lines 87–87path.write_text(json.dumps(snapshot, indent=1, sort_keys=True) + "\n", encoding="utf-8")lines 88–88listing = _versions(out)lines 89–89entry = {"key": key, "commit": snapshot.get("commit", "")}lines 90–90keys = [v["key"] for v in listing]lines 91–91◇ if key in keyslines 92–92listing[keys.index(key)] = entrylines 93–93elselines 94–94listing.append(entry)lines 95–95(out / "versions.json").write_text(json.dumps(listing, indent=1) + "\n", encoding="utf-8")lines 96–100rows = "".join( f'<li><a href="{html.escape(v["key"])}/html/index.html">{html.escape(v["key"])}</a>' f" <code>{html.escape(v['commit'][:12])}</code></li>" for v in listing )lines 101–101chart = burndown(series(out, key, snapshot), list(milestones))lines 102–102_page(out / "index.html", f"{title} — versions", f"<ul>{rows}</ul><h2>Burndown</h2>{chart}")lines 103–103return path

Requirements

REQ-DDB-WIKI-007

series

list[tuple[str, dict[str, int]]] clew.wiki.versions.series(Path out, str key, dict[str, Any] snapshot)

Tier counts per recorded version, in recording order, with one version's snapshot taken from the build in hand (it may not be recorded yet).

clew/wiki/versions.py:114

Source · 21 lines
def series(out: Path, key: str, snapshot: dict[str, Any]) -> list[tuple[str, dict[str, int]]]:
    """A RECORDED VERSION WHOSE SNAPSHOT IS GONE is left out, not drawn as zero open.

    @brief Build the series.
    @return Pairs.
    """
    keys = [v["key"] for v in _versions(Path(out))]
    if key not in keys:
        keys.append(key)
    out_series = []
    for k in keys:
        snap = snapshot if k == key else _maybe_snapshot(Path(out), k)
        if snap is None:
            continue
        counts: dict[str, int] = {}
        for tier in (snap.get("requirements") or {}).values():
            counts[tier] = counts.get(tier, 0) + 1
        out_series.append((k, counts))
    return out_series

Activity · 13 steps
lines 120–120keys = [v["key"] for v in _versions(Path(out))]lines 121–121◇ if key not in keyslines 122–122keys.append(key)lines 123–123out_series = []lines 124–124◇ for k in keyslines 125–125snap = snapshot if k == key else _maybe_snapshot(Path(out), k)lines 126–126◇ if snap is Nonelines 127–127continuelines 128–128counts: dict[str, int] = {}lines 129–129◇ for tier in (snap.get("requirements") or {}).values()lines 130–130counts[tier] = counts.get(tier, 0) + 1lines 131–131out_series.append((k, counts))lines 132–132return out_series

Requirements

REQ-DDB-WIKI-013

Flows

valid_key

str clew.wiki.versions.valid_key(str key)

A version key, refused when it cannot be a directory name.

clew/wiki/versions.py:54

Show on the map →

Called by _build_site, _snapshot, record_version

Calls none

Source · 7 lines
def valid_key(key: str) -> str:
    """@brief Validate a key. @return Key."""
    if not _KEY.match(key or ""):
        raise ValueError(f"version key {key!r} is not usable as a directory name")
    return key

Activity · 3 steps
lines 56–56◇ if not _KEY.match(key or "")lines 57–57raise ValueError(f"version key {key!r} is not usable as a directory name")lines 58–58return key

Requirements

REQ-DDB-WIKI-007

Flows