diff --git a/.github/workflows/azure-static-web-apps-lemon-flower-08f5ff603.yml b/.github/workflows/azure-static-web-apps-lemon-flower-08f5ff603.yml index 69e926e..2f29a1b 100644 --- a/.github/workflows/azure-static-web-apps-lemon-flower-08f5ff603.yml +++ b/.github/workflows/azure-static-web-apps-lemon-flower-08f5ff603.yml @@ -7,6 +7,15 @@ on: description: 'Force re-render executable posts' type: boolean default: false + raise_issues: + description: 'File render diagnostics as issues (main does this anyway)' + type: boolean + default: false + schedule: + # Weekly deployment - Sunday 19:00 UTC (GitHub Actions cron is always UTC). + # Note: UTC does not observe daylight saving, so this lands at 20:00 UK time + # during BST and 19:00 during GMT. + - cron: '0 19 * * 0' push: branches: - main @@ -19,14 +28,15 @@ on: jobs: render_site: runs-on: ubuntu-latest + permissions: + contents: read + issues: write steps: - - uses: actions/checkout@v2 - - name: Install GDebi first - run: sudo apt-get install gdebi-core - - name: Download the deb file - run: sudo curl -LO https://quarto.org/download/latest/quarto-linux-amd64.deb - - name: Install the deb file - run: sudo apt-get install -y ./quarto-linux-amd64.deb + - uses: actions/checkout@v4 + - name: Setup Quarto (latest stable release) + uses: quarto-dev/quarto-actions/setup@v2 + with: + version: release - name: Setup Python uses: actions/setup-python@v5 with: @@ -34,7 +44,9 @@ jobs: - name: Install Jupyter run: pip install jupyter - name: Verify Install - run: /usr/local/bin/quarto check + run: | + quarto --version + quarto check - name: Setup post venvs and re-render if: inputs.rerender == true run: | @@ -54,17 +66,64 @@ jobs: DATABRICKS_TOKEN: ${{ secrets.DATABRICKS_TOKEN }} DATABRICKS_CLUSTER_ID: ${{ secrets.DATABRICKS_CLUSTER_ID }} - name: render site - run: quarto render site/ + id: render + # Keep the log so the steps below can turn Quarto's diagnostics into + # tickets. A failed render must still reach those steps, so the job is + # failed explicitly at the end rather than here. + continue-on-error: true + run: | + set -o pipefail + quarto render site/ 2>&1 | tee render.log + - name: Collect render diagnostics + run: | + python3 scripts/parse_render_log.py render.log \ + ${{ steps.render.outcome == 'failure' && '--render-failed' || '' }} \ + > render-findings.json + cat render-findings.json + - name: Ensure render issue labels exist + if: github.ref == 'refs/heads/main' || inputs.raise_issues == true + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh label create render-issue --force --color B60205 \ + --description 'Raised automatically from a site render' + gh label create render-error --force --color D93F0B \ + --description 'Render diagnostic: error' + gh label create render-warning --force --color FBCA04 \ + --description 'Render diagnostic: warning' + gh label create automated --force --color C5DEF5 \ + --description 'Opened by automation' + - name: Raise issues for render diagnostics + # The default branch files real tickets, as does a dispatch that asks + # for them; every other ref only reports what it would have filed, so + # branches cannot spam the tracker. + # + # The condition is phrased negatively on purpose. GitHub's && and || + # yield operands rather than booleans, and '' is falsy, so the natural + # reading -- cond && '' || '--dry-run' -- collapses to '--dry-run' on + # both branches. Keep the non-empty value out of the falsy slot. + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + DRY_RUN: ${{ (github.ref != 'refs/heads/main' && inputs.raise_issues != true) && '--dry-run' || '' }} + run: python3 scripts/report_render_issues.py render-findings.json $DRY_RUN - name: Output folder directories run: ls - name: Upload _site directory for deploy job + if: steps.render.outcome == 'success' uses: actions/upload-artifact@v4 with: name: site_deployment path: site/_site + - name: Fail the job if the render failed + if: steps.render.outcome == 'failure' + run: | + echo "::error::quarto render failed - see the issues raised above" + exit 1 deploy_to_azure_static_webapp: needs: render_site - if: success() && github.event.ref == 'refs/heads/main' + # github.ref (unlike github.event.ref) is populated for every event type, so + # scheduled and manually dispatched runs on main deploy as well as pushes. + if: success() && github.ref == 'refs/heads/main' runs-on: ubuntu-latest name: Deploy to Azure App Service steps: diff --git a/scripts/parse_render_log.py b/scripts/parse_render_log.py new file mode 100755 index 0000000..a1d998d --- /dev/null +++ b/scripts/parse_render_log.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Extract diagnostics from a `quarto render` log and emit them as JSON. + +Quarto reports problems on stderr/stdout as it walks the document list, but a +green build hides them: the render succeeds and the warnings scroll away. This +parses the captured log, attributes each diagnostic to the document that was +being rendered at the time, and collapses repeats so the caller can raise one +ticket per distinct problem. + +Usage: parse_render_log.py render.log [--render-failed] > findings.json +""" + +import argparse +import hashlib +import json +import re +import sys + +ANSI = re.compile(r"\x1b\[[0-9;]*[A-Za-z]") +# "[ 8/30] tips/Notebook/Customcellmagics.qmd" - the document Quarto is on. +DOC = re.compile(r"^\[\s*\d+\s*/\s*\d+\]\s+(?P\S.*?)\s*$") +# "WARN: ...", "WARNING (/opt/quarto/.../main.lua:10090)", "ERROR: ..." +DIAG = re.compile(r"^(?PWARN|WARNING|ERROR)\b:?\s*(?P.*)$") +# Quarto embeds its own install paths and line numbers; they churn between +# versions and would otherwise fingerprint as a brand new problem each upgrade. +NOISE = re.compile(r"\((?:/|[A-Za-z]:\\)[^)]*?:\d+\)") + +SEVERITY = {"WARN": "warning", "WARNING": "warning", "ERROR": "error"} + + +def normalise(message): + """Strip version-dependent detail so the same problem fingerprints alike.""" + message = NOISE.sub("", message) + message = re.sub(r"\s+", " ", message) + return message.strip(" :\t") + + +def parse(lines): + findings = {} + current_doc = None + index = 0 + + while index < len(lines): + line = ANSI.sub("", lines[index]).rstrip() + + doc_match = DOC.match(line) + if doc_match: + current_doc = doc_match.group("path") + index += 1 + continue + + diag_match = DIAG.match(line) + if not diag_match: + index += 1 + continue + + severity = SEVERITY[diag_match.group("sev")] + parts = [diag_match.group("rest").strip()] + + # A Quarto warning header is often bare, with the actual complaint on + # the following lines. Keep reading until the next document or + # diagnostic, tolerating the blank line Quarto puts mid-message. + lookahead = index + 1 + blanks = 0 + while lookahead < len(lines): + nxt = ANSI.sub("", lines[lookahead]).rstrip() + if not nxt.strip(): + blanks += 1 + if blanks > 1: + break + lookahead += 1 + continue + if DOC.match(nxt) or DIAG.match(nxt) or nxt.startswith("Output created:"): + break + parts.append(nxt.strip()) + lookahead += 1 + index = lookahead + + message = normalise(" ".join(p for p in parts if p)) + if not message: + continue + + document = current_doc or "(site)" + fingerprint = hashlib.sha1( + f"{document}\n{message}".encode("utf-8") + ).hexdigest()[:12] + + if fingerprint in findings: + findings[fingerprint]["occurrences"] += 1 + else: + findings[fingerprint] = { + "fingerprint": fingerprint, + "severity": severity, + "document": document, + "message": message, + "occurrences": 1, + } + + return list(findings.values()) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("log", help="captured `quarto render` output") + parser.add_argument( + "--render-failed", + action="store_true", + help="the render itself exited non-zero; ensure that is reported even " + "if no line matched", + ) + args = parser.parse_args() + + with open(args.log, encoding="utf-8", errors="replace") as handle: + findings = parse(handle.read().splitlines()) + + if args.render_failed and not any(f["severity"] == "error" for f in findings): + findings.append({ + "fingerprint": "render-failed", + "severity": "error", + "document": "(site)", + "message": "quarto render exited non-zero without a parseable error " + "line; see the workflow log", + "occurrences": 1, + }) + + findings.sort(key=lambda f: (f["severity"] != "error", f["document"], f["message"])) + json.dump(findings, sys.stdout, indent=2) + sys.stdout.write("\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/report_render_issues.py b/scripts/report_render_issues.py new file mode 100755 index 0000000..b4932c3 --- /dev/null +++ b/scripts/report_render_issues.py @@ -0,0 +1,170 @@ +#!/usr/bin/env python3 +"""Raise (or revive) a GitHub issue for each finding from the render log. + +One ticket per distinct problem, keyed by the fingerprint the parser assigns and +embedded in the issue body as an HTML comment. A finding whose fingerprint is +already tracked never opens a second ticket: an open issue is left alone, and a +closed one is reopened with a note pointing at the run that brought it back. + +Issues are deliberately never auto-closed. Quarto's freeze cache means an +unchanged document is not re-rendered, so a warning missing from one run is not +evidence that it was fixed. + +Usage: report_render_issues.py findings.json [--dry-run] +""" + +import argparse +import json +import os +import re +import subprocess +import sys + +MARKER_LABEL = "render-issue" +FINGERPRINT = re.compile(r"") +TITLE_LIMIT = 100 + + +def gh(*args, **kwargs): + """Run a gh command, returning stdout.""" + return subprocess.run( + ["gh", *args], check=True, capture_output=True, text=True, **kwargs + ).stdout + + +def tracked_issues(): + """Map fingerprint -> issue, for every issue this workflow has ever filed.""" + raw = gh( + "issue", "list", + "--label", MARKER_LABEL, + "--state", "all", + "--limit", "500", + "--json", "number,state,title,body", + ) + tracked = {} + for issue in json.loads(raw or "[]"): + match = FINGERPRINT.search(issue.get("body") or "") + if match: + tracked[match.group("fp")] = issue + return tracked + + +def build_title(finding): + title = f"[render] {finding['document']}: {finding['message']}" + if len(title) > TITLE_LIMIT: + title = title[: TITLE_LIMIT - 1].rstrip() + "…" + return title + + +def build_body(finding, run_url): + document = finding["document"] + source = f"site/{document}" if document != "(site)" else "site/" + occurrences = finding["occurrences"] + plural = "" if occurrences == 1 else "s" + return f"""\ +Raised automatically by the **Validate Site and Deploy** workflow while rendering the site. + +| | | +|---|---| +| Document | `{document}` | +| Severity | {finding['severity']} | +| Occurrences in that run | {occurrences} time{plural} | + +### Message + +``` +{finding['message']} +``` + +### Reproduce locally + +```bash +quarto render "{source}" +``` + +Source run: {run_url} + + +""" + + +def summarise(lines): + summary_path = os.environ.get("GITHUB_STEP_SUMMARY") + text = "\n".join(lines) + print(text) + if summary_path: + with open(summary_path, "a", encoding="utf-8") as handle: + handle.write(text + "\n") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("findings", help="JSON produced by parse_render_log.py") + parser.add_argument( + "--dry-run", + action="store_true", + help="report what would be filed without touching GitHub", + ) + args = parser.parse_args() + + with open(args.findings, encoding="utf-8") as handle: + findings = json.load(handle) + + server = os.environ.get("GITHUB_SERVER_URL", "https://github.com") + repository = os.environ.get("GITHUB_REPOSITORY", "") + run_id = os.environ.get("GITHUB_RUN_ID", "") + run_url = f"{server}/{repository}/actions/runs/{run_id}" if run_id else "(local run)" + + if not findings: + summarise(["## Render diagnostics", "", "No warnings or errors. ✅"]) + return 0 + + tracked = {} if args.dry_run else tracked_issues() + lines = [ + "## Render diagnostics", + "", + f"{len(findings)} distinct problem(s) found." + + (" _Dry run - no issues were filed._" if args.dry_run else ""), + "", + "| Severity | Document | Problem | Action |", + "|---|---|---|---|", + ] + + for finding in findings: + fingerprint = finding["fingerprint"] + title = build_title(finding) + existing = tracked.get(fingerprint) + + if args.dry_run: + action = "would file" + elif existing and existing["state"].upper() == "OPEN": + action = f"already open (#{existing['number']})" + elif existing: + number = str(existing["number"]) + gh("issue", "reopen", number, + "--comment", f"This recurred in {run_url}.") + action = f"reopened (#{number})" + else: + url = gh( + "issue", "create", + "--title", title, + "--body", build_body(finding, run_url), + "--label", MARKER_LABEL, + "--label", f"render-{finding['severity']}", + "--label", "automated", + ).strip() + action = f"filed ({url.rsplit('/', 1)[-1] if url else 'new'})" + + cell = finding["message"].replace("|", "\\|") + if len(cell) > 80: + cell = cell[:79].rstrip() + "…" + lines.append( + f"| {finding['severity']} | `{finding['document']}` | {cell} | {action} |" + ) + + summarise(lines) + return 0 + + +if __name__ == "__main__": + sys.exit(main())