From b852cd1fc4bec2faab05c4dc31d25b7bbfe401c1 Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Fri, 20 Nov 2026 10:07:03 -0800 Subject: [PATCH 1/3] ci: fail a PR that changes a published OpenAPI document Adds a check that regenerates the website's OpenAPI documents and fails when any document at or below core's released version differs from the base branch, by hand or through TypeSpec. The published-openapi-change label allows a deliberate change; the diffs still print. Refs #1392 --- .github/workflows/ci-published-openapi.yml | 62 +++ lib/README.md | 1 + lib/core/DEVELOPMENT.md | 3 +- .../scripts/check-published-openapi.spec.ts | 221 +++++++++++ website/package.json | 1 + .../src/scripts/check-published-openapi.ts | 362 ++++++++++++++++++ 6 files changed, 649 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/ci-published-openapi.yml create mode 100644 website/__tests__/scripts/check-published-openapi.spec.ts create mode 100644 website/src/scripts/check-published-openapi.ts diff --git a/.github/workflows/ci-published-openapi.yml b/.github/workflows/ci-published-openapi.yml new file mode 100644 index 000000000..299561ffa --- /dev/null +++ b/.github/workflows/ci-published-openapi.yml @@ -0,0 +1,62 @@ +name: "CI - Website: Check Published OpenAPI Documents" + +# Fails a PR that changes a published OpenAPI document in +# website/public/openapi/, by hand or through a TypeSpec change. The +# `published-openapi-change` label allows a deliberate change; the diffs still +# print. See lib/core/DEVELOPMENT.md. + +on: + pull_request: + types: [opened, synchronize, reopened, labeled, unlabeled] + paths: + - lib/core/** + - website/public/openapi/** + - website/src/specs/** + - website/src/scripts/prune-openapi-tags.ts + - website/src/scripts/check-published-openapi.ts + - website/package.json + # A TypeSpec compiler bump can change the generated documents + - pnpm-lock.yaml + - pnpm-workspace.yaml + - .github/workflows/ci-published-openapi.yml + +defaults: + run: + working-directory: ./website + +jobs: + check: + runs-on: ubuntu-latest + + steps: + # The default pull_request checkout is the merge commit, so the check + # compares the merged result with the base branch tip. + - name: Checkout code + uses: actions/checkout@v7 + + - name: Fetch base branch + working-directory: . + run: git fetch --no-tags --depth=1 origin "$BASE_REF" + env: + BASE_REF: ${{ github.base_ref }} + + - name: Install pnpm + uses: pnpm/action-setup@v6 + + - name: Install Node.js + uses: actions/setup-node@v7 + with: + node-version-file: .nvmrc + cache: "pnpm" + + - name: Install dependencies + working-directory: . + run: pnpm install --frozen-lockfile + + # Checks the committed documents, regenerates them with + # `pnpm run typespec`, then checks again. + - name: Check published OpenAPI documents + run: pnpm run check:published-openapi --base "origin/$BASE_REF" + env: + BASE_REF: ${{ github.base_ref }} + PUBLISHED_OPENAPI_CHANGE_ALLOWED: ${{ contains(github.event.pull_request.labels.*.name, 'published-openapi-change') }} diff --git a/lib/README.md b/lib/README.md index 232d24c69..17e69d716 100644 --- a/lib/README.md +++ b/lib/README.md @@ -95,6 +95,7 @@ The rules: - **What goes into the hold branch:** `feat` and breaking (`!`) work for that release, and fixes to that unreleased work. - **What goes straight to `main`:** `fix` PRs for code already released on `main`, Dependabot and security updates, and docs-only changes. Docs for unreleased work, like migration notes, go in the hold branch with that work. - **Releases are always cut from `main`.** +- **Released OpenAPI documents stay fixed.** CI fails a PR, into `main` or a hold branch, that changes the website's OpenAPI document for any already released core version. The new version's document can change freely until its release. A deliberate edit needs the `published-openapi-change` label and a note in the PR saying why. See [core's development checklist](core/DEVELOPMENT.md#development-checklist). - **Hold branches aren't for blocked work.** A PR waiting on a review, a decision or another PR stays open against its usual base. The hold branch is for next-release work clustered in planning. Work continues on it normally. - **Keep it current with `main`.** Merge `main` into the hold branch at least weekly (**Update branch** on the staging PR does this). Rebasing works too. - **Open the staging PR early.** Open the staging PR as a draft early on. CI and the website preview then run on all the release's changes together, and the PR updates as each PR lands. "This branch is out-of-date with the base branch" is normal. A real merge conflict stops CI and the preview, so resolve it right away. diff --git a/lib/core/DEVELOPMENT.md b/lib/core/DEVELOPMENT.md index a1aafeae1..e5b0fead6 100644 --- a/lib/core/DEVELOPMENT.md +++ b/lib/core/DEVELOPMENT.md @@ -39,6 +39,7 @@ Patch releases skip the hold branch: `fix(core)` PRs go straight to `main`. Befo - [ ] An early PR into the hold branch adds the new version to the `Versions` enum in [`main.tsp`](lib/main.tsp) - [ ] Every PR decorates what it changes with the matching [versioning decorators](https://typespec.io/docs/libraries/versioning/reference/decorators/#@TypeSpec.Versioning.removed) - [ ] Every core PR runs `pnpm --filter website run typespec` and commits the regenerated files in [`website/public/openapi/`](../../website/public/openapi/) and [`website/public/schemas/yaml/`](../../website/public/schemas/yaml/) +- [ ] Published OpenAPI documents don't change. CI (`ci-published-openapi.yml`) fails a PR that changes any document whose version is at or below core's released version, whether by hand or through regeneration. If the change is deliberate, such as a description or example fix, add the `published-openapi-change` label and say why in the PR. Run it locally with `pnpm --filter website run check:published-openapi --base origin/`. ### Release review checklist @@ -47,7 +48,7 @@ Run this on the hold branch before merging the staging PR, and note the results - [ ] Regenerated specs match the committed files: after `pnpm --filter website run typespec`, `git status` shows no changes - [ ] Older versions are unchanged except for intended edits: - [ ] `git fetch origin` and `git diff origin/main...origin/ -- website/public/openapi/` have been run - - [ ] The diff adds `openapi..yaml`, and older versions show only edits you meant to make, such as a description or example fix + - [ ] The diff adds `openapi..yaml`, and older versions show only edits you meant to make, such as a description or example fix. CI already fails on any other change to a released version unless the PR has the `published-openapi-change` label; check that each labelled PR says why. - Comparing against `main` is what confirms the versioning decorators. Don't diff `lib/core/tsp-output/` against `website/public/openapi/`: the website build prunes unused tags (`website/src/scripts/prune-openapi-tags.ts`), so older versions always differ. - [ ] The new version has been reviewed in Swagger with `cg preview`: - [ ] From the repo root: `node lib/cli/dist/index.js preview website/public/openapi/openapi..yaml` (`pnpm install` builds the CLI), or `pnpm dlx @common-grants/cli preview ` diff --git a/website/__tests__/scripts/check-published-openapi.spec.ts b/website/__tests__/scripts/check-published-openapi.spec.ts new file mode 100644 index 000000000..9627f876e --- /dev/null +++ b/website/__tests__/scripts/check-published-openapi.spec.ts @@ -0,0 +1,221 @@ +/** + * Tests for `src/scripts/check-published-openapi.ts` (#1392): which documents + * count as published, and when the check fails. + */ + +import { describe, it, expect } from "vitest"; +import { + baseRefFromArgv, + classifyChange, + compareSemver, + decideOutcome, + dedupeResults, + overrideFromInputs, + selectPublishedDocuments, + versionFromFilename, + OVERRIDE_LABEL, + type DocumentResult, +} from "@/scripts/check-published-openapi"; + +const dir = "website/public/openapi"; +const files = (...versions: string[]) => + versions.map((v) => `${dir}/openapi.${v}.yaml`); + +describe("versionFromFilename", () => { + it("reads the version from a document filename", () => { + expect(versionFromFilename(`${dir}/openapi.0.5.0.yaml`)).toBe("0.5.0"); + expect(versionFromFilename("openapi.10.2.31.yaml")).toBe("10.2.31"); + }); + + it("ignores other files", () => { + expect(versionFromFilename(`${dir}/README.md`)).toBeNull(); + expect(versionFromFilename("openapi.yaml")).toBeNull(); + expect(versionFromFilename("openapi.0.5.yaml")).toBeNull(); + }); +}); + +describe("compareSemver", () => { + it("compares numerically, not as strings", () => { + expect(compareSemver("0.10.0", "0.9.0")).toBeGreaterThan(0); + expect(compareSemver("0.5.0", "0.6.0")).toBeLessThan(0); + expect(compareSemver("1.0.0", "0.99.99")).toBeGreaterThan(0); + expect(compareSemver("0.5.0", "0.5.0")).toBe(0); + }); + + it("ignores pre-release and build suffixes", () => { + expect(compareSemver("0.6.0-rc.1", "0.6.0")).toBe(0); + }); + + it("rejects non-versions", () => { + expect(() => compareSemver("latest", "0.5.0")).toThrow(); + }); +}); + +describe("selectPublishedDocuments", () => { + it("covers every version up to core's released version", () => { + const published = selectPublishedDocuments( + files("0.1.0", "0.2.0", "0.3.0", "0.4.0", "0.5.0"), + "0.5.0", + ); + expect(published.map((d) => d.version)).toEqual([ + "0.1.0", + "0.2.0", + "0.3.0", + "0.4.0", + "0.5.0", + ]); + expect(published[0].path).toBe(`${dir}/openapi.0.1.0.yaml`); + }); + + it("leaves out a hold branch's next version until core's version moves", () => { + const onHold = files("0.1.0", "0.2.0", "0.3.0", "0.4.0", "0.5.0", "0.6.0"); + expect( + selectPublishedDocuments(onHold, "0.5.0").map((d) => d.version), + ).not.toContain("0.6.0"); + expect( + selectPublishedDocuments(onHold, "0.6.0").map((d) => d.version), + ).toContain("0.6.0"); + }); + + it("sorts by version and skips unrelated files", () => { + const published = selectPublishedDocuments( + [...files("0.10.0", "0.2.0", "0.9.0"), `${dir}/notes.txt`], + "0.10.0", + ); + expect(published.map((d) => d.version)).toEqual([ + "0.2.0", + "0.9.0", + "0.10.0", + ]); + }); +}); + +describe("classifyChange", () => { + it("classifies unchanged, changed and deleted documents", () => { + expect(classifyChange("a\n", "a\n")).toBe("unchanged"); + expect(classifyChange("a\n", "b\n")).toBe("changed"); + expect(classifyChange("a\n", null)).toBe("deleted"); + }); +}); + +const result = ( + overrides: Partial & Pick, +): DocumentResult => ({ + phase: "committed", + change: "changed", + diff: "--- a\n+++ b\n-old\n+new\n", + ...overrides, +}); + +describe("dedupeResults", () => { + it("drops a regenerated diff that repeats the committed one", () => { + const path = `${dir}/openapi.0.3.0.yaml`; + const deduped = dedupeResults([ + result({ path }), + result({ path, phase: "regenerated" }), + ]); + expect(deduped).toHaveLength(1); + expect(deduped[0].phase).toBe("committed"); + }); + + it("keeps a regenerated diff that differs from the committed one", () => { + const path = `${dir}/openapi.0.3.0.yaml`; + const deduped = dedupeResults([ + result({ path }), + result({ path, phase: "regenerated", diff: "other" }), + ]); + expect(deduped).toHaveLength(2); + }); +}); + +describe("decideOutcome", () => { + const published = selectPublishedDocuments(files("0.4.0", "0.5.0"), "0.5.0"); + + it("passes when nothing changed", () => { + const outcome = decideOutcome({ + baseRef: "origin/main", + published, + results: [], + overrideAllowed: false, + }); + expect(outcome.exitCode).toBe(0); + expect(outcome.report).toContain("0.4.0, 0.5.0"); + }); + + it("fails, names each changed document and shows its diff", () => { + const outcome = decideOutcome({ + baseRef: "origin/main", + published, + results: [ + result({ path: `${dir}/openapi.0.4.0.yaml`, phase: "regenerated" }), + result({ path: `${dir}/openapi.0.5.0.yaml`, change: "deleted" }), + ], + overrideAllowed: false, + }); + expect(outcome.exitCode).toBe(1); + expect(outcome.report).toContain(`\`${dir}/openapi.0.4.0.yaml\` changed`); + expect(outcome.report).toContain(`\`${dir}/openapi.0.5.0.yaml\` deleted`); + expect(outcome.report).toContain("+new"); + expect(outcome.report).toContain("@returnTypeChangedFrom"); + expect(outcome.report).toContain(OVERRIDE_LABEL); + }); + + it("passes with the override but still shows every diff", () => { + const outcome = decideOutcome({ + baseRef: "origin/main", + published, + results: [result({ path: `${dir}/openapi.0.4.0.yaml` })], + overrideAllowed: true, + }); + expect(outcome.exitCode).toBe(0); + expect(outcome.report).toContain(`allowed by the \`${OVERRIDE_LABEL}\``); + expect(outcome.report).toContain("+new"); + }); + + it("truncates long diffs when asked, for the step summary", () => { + const long = Array.from({ length: 50 }, (_, i) => `+line ${i}`).join("\n"); + const outcome = decideOutcome({ + baseRef: "origin/main", + published, + results: [result({ path: `${dir}/openapi.0.4.0.yaml`, diff: long })], + overrideAllowed: false, + maxDiffLines: 10, + }); + expect(outcome.report).toContain("+line 9"); + expect(outcome.report).not.toContain("+line 10"); + expect(outcome.report).toContain("40 more lines"); + }); + + it("notes when the committed change also shows after regeneration", () => { + const path = `${dir}/openapi.0.4.0.yaml`; + const outcome = decideOutcome({ + baseRef: "origin/main", + published, + results: [result({ path }), result({ path, phase: "regenerated" })], + overrideAllowed: false, + }); + expect(outcome.report.match(/```diff/g)).toHaveLength(1); + expect(outcome.report).toContain("same diff after regeneration"); + }); +}); + +describe("inputs", () => { + it("reads the override from the flag or the environment", () => { + expect(overrideFromInputs(["--allow-changes"], {})).toBe(true); + expect( + overrideFromInputs([], { PUBLISHED_OPENAPI_CHANGE_ALLOWED: "true" }), + ).toBe(true); + expect( + overrideFromInputs([], { PUBLISHED_OPENAPI_CHANGE_ALLOWED: "false" }), + ).toBe(false); + expect(overrideFromInputs([], {})).toBe(false); + }); + + it("reads the base ref, defaulting to origin/main", () => { + expect(baseRefFromArgv([])).toBe("origin/main"); + expect(baseRefFromArgv(["--base", "origin/CORE-v0.6.0"])).toBe( + "origin/CORE-v0.6.0", + ); + expect(() => baseRefFromArgv(["--base"])).toThrow(); + }); +}); diff --git a/website/package.json b/website/package.json index 7114c77ed..7b65da522 100644 --- a/website/package.json +++ b/website/package.json @@ -30,6 +30,7 @@ "check:a11y": "tsx src/scripts/a11y-scan.ts", "check:quickstarts": "tsx src/scripts/check-quickstarts.ts", "check:types": "tsc --noEmit", + "check:published-openapi": "tsx src/scripts/check-published-openapi.ts", "checks": "pnpm check:lint && pnpm check:format && pnpm check:types && pnpm check:astro && pnpm check:spelling", "ci": "pnpm run build && pnpm run checks && pnpm run test", "audit:moderate": "pnpm audit --audit-level=moderate", diff --git a/website/src/scripts/check-published-openapi.ts b/website/src/scripts/check-published-openapi.ts new file mode 100644 index 000000000..e3695e037 --- /dev/null +++ b/website/src/scripts/check-published-openapi.ts @@ -0,0 +1,362 @@ +import { execFileSync } from "child_process"; +import { + existsSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "fs"; +import { tmpdir } from "os"; +import path from "path"; + +/** + * Fails when a published OpenAPI document changes (#1392). + * + * A document is published when `website/public/openapi/openapi..yaml` + * exists on the base ref and `` is at or below the version in the base + * ref's `lib/core/package.json`. A hold branch can add the next version's + * document before the release bumps core's version, so that document isn't + * covered until the release merges. + * + * Each published document is compared with the base ref's copy twice: as + * committed (catches hand edits and deletions), then after regenerating with + * `pnpm run typespec` (catches TypeSpec changes that alter older versions). + * Regenerating overwrites `public/openapi/` in the working tree. + * + * Usage (from `website/`): + * tsx src/scripts/check-published-openapi.ts [--base ] [--allow-changes] + * + * `--allow-changes`, or `PUBLISHED_OPENAPI_CHANGE_ALLOWED=true`, still prints + * every diff but exits 0. CI sets it when the PR has the + * `published-openapi-change` label. + */ + +export const OVERRIDE_LABEL = "published-openapi-change"; +export const OPENAPI_DIR = "website/public/openapi"; +export const CORE_PACKAGE_JSON = "lib/core/package.json"; + +const FILENAME_PATTERN = /^openapi\.(\d+)\.(\d+)\.(\d+)\.yaml$/; + +// ############################################################ +// Pure logic +// ############################################################ + +/** The version in an `openapi..yaml` filename, or null for any other file. */ +export function versionFromFilename(filename: string): string | null { + const match = FILENAME_PATTERN.exec(path.basename(filename)); + return match ? `${match[1]}.${match[2]}.${match[3]}` : null; +} + +/** Compares two `major.minor.patch` versions; pre-release suffixes are ignored. */ +export function compareSemver(a: string, b: string): number { + const parse = (v: string): number[] => { + const core = v.trim().replace(/^v/, "").split(/[-+]/)[0]; + const parts = core.split(".").map((p) => Number(p)); + if ( + parts.length !== 3 || + parts.some((p) => !Number.isInteger(p) || p < 0) + ) { + throw new Error(`Not a semver version: "${v}"`); + } + return parts; + }; + const [pa, pb] = [parse(a), parse(b)]; + for (let i = 0; i < 3; i++) { + if (pa[i] !== pb[i]) return pa[i] - pb[i]; + } + return 0; +} + +export interface PublishedDocument { + version: string; + /** Repo-relative path, e.g. `website/public/openapi/openapi.0.5.0.yaml`. */ + path: string; +} + +/** + * The published documents: those on the base ref whose version is at or + * below core's released version, oldest first. + */ +export function selectPublishedDocuments( + baseFiles: string[], + coreVersion: string, +): PublishedDocument[] { + return baseFiles + .map((file) => ({ file, version: versionFromFilename(file) })) + .filter( + (entry): entry is { file: string; version: string } => + entry.version !== null && + compareSemver(entry.version, coreVersion) <= 0, + ) + .sort((a, b) => compareSemver(a.version, b.version)) + .map(({ file, version }) => ({ + version, + path: `${OPENAPI_DIR}/${path.basename(file)}`, + })); +} + +export type Phase = "committed" | "regenerated"; +export type Change = "unchanged" | "changed" | "deleted"; + +/** How a document differs from the base ref's copy; `current` is null when missing. */ +export function classifyChange(base: string, current: string | null): Change { + if (current === null) return "deleted"; + return current === base ? "unchanged" : "changed"; +} + +export interface DocumentResult { + path: string; + phase: Phase; + change: Exclude; + /** Unified diff against the base ref's copy. */ + diff: string; +} + +/** + * Drops a regenerated-phase result that repeats a committed-phase result for + * the same document, so the same diff isn't printed twice. + */ +export function dedupeResults(results: DocumentResult[]): DocumentResult[] { + const committed = new Map( + results + .filter((r) => r.phase === "committed") + .map((r) => [r.path, r] as const), + ); + return results.filter((r) => { + if (r.phase !== "regenerated") return true; + const earlier = committed.get(r.path); + return !(earlier && earlier.change === r.change && earlier.diff === r.diff); + }); +} + +export interface Outcome { + exitCode: 0 | 1; + /** Markdown report, also used for `$GITHUB_STEP_SUMMARY`. */ + report: string; +} + +const PHASE_LABEL: Record = { + committed: "committed file", + regenerated: "after `pnpm --filter website run typespec`", +}; + +/** The exit code and report for a run. */ +export function decideOutcome(args: { + baseRef: string; + published: PublishedDocument[]; + results: DocumentResult[]; + overrideAllowed: boolean; + /** Truncate each diff to this many lines (for `$GITHUB_STEP_SUMMARY`). */ + maxDiffLines?: number; +}): Outcome { + const { baseRef, published, overrideAllowed } = args; + const results = dedupeResults(args.results); + const covered = published.map((d) => d.version).join(", ") || "none"; + + if (results.length === 0) { + return { + exitCode: 0, + report: + `## Published OpenAPI documents unchanged\n\n` + + `Compared with \`${baseRef}\`. Published versions: ${covered}.\n`, + }; + } + + const changedPaths = [...new Set(results.map((r) => r.path))]; + const sections = results.map((r) => { + const what = r.change === "deleted" ? "deleted" : "changed"; + const both = + r.phase === "committed" && + args.results.some( + (o) => o.path === r.path && o.phase === "regenerated", + ) && + !results.some((o) => o.path === r.path && o.phase === "regenerated"); + const phase = both + ? `${PHASE_LABEL.committed}; same diff after regeneration` + : PHASE_LABEL[r.phase]; + const body = r.diff + ? `\n\`\`\`diff\n${truncateLines(r.diff.trimEnd(), args.maxDiffLines)}\n\`\`\`\n` + : "\n"; + return `### \`${r.path}\` ${what} (${phase})\n${body}`; + }); + + const header = overrideAllowed + ? `## Published OpenAPI documents changed (allowed by the \`${OVERRIDE_LABEL}\` label)` + : `## Published OpenAPI documents changed`; + const advice = overrideAllowed + ? `The \`${OVERRIDE_LABEL}\` label allows these changes. Say in the PR why they're intended.` + : `To proceed, fix the TypeSpec so older versions keep their shape (versioning decorators such as \`@returnTypeChangedFrom\`), ` + + `or, if the change is deliberate, add the \`${OVERRIDE_LABEL}\` label and say why in the PR.`; + + const report = + `${header}\n\n` + + `Compared with \`${baseRef}\`. Published versions: ${covered}.\n\n` + + `Changed: ${changedPaths.map((p) => `\`${p}\``).join(", ")}\n\n` + + `${advice}\n\n` + + sections.join("\n"); + + return { exitCode: overrideAllowed ? 0 : 1, report }; +} + +function truncateLines(text: string, max: number | undefined): string { + const lines = text.split("\n"); + if (max === undefined || lines.length <= max) return text; + return [ + ...lines.slice(0, max), + `... ${lines.length - max} more lines; see the job log for the full diff`, + ].join("\n"); +} + +/** True for `--allow-changes` or a truthy `PUBLISHED_OPENAPI_CHANGE_ALLOWED`. */ +export function overrideFromInputs( + argv: string[], + env: Record, +): boolean { + if (argv.includes("--allow-changes")) return true; + const value = env.PUBLISHED_OPENAPI_CHANGE_ALLOWED?.trim().toLowerCase(); + return value === "true" || value === "1"; +} + +/** The base ref from `--base `, defaulting to `origin/main`. */ +export function baseRefFromArgv(argv: string[]): string { + const index = argv.indexOf("--base"); + if (index === -1) return "origin/main"; + const ref = argv[index + 1]; + if (!ref || ref.startsWith("--")) throw new Error("--base needs a ref"); + return ref; +} + +// ############################################################ +// Git and filesystem +// ############################################################ + +function git(repoRoot: string, args: string[]): string { + return execFileSync("git", args, { + cwd: repoRoot, + encoding: "utf8", + maxBuffer: 64 * 1024 * 1024, + }); +} + +/** Unified diff of base vs current text, labelled with the document path. */ +function unifiedDiff( + docPath: string, + base: string, + current: string | null, +): string { + const dir = mkdtempSync(path.join(tmpdir(), "published-openapi-")); + try { + const basePath = path.join(dir, "base"); + const currentPath = path.join(dir, "current"); + writeFileSync(basePath, base); + writeFileSync(currentPath, current ?? ""); + try { + execFileSync( + "diff", + [ + "-u", + "--label", + `a/${docPath}`, + "--label", + current === null ? "/dev/null" : `b/${docPath}`, + basePath, + currentPath, + ], + { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }, + ); + return ""; + } catch (error) { + const { status, stdout } = error as { status?: number; stdout?: string }; + if (status === 1 && typeof stdout === "string") return stdout; + throw error; + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +function checkPhase( + repoRoot: string, + phase: Phase, + docs: PublishedDocument[], + baseTexts: Map, +): DocumentResult[] { + const results: DocumentResult[] = []; + for (const doc of docs) { + const base = baseTexts.get(doc.path)!; + const file = path.join(repoRoot, doc.path); + const current = existsSync(file) ? readFileSync(file, "utf8") : null; + const change = classifyChange(base, current); + if (change === "unchanged") continue; + results.push({ + path: doc.path, + phase, + change, + // A deletion is named in the heading; its diff would only repeat the whole file. + diff: current === null ? "" : unifiedDiff(doc.path, base, current), + }); + } + return results; +} + +function main(): void { + const argv = process.argv.slice(2); + const baseRef = baseRefFromArgv(argv); + const overrideAllowed = overrideFromInputs(argv, process.env); + const regenerate = !argv.includes("--no-regenerate"); + const repoRoot = git(process.cwd(), ["rev-parse", "--show-toplevel"]).trim(); + + const coreVersion = JSON.parse( + git(repoRoot, ["show", `${baseRef}:${CORE_PACKAGE_JSON}`]), + ).version as string; + const baseFiles = git(repoRoot, [ + "ls-tree", + "--name-only", + baseRef, + `${OPENAPI_DIR}/`, + ]) + .split("\n") + .filter(Boolean); + const published = selectPublishedDocuments(baseFiles, coreVersion); + const baseTexts = new Map( + published.map((d) => [ + d.path, + git(repoRoot, ["show", `${baseRef}:${d.path}`]), + ]), + ); + + console.log( + `Base ${baseRef}: core ${coreVersion}; published versions ${published.map((d) => d.version).join(", ") || "none"}`, + ); + + const results = checkPhase(repoRoot, "committed", published, baseTexts); + if (regenerate) { + console.log("Regenerating with `pnpm run typespec`..."); + execFileSync("pnpm", ["run", "typespec"], { + cwd: path.join(repoRoot, "website"), + stdio: "inherit", + }); + results.push(...checkPhase(repoRoot, "regenerated", published, baseTexts)); + } + + const outcome = { baseRef, published, results, overrideAllowed }; + const { exitCode, report } = decideOutcome(outcome); + console.log(`\n${report}`); + if (process.env.GITHUB_STEP_SUMMARY) { + // GitHub rejects step summaries over 1 MiB, so cap each diff there. + const summary = decideOutcome({ ...outcome, maxDiffLines: 200 }).report; + writeFileSync(process.env.GITHUB_STEP_SUMMARY, `${summary}\n`, { + flag: "a", + }); + } + process.exit(exitCode); +} + +if (import.meta.url === `file://${process.argv[1]}`) { + try { + main(); + } catch (error) { + console.error("Failed to check the published OpenAPI documents:", error); + process.exit(1); + } +} From 3b6fcadb8881accb163126e1bf1f7e7659298871 Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Fri, 20 Nov 2026 10:22:47 -0800 Subject: [PATCH 2/3] ci: compare published OpenAPI documents with the merge base parent Checks the PR's merge commit against its first parent instead of refetching the base branch, adds website/tspconfig.yaml to the trigger paths, and builds the diff with one git diff call. Refs #1392 --- .github/workflows/ci-published-openapi.yml | 19 ++--- .../src/scripts/check-published-openapi.ts | 82 +++++++++---------- 2 files changed, 48 insertions(+), 53 deletions(-) diff --git a/.github/workflows/ci-published-openapi.yml b/.github/workflows/ci-published-openapi.yml index 299561ffa..d582c9ebd 100644 --- a/.github/workflows/ci-published-openapi.yml +++ b/.github/workflows/ci-published-openapi.yml @@ -15,6 +15,8 @@ on: - website/src/scripts/prune-openapi-tags.ts - website/src/scripts/check-published-openapi.ts - website/package.json + # Holds the openapi3 emitter options, so a change rewrites every document + - website/tspconfig.yaml # A TypeSpec compiler bump can change the generated documents - pnpm-lock.yaml - pnpm-workspace.yaml @@ -29,16 +31,14 @@ jobs: runs-on: ubuntu-latest steps: - # The default pull_request checkout is the merge commit, so the check - # compares the merged result with the base branch tip. + # The default pull_request checkout is the merge commit. Its first parent + # (HEAD^1) is the base branch tip the PR was merged against, so the check + # compares the merged result with that exact commit. fetch-depth 2 brings + # that parent along. - name: Checkout code uses: actions/checkout@v7 - - - name: Fetch base branch - working-directory: . - run: git fetch --no-tags --depth=1 origin "$BASE_REF" - env: - BASE_REF: ${{ github.base_ref }} + with: + fetch-depth: 2 - name: Install pnpm uses: pnpm/action-setup@v6 @@ -56,7 +56,6 @@ jobs: # Checks the committed documents, regenerates them with # `pnpm run typespec`, then checks again. - name: Check published OpenAPI documents - run: pnpm run check:published-openapi --base "origin/$BASE_REF" + run: pnpm run check:published-openapi --base HEAD^1 env: - BASE_REF: ${{ github.base_ref }} PUBLISHED_OPENAPI_CHANGE_ALLOWED: ${{ contains(github.event.pull_request.labels.*.name, 'published-openapi-change') }} diff --git a/website/src/scripts/check-published-openapi.ts b/website/src/scripts/check-published-openapi.ts index e3695e037..44774491d 100644 --- a/website/src/scripts/check-published-openapi.ts +++ b/website/src/scripts/check-published-openapi.ts @@ -1,12 +1,5 @@ import { execFileSync } from "child_process"; -import { - existsSync, - mkdtempSync, - readFileSync, - rmSync, - writeFileSync, -} from "fs"; -import { tmpdir } from "os"; +import { existsSync, readFileSync, writeFileSync } from "fs"; import path from "path"; /** @@ -238,47 +231,42 @@ function git(repoRoot: string, args: string[]): string { }); } -/** Unified diff of base vs current text, labelled with the document path. */ +/** + * Unified diff of the base ref's copy against the working-tree file, with + * `a/` and `b/` labels. The flags and `-c` settings pin the + * output so local git config (external diff tools, textconv, prefixes, + * context size, algorithm) can't change it. + */ function unifiedDiff( + repoRoot: string, + baseRef: string, docPath: string, - base: string, - current: string | null, ): string { - const dir = mkdtempSync(path.join(tmpdir(), "published-openapi-")); - try { - const basePath = path.join(dir, "base"); - const currentPath = path.join(dir, "current"); - writeFileSync(basePath, base); - writeFileSync(currentPath, current ?? ""); - try { - execFileSync( - "diff", - [ - "-u", - "--label", - `a/${docPath}`, - "--label", - current === null ? "/dev/null" : `b/${docPath}`, - basePath, - currentPath, - ], - { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }, - ); - return ""; - } catch (error) { - const { status, stdout } = error as { status?: number; stdout?: string }; - if (status === 1 && typeof stdout === "string") return stdout; - throw error; - } - } finally { - rmSync(dir, { recursive: true, force: true }); - } + return git(repoRoot, [ + "-c", + "diff.suppressBlankEmpty=false", + "diff", + "--no-color", + "--no-ext-diff", + "--no-textconv", + "--no-relative", + "--src-prefix=a/", + "--dst-prefix=b/", + "--unified=3", + "--inter-hunk-context=0", + "--diff-algorithm=myers", + "--indent-heuristic", + baseRef, + "--", + docPath, + ]); } function checkPhase( repoRoot: string, phase: Phase, docs: PublishedDocument[], + baseRef: string, baseTexts: Map, ): DocumentResult[] { const results: DocumentResult[] = []; @@ -293,7 +281,7 @@ function checkPhase( phase, change, // A deletion is named in the heading; its diff would only repeat the whole file. - diff: current === null ? "" : unifiedDiff(doc.path, base, current), + diff: current === null ? "" : unifiedDiff(repoRoot, baseRef, doc.path), }); } return results; @@ -329,14 +317,22 @@ function main(): void { `Base ${baseRef}: core ${coreVersion}; published versions ${published.map((d) => d.version).join(", ") || "none"}`, ); - const results = checkPhase(repoRoot, "committed", published, baseTexts); + const results = checkPhase( + repoRoot, + "committed", + published, + baseRef, + baseTexts, + ); if (regenerate) { console.log("Regenerating with `pnpm run typespec`..."); execFileSync("pnpm", ["run", "typespec"], { cwd: path.join(repoRoot, "website"), stdio: "inherit", }); - results.push(...checkPhase(repoRoot, "regenerated", published, baseTexts)); + results.push( + ...checkPhase(repoRoot, "regenerated", published, baseRef, baseTexts), + ); } const outcome = { baseRef, published, results, overrideAllowed }; From 1ab800cbf5be48474c4abc3128999ea99d993b73 Mon Sep 17 00:00:00 2001 From: Bryan Thompson Date: Fri, 20 Nov 2026 10:28:01 -0800 Subject: [PATCH 3/3] ci: add textconv to the website spelling words Refs #1392 --- website/.cspell.json | 1 + 1 file changed, 1 insertion(+) diff --git a/website/.cspell.json b/website/.cspell.json index 72a68ac8a..4ed3a9b0a 100644 --- a/website/.cspell.json +++ b/website/.cspell.json @@ -72,6 +72,7 @@ "Snohomish", "subrecipient", "TCCUs", + "textconv", "Temelio", "tiktok", "timebox",