Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 50 additions & 5 deletions RELEASES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -74,6 +81,14 @@ jobs:
checks: |
ci.yml: Checks

freeze:
needs: preflight
Comment on lines +84 to +85

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Make publishing depend on a successful freeze

In the release workflow template, freeze depends on preflight, but neither verify, publish, nor release depends on freeze. Consequently, publishing can begin while the freeze is still being applied, and a failed freeze does not stop publishing or tagging at all. If status posting fails or a workflow-changing PR merges before its status is updated, the release can still end up published but untagged—the failure this change is intended to prevent. Make successful freezing a prerequisite of the publishing path.

Useful? React with 👍 / 👎.

runs-on: ubuntu-24.04
permissions: { statuses: write, pull-requests: read, actions: read }
steps:
- uses: MaudeCode/.github/actions/release-freeze@<full commit SHA>
with: { mode: start }

# Runs only when CI has not already passed on this commit.
verify:
needs: preflight
Expand Down Expand Up @@ -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()
Comment on lines +134 to +136

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Re-establish the freeze when retrying failed release jobs

If publish fails, this unconditional thaw succeeds and clears the freeze. Following the documented recovery instruction to re-run failed jobs then retries publishing without rerunning the already-successful freeze job. GitHub documents that these retries include dependent jobs, not successful prerequisite jobs. Existing workflow-changing PRs therefore remain green throughout the retry and can merge before tagging. Ensure the freeze is reapplied on publishing retries, or change the supported recovery procedure so it necessarily reruns the freeze.

Useful? React with 👍 / 👎.

runs-on: ubuntu-24.04
permissions: { statuses: write, pull-requests: read, actions: read }
steps:
- uses: MaudeCode/.github/actions/release-freeze@<full commit SHA>
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@<full commit SHA>
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

Expand All @@ -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.
Expand All @@ -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.
22 changes: 22 additions & 0 deletions actions/release-freeze/action.yml
Original file line number Diff line number Diff line change
@@ -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
18 changes: 18 additions & 0 deletions actions/release-freeze/index.js
Original file line number Diff line number Diff line change
@@ -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"}.`);
});
63 changes: 62 additions & 1 deletion lib/release.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Comment on lines +231 to +233

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Prevent PR checks from restoring the freeze after thawing

If a PR's freeze check runs after mode: end has posted success but before the release workflow finishes, this query still sees that release as in_progress and posts failure again. The release's thaw has already processed the PR, so nothing clears the new failure after the run completes; a required release-freeze status leaves the PR blocked until another check or release updates it. This also affects PRs opened during the final thaw job. Coordinate PR checks with an explicit thawed state or perform reconciliation after workflow completion rather than treating every in-progress run as still frozen.

Useful? React with 👍 / 👎.

}
// 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) => {
Expand All @@ -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 };
42 changes: 41 additions & 1 deletion test/release.test.js
Original file line number Diff line number Diff line change
@@ -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);
Expand Down Expand Up @@ -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: [] });
});