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
13 changes: 9 additions & 4 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,16 @@ jobs:
TAG: ${{ needs.verify.outputs.tag }}
ALIAS: ${{ needs.verify.outputs.alias }}
steps:
- name: Require a branch-restricted release environment
- name: Require a release environment restricted to main
run: |
restricted="$(gh api "repos/$REPOSITORY/environments/release" --jq '.deployment_branch_policy != null')"
if [ "$restricted" != true ]; then
echo "::error::The release environment must restrict deployments to selected branches before unattended publication."
policy="$(gh api "repos/$REPOSITORY/environments/release" --jq '"\(.deployment_branch_policy.protected_branches // false) \(.deployment_branch_policy.custom_branch_policies // false)"')"
if [ "$policy" != "false true" ]; then
echo "::error::The release environment must restrict deployments to exactly branch main before unattended publication."
exit 1
fi
branches="$(gh api --paginate "repos/$REPOSITORY/environments/release/deployment-branch-policies" --jq '.branch_policies[] | "\(.type):\(.name)"')"
if [ "$branches" != "branch:main" ]; then
echo "::error::The release environment must restrict deployments to exactly branch main before unattended publication."
exit 1
fi
- uses: actions/checkout@v7
Expand Down
22 changes: 13 additions & 9 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,11 @@ The [`Release` workflow](.github/workflows/release.yml) publishes the current
when `src/`, `dist/` or `action.yml` changed since the newest version tag, and
skip docs-, test- or workflow-only changes. A commit since that tag with a
`type!:` subject or `BREAKING CHANGE:` footer fails the run instead of being
released as a patch. `AUTO_RELEASE_PRERELEASE` (default `true`) selects the
prerelease setting. Set `AUTO_RELEASE` to anything else to stop unattended
releases.
released as a patch. If the newest version tag is not in `main`'s history,
automatic runs fail; dispatch a manual release from `main` to supersede it
instead of moving the published tag. `AUTO_RELEASE_PRERELEASE` (default
`true`) selects the prerelease setting. Set `AUTO_RELEASE` to anything else
to stop unattended releases.
- **Manual releases** use `workflow_dispatch` from `main` with `bump`
(`patch`, `minor` or `major`; default `minor`), `prerelease` (default `true`)
and `dry_run` (default `true`). Use them for minor and major versions.
Expand All @@ -128,16 +130,18 @@ The publish job runs in the `release` environment, creates an annotated version
tag on that commit, publishes the GitHub Release with generated notes, advances the matching
major alias (`v0` for 0.x, `v1` for 1.x) only when the release is the newest of its
major line, and verifies that each written tag resolves to the verified commit.
No version bump commit is needed; `package.json` stays at `0.0.0`. Restrict the
`release` environment's deployment branches to `main`; the publish job fails
before any write when the environment has no branch restriction. It does not
No version bump commit is needed; `package.json` stays at `0.0.0`. Set the
`release` environment's deployment branches to **Selected branches and tags**
with the single branch rule `main`; the publish job fails before any write
otherwise (including **Protected branches only**). It does not
require reviewers, so releases complete without manual approval.
If publication fails partway, use **Re-run failed jobs** on the same run. It
resumes only when an existing version tag already points to the verified commit
and any existing GitHub Release is published with the requested prerelease
setting. It rejects the retry if version tags changed after verification would
alter the alias or latest decision; the next automatic check or a new dispatch
replans in that case.
setting. It rejects the retry if a version tag at or above the planned version
appeared after verification, or if changed version tags would alter the alias
or latest decision; the next automatic check or a new dispatch replans in that
case.
GitHub Release is marked latest only for a stable release newer than every
existing version tag.

Expand Down
9 changes: 8 additions & 1 deletion tests/example.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,10 +200,17 @@ describe('release workflow contract', () => {
expect(pinned[1]).toMatch(/^actions\/setup-node@[0-9a-f]{40}$/);
expect(publish.steps.find((step) => step.uses === 'actions/checkout@v7')!.with).toMatchObject({ 'persist-credentials': false });
const publishRuns = publish.steps.map((step) => step.run ?? '');
const branchPolicy = publishRuns.findIndex((run) => run.includes('.deployment_branch_policy != null'));
const branchPolicy = publishRuns.findIndex((run) => run.includes('deployment-branch-policies') && run.includes('"false true"') && run.includes('"branch:main"'));
const recheck = publishRuns.findIndex((run) => run.includes('tooling/release.mjs recheck'));
const firstWrite = publishRuns.findIndex((run) => run.includes('git/tags'));
expect(branchPolicy).toBe(0);
const releaseGate = publishRuns[branchPolicy]!;
const policyGuard = releaseGate.indexOf('if [ "$policy" != "false true" ]');
const branchPolicyLookup = releaseGate.indexOf('deployment-branch-policies');
expect(policyGuard).toBeGreaterThanOrEqual(0);
expect(policyGuard).toBeLessThan(branchPolicyLookup);
expect(releaseGate).not.toContain('.type // "branch"');
expect(releaseGate).toContain('if [ "$branches" != "branch:main" ]');
expect(recheck).toBeGreaterThan(branchPolicy);
expect(recheck).toBeLessThan(firstWrite);
const script = publishRuns.join('\n');
Expand Down
28 changes: 21 additions & 7 deletions tooling/release.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,11 @@ export function planAutomatic({ tags, latestIsAncestor, changedFiles, messages }

// A retried publish job reuses verify outputs; reject them if newer tags appeared since verification.
export function recheckPlan({ version, prerelease, tags, missingLicenseText, moveAlias, latest }) {
const plan = planRelease({ version, prerelease, tags: tags.filter((tag) => tag !== version), missingLicenseText });
if (plan.moveAlias !== moveAlias || plan.latest !== latest) {
const currentTags = tags.filter((tag) => tag !== version);
const plan = planRelease({ version, prerelease, tags: currentTags, missingLicenseText });
const newest = newestVersion(currentTags);
if ((newest && compare(parseVersion(newest), parseVersion(version)) >= 0) ||
plan.moveAlias !== moveAlias || plan.latest !== latest) {
Comment thread
jongio marked this conversation as resolved.
Resolved
throw new Error(`Release plan for ${version} is stale: version tags changed after verification. Dispatch a new release run.`);
}
return plan;
Expand All @@ -75,14 +78,25 @@ function git(...args) {
return execFileSync('git', args, { encoding: 'utf8' });
}

// `git merge-base --is-ancestor` exits 1 for "no"; any other failure is a git error.
export function isAncestor(ancestor, descendant, run = execFileSync) {
try {
run('git', ['merge-base', '--is-ancestor', ancestor, descendant], { encoding: 'utf8' });
return true;
} catch (error) {
if (error.status === 1) return false;
const stderr = error.stderr?.toString().trim();
if (stderr) throw new Error(`${error.message}\n${stderr}`, { cause: error });
throw error;
}
}

function automaticInput(tags) {
const latest = newestVersion(tags);
if (!latest) return { tags, latestIsAncestor: true, changedFiles: git('ls-files').split('\n').filter(Boolean), messages: [] };
let latestIsAncestor = true;
try {
execFileSync('git', ['merge-base', '--is-ancestor', latest, 'HEAD']);
} catch {
latestIsAncestor = false;
const latestIsAncestor = isAncestor(latest, 'HEAD');
if (!latestIsAncestor && !isAncestor('HEAD', latest)) {
throw new Error(`${latest} and this commit have diverged; dispatch a manual release from main to supersede it; do not move published version tags.`);
}
return {
tags,
Expand Down
56 changes: 55 additions & 1 deletion tooling/release.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,17 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { nextVersion, parseVersion, planAutomatic, planRelease, recheckPlan } from './release.mjs';
import { isAncestor, nextVersion, parseVersion, planAutomatic, planRelease, recheckPlan } from './release.mjs';

test('isAncestor treats only git exit 1 as "not an ancestor" and rethrows git errors', () => {
const exit = (status) => () => {
throw Object.assign(new Error('git failed'), { status });
};
assert.equal(isAncestor('v0.2.0', 'HEAD', () => ''), true);
assert.equal(isAncestor('v0.2.0', 'HEAD', exit(1)), false);
const gitError = Object.assign(new Error('git failed'), { status: 128, stderr: 'fatal: bad object' });
assert.throws(() => isAncestor('v0.2.0', 'HEAD', () => { throw gitError; }), /fatal: bad object/);
});
Comment thread
jongio marked this conversation as resolved.
Resolved

test('accepts only plain vMAJOR.MINOR.PATCH release tags', () => {
assert.deepEqual(parseVersion('v0.3.0'), [0, 3, 0]);
Expand Down Expand Up @@ -50,6 +60,12 @@ test('rechecks retried publications against current tags', () => {
assert.throws(() => recheckPlan({ ...base, tags: ['v0.2.0', 'v1.0.0'] }), /stale/);
});

test('rejects prerelease plans when a higher-major tag appeared after verification', () => {
const base = { version: 'v0.3.0', prerelease: true, missingLicenseText: 0, moveAlias: true, latest: false };
assert.equal(recheckPlan({ ...base, tags: ['v0.2.0'] }).tag, 'v0.3.0');
assert.throws(() => recheckPlan({ ...base, tags: ['v0.2.0', 'v1.0.0'] }), /stale/);
});

test('bumps from the newest version tag', () => {
const tags = ['v0', 'v0.1.0', 'v0.2.0', 'v0.10.1', 'v0.2.0-rc.1', 'other'];
assert.equal(nextVersion(tags, 'patch'), 'v0.10.2');
Expand Down Expand Up @@ -101,4 +117,42 @@ test('plan releases a patch when a shipped file moves out of a shipped path', (t
const output = execFileSync(process.execPath, [fileURLToPath(new URL('./release.mjs', import.meta.url)), 'plan', 'patch', 'false', 'true'], { cwd: repo, encoding: 'utf8', env: { ...process.env, GITHUB_OUTPUT: '' } });
assert.match(output, /^release=true$/m);
assert.match(output, /^tag=v0\.1\.1$/m);
});

test('CLI rejects diverged tags and skips a HEAD behind the latest release', (t) => {
const repo = mkdtempSync(join(tmpdir(), 'release-plan-'));
t.after(() => rmSync(repo, { recursive: true, force: true }));
const git = (...args) => execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@example.com', '-c', 'commit.gpgsign=false', '-c', 'tag.gpgsign=false', ...args], { cwd: repo, encoding: 'utf8' });
mkdirSync(join(repo, 'src'));
mkdirSync(join(repo, 'dist'));
writeFileSync(join(repo, 'src', 'index.js'), 'export const value = 1;\n');
writeFileSync(join(repo, 'dist', 'bundled-dependencies.json'), '[]\n');
git('init', '-q');
git('add', '.');
git('commit', '-q', '-m', 'feat: initial');
git('branch', '-M', 'main');
git('tag', 'v0.2.0');

writeFileSync(join(repo, 'src', 'index.js'), 'export const value = 2;\n');
git('commit', '-q', '-am', 'fix: main change');
git('checkout', '-b', 'release-line', 'v0.2.0');
writeFileSync(join(repo, 'src', 'index.js'), 'export const value = 3;\n');
git('commit', '-q', '-am', 'fix: release change');
git('tag', 'v0.2.1');
git('checkout', 'main');

const plan = () => execFileSync(process.execPath, [fileURLToPath(new URL('./release.mjs', import.meta.url)), 'plan', 'patch', 'true', 'true'], {
cwd: repo,
encoding: 'utf8',
env: { ...process.env, GITHUB_OUTPUT: '' },
});
assert.throws(() => plan(), (error) => {
assert.match(error.stderr.toString(), /v0\.2\.1 and this commit have diverged/);
return true;
});

git('checkout', '--detach', 'v0.2.0');
const output = plan();
assert.match(output, /^release=false$/m);
assert.match(output, /v0\.2\.1 is not an ancestor/);
});
Loading