Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

12.4 KB
Raw Blame
#!/usr/bin/env python3
"""kwant.si, the GitHub README and the in-app "What's new" must cover the newest release before it counts as done.

Reads the newest `## [Mac X.Y.Z]` heading in CHANGELOG.md and checks site-src/, README.md and frontend/src/whatsnew/:

1. features.html has a "New in" section for it: `id="new-<id>"`, where <id> is the version without dots or a
   trailing .0 (0.7.0 -> new-07, 0.7.1 -> new-071, 0.6.11 -> new-0611), or any section whose `data-covers` lists
   the version (a small fix release folded into a bigger section).
2. index.html's "Added in" strip links to that section.
3. Every guide the CHANGELOG entry names (`docs/NAME.md`) has a page, site-src/docs-NAME.html, or an entry in
   GUIDE_PAGES saying where the site covers it.
4. Every screenshot, video and media file that site-src names exists in site/assets/media.
5. README.md has a `## New in X.Y` section for the release's minor version, and that section names the release
   (0.7.2 as "(0.7.2)" on a bullet, say). A small fix release with no bullet of its own can be named in an HTML
   comment in the section: `<!-- covers: 0.7.3 -->`.
6. frontend/src/whatsnew/X.Y.Z.json exists and keeps the limits of the in-app "What's new" sheet: 2-6 highlights
   (title 60 characters or fewer, text 200 or fewer, image null or a .webp of 80 KB or less in
   frontend/public/whatsnew/X.Y.Z/, open null or an in-app place such as "settings/teams") and 0-15 fixes of 140
   characters or fewer. frontend/src/whatsNewSheet.ts checks the same limits in the app.
7. site-src/media-versions.json names, for every home page clip and the reel, the CHANGELOG version it was last
   recorded on. A clip fails once it's on an older minor version than the newest release, or more than 3 patch
   releases behind it on the same minor (the reel is exempt: it's a standing "Watch it work" piece, not tied to
   a feature).

Usage: python3 scripts/site_release_gate.py [--warn]
Exit 0 when kwant.si and the README are current, else 1 with one line per gap. --warn prints the gaps and exits 0:
check_site.py uses it, because the release PR bumps CHANGELOG.md before the site PR lands. The release script uses
the strict form, so a release isn't done until the site and the README are.
"""
import json
import re
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
SRC = ROOT / "site-src"
MEDIA = ROOT / "site" / "assets" / "media"

# Guides that have no page of their own on kwant.si: name -> the page that covers them.
GUIDE_PAGES = {
    "payments": "flight-school.html#payments",
    "saved-passwords": "approvals.html",
    "self-host-stores": "install.html#stores",
}

HEAD = re.compile(r"^## \[Mac (\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}\s*$", re.M)
README_NEW = re.compile(r"^## New in (\d+)\.(\d+)\s*$", re.M)


def section_id(version):
    """0.7.0 -> 07, 0.7.1 -> 071, 0.6.11 -> 0611, 1.0.0 -> 10."""
    major, minor, patch = version.split(".")
    return f"{major}{minor}" + ("" if patch == "0" else patch)


def newest(changelog):
    """(version, entry text) of the first release heading."""
    m = HEAD.search(changelog)
    if not m:
        raise SystemExit("CHANGELOG.md has no '## [Mac X.Y.Z] - YYYY-MM-DD' release headings")
    nxt = re.search(r"^## \[", changelog[m.end():], re.M)
    return m[1], changelog[m.end(): m.end() + nxt.start()] if nxt else changelog[m.end():]


def readme_gap(version, readme):
    """None when README.md's "## New in X.Y" section names `version`, else the gap. The section ends at the next
    `## ` heading or `---` rule."""
    major, minor, _ = version.split(".")
    for m in README_NEW.finditer(readme):
        if (m[1], m[2]) != (major, minor):
            continue
        end = re.search(r"^(?:## |---\s*$)", readme[m.end():], re.M)
        body = readme[m.end(): m.end() + end.start()] if end else readme[m.end():]
        if re.search(rf"(?<![0-9.]){re.escape(version)}(?![0-9])", body):
            return None
        return (f"README.md: the 'New in {major}.{minor}' section doesn't name {version} (add a bullet tagged "
                f"({version}), or <!-- covers: {version} --> for a fix release)")
    return (f"README.md: no '## New in {major}.{minor}' section for {version} (replace the old New in section "
            f"with one for {major}.{minor}, its bullets tagged by version)")


