diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a3d6bbeabc7..21ff7d2cb0b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,6 +29,7 @@ jobs: STABLE_LANE: ${{ github.ref_name == 'master' || github.base_ref == 'master' || (github.event_name == 'merge_group' && github.event.merge_group.base_ref == 'refs/heads/master') }} outputs: docs: ${{ steps.classify.outputs.docs }} + release: ${{ steps.classify.outputs.release }} javascript: ${{ steps.classify.outputs.javascript }} napi: ${{ steps.classify.outputs.napi }} napi_arm64: ${{ steps.classify.outputs.napi_arm64 }} @@ -45,6 +46,8 @@ jobs: BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }} HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }} FULL_VALIDATION: ${{ github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' }} + MERGE_GROUP_BASE_REF: ${{ github.event.merge_group.base_ref }} + RELEASE_PLEASE_PR: ${{ github.event_name == 'pull_request' && github.head_ref == 'release-please--branches--master--components--celox' && github.event.pull_request.head.repo.full_name == github.repository }} run: node scripts/ci-changes.mjs "$BASE_SHA" "$HEAD_SHA" - name: Reject development dependencies from the stable lane @@ -217,7 +220,10 @@ jobs: external-suites: name: External suite (${{ matrix.suite }}, ${{ matrix.tool }}) - if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + needs: changes + # Scheduled and manual runs compare even when change detection fails. A + # merge group that cuts a release also compares before it can merge. + if: always() && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || needs.changes.outputs.release == 'true') runs-on: ubuntu-latest timeout-minutes: 90 strategy: @@ -403,7 +409,7 @@ jobs: # into a successful check merely because a downstream job was skipped. rust: name: Rust Test & NAPI Build - needs: [changes, rust-tests, napi-linux, napi-wasm] + needs: [changes, rust-tests, napi-linux, napi-wasm, external-suites] if: always() && (needs.changes.result != 'success' || needs.changes.outputs.rust == 'true' || needs.changes.outputs.napi == 'true') runs-on: ubuntu-latest env: @@ -413,6 +419,10 @@ jobs: NAPI_REQUIRED: ${{ needs.changes.outputs.napi }} NATIVE_RESULT: ${{ needs.napi-linux.result }} WASM_RESULT: ${{ needs.napi-wasm.result }} + # Only a release merge group gates on the comparisons. Full runs report + # them through report-full-validation instead. + RELEASE_REQUIRED: ${{ needs.changes.outputs.release }} + EXTERNAL_RESULT: ${{ needs.external-suites.result }} steps: - name: Check tests and builds run: | @@ -426,6 +436,9 @@ jobs: if [ "$NAPI_REQUIRED" != false ] || [ "$WASM_RESULT" != skipped ]; then test "$WASM_RESULT" = success fi + if [ "$RELEASE_REQUIRED" != false ]; then + test "$EXTERNAL_RESULT" = success + fi arm64-backend: name: ARM64 Backend Test @@ -661,3 +674,43 @@ jobs: - name: Run Playground browser tests timeout-minutes: 5 run: pnpm --filter @celox-sim/playground exec playwright test + + # Full runs are not merge gates, so a failure must reach someone. Keep one + # issue per branch open while full CI fails and close it once it passes. + report-full-validation: + name: Report full validation + needs: + [ + changes, + docs, + lint, + rust-tests, + external-suites, + napi-linux, + napi-wasm, + rust, + arm64-backend, + napi-windows, + napi-linux-arm64, + js-ubuntu, + js-windows, + playground-browser, + ] + if: always() && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') && (github.ref_name == 'master' || github.ref_name == 'develop') + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + steps: + - uses: actions/checkout@v7 + with: + sparse-checkout: scripts + + - name: Open, update, or close the full CI issue + env: + GH_TOKEN: ${{ github.token }} + NEEDS: ${{ toJSON(needs) }} + BRANCH: ${{ github.ref_name }} + SHA: ${{ github.sha }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: node scripts/report-full-ci.mjs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2ffcaee4918..18ec9043f34 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -88,9 +88,13 @@ uses the finer behavior-based matrix above. | Every full CI run | Run every shared Veryl and SystemVerilog case against both Verilator and Icarus, with locked Nix tools. Run the live adapter tests normally marked ignored because they need external tools. Preserve reports and per-case diagnostics as artifacts for 14 days, including on failure; matrix failures do not cancel the other comparisons. | | Weekly and on relevant changes | Existing `lydite.yml` proof, conformance, editor, and mutation gates. Existing Heliodor scheduled runs cover the longer simulator workloads daily. | | On demand | Dispatch `ci.yml` on the desired branch to run full CI and external comparisons, regardless of its diff. | +| Merge groups that cut a release | A `master` merge group whose diff changes `.release-please-manifest.json` (only the release pull request does there; syncing it into `develop` is not a release) runs full CI and the external comparisons. `Rust Test & NAPI Build` then requires the comparisons to pass, so a release cannot merge after only change-based checks. Daily and manual full runs do not gate on the comparisons; their failures reach the full CI issue below. A `master` merge group whose diff cannot be determined is treated the same way. | Full runs have a separate concurrency group so ordinary pushes cannot cancel -them. They report failures normally; they are not advisory jobs with +them. Scheduled and dispatched full runs on `master` and `develop` end with +`Report full validation`: a failed or cancelled job opens the issue +"Full CI is failing on ", or comments on it while it stays open, and +the next passing full run closes it. They report failures normally; they are not advisory jobs with `continue-on-error`. The external comparison gate accepts an existing retained failure only when its case ID, expectation, status, phase, retained diagnostic, and tool version match the checked-in baseline. These cases still run every diff --git a/scripts/ci-changes.mjs b/scripts/ci-changes.mjs index 5aa282f5deb..9746f98ba0e 100644 --- a/scripts/ci-changes.mjs +++ b/scripts/ci-changes.mjs @@ -24,9 +24,14 @@ const NEUTRAL_FILES = new Set([ "renovate.json", ]); +// Release Please also bumps workspace versions in the Cargo manifest and lock. +// Its pull request can skip product validation because the merge group that +// cuts the release runs full validation (see isReleaseMergeGroup). const RELEASE_PLEASE_FILES = new Set([ ".release-please-manifest.json", "CHANGELOG.md", + "Cargo.lock", + "Cargo.toml", "VERSION", "crates/celox-napi/package.json", "packages/celox/package.json", @@ -90,6 +95,24 @@ export function affectsHeliodorArm64(files) { ); } +export function cutsRelease(files) { + return files.some( + (path) => path.replace(/^\.\//, "") === ".release-please-manifest.json", + ); +} + +// On master, only the release pull request changes the release manifest, so a +// merge group carrying it is about to tag a release and gets full validation +// instead of the change-based subset. Syncing master into develop carries the +// same change without releasing anything. An undeterminable diff fails open. +export function isReleaseMergeGroup({ event, baseRef, files }) { + return ( + event === "merge_group" && + baseRef === "refs/heads/master" && + (files === null || cutsRelease(files)) + ); +} + export function classifyFiles(files, { releasePlease = false } = {}) { const affected = { docs: false, @@ -230,12 +253,17 @@ if ( process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href ) { - const files = - process.env.FULL_VALIDATION === "true" - ? null - : changedFiles(process.argv[2] ?? "", process.argv[3] ?? ""); + const scheduledFull = process.env.FULL_VALIDATION === "true"; + const files = scheduledFull + ? null + : changedFiles(process.argv[2] ?? "", process.argv[3] ?? ""); + const release = isReleaseMergeGroup({ + event: process.env.GITHUB_EVENT_NAME, + baseRef: process.env.MERGE_GROUP_BASE_REF, + files, + }); const affected = - files === null + files === null || release ? { ...ALL_AFFECTED, heliodor_arm64: true } : { ...classifyFiles(files, { @@ -243,5 +271,5 @@ if ( }), heliodor_arm64: affectsHeliodorArm64(files), }; - writeOutputs(affected); + writeOutputs({ ...affected, release }); } diff --git a/scripts/ci-changes.test.mjs b/scripts/ci-changes.test.mjs index 13f77d2e627..ebbee8972dc 100644 --- a/scripts/ci-changes.test.mjs +++ b/scripts/ci-changes.test.mjs @@ -1,10 +1,17 @@ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { dirname, relative } from "node:path"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, relative } from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; -import { affectsHeliodorArm64, classifyFiles } from "./ci-changes.mjs"; +import { + affectsHeliodorArm64, + classifyFiles, + cutsRelease, + isReleaseMergeGroup, +} from "./ci-changes.mjs"; const none = { docs: false, @@ -109,7 +116,13 @@ test("full validation overrides even an empty valid diff", () => { ["scripts/ci-changes.mjs", head, head], { cwd: root, - env: { ...process.env, FULL_VALIDATION: "true", GITHUB_OUTPUT: "" }, + env: { + ...process.env, + FULL_VALIDATION: "true", + GITHUB_EVENT_NAME: "schedule", + MERGE_GROUP_BASE_REF: "", + GITHUB_OUTPUT: "", + }, encoding: "utf8", }, ); @@ -123,7 +136,145 @@ test("full validation overrides even an empty valid diff", () => { return [name, value === "true"]; }), ), - { ...all, heliodor_arm64: true }, + { ...all, heliodor_arm64: true, release: false }, + ); +}); + +const MASTER_GROUP = { + GITHUB_EVENT_NAME: "merge_group", + MERGE_GROUP_BASE_REF: "refs/heads/master", +}; + +const classifier = fileURLToPath(new URL("./ci-changes.mjs", import.meta.url)); + +// The classifier diffs base..head in the repository at cwd. +function runClassifier( + base, + head, + env, + cwd = fileURLToPath(new URL("../", import.meta.url)), +) { + const output = execFileSync( + process.execPath, + [classifier, base, head], + { + cwd, + env: { + ...process.env, + FULL_VALIDATION: "", + GITHUB_EVENT_NAME: "", + MERGE_GROUP_BASE_REF: "", + GITHUB_OUTPUT: "", + ...env, + }, + encoding: "utf8", + }, + ); + return Object.fromEntries( + output + .trim() + .split("\n") + .map((line) => { + const [name, value] = line.split("="); + return [name, value === "true"]; + }), + ); +} + +test("only the release manifest marks a release", () => { + assert.equal(cutsRelease([".release-please-manifest.json"]), true); + assert.equal( + cutsRelease(["crates/celox/src/lib.rs", "./.release-please-manifest.json"]), + true, + ); + assert.equal(cutsRelease([]), false); + assert.equal( + cutsRelease(["CHANGELOG.md", "release-please-config.json"]), + false, + ); +}); + +test("only master merge groups that change the release manifest are releases", () => { + const manifest = [".release-please-manifest.json"]; + const master = { event: "merge_group", baseRef: "refs/heads/master" }; + assert.equal(isReleaseMergeGroup({ ...master, files: manifest }), true); + assert.equal(isReleaseMergeGroup({ ...master, files: null }), true); + assert.equal(isReleaseMergeGroup({ ...master, files: ["README.md"] }), false); + // Syncing a release into develop carries the manifest but tags nothing. + for (const files of [manifest, null]) { + assert.equal( + isReleaseMergeGroup({ + event: "merge_group", + baseRef: "refs/heads/develop", + files, + }), + false, + ); + } + for (const event of ["pull_request", "push", "schedule"]) { + assert.equal( + isReleaseMergeGroup({ event, baseRef: "refs/heads/master", files: manifest }), + false, + ); + } +}); + +test("merge groups with an unknown diff are treated as releases", () => { + assert.deepEqual( + runClassifier("", "", MASTER_GROUP), + { ...all, heliodor_arm64: true, release: true }, + ); + // Other events still run every path, but without the release gate. + assert.deepEqual( + runClassifier("", "", { GITHUB_EVENT_NAME: "pull_request" }), + { ...all, heliodor_arm64: true, release: false }, + ); +}); + +// CI checks out a single commit, so build the history this test needs. +test("a merge group that changes the release manifest is a release", (t) => { + const repository = mkdtempSync(join(tmpdir(), "celox-ci-changes-")); + t.after(() => rmSync(repository, { recursive: true, force: true })); + const git = (...args) => + execFileSync("git", args, { cwd: repository, encoding: "utf8" }).trim(); + const commitManifest = (version) => { + writeFileSync( + join(repository, ".release-please-manifest.json"), + `{".": "${version}"}\n`, + ); + git("add", ".release-please-manifest.json"); + git("commit", "--quiet", "-m", `release ${version}`); + return git("rev-parse", "HEAD"); + }; + git("init", "--quiet"); + git("config", "user.name", "test"); + git("config", "user.email", "test@example.com"); + git("config", "commit.gpgsign", "false"); + const base = commitManifest("0.1.0"); + const release = commitManifest("0.2.0"); + const classify = (env) => + runClassifier(base, release, env, repository).release; + + assert.equal(classify(MASTER_GROUP), true); + assert.equal(classify({ GITHUB_EVENT_NAME: "pull_request" }), false); + assert.equal( + classify({ + GITHUB_EVENT_NAME: "merge_group", + MERGE_GROUP_BASE_REF: "refs/heads/develop", + }), + false, + ); +}); + +test("other merge groups are not releases", () => { + const root = fileURLToPath(new URL("../", import.meta.url)); + const head = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: root, + encoding: "utf8", + }).trim(); + assert.deepEqual( + runClassifier(head, head, MASTER_GROUP), + { ...none, heliodor_arm64: false, release: false }, ); }); @@ -216,8 +367,20 @@ test("ordinary package version changes exercise JavaScript and NAPI", () => { }); }); +// The files a release pull request changes, as in #1007. +const releasePullRequestFiles = [...releaseFiles, "Cargo.lock", "Cargo.toml"]; + test("Release Please version updates skip product validation", () => { assert.deepEqual(classifyFiles(releaseFiles, { releasePlease: true }), none); + assert.deepEqual( + classifyFiles(releasePullRequestFiles, { releasePlease: true }), + none, + ); +}); + +test("Cargo version bumps outside Release Please keep broad coverage", () => { + assert.equal(classifyFiles(releasePullRequestFiles).rust, true); + assert.equal(classifyFiles(["Cargo.lock"]).napi, true); }); test("Release Please source changes still exercise affected products", () => { diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index 8cda5ce2fbf..95792f40659 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -19,7 +19,10 @@ test("the required gate rejects failures and only accepts explicitly optional sk const gate = job("rust"); assert.match(gate, /name: Rust Test & NAPI Build/); assert.match(gate, /if: always\(\)/); - assert.match(gate, /needs: \[changes, rust-tests, napi-linux, napi-wasm\]/); + assert.match( + gate, + /needs: \[changes, rust-tests, napi-linux, napi-wasm, external-suites\]/, + ); assert.match( gate, /if: .*outputs\.rust == 'true' \|\| needs\.changes\.outputs\.napi == 'true'/, @@ -32,6 +35,8 @@ test("the required gate rejects failures and only accepts explicitly optional sk NAPI_REQUIRED: "true", NATIVE_RESULT: "success", WASM_RESULT: "success", + RELEASE_REQUIRED: "false", + EXTERNAL_RESULT: "skipped", }; const cases = [ { @@ -90,6 +95,21 @@ test("the required gate rejects failures and only accepts explicitly optional sk passes: false, }); } + // A merge group that cuts a release must pass every external comparison. + const release = { + ...success, + RELEASE_REQUIRED: "true", + EXTERNAL_RESULT: "success", + }; + cases.push({ env: release, passes: true }); + for (const status of ["failure", "cancelled", "skipped", ""]) { + cases.push({ env: { ...release, EXTERNAL_RESULT: status }, passes: false }); + } + // Full runs report comparison failures through an issue, not this gate. + for (const status of ["success", "failure", "cancelled", ""]) { + cases.push({ env: { ...success, EXTERNAL_RESULT: status }, passes: true }); + } + cases.push({ env: { ...success, RELEASE_REQUIRED: "" }, passes: false }); for (const { env, passes } of cases) { const result = spawnSync("bash", ["-e", "-c", script], { env: { ...process.env, ...env }, @@ -112,9 +132,23 @@ test("scheduled and manual validation run all paths and external suites", () => assert.match(job("changes"), /STABLE_LANE: .*github\.ref_name == 'master'/); assert.match(job("lint"), /VERYL_LANE: .*github\.ref_name == 'develop'/); const external = job("external-suites"); + assert.match(external, /needs: changes\n/); assert.match( external, - /if: github\.event_name == 'schedule' \|\| github\.event_name == 'workflow_dispatch'/, + /if: always\(\) && \(github\.event_name == 'schedule' \|\| github\.event_name == 'workflow_dispatch' \|\| needs\.changes\.outputs\.release == 'true'\)/, + ); + assert.match( + job("changes"), + /release: \$\{\{ steps\.classify\.outputs\.release \}\}/, + ); + assert.match( + job("changes"), + /MERGE_GROUP_BASE_REF: \$\{\{ github\.event\.merge_group\.base_ref \}\}/, + ); + // Only the repository's own release branch may skip PR product checks. + assert.match( + job("changes"), + /RELEASE_PLEASE_PR: \$\{\{ github\.event_name == 'pull_request' && github\.head_ref == 'release-please--branches--master--components--celox' && github\.event\.pull_request\.head\.repo\.full_name == github\.repository \}\}/, ); assert.match(external, /fail-fast: false/); assert.match(external, /suite: \[veryl, sv\]/); @@ -178,3 +212,23 @@ test("artifact consumers wait for their producer rather than the Rust test gate" assert.match(browser, /needs: \[changes, napi-wasm\]/); assert.match(browser, /name: napi-wasm32-wasi/); }); + +test("full runs on long-lived branches report every job's result", () => { + const report = job("report-full-validation"); + const jobs = [...workflow.split(/^jobs:\n/m)[1].matchAll(/^ ([\w-]+):\n/gm)] + .map((match) => match[1]) + .filter((name) => name !== "report-full-validation"); + const needs = report + .match(/needs:\s*\[([^\]]*)\]/)[1] + .split(",") + .map((name) => name.trim()) + .filter(Boolean); + assert.deepEqual([...needs].sort(), [...jobs].sort()); + assert.match( + report, + /if: always\(\) && \(github\.event_name == 'schedule' \|\| github\.event_name == 'workflow_dispatch'\) && \(github\.ref_name == 'master' \|\| github\.ref_name == 'develop'\)/, + ); + assert.match(report, /issues: write/); + assert.match(report, /NEEDS: \$\{\{ toJSON\(needs\) \}\}/); + assert.match(report, /run: node scripts\/report-full-ci\.mjs/); +}); diff --git a/scripts/report-full-ci.mjs b/scripts/report-full-ci.mjs new file mode 100644 index 00000000000..0fd5f6ff9b4 --- /dev/null +++ b/scripts/report-full-ci.mjs @@ -0,0 +1,156 @@ +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { pathToFileURL } from "node:url"; + +const execFileAsync = promisify(execFile); + +const FAILED_RESULTS = new Set(["failure", "cancelled"]); + +export function issueTitle(branch) { + return `Full CI is failing on ${branch}`; +} + +// `needs` is the workflow's toJSON(needs). Skipped jobs are not failures: a +// full run enables every path, so a skip only follows an upstream failure. +export function failedJobs(needs) { + return Object.entries(needs) + .filter(([, job]) => FAILED_RESULTS.has(job.result)) + .map(([name, job]) => `${name} (${job.result})`) + .sort(); +} + +export async function reportFullCi({ github, needs, branch, sha, runUrl, log = console.log }) { + const title = issueTitle(branch); + const failed = failedJobs(needs); + const open = (await github.listOpenIssues(title)).filter( + (issue) => issue.title === title, + ); + if (open.length > 1) { + throw new Error(`Found ${open.length} open issues titled "${title}"`); + } + const issue = open[0] ?? null; + + if (failed.length === 0) { + if (issue === null) { + log(`Full CI passed on ${branch}.`); + return { outcome: "passed" }; + } + await github.comment( + issue.number, + `Full CI passed again on \`${sha}\`: ${runUrl}`, + ); + await github.close(issue.number); + log(`Closed #${issue.number}: full CI passed on ${branch}.`); + return { outcome: "closed", number: issue.number }; + } + + const body = [ + `Full CI failed on \`${branch}\` at \`${sha}\`: ${runUrl}`, + "", + "Failed jobs:", + ...failed.map((job) => `- ${job}`), + ].join("\n"); + if (issue !== null) { + await github.comment(issue.number, body); + log(`Commented on #${issue.number}.`); + return { outcome: "commented", number: issue.number }; + } + const number = await github.create( + title, + `${body}\n\nThis issue closes automatically when full CI passes on \`${branch}\` again.`, + ); + log(`Opened #${number}.`); + return { outcome: "opened", number }; +} + +export class GitHubCli { + constructor(repository) { + if (!/^[^/]+\/[^/]+$/.test(repository)) { + throw new Error(`Invalid GITHUB_REPOSITORY: ${repository}`); + } + this.repository = repository; + } + + async run(args) { + try { + const { stdout } = await execFileAsync("gh", args, { + encoding: "utf8", + maxBuffer: 10 * 1024 * 1024, + }); + return stdout; + } catch (error) { + const detail = error.stderr?.trim() || error.stdout?.trim() || error.message; + throw new Error(detail); + } + } + + async listOpenIssues(title) { + const output = await this.run([ + "issue", + "list", + "--repo", + this.repository, + "--state", + "open", + "--search", + `"${title}" in:title`, + "--limit", + "100", + "--json", + "number,title", + ]); + return JSON.parse(output); + } + + async comment(number, body) { + await this.run([ + "issue", + "comment", + String(number), + "--repo", + this.repository, + "--body", + body, + ]); + } + + async close(number) { + await this.run(["issue", "close", String(number), "--repo", this.repository]); + } + + async create(title, body) { + const output = await this.run([ + "issue", + "create", + "--repo", + this.repository, + "--title", + title, + "--body", + body, + ]); + const match = /\/issues\/(\d+)\s*$/.exec(output.trim()); + if (!match) { + throw new Error(`Unexpected gh issue create output: ${output}`); + } + return Number(match[1]); + } +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(process.argv[1]).href +) { + try { + await reportFullCi({ + github: new GitHubCli(process.env.GITHUB_REPOSITORY ?? ""), + needs: JSON.parse(process.env.NEEDS ?? ""), + branch: process.env.BRANCH, + sha: process.env.SHA, + runUrl: process.env.RUN_URL, + }); + } catch (error) { + console.error(error.message); + process.exitCode = 1; + } +} diff --git a/scripts/report-full-ci.test.mjs b/scripts/report-full-ci.test.mjs new file mode 100644 index 00000000000..ba7426e8626 --- /dev/null +++ b/scripts/report-full-ci.test.mjs @@ -0,0 +1,107 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { failedJobs, issueTitle, reportFullCi } from "./report-full-ci.mjs"; + +const passing = { + changes: { result: "success" }, + "rust-tests": { result: "success" }, + "external-suites": { result: "success" }, +}; + +function fakeGitHub(openIssues = []) { + const calls = []; + return { + calls, + async listOpenIssues(title) { + calls.push(["list", title]); + return openIssues; + }, + async comment(number, body) { + calls.push(["comment", number, body]); + }, + async close(number) { + calls.push(["close", number]); + }, + async create(title, body) { + calls.push(["create", title, body]); + return 42; + }, + }; +} + +function report(github, needs, branch = "master") { + return reportFullCi({ + github, + needs, + branch, + sha: "abc123", + runUrl: "https://example.test/runs/1", + log: () => {}, + }); +} + +test("failed and cancelled jobs are failures; skipped jobs are not", () => { + assert.deepEqual( + failedJobs({ + ...passing, + lint: { result: "failure" }, + docs: { result: "skipped" }, + "js-ubuntu": { result: "cancelled" }, + }), + ["js-ubuntu (cancelled)", "lint (failure)"], + ); +}); + +test("a first failure opens an issue naming the branch, run, and jobs", async () => { + const github = fakeGitHub(); + const result = await report( + github, + { ...passing, "external-suites": { result: "failure" } }, + "develop", + ); + assert.deepEqual(result, { outcome: "opened", number: 42 }); + const [, title, body] = github.calls.find((call) => call[0] === "create"); + assert.equal(title, issueTitle("develop")); + assert.match(body, /`develop` at `abc123`: https:\/\/example\.test\/runs\/1/); + assert.match(body, /- external-suites \(failure\)/); +}); + +test("a repeated failure comments on the open issue", async () => { + const github = fakeGitHub([{ number: 7, title: issueTitle("master") }]); + const result = await report(github, { ...passing, lint: { result: "failure" } }); + assert.deepEqual(result, { outcome: "commented", number: 7 }); + assert.equal(github.calls.some((call) => call[0] === "create"), false); + assert.match(github.calls.find((call) => call[0] === "comment")[2], /lint/); +}); + +test("a passing run closes the open issue", async () => { + const github = fakeGitHub([{ number: 7, title: issueTitle("master") }]); + assert.deepEqual(await report(github, passing), { + outcome: "closed", + number: 7, + }); + assert.deepEqual(github.calls.at(-1), ["close", 7]); +}); + +test("a passing run without an issue does nothing", async () => { + const github = fakeGitHub(); + assert.deepEqual(await report(github, passing), { outcome: "passed" }); + assert.deepEqual(github.calls.map((call) => call[0]), ["list"]); +}); + +test("search matches with other titles are ignored", async () => { + const github = fakeGitHub([ + { number: 3, title: `${issueTitle("master")} (old)` }, + { number: 4, title: issueTitle("develop") }, + ]); + assert.deepEqual(await report(github, passing), { outcome: "passed" }); +}); + +test("duplicate open issues are an error rather than a guess", async () => { + const github = fakeGitHub([ + { number: 3, title: issueTitle("master") }, + { number: 4, title: issueTitle("master") }, + ]); + await assert.rejects(report(github, passing), /Found 2 open issues/); +});