diff --git a/RELEASES.md b/RELEASES.md index 4273bb7..2605c9b 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -32,9 +32,16 @@ copy the workflow below, name its CI's gate job in `checks`, and release its fir a release's sake. 5. **Uses no credential of its own.** Every ref and tag is written with the workflow's `github.token`. A release workflow adds no token, deploy key or App for tagging. -6. **Publishes steps that can run again.** Re-running failed jobs, or dispatching the same version again from the same +6. **Holds workflow changes while it runs.** GitHub refuses a workflow's own token when it tags a commit whose workflow + files differ from the default branch's, so a workflow change that merges during a release leaves it published and + untagged. The `release-freeze` action prevents that with a commit status of the same name. The release's first job + runs it with `mode: start`, which fails that status on every open pull request that changes a workflow file; a + last job with `if: always()` runs `mode: end`, which passes it again however the release ended. CI runs it on every + pull request with `mode: pull-request`, so one opened or pushed mid-release is caught, and every pull request + carries the status. List `release-freeze` as a required status check on the default branch. +7. **Publishes steps that can run again.** Re-running failed jobs, or dispatching the same version again from the same commit, must not fail on what an earlier attempt already published. -7. **Tags last.** One final job, needing every publishing job, runs `release-tag` and then creates the GitHub release. +8. **Tags last.** One final job, needing every publishing job, runs `release-tag` and then creates the GitHub release. Nothing else creates the tag. ```yaml @@ -74,6 +81,14 @@ jobs: checks: | ci.yml: Checks + freeze: + needs: preflight + runs-on: ubuntu-24.04 + permissions: { statuses: write, pull-requests: read, actions: read } + steps: + - uses: MaudeCode/.github/actions/release-freeze@ + with: { mode: start } + # Runs only when CI has not already passed on this commit. verify: needs: preflight @@ -112,7 +127,32 @@ jobs: $([[ "$PRERELEASE" == true ]] && echo --prerelease) ``` -Pin both actions to a full commit SHA of this repository. +The release's last job, and CI's job for pull requests: + +```yaml + # In release.yml: after everything else, whatever happened. + thaw: + needs: [freeze, release] + if: always() + runs-on: ubuntu-24.04 + permissions: { statuses: write, pull-requests: read, actions: read } + steps: + - uses: MaudeCode/.github/actions/release-freeze@ + with: { mode: end } + + # In ci.yml: on every pull request. + release-freeze: + if: github.event_name == 'pull_request' + runs-on: ubuntu-24.04 + permissions: { statuses: write, pull-requests: read, actions: read } + steps: + - uses: MaudeCode/.github/actions/release-freeze@ + with: { mode: pull-request } +``` + +A release workflow not named `release.yml` passes its file name as `workflow` to all three. + +Pin every action to a full commit SHA of this repository. ## Starting a release @@ -128,7 +168,8 @@ gh workflow run release.yml --repo OWNER/REPO --ref main -f tag=v1.2.3 - **Before anything published** (a failing test or build): fix it, then release the same version from the new commit. - **A flaky step:** re-run the failed jobs of the same run. -- **The tag step is refused (HTTP 403):** a workflow file changed on the default branch while the release ran. +- **The tag step is refused (HTTP 403):** a workflow file changed on the default branch while the release ran, which + `release-freeze` exists to prevent (a direct push, or a merge made over a failing status, still can). Everything has published; the step prints the `git tag` and `git push` commands to finish it by hand. - **After something published under that version from a commit that has since changed:** registries do not take a version twice, so release the next version. @@ -141,7 +182,11 @@ gh workflow run release.yml --repo OWNER/REPO --ref main -f tag=v1.2.3 - `actions/release-tag`: inputs `tag`, `sha`, optional `message`. Needs `contents: write`. Creating the tag again at the same commit succeeds; at another commit it fails. -Both run on the runner's own Node and depend on nothing else. `node --test` runs their tests. +- `actions/release-freeze`: inputs `mode` (`pull-request`, `start` or `end`), optional `workflow` (the release workflow's + file name, `release.yml` by default); outputs `frozen` and `thawed`, the pull request numbers set each way. Needs + `statuses: write`, `pull-requests: read` and `actions: read`. + +All run on the runner's own Node and depend on nothing else. `node --test` runs their tests. An iOS app's publishing job signs, numbers and uploads to TestFlight through `ios-signing`, `ios-build-number` and `ios-publish`; see [IOS.md](IOS.md). Re-running it for the same version and commit uploads nothing twice. diff --git a/actions/release-freeze/action.yml b/actions/release-freeze/action.yml new file mode 100644 index 0000000..92078be --- /dev/null +++ b/actions/release-freeze/action.yml @@ -0,0 +1,22 @@ +name: Release freeze +description: Keep pull requests that change a workflow file from merging while a release runs, through the release-freeze commit status. +inputs: + mode: + description: >- + "pull-request" on a pull request's push sets that pull request's status. "start" as a release's first job + freezes the open pull requests that change a workflow file. "end" as its last job, with if always(), thaws them. + required: true + workflow: + description: The release workflow's file name. + default: release.yml + token: + description: Token with statuses write, pull requests read and actions read on the repository. + default: ${{ github.token }} +outputs: + frozen: + description: The pull request numbers set to failure, as JSON. + thawed: + description: The pull request numbers set to success, as JSON. +runs: + using: node24 + main: index.js diff --git a/actions/release-freeze/index.js b/actions/release-freeze/index.js new file mode 100644 index 0000000..0cdcd4e --- /dev/null +++ b/actions/release-freeze/index.js @@ -0,0 +1,18 @@ +"use strict"; +const { appendFileSync, readFileSync } = require("node:fs"); +const { freeze, github, run } = require("../../lib/release.js"); + +run(async () => { + const env = process.env; + const mode = env.INPUT_MODE.trim(); + if (!["pull-request", "start", "end"].includes(mode)) throw new Error(`mode is "pull-request", "start" or "end", not ${JSON.stringify(mode)}.`); + const api = github({ token: env.INPUT_TOKEN, repository: env.GITHUB_REPOSITORY, apiUrl: env.GITHUB_API_URL }); + const repository = await api("GET", ""); + if (repository.status !== 200) throw new Error(`Reading the repository failed: HTTP ${repository.status}`); + const event = JSON.parse(readFileSync(env.GITHUB_EVENT_PATH, "utf8")); + const pull = event.pull_request && { number: event.pull_request.number, sha: event.pull_request.head.sha }; + if (mode === "pull-request" && !pull) throw new Error('mode "pull-request" runs on a pull_request event.'); + const result = await freeze(api, { mode, workflow: env.INPUT_WORKFLOW, branch: repository.data.default_branch, runId: env.GITHUB_RUN_ID, pull }); + appendFileSync(env.GITHUB_OUTPUT, `frozen=${JSON.stringify(result.frozen)}\nthawed=${JSON.stringify(result.thawed)}\n`); + console.log(`Frozen: ${result.frozen.join(", ") || "none"}. Thawed: ${result.thawed.join(", ") || "none"}.`); +}); diff --git a/lib/release.js b/lib/release.js index 1c044a8..dbbb2f3 100644 --- a/lib/release.js +++ b/lib/release.js @@ -182,6 +182,67 @@ async function createTag(api, { tag, sha, message }) { throw failed("Creating the tag failed", ref); } +/** The commit status a pull request carries while a release may not be disturbed. */ +const FREEZE = "release-freeze"; + +/** Whether pull request `number` changes a workflow file. */ +async function changesWorkflows(api, number) { + for (let path = `/pulls/${number}/files?per_page=100`; path; ) { + const page = await api("GET", path); + if (page.status !== 200) throw failed("Reading the pull request's files failed", page); + if (page.data.some((file) => [file.filename, file.previous_filename].some((name) => name?.startsWith(".github/workflows/")))) return true; + path = page.next; + } + return false; +} + +/** Whether a release run other than `except` is queued or running: a dispatch of `workflow` on the default branch. */ +async function releaseRunning(api, { workflow, branch, except }) { + for (const status of ["in_progress", "queued"]) { + const runs = await api("GET", `/actions/workflows/${encodeURIComponent(workflow)}/runs?event=workflow_dispatch&branch=${encodeURIComponent(branch)}&status=${status}&per_page=20`); + if (runs.status !== 200) throw failed("Reading release runs failed (the job needs actions: read)", runs); + if (runs.data.workflow_runs.some((run) => String(run.id) !== String(except))) return true; + } + return false; +} + +async function setFreeze(api, sha, frozen) { + const body = frozen + ? { state: "failure", description: "A release is running. This changes a workflow file, so it merges when the release finishes." } + : { state: "success", description: "No release is running, or this changes no workflow file." }; + const posted = await api("POST", `/statuses/${sha}`, { ...body, context: FREEZE }); + if (posted.status !== 201) throw failed("Posting the status failed (the job needs statuses: write)", posted); +} + +/** + * Keep workflow changes from merging while a release runs: GitHub refuses a release's own token when it tags a commit + * whose workflow files differ from the default branch's, so a workflow change that merges mid-release leaves the + * release published and untagged. A pull request's push sets its own status; a release freezes the open pull + * requests that change a workflow file when it starts and thaws them when it ends, however it ends. + * @param {{ mode: "pull-request" | "start" | "end", workflow: string, branch: string, runId: string, pull?: { number: number, sha: string } }} event + * @returns {Promise<{ frozen: number[], thawed: number[] }>} the pull requests whose status was set to each + */ +async function freeze(api, { mode, workflow, branch, runId, pull }) { + const [frozen, thawed] = [[], []]; + const set = async ({ number, sha }, on) => { + await setFreeze(api, sha, on); + (on ? frozen : thawed).push(number); + }; + if (mode === "pull-request") { + await set(pull, (await changesWorkflows(api, pull.number)) && (await releaseRunning(api, { workflow, branch }))); + return { frozen, thawed }; + } + // A release ending leaves the freeze in place while another is still going. + const on = mode === "start" || (await releaseRunning(api, { workflow, branch, except: runId })); + for (let path = "/pulls?state=open&per_page=100"; path; ) { + const page = await api("GET", path); + if (page.status !== 200) throw failed("Listing pull requests failed", page); + for (const open of page.data) if (await changesWorkflows(api, open.number)) await set({ number: open.number, sha: open.head.sha }, on); + path = page.next; + } + return { frozen, thawed }; +} + /** Run an action's body, turning a thrown error into the job's failure message. */ function run(main) { main().catch((error) => { @@ -190,4 +251,4 @@ function run(main) { }); } -module.exports = { parseVersion, compareVersions, latestVersion, refusal, earlierCommitRefusal, passedChecks, parseChecks, github, versionTags, taggedCommit, createTag, run }; +module.exports = { parseVersion, compareVersions, latestVersion, refusal, earlierCommitRefusal, passedChecks, parseChecks, freeze, github, versionTags, taggedCommit, createTag, run }; diff --git a/test/release.test.js b/test/release.test.js index 05d2e31..a8c48b2 100644 --- a/test/release.test.js +++ b/test/release.test.js @@ -1,7 +1,7 @@ "use strict"; const assert = require("node:assert/strict"); const { test } = require("node:test"); -const { compareVersions, createTag, earlierCommitRefusal, parseChecks, parseVersion, passedChecks, refusal, versionTags } = require("../lib/release.js"); +const { compareVersions, createTag, earlierCommitRefusal, freeze, parseChecks, parseVersion, passedChecks, refusal, versionTags } = require("../lib/release.js"); const SHA = "a".repeat(40); const OTHER = "b".repeat(40); @@ -148,3 +148,43 @@ test("a check counts as passed only when its job succeeded in the workflow's pus await assert.rejects(passedChecks(api, { sha: SHA, checks: [{ workflow: "missing.yml", job: "Checks" }] }), /missing\.yml is not a workflow/); assert.throws(() => parseChecks("Checks"), /not a check such as/); }); + +test("a pull request that changes a workflow file is frozen while a release runs, and thawed when the last one ends", async () => { + /** Open pull requests by number, each with the files it changes, and the release runs going on, by id. */ + const repository = (pulls, releases) => { + const statuses = {}; + const api = async (method, path, body) => { + const files = /^\/pulls\/(\d+)\/files\?per_page=100$/.exec(path); + if (files) return { status: 200, data: pulls[files[1]].map((filename) => ({ filename })) }; + if (path === "/pulls?state=open&per_page=100") return { status: 200, data: Object.keys(pulls).map((number) => ({ number: Number(number), head: { sha: `sha${number}` } })) }; + const runs = /^\/actions\/workflows\/release\.yml\/runs\?event=workflow_dispatch&branch=main&status=(\w+)&per_page=20$/.exec(path); + if (runs) return { status: 200, data: { workflow_runs: (releases[runs[1]] ?? []).map((id) => ({ id })) } }; + const status = /^\/statuses\/(\w+)$/.exec(path); + if (method === "POST" && status && body.context === "release-freeze") return (statuses[status[1]] = body.state), { status: 201, data: {} }; + throw new Error(`unexpected ${method} ${path}`); + }; + return { api, statuses }; + }; + const pulls = { 1: ["src/app.ts"], 2: ["src/app.ts", ".github/workflows/ci.yml"], 3: ["docs/a.md"] }; + const on = { workflow: "release.yml", branch: "main", runId: "70" }; + + // A release starting freezes only what changes a workflow file; ending thaws it, whatever the release's result. + const quiet = repository(pulls, {}); + assert.deepEqual(await freeze(quiet.api, { ...on, mode: "start" }), { frozen: [2], thawed: [] }); + assert.deepEqual(quiet.statuses, { sha2: "failure" }); + assert.deepEqual(await freeze(quiet.api, { ...on, mode: "end" }), { frozen: [], thawed: [2] }); + assert.deepEqual(quiet.statuses, { sha2: "success" }); + // This run still counts as going on while its own last job runs; another release keeps the freeze. + assert.deepEqual(await freeze(repository(pulls, { in_progress: [70] }).api, { ...on, mode: "end" }), { frozen: [], thawed: [2] }); + assert.deepEqual(await freeze(repository(pulls, { in_progress: [70], queued: [71] }).api, { ...on, mode: "end" }), { frozen: [2], thawed: [] }); + + // A push to a pull request sets its own status, so one opened or changed mid-release is caught too. + const pushed = (number, releases) => freeze(repository(pulls, releases).api, { ...on, mode: "pull-request", pull: { number, sha: `sha${number}` } }); + assert.deepEqual(await pushed(2, { queued: [71] }), { frozen: [2], thawed: [] }); + assert.deepEqual(await pushed(2, {}), { frozen: [], thawed: [2] }, "no release is running"); + assert.deepEqual(await pushed(1, { in_progress: [71] }), { frozen: [], thawed: [1] }, "it changes no workflow file"); + // A renamed workflow file counts by its old name too. + const renamed = repository({ 4: [] }, { in_progress: [71] }); + const withRename = async (method, path, body) => (path.startsWith("/pulls/4/files") ? { status: 200, data: [{ filename: "old.yml", previous_filename: ".github/workflows/old.yml" }] } : renamed.api(method, path, body)); + assert.deepEqual(await freeze(withRename, { ...on, mode: "pull-request", pull: { number: 4, sha: "sha4" } }), { frozen: [4], thawed: [] }); +});