def media_files(name):
    if name.startswith("phone-"):
        return [f"{name}-390.webp", f"{name}-780.webp"]
    return [f"{name}-1440.webp", f"{name}-2880.webp"]


# The "What's new" limits, as in frontend/src/whatsNewSheet.ts (LIMITS).
WN_HIGHLIGHTS = (2, 6)
WN_TITLE, WN_TEXT, WN_FIXES, WN_FIX = 60, 200, 15, 140
WN_IMAGE_BYTES = 80 * 1024
WN_TOP = {"inbox", "inbox/loose-ends", "board", "parallel", "dev", "jar", "settings/app"}


def whatsnew_places(root):
    """The in-app places a highlight's "open" may name: the views in frontend/src/nav.ts."""
    nav = root / "frontend" / "src" / "nav.ts"
    tabs = re.search(r"SPACE_SETTINGS_TABS = \[([^\]]*)\]", nav.read_text()) if nav.exists() else None
    return WN_TOP | {f"settings/{t}" for t in re.findall(r"'([a-z-]+)'", tabs[1] if tabs else "")}


def whatsnew_gaps(version, root=ROOT):
    """Every way frontend/src/whatsnew/<version>.json is missing or breaks the sheet's limits."""
    rel = f"frontend/src/whatsnew/{version}.json"
    path = root / rel
    if not path.exists():
        return [f"{rel} is missing: write the in-app \"What's new in kwant {version}\" from the CHANGELOG entry "
                f"(2-6 highlights and the fixes; see next-076/whats-new/spec.md)"]
    try:
        e = json.loads(path.read_text())
    except ValueError as err:
        return [f"{rel} isn't valid JSON ({err})"]
    if not isinstance(e, dict):
        return [f"{rel} must be a JSON object"]
    out = []
    say = lambda msg: out.append(f"{rel}: {msg}")
    if e.get("version") != version:
        say(f"version is {e.get('version')!r}, should be {version!r}")
    if not isinstance(e.get("date"), str) or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", e["date"]):
        say("date must be YYYY-MM-DD")
    hs = e.get("highlights")
    places = whatsnew_places(root)
    if not isinstance(hs, list):
        say("highlights must be a list")
        hs = []
    elif not WN_HIGHLIGHTS[0] <= len(hs) <= WN_HIGHLIGHTS[1]:
        say(f"{len(hs)} highlights, needs {WN_HIGHLIGHTS[0]}-{WN_HIGHLIGHTS[1]}")
    ids = set()
    for i, h in enumerate(hs):
        at = f"highlights[{i}]"
        if not isinstance(h, dict):
            say(f"{at} must be an object")
            continue
        hid = h.get("id")
        if not isinstance(hid, str) or not re.fullmatch(r"[a-z0-9-]+", hid):
            say(f"{at}.id must be lowercase letters, digits and dashes")
        elif hid in ids:
            say(f"{at}.id {hid!r} is used twice")
        ids.add(hid)
        for key, limit in (("title", WN_TITLE), ("text", WN_TEXT)):
            v = h.get(key)
            if not isinstance(v, str) or not v.strip():
                say(f"{at}.{key} is empty")
            elif len(v) > limit:
                say(f"{at}.{key} is {len(v)} characters, max {limit}")
        img = h.get("image")
        if img is not None:
            if not isinstance(img, str) or not re.fullmatch(r"[a-z0-9][a-z0-9._-]*\.webp", img):
                say(f"{at}.image must be null or a .webp file name")
            else:
                f = root / "frontend" / "public" / "whatsnew" / version / img
                if not f.exists():
                    say(f"{at}.image: frontend/public/whatsnew/{version}/{img} is missing")
                elif f.stat().st_size > WN_IMAGE_BYTES:
                    say(f"{at}.image: {img} is {f.stat().st_size / 1024:.1f} KB, max 80 KB")
        place = h.get("open")
        if place is not None and (not isinstance(place, str) or place.strip("/").lower() not in places):
            say(f"{at}.open {place!r} isn't an in-app place (null, or one of: {', '.join(sorted(places))})")
    fixes = e.get("fixes")
    if not isinstance(fixes, list):
        say("fixes must be a list")
    else:
        if len(fixes) > WN_FIXES:
            say(f"{len(fixes)} fixes, max {WN_FIXES}")
        for i, f in enumerate(fixes):
            if not isinstance(f, str) or not f.strip():
                say(f"fixes[{i}] is empty")
            elif len(f) > WN_FIX:
                say(f"fixes[{i}] is {len(f)} characters, max {WN_FIX}")
    return out


def media_freshness_gaps(version, root=ROOT):
    """Every home page clip in site-src/media-versions.json that's gone stale against the newest release
    `version`: on an older minor, or more than 3 patch releases behind on the same minor. The "reel" entry
    (the "Watch it work" clip) is never checked: it isn't tied to a release."""
    rel = "site-src/media-versions.json"
    path = root / rel
    if not path.exists():
        return [f"{rel} is missing: list every home page clip (and \"reel\") with the CHANGELOG version it was "
                f"last recorded on"]
    try:
        versions = json.loads(path.read_text())
    except ValueError as err:
        return [f"{rel} isn't valid JSON ({err})"]
    if not isinstance(versions, dict):
        return [f"{rel} must be a JSON object"]
    newest = tuple(int(x) for x in version.split("."))
    out = []
    for name, v in sorted(versions.items()):
        if name == "reel":
            continue
        if not isinstance(v, str) or not re.fullmatch(r"\d+\.\d+\.\d+", v):
            out.append(f"{rel}: {name} is {v!r}, should be a \"X.Y.Z\" version")
            continue
        major, minor, patch = (int(x) for x in v.split("."))
        stale = (major, minor) != newest[:2] or newest[2] - patch > 3
        if stale:
            out.append(f"{rel}: {name} was recorded on {v}, {version} is current (re-record it: "
                       f"site-media-kit/shoot.sh <sha> shots.json out-dir, keeping the name {name}, then update "
                       f"{rel} to {version})")
    return out


def gaps(root=ROOT):
    src, media = root / "site-src", root / "site" / "assets" / "media"
    version, entry = newest((root / "CHANGELOG.md").read_text())
    out = []
    features = (src / "features.html").read_text()
    sid = None
    for m in re.finditer(r"<section\b([^>]*)>", features):
        attrs = m[1]
        sec = re.search(r'\bid="(new-[0-9]+)"', attrs)
        covers = re.search(r'\bdata-covers="([^"]*)"', attrs)
        if sec and (sec[1] == f"new-{section_id(version)}" or (covers and version in covers[1].split())):
            sid = sec[1]
            break
    if not sid:
        out.append(f"features.html: no 'New in {version}' section (id=\"new-{section_id(version)}\", "
                   f"or data-covers=\"{version}\" on another New in section)")
    elif f'features.html#{sid}"' not in (src / "index.html").read_text():
        out.append(f"index.html: the Added in strip doesn't link to features.html#{sid}")
    for guide in sorted(set(re.findall(r"docs/([a-z0-9-]+)\.md", entry))):
        if not (src / f"docs-{guide}.html").exists() and guide not in GUIDE_PAGES:
            out.append(f"docs/{guide}.md is named in the {version} entry but kwant.si has no docs-{guide}.html "
                       f"(write one, or add it to GUIDE_PAGES in scripts/site_release_gate.py)")
    missing = {}
    for page in sorted(src.rglob("*.html")):
        text = page.read_text()
        need = []
        for name in re.findall(r"\{\{shot:([^|}]+)\|", text):
            need += media_files(name)
        for name in re.findall(r"\{\{video:([^|}]+)\|", text):
            need += [f"{name}.mp4", f"{name}-poster.webp"]
        need += re.findall(r'assets/media/([A-Za-z0-9._-]+\.(?:webp|png|jpg|mp4|gif|svg))', text)
        for f in set(need):
            if not (media / f).exists():
                missing.setdefault(f, []).append(page.name)
    for f, pages in sorted(missing.items()):
        out.append(f"site/assets/media/{f} is missing (used in {', '.join(pages)})")
    readme = root / "README.md"
    gap = readme_gap(version, readme.read_text()) if readme.exists() else "README.md is missing"
    if gap:
        out.append(gap)
    out += whatsnew_gaps(version, root)
    out += media_freshness_gaps(version, root)
    return out


def main():
    warn = "--warn" in sys.argv[1:]
    version, _ = newest((ROOT / "CHANGELOG.md").read_text())
    found = gaps()
    for g in found:
        print(("WARN " if warn else "GAP ") + g)
    if not found:
        print(f"kwant.si, README.md and What's new cover {version}")
    sys.exit(0 if warn or not found else 1)


if __name__ == "__main__":
    main()