diff --git a/.gitea/workflows/pages.yml b/.gitea/workflows/pages.yml new file mode 100644 index 00000000..f9af984d --- /dev/null +++ b/.gitea/workflows/pages.yml @@ -0,0 +1,47 @@ +name: pages + +# The project site, https://blueflare.gitea.bluefla.re/alkane-toolkit/ : +# overview, user manual (docs/manual), code-quality dashboard (from the +# quality record main CI publishes with the badges) and benchmark history. +# Rebuilt after every main build-test-release run and published to this +# repository's gh-pages branch. +on: + workflow_run: + workflows: [build-test-release] + types: [completed] + workflow_dispatch: + +concurrency: + group: alkane-toolkit-pages + cancel-in-progress: false + +jobs: + publish: + runs-on: alkane-verify + container: + image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5 + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + - name: Install page tools + run: bash ci/ensure-build-deps.sh pages + - name: Render measured benchmark history + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: python3 ci/bench_history.py render + - name: Fetch measured quality record + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: python3 ci/fetch-quality.py quality.json + - name: Build site + run: | + python3 ci/build-pages.py --out site --quality quality.json \ + --bench bench-site/index.html --sha "$GITHUB_SHA" + - name: Publish site + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: python3 ci/publish-pages.py site + - name: Clean generated site + if: always() + run: python3 ci/cleanup-generated.py diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 10df1e5c..2c06e3ff 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -271,8 +271,10 @@ jobs: set -euo pipefail rustup component add llvm-tools-preview >/dev/null 2>&1 || true [ "$(cargo llvm-cov --version)" = 'cargo-llvm-cov 0.8.7' ] - PCT=$(bash ci/coverage.sh --summary-only \ - | awk '/^TOTAL/{gsub(/%/,"",$10); print $10}') + # Keep the whole table: gen-badges turns it into the per-crate and + # per-file breakdown on the Pages quality dashboard. + bash ci/coverage.sh --summary-only | tee coverage-summary.txt + PCT=$(awk '/^TOTAL/{gsub(/%/,"",$10); print $10}' coverage-summary.txt) [ -n "$PCT" ] || { echo "coverage report produced no TOTAL line" >&2; exit 1; } echo "pct=${PCT}" >> "$GITHUB_OUTPUT" echo "line coverage (tests + self-test): ${PCT}%" @@ -300,7 +302,8 @@ jobs: python3 ci/gen-badges.py --tests "$PASS" \ --coverage "${{ steps.cov.outputs.pct }}" \ --bench-coverage "${{ steps.benchcov.outputs.pct }}" \ - --bench-delta "$BENCH_DELTA" --clippy clean + --bench-delta "$BENCH_DELTA" --clippy clean \ + --coverage-summary coverage-summary.txt - name: Publish measured badges env: diff --git a/ci/build-pages.py b/ci/build-pages.py new file mode 100755 index 00000000..c2bc35c7 --- /dev/null +++ b/ci/build-pages.py @@ -0,0 +1,293 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Build the Alkane Toolkit Pages site (served from this repo's gh-pages). + + build-pages.py --out site [--manual docs/manual] [--quality quality.json] + [--bench bench-site/index.html] [--sha SHA] + +Pages: + / overview and downloads + /manual/ the user manual, one page per docs/manual/NN-name.md chapter + /quality/ code-quality dashboard from the measured quality.json that main + CI publishes next to the badges (ci/gen-badges.py) + /bench/ the measured benchmark history (ci/bench_history.py render) + +Every value taken from CI data is HTML-escaped; the manual is Markdown written +in this repository. +""" + +import argparse +import html +import json +import re +import shutil +from pathlib import Path + +import markdown + +REPO = "https://gitea.bluefla.re/blueflare/alkane-toolkit" +RELEASES = REPO + "/releases" +SECTIONS = (("", "Overview"), ("manual/", "Manual"), ("quality/", "Code quality"), + ("bench/", "Benchmarks")) + +CSS = """ +:root { --bg:#ffffff; --fg:#1f2328; --muted:#59636e; --line:#d1d9e0; --card:#f6f8fa; + --accent:#d9822b; --link:#0969da; --good:#1a7f37; --warn:#9a6700; --bad:#cf222e; } +@media (prefers-color-scheme: dark) { :root { --bg:#0d1117; --fg:#e6edf3; --muted:#9198a1; + --line:#30363d; --card:#151b23; --link:#4493f8; --good:#3fb950; --warn:#d29922; --bad:#f85149; } } +* { box-sizing: border-box; } +body { margin:0; background:var(--bg); color:var(--fg); + font:16px/1.55 system-ui,-apple-system,"Segoe UI",Roboto,Ubuntu,sans-serif; } +a { color:var(--link); text-decoration:none; } a:hover { text-decoration:underline; } +header { border-bottom:1px solid var(--line); } +header .bar, main { max-width:1040px; margin:0 auto; padding:0 16px; } +header .bar { display:flex; align-items:center; gap:24px; height:56px; flex-wrap:wrap; } +header .brand { font-weight:700; color:var(--fg); display:flex; gap:8px; align-items:center; } +header .brand i { width:20px; height:20px; border-radius:5px; background:var(--accent); display:inline-block; } +header nav { display:flex; gap:18px; flex-wrap:wrap; } +header nav a { color:var(--muted); } header nav a.on { color:var(--fg); font-weight:600; } +main { padding:28px 16px 64px; } +h1 { font-size:1.9rem; margin:.2em 0 .4em; } h2 { margin-top:1.8em; border-bottom:1px solid var(--line); padding-bottom:.25em; } +code { background:var(--card); border:1px solid var(--line); border-radius:5px; padding:.1em .35em; font-size:.92em; } +pre { background:var(--card); border:1px solid var(--line); border-radius:8px; padding:12px; overflow:auto; } +pre code { border:0; padding:0; } +table { border-collapse:collapse; width:100%; margin:1em 0; display:block; overflow-x:auto; } +th, td { border:1px solid var(--line); padding:6px 10px; text-align:left; vertical-align:top; } +th { background:var(--card); } +td.num, th.num { text-align:right; font-variant-numeric:tabular-nums; white-space:nowrap; } +.cards { display:grid; grid-template-columns:repeat(auto-fill,minmax(180px,1fr)); gap:12px; margin:1.2em 0; } +.card { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:14px; } +.card b { display:block; font-size:1.6rem; } .card span { color:var(--muted); font-size:.9rem; } +.good { color:var(--good); } .warn { color:var(--warn); } .bad { color:var(--bad); } +.bar-cell { min-width:120px; } .meter { height:8px; background:var(--line); border-radius:4px; overflow:hidden; } +.meter i { display:block; height:100%; } +.layout { display:grid; grid-template-columns:220px 1fr; gap:32px; } +.layout aside ol { padding-left:1.2em; margin:0; } .layout aside li { margin:.3em 0; } +.layout aside a.on { font-weight:600; color:var(--fg); } +@media (max-width:760px) { .layout { grid-template-columns:1fr; } } +.buttons a { display:inline-block; margin:4px 8px 4px 0; padding:8px 14px; border-radius:8px; + border:1px solid var(--line); background:var(--card); color:var(--fg); } +.buttons a.primary { background:var(--accent); border-color:var(--accent); color:#fff; } +footer { color:var(--muted); font-size:.85rem; margin-top:48px; } +""" + + +def page(title: str, body: str, depth: int, current: str, sha: str) -> str: + up = "../" * depth + nav = "".join( + f'{label}' + for path, label in SECTIONS) + built = f"Built from {html.escape(sha[:10])}. " if sha else "" + return f""" + + +{html.escape(title)} - Alkane Toolkit + +
Alkane Toolkit +
+
{body} +
+""" + + +def write(out: Path, rel: str, text: str) -> None: + path = out / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +# ---- manual ----------------------------------------------------------------- + +def chapters(manual: Path) -> list[tuple[str, str, str]]: + """(slug, title, markdown) for docs/manual/NN-slug.md, in file-name order.""" + out = [] + for path in sorted(manual.glob("[0-9][0-9]-*.md")): + text = path.read_text(encoding="utf-8") + m = re.search(r"^# (.+)$", text, re.M) + title = m.group(1).strip() if m else path.stem + out.append((path.stem[3:], title, text)) + return out + + +def build_manual(out: Path, manual: Path, sha: str) -> None: + items = chapters(manual) + if not items: + raise SystemExit(f"no manual chapters in {manual}") + + def toc(current: str) -> str: + links = "".join( + f'
  • ' + f"{html.escape(title)}
  • " for slug, title, _ in items) + return f"" + + for slug, title, text in items: + # Chapters link to each other as NN-name.md in the repo; on the site + # they are name.html. + text = re.sub(r"\]\((?:\./)?[0-9][0-9]-([a-z0-9-]+)\.md(#[^)]*)?\)", r"](\1.html\2)", text) + body_html = markdown.markdown(text, extensions=["tables", "fenced_code", "toc"]) + write(out, f"manual/{slug}.html", + page(title, f'
    {toc(slug)}
    {body_html}
    ', + 1, "manual/", sha)) + first = items[0][0] + listing = "".join(f'
  • {html.escape(t)}
  • ' for s, t, _ in items) + write(out, "manual/index.html", + page("Manual", f"

    Manual

    Start with " + f'{html.escape(items[0][1])}.

      {listing}
    ', + 1, "manual/", sha)) + + +# ---- quality dashboard --------------------------------------------------------- + +def pct_class(pct: float | None) -> str: + if pct is None: + return "" + return "good" if pct >= 80 else "warn" if pct >= 40 else "bad" + + +def meter(pct: float) -> str: + colour = {"good": "var(--good)", "warn": "var(--warn)", "bad": "var(--bad)"}[pct_class(pct)] + return f'
    ' + + +def build_quality(out: Path, quality: dict | None, sha: str) -> None: + e = html.escape + if not quality: + write(out, "quality/index.html", page( + "Code quality", "

    Code quality

    No measurement has been published yet; " + "the next main build will fill this page.

    ", 1, "quality/", sha)) + return + grade = str(quality.get("grade", "pending")) + cov = quality.get("coverage_pct") + bench_cov = quality.get("bench_coverage_pct") + delta = quality.get("bench_delta_pct") + + def card(value: str, label: str, cls: str = "") -> str: + return f'
    {value}{label}
    ' + + cards = "".join([ + card(e(grade), "Quality grade", {"A": "good", "B": "good", "C": "warn"}.get(grade, "bad")), + card(e(str(quality.get("tests_passed", "-"))), "Tests passing", "good"), + card(f"{cov:.1f}%" if cov is not None else "-", "Line coverage", pct_class(cov)), + card(f"{bench_cov:.1f}%" if bench_cov is not None else "-", "Benchmark coverage", pct_class(bench_cov)), + card(e(str(quality.get("clippy") or "-")), "Clippy (warnings are errors)", + "good" if quality.get("clippy") == "clean" else "bad"), + card(e(str(quality.get("rustfmt") or "-")), "rustfmt", "good" if quality.get("rustfmt") == "clean" else ""), + card(f"{quality.get('loc', 0):,}", "Lines of Rust"), + card(e(str(quality.get("dependencies", "-"))), "Crates in Cargo.lock"), + card((f"{'+' if delta > 0 else ''}{delta:.1f}%" if delta is not None else "-"), + "Benchmarks vs previous" + (" (same inputs)" if quality.get("bench_same_inputs") else ""), + "" if delta is None else "good" if delta >= 2 else "" if delta > -2 else "warn"), + ]) + bands = ", ".join(f"{e(str(letter))} at {floor:.0f}% or more" + for floor, letter in quality.get("grade_bands", [])) + grade_rule = (f"

    The grade is F if Clippy or rustfmt fails on main. Otherwise it is the " + f"line-coverage band: {bands}, and F below that. The coverage badge uses the " + f"same bands for its colour, so the two never disagree.

    ") + + crates = quality.get("coverage_by_crate", {}) + loc = quality.get("loc_by_crate", {}) + rows = [] + for name in sorted(set(crates) | set(loc)): + c = crates.get(name) + if c and c["lines"]: + pct = 100.0 * (c["lines"] - c["missed"]) / c["lines"] + cov_cells = (f'{pct:.1f}%' + f'{meter(pct)}' + f'{c["lines"] - c["missed"]:,} / {c["lines"]:,}') + else: + cov_cells = '--' + rows.append(f"{e(name)}{cov_cells}{loc.get(name, 0):,}") + crate_table = ("" + "" + + "".join(rows) + "
    CrateLine coverageCovered linesLines of Rust
    ") + + files = sorted(quality.get("coverage_by_file", []), + key=lambda r: (r["lines"] - r["missed"]) / r["lines"] if r["lines"] else 1) + file_rows = "".join( + f"{e(r['file'])}" + f"" + f"{100.0 * (r['lines'] - r['missed']) / r['lines']:.1f}%" + f"{r['missed']:,}{r['lines']:,}" + for r in files if r["lines"]) + file_table = ("" + "" + + file_rows + "
    File (least covered first)CoverageUncovered linesLines
    ") if file_rows else "" + + measured = str(quality.get("sha", ""))[:10] + of_build = f" (this page: {e(measured)})" if measured else "" + body = f"""

    Code quality

    +

    Measured by main CI on every build{of_build}: +unit tests, line coverage (unit tests plus the headless UI self-test), Clippy with +warnings as errors, and rustfmt. Windows builds run the same tests under Wine and +on real Windows 11.

    +
    {cards}
    +

    How the grade is set

    {grade_rule} +

    Coverage by crate

    {crate_table} +

    Coverage by file

    {file_table} +

    The dependency count is every package in Cargo.lock, direct and +transitive. Lines of Rust count every .rs line under crates/, +tests included.

    """ + write(out, "quality/index.html", page("Code quality", body, 1, "quality/", sha)) + + +# ---- benchmarks + overview ------------------------------------------------------- + +def build_bench(out: Path, bench: Path | None, sha: str) -> None: + if bench is None or not bench.is_file(): + write(out, "bench/index.html", page( + "Benchmarks", "

    Benchmarks

    No benchmark history yet.

    ", 1, "bench/", sha)) + return + rendered = bench.read_text(encoding="utf-8") + # The history renderer emits a complete document; keep its body (and its + # own styles) under the site's header. + styles = "".join(re.findall(r"]*>.*?", rendered, re.S | re.I)) + m = re.search(r"]*>(.*)", rendered, re.S | re.I) + inner = m.group(1) if m else rendered + text = page("Benchmarks", inner, 1, "bench/", sha) + write(out, "bench/index.html", text.replace("", styles + "", 1)) + + +def build_index(out: Path, quality: dict | None, sha: str) -> None: + grade = html.escape(str((quality or {}).get("grade", "pending"))) + body = f"""

    Alkane Toolkit

    +

    Desktop discovery and monitoring for ASIC miners on your network: find every +miner in your IP ranges, see hashrate, power, temperatures, fans and hashboard +health at a glance, and run the controls each firmware supports.

    + +

    Platforms

    + +

    Every release is built, tested and signed by CI from the public source.

    """ + write(out, "index.html", page("Overview", body, 0, "", sha)) + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--out", required=True) + ap.add_argument("--manual", default="docs/manual") + ap.add_argument("--quality", default=None) + ap.add_argument("--bench", default=None) + ap.add_argument("--sha", default="") + args = ap.parse_args() + out = Path(args.out) + if out.exists(): + shutil.rmtree(out) + out.mkdir(parents=True) + quality = None + if args.quality and Path(args.quality).is_file(): + quality = json.loads(Path(args.quality).read_text()) + if not isinstance(quality, dict) or quality.get("schema") != 1: + raise SystemExit("unsupported quality.json") + (out / "style.css").write_text(CSS.strip() + "\n", encoding="utf-8") + build_index(out, quality, args.sha) + build_manual(out, Path(args.manual), args.sha) + build_quality(out, quality, args.sha) + build_bench(out, Path(args.bench) if args.bench else None, args.sha) + print(f"built {sum(1 for _ in out.rglob('*.html'))} pages in {out}") + + +if __name__ == "__main__": + main() diff --git a/ci/check-runner-image.py b/ci/check-runner-image.py index 61730880..d8244918 100644 --- a/ci/check-runner-image.py +++ b/ci/check-runner-image.py @@ -32,12 +32,12 @@ def main() -> int: print(f"{path.name}: {name} has a different runner image", file=sys.stderr) return 1 pages = yaml.load( - (ROOT / ".gitea/workflows/bench-pages.yml").read_text(), + (ROOT / ".gitea/workflows/pages.yml").read_text(), Loader=yaml.BaseLoader, ) if (pages["on"]["workflow_run"]["workflows"] != ["build-test-release"] or pages["jobs"]["publish"].get("runs-on") != "alkane-verify"): - print("Benchmark Pages must follow main CI on the trusted verifier", file=sys.stderr) + print("Pages must follow main CI on the trusted verifier", file=sys.stderr) return 1 release = yaml.load( (ROOT / ".gitea/workflows/release.yml").read_text(), @@ -46,7 +46,7 @@ def main() -> int: if release["jobs"]["release"].get("runs-on") != "alkane-ci": print("Main release must use the dedicated Alkane build pool", file=sys.stderr) return 1 - if any("ci/publish-bench-pages.py" in step.get("run", "") + if any("ci/publish-pages.py" in step.get("run", "") for step in release["jobs"]["release"]["steps"]): print("Main release must not publish Pages from GARM", file=sys.stderr) return 1 diff --git a/ci/cleanup-generated.py b/ci/cleanup-generated.py index f0096c82..3def2858 100644 --- a/ci/cleanup-generated.py +++ b/ci/cleanup-generated.py @@ -9,9 +9,9 @@ import sys ROOT = Path(__file__).resolve().parents[1] -DIRECTORIES = ("target", "dist", "coverage", "bench-site") -FILES = ("bench-current.txt",) -BADGE_FILES = ("bench-baseline.json", "bench-context.json") +DIRECTORIES = ("target", "dist", "coverage", "bench-site", "site") +FILES = ("bench-current.txt", "coverage-summary.txt", "quality.json") +BADGE_FILES = ("bench-baseline.json", "bench-context.json", "quality.json") def cleanup() -> None: diff --git a/ci/ensure-build-deps.sh b/ci/ensure-build-deps.sh index c60f5c0f..68d9c15d 100644 --- a/ci/ensure-build-deps.sh +++ b/ci/ensure-build-deps.sh @@ -3,11 +3,12 @@ # Use the preinstalled CI image or install missing packages on older runners. set -euo pipefail -mode="${1:?usage: ensure-build-deps.sh base|ui|all|ssh|windows}" +mode="${1:?usage: ensure-build-deps.sh base|ui|all|ssh|windows|pages}" case "$mode" in base) packages=(libssl-dev pkg-config ca-certificates) ;; ui) packages=(xvfb xauth dbus-x11 fonts-dejavu-core) ;; ssh) packages=(openssh-client) ;; + pages) packages=(python3-markdown) ;; all) packages=(libssl-dev pkg-config ca-certificates openssh-client xvfb xauth dbus-x11 fonts-dejavu-core) ;; # Windows cross build (mingw-w64, posix threads) + Wine for its tests. diff --git a/ci/fetch-quality.py b/ci/fetch-quality.py new file mode 100755 index 00000000..00dfa8b4 --- /dev/null +++ b/ci/fetch-quality.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Download the measured quality record (badges/quality.json on ci-badges). + + fetch-quality.py OUT.json + +Writes nothing (and exits 0) when main CI has not published one yet, so the +Pages build shows a "not measured yet" dashboard instead of failing. +""" + +import base64 +import json +import os +from pathlib import Path +import sys +from urllib.error import HTTPError +from urllib.request import Request, urlopen + + +def main() -> None: + out = Path(sys.argv[1]) + api = os.environ["GITHUB_API_URL"].rstrip("/") + repo = os.environ["GITHUB_REPOSITORY"] + url = f"{api}/repos/{repo}/contents/badges/quality.json?ref=ci-badges" + request = Request(url, headers={"Authorization": f"token {os.environ['GITEA_TOKEN']}"}) + try: + with urlopen(request, timeout=20) as response: + content = base64.b64decode(json.load(response)["content"]) + except HTTPError as error: + if error.code == 404: + print("No quality record published yet") + return + raise + if not isinstance(json.loads(content), dict): + sys.exit("invalid quality record") + out.write_bytes(content) + print(f"Fetched quality record ({len(content)} bytes)") + + +if __name__ == "__main__": + main() diff --git a/ci/gen-badges.py b/ci/gen-badges.py index ba9f005c..35484843 100644 --- a/ci/gen-badges.py +++ b/ci/gen-badges.py @@ -135,10 +135,66 @@ def cov_color(pct: float) -> str: return "red" -def quality_grade(clippy: str | None) -> str: - if clippy is None: +# Code-quality grade (shown on the badge and explained on the Pages quality +# dashboard). Lint failures fail the grade outright; otherwise the grade is the +# measured line-coverage band, using the same bands as the coverage badge +# colour, so the two badges can never disagree. +GRADE_BANDS = ((80.0, "A"), (60.0, "B"), (40.0, "C"), (20.0, "D")) +GRADE_COLORS = {"A": "brightgreen", "B": "yellowgreen", "C": "yellow", + "D": "orange", "F": "red", "pending": "lightgrey"} + + +def quality_grade(clippy: str | None, coverage: float | None = None) -> str: + if clippy is None or (clippy == "clean" and coverage is None): return "pending" - return "A" if clippy == "clean" else "F" + if clippy != "clean": + return "F" + for floor, grade in GRADE_BANDS: + if coverage >= floor: + return grade + return "F" + + +def coverage_by_file(summary_path: str | None, root: str) -> list[dict]: + """Per-file line coverage from a `cargo llvm-cov --summary-only` table. + + Columns: Filename, Regions, Missed Regions, Cover, Functions, Missed + Functions, Executed, Lines, Missed Lines, Cover, ... + """ + if not summary_path: + return [] + rows = [] + root_abs = os.path.abspath(root).rstrip("/") + "/" + for line in Path(summary_path).read_text(errors="replace").splitlines(): + cols = line.split() + if len(cols) < 10 or cols[0] in ("Filename", "TOTAL") or not cols[0].endswith(".rs"): + continue + try: + lines, missed = int(cols[7]), int(cols[8]) + except ValueError: + continue + name = cols[0][len(root_abs):] if cols[0].startswith(root_abs) else cols[0] + rows.append({"file": name, "lines": lines, "missed": missed}) + return rows + + +def crate_of(path: str) -> str: + parts = Path(path).parts + if "crates" in parts and parts.index("crates") + 1 < len(parts): + return parts[parts.index("crates") + 1] + if "wx-rs-0.2.0-patched" in parts: + return "wx-rs (bridge)" + return "other" + + +def loc_by_crate(root: str) -> dict[str, int]: + out: dict[str, int] = {} + crates = Path(root) / "crates" + for path in sorted(crates.glob("*/**/*.rs")): + crate = path.relative_to(crates).parts[0] + with open(path, encoding="utf-8", errors="ignore") as fh: + out[crate] = out.get(crate, 0) + sum(1 for _ in fh) + return out def human(n: int) -> str: @@ -169,6 +225,9 @@ def main() -> int: # percentage string, or "NEW" when there is no baseline. ap.add_argument("--bench-delta", default=None) ap.add_argument("--clippy", choices=("clean", "failed")) + # The full `cargo llvm-cov --summary-only` table, for the per-crate and + # per-file breakdown in quality.json (the Pages quality dashboard). + ap.add_argument("--coverage-summary", default=None) args = ap.parse_args() for value in (args.coverage, args.bench_coverage): if value is not None and (not math.isfinite(value) or not 0 <= value <= 100): @@ -189,11 +248,9 @@ def main() -> int: write("loc", "lines of code", human(loc), loc_color(loc)) write("license", "license", lic, "blue") write("dependencies", "dependencies", str(deps), "blue") - grade = quality_grade(args.clippy) - write("quality", "code quality", grade, - {"A": "brightgreen", "B": "yellowgreen", "C": "yellow", - "D": "orange", "F": "red", "pending": "lightgrey"}[grade], - f"code quality: {grade} (GUI Clippy and first-party rustfmt)") + grade = quality_grade(args.clippy, args.coverage) + write("quality", "code quality", grade, GRADE_COLORS[grade], + f"code quality: {grade} (Clippy, rustfmt and line coverage)") if args.tests is not None: write("tests", "tests", f"{args.tests} passing", "brightgreen") if args.coverage is not None: @@ -228,6 +285,38 @@ def main() -> int: write("bench", "bench", "baseline set", "blue") elif args.bench is not None: write("bench", "bench", args.bench, "blue") + + # Everything above, plus the per-crate breakdowns, for the Pages quality + # dashboard (ci/build-pages.py). + files = coverage_by_file(args.coverage_summary, args.root) + crates: dict[str, dict] = {} + for row in files: + c = crates.setdefault(crate_of(row["file"]), {"lines": 0, "missed": 0}) + c["lines"] += row["lines"] + c["missed"] += row["missed"] + quality = { + "schema": 1, + "sha": os.environ.get("GITHUB_SHA", ""), + "grade": grade, + "grade_bands": [[floor, letter] for floor, letter in GRADE_BANDS], + "clippy": args.clippy, + "rustfmt": "clean" if args.clippy is not None else None, + "tests_passed": args.tests, + "coverage_pct": args.coverage, + "bench_coverage_pct": args.bench_coverage, + "bench_delta_pct": delta, + "bench_same_inputs": same_inputs, + "loc": loc, + "loc_by_crate": loc_by_crate(args.root), + "dependencies": deps, + "license": lic, + "coverage_by_crate": crates, + "coverage_by_file": files, + } + path = os.path.join(args.root, args.out, "quality.json") + with open(path, "w", encoding="utf-8") as fh: + json.dump(quality, fh, indent=1, sort_keys=True) + print(f"wrote {path}") return 0 diff --git a/ci/publish-metrics.py b/ci/publish-metrics.py index 3a6f06f0..35384c99 100644 --- a/ci/publish-metrics.py +++ b/ci/publish-metrics.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT """Publish measured toolkit badges to the private Gitea badge branch.""" +import json import os from pathlib import Path @@ -22,7 +23,14 @@ def main() -> None: raise ValueError(f"invalid {name} SVG") publish_file(api, repo, f"badges/{name}.svg", data, token, f"Update measured {name} badge") - print(f"Published {len(NAMES)} measured badge SVGs") + # The full measurement record behind the badges, read by the Pages + # quality dashboard (ci/build-pages.py). + data = (ROOT / "badges" / "quality.json").read_bytes() + if not isinstance(json.loads(data), dict): + raise ValueError("invalid quality.json") + publish_file(api, repo, "badges/quality.json", data, token, + "Update measured quality record", max_bytes=262_144) + print(f"Published {len(NAMES)} measured badge SVGs and quality.json") if __name__ == "__main__": diff --git a/ci/publish-pages.py b/ci/publish-pages.py new file mode 100755 index 00000000..71334039 --- /dev/null +++ b/ci/publish-pages.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Publish the built Pages site to this repository's gh-pages branch. + + publish-pages.py SITE_DIR + +Served at https://blueflare.gitea.bluefla.re/alkane-toolkit/ by the Pages +server, which serves the gh-pages branch of public repositories. Each publish +is one orphan commit (force-pushed), so the branch never accumulates history. +Only main may publish, and a run for a superseded main commit skips. +""" + +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +from urllib.request import Request, urlopen + +BRANCH = "gh-pages" +MAX_BYTES = 20 * 1024 * 1024 + + +def current_main_sha(api: str, repo: str, token: str) -> str: + request = Request(f"{api}/repos/{repo}/branches/main", + headers={"Authorization": f"token {token}"}) + with urlopen(request, timeout=20) as response: + return json.load(response)["commit"]["id"] + + +def git(*args: str, cwd: Path, env: dict | None = None) -> None: + subprocess.run(("git", *args), cwd=cwd, env=env, check=True) + + +def main() -> None: + if len(sys.argv) != 2: + sys.exit(__doc__) + site = Path(sys.argv[1]) + if not (site / "index.html").is_file(): + sys.exit(f"{site} has no index.html") + size = sum(p.stat().st_size for p in site.rglob("*") if p.is_file()) + if size > MAX_BYTES: + sys.exit(f"site is {size} bytes, over the {MAX_BYTES} byte limit") + for path in site.rglob("*"): + if path.is_file() and path.suffix not in {".html", ".css", ".svg", ".png", ".json"}: + sys.exit(f"unexpected file type on the site: {path}") + + api = os.environ["GITHUB_API_URL"].rstrip("/") + repo = os.environ["GITHUB_REPOSITORY"] + sha = os.environ["GITHUB_SHA"] + token = os.environ["GITEA_TOKEN"] + if os.environ.get("GITHUB_REF") != "refs/heads/main": + sys.exit("Pages publication requires main") + if current_main_sha(api, repo, token) != sha: + print("Skipping Pages for a superseded main commit") + return + + server = api.removesuffix("/api/v1") + with tempfile.TemporaryDirectory(prefix="alkane-pages-") as directory: + work = Path(directory) + shutil.copytree(site, work, dirs_exist_ok=True) + env = dict(os.environ, GIT_TERMINAL_PROMPT="0") + git("init", "-q", "-b", BRANCH, cwd=work) + git("-c", "user.name=Alkane CI", "-c", "user.email=ci@noreply.gitea.bluefla.re", + "add", "-A", cwd=work) + git("-c", "user.name=Alkane CI", "-c", "user.email=ci@noreply.gitea.bluefla.re", + "commit", "-q", "-m", f"Publish site for {sha[:10]} [skip ci]", cwd=work) + # The token is read from the environment by the credential helper at + # push time; it never appears on a command line or in the remote URL. + helper = '!f() { echo username=alkane-ci; echo "password=$GITEA_TOKEN"; }; f' + git("-c", f"credential.helper={helper}", "push", "-q", "--force", + f"{server}/{repo}.git", f"HEAD:refs/heads/{BRANCH}", cwd=work, env=env) + print(f"Published Pages for {sha[:10]} to {BRANCH}") + + +if __name__ == "__main__": + main() diff --git a/ci/test-bench-badge.py b/ci/test-bench-badge.py index 1cf6ff3d..76af8343 100644 --- a/ci/test-bench-badge.py +++ b/ci/test-bench-badge.py @@ -5,6 +5,7 @@ import importlib.util import re from pathlib import Path +import tempfile import unittest @@ -50,16 +51,35 @@ class BenchBadgeTests(unittest.TestCase): self.assertEqual(gen_badges.bench_color(30.0), "brightgreen") self.assertEqual(gen_badges.bench_color(-55.5555556), "orange") - def test_quality_grade_is_only_the_clippy_result(self): - self.assertEqual(gen_badges.quality_grade("clean"), "A") - self.assertEqual(gen_badges.quality_grade("failed"), "F") - self.assertEqual(gen_badges.quality_grade(None), "pending") - svg = gen_badges.badge_svg( - "code quality", "A", "brightgreen", - "code quality: A (GUI Clippy and first-party rustfmt)", - ) - self.assertIn('aria-label="code quality: A (GUI Clippy and first-party rustfmt)"', svg) - self.assertIn('>A', svg) + def test_quality_grade_follows_lint_and_coverage(self): + # A lint failure fails the grade; otherwise it is the coverage band, + # with the same floors as the coverage badge colour. + self.assertEqual(gen_badges.quality_grade("failed", 95.0), "F") + self.assertEqual(gen_badges.quality_grade("clean", 85.0), "A") + self.assertEqual(gen_badges.quality_grade("clean", 65.6), "B") + self.assertEqual(gen_badges.quality_grade("clean", 48.0), "C") + self.assertEqual(gen_badges.quality_grade("clean", 25.0), "D") + self.assertEqual(gen_badges.quality_grade("clean", 5.0), "F") + self.assertEqual(gen_badges.quality_grade("clean"), "pending") + self.assertEqual(gen_badges.quality_grade(None, 90.0), "pending") + for pct in (85.0, 65.6, 48.0, 25.0): + grade = gen_badges.quality_grade("clean", pct) + self.assertEqual(gen_badges.GRADE_COLORS[grade], gen_badges.cov_color(pct)) + + def test_coverage_table_is_split_by_crate(self): + with tempfile.TemporaryDirectory(prefix="alkane-cov-") as directory: + summary = Path(directory) / "summary.txt" + summary.write_text( + "Filename Regions Missed Regions Cover Functions Missed Functions " + "Executed Lines Missed Lines Cover\n" + "crates/alkane-gui/src/ui.rs 10 5 50.00% 4 2 50.00% 100 60 40.00%\n" + "crates/alkane-core/src/platform.rs 4 0 100.00% 2 0 100.00% 50 5 90.00%\n" + "TOTAL 14 5 64.29% 6 2 66.67% 150 65 56.67%\n") + rows = gen_badges.coverage_by_file(str(summary), directory) + self.assertEqual([r["file"] for r in rows], + ["crates/alkane-gui/src/ui.rs", "crates/alkane-core/src/platform.rs"]) + self.assertEqual(rows[0]["missed"], 60) + self.assertEqual(gen_badges.crate_of(rows[1]["file"]), "alkane-core") if __name__ == "__main__":