diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..2cf9d83 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,208 @@ +name: Release +on: + workflow_run: + workflows: [Model-free CI] + types: [completed] + branches: [main] + schedule: + - cron: '23 */6 * * *' + workflow_dispatch: + inputs: + bump: + description: Version bump from the newest vMAJOR.MINOR.PATCH tag + required: true + default: minor + type: choice + options: [patch, minor, major] + prerelease: + description: Publish as a prerelease (required while bundled license text is unresolved) + required: true + default: true + type: boolean + dry_run: + description: Verify only; do not create tags or a release + required: true + default: true + type: boolean +permissions: + contents: read +concurrency: + group: release + cancel-in-progress: false + # Keep every pending run (such as a manual release) instead of replacing it. + queue: max +jobs: + verify: + name: Verify release candidate + # Unattended runs follow successful main pushes or reconcile on schedule; AUTO_RELEASE is the off switch. + if: >- + github.event_name == 'workflow_dispatch' || + (vars.AUTO_RELEASE == 'true' && (github.event_name == 'schedule' || + (github.event.workflow_run.event == 'push' && github.event.workflow_run.conclusion == 'success'))) + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + actions: read + contents: read + outputs: + release: ${{ steps.ci.outputs.release }} + sha: ${{ steps.head.outputs.sha }} + tag: ${{ steps.plan.outputs.tag }} + alias: ${{ steps.plan.outputs.alias }} + move-alias: ${{ steps.plan.outputs.move-alias }} + prerelease: ${{ steps.plan.outputs.prerelease }} + latest: ${{ steps.plan.outputs.latest }} + steps: + - name: Require dispatch from main + if: github.event_name == 'workflow_dispatch' && github.ref != 'refs/heads/main' + run: | + echo "::error::Releases are cut only from main." + exit 1 + - uses: actions/checkout@v7 + with: + ref: main + fetch-depth: 0 + persist-credentials: false + - name: Resolve main head + id: head + run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version-file: .node-version + - name: Plan release + id: plan + env: + EVENT: ${{ github.event_name }} + BUMP: ${{ inputs.bump }} + PRERELEASE: ${{ inputs.prerelease }} + AUTO_PRERELEASE: ${{ vars.AUTO_RELEASE_PRERELEASE }} + run: | + if [ "$EVENT" = workflow_dispatch ]; then + node tooling/release.mjs plan "$BUMP" "$PRERELEASE" false + else + node tooling/release.mjs plan patch "${AUTO_PRERELEASE:-true}" true + fi + - name: Require Model-free CI success on this exact commit + id: ci + if: steps.plan.outputs.release == 'true' + env: + GH_TOKEN: ${{ github.token }} + EVENT: ${{ github.event_name }} + REPOSITORY: ${{ github.repository }} + SHA: ${{ steps.head.outputs.sha }} + run: | + count="$(gh api "repos/$REPOSITORY/actions/workflows/ci.yml/runs?head_sha=$SHA&event=push&branch=main&status=success&per_page=1" --jq '.total_count')" + if [ "$count" -lt 1 ]; then + if [ "$EVENT" = workflow_dispatch ]; then + echo "::error::Model-free CI has not succeeded for push $SHA on main." + exit 1 + fi + echo "::notice::Model-free CI has not succeeded for $SHA yet; its completion triggers the next release check." + echo "release=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + echo "release=true" >> "$GITHUB_OUTPUT" + - run: corepack enable + if: steps.ci.outputs.release == 'true' + - run: corepack pnpm install --frozen-lockfile --ignore-scripts + if: steps.ci.outputs.release == 'true' + - run: corepack pnpm check + if: steps.ci.outputs.release == 'true' + - name: Require a clean checkout + if: steps.ci.outputs.release == 'true' + run: | + if [ -n "$(git status --porcelain --untracked-files=normal)" ]; then + git status --short + echo "::error::pnpm check left the checkout dirty." + exit 1 + fi + publish: + name: Publish ${{ needs.verify.outputs.tag }} + needs: verify + if: needs.verify.outputs.release == 'true' && inputs.dry_run != true + runs-on: ubuntu-latest + timeout-minutes: 5 + environment: release + permissions: + actions: read + contents: write + env: + GH_TOKEN: ${{ github.token }} + REPOSITORY: ${{ github.repository }} + SHA: ${{ needs.verify.outputs.sha }} + TAG: ${{ needs.verify.outputs.tag }} + ALIAS: ${{ needs.verify.outputs.alias }} + steps: + - name: Require a branch-restricted release environment + 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." + exit 1 + fi + - uses: actions/checkout@v7 + with: + ref: ${{ needs.verify.outputs.sha }} + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version-file: .node-version + - name: Recheck release plan against current tags + env: + PRERELEASE: ${{ needs.verify.outputs.prerelease }} + MOVE_ALIAS: ${{ needs.verify.outputs.move-alias }} + LATEST: ${{ needs.verify.outputs.latest }} + run: | + RELEASE_TAGS="$(gh api --paginate "repos/$REPOSITORY/git/matching-refs/tags/v" --jq '.[].ref | ltrimstr("refs/tags/")')" + export RELEASE_TAGS + node tooling/release.mjs recheck "$TAG" "$PRERELEASE" "$MOVE_ALIAS" "$LATEST" + - name: Create annotated version tag + run: | + if gh api "repos/$REPOSITORY/git/ref/tags/$TAG" > /dev/null 2>&1; then + actual="$(gh api "repos/$REPOSITORY/commits/refs/tags/$TAG" --jq '.sha')" + if [ "$actual" != "$SHA" ]; then + echo "::error::$TAG already exists at $actual, expected $SHA." + exit 1 + fi + echo "$TAG already points to $SHA; resuming." + else + object="$(gh api "repos/$REPOSITORY/git/tags" -f tag="$TAG" -f message="$TAG" -f object="$SHA" -f type=commit --jq '.sha')" + gh api "repos/$REPOSITORY/git/refs" -f ref="refs/tags/$TAG" -f sha="$object" > /dev/null + fi + - name: Publish GitHub Release + env: + PRERELEASE: ${{ needs.verify.outputs.prerelease }} + LATEST: ${{ needs.verify.outputs.latest }} + run: | + if state="$(gh release view "$TAG" --repo "$REPOSITORY" --json isDraft,isPrerelease --jq '"\(.isDraft) \(.isPrerelease)"' 2>/dev/null)"; then + if [ "$state" != "false $PRERELEASE" ]; then + echo "::error::Release $TAG exists but is not a published release with prerelease=$PRERELEASE (draft/prerelease: $state)." + exit 1 + fi + echo "Release $TAG is already published; resuming." + exit 0 + fi + flags=(--verify-tag --generate-notes --title "$TAG" "--latest=$LATEST") + if [ "$PRERELEASE" = true ]; then flags+=(--prerelease); fi + gh release create "$TAG" --repo "$REPOSITORY" "${flags[@]}" + - name: Advance major alias + if: needs.verify.outputs.move-alias == 'true' + run: | + if gh api "repos/$REPOSITORY/git/ref/tags/$ALIAS" > /dev/null 2>&1; then + gh api -X PATCH "repos/$REPOSITORY/git/refs/tags/$ALIAS" -f sha="$SHA" -F force=true > /dev/null + else + gh api "repos/$REPOSITORY/git/refs" -f ref="refs/tags/$ALIAS" -f sha="$SHA" > /dev/null + fi + - name: Verify published refs + env: + MOVE_ALIAS: ${{ needs.verify.outputs.move-alias }} + run: | + refs=("$TAG") + if [ "$MOVE_ALIAS" = true ]; then refs+=("$ALIAS"); fi + for ref in "${refs[@]}"; do + actual="$(gh api "repos/$REPOSITORY/commits/refs/tags/$ref" --jq '.sha')" + if [ "$actual" != "$SHA" ]; then + echo "::error::$ref resolves to $actual, expected $SHA." + exit 1 + fi + done diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ccaae2c..b5e5192 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,7 +19,8 @@ pnpm check ``` `pnpm check` runs type checking, lint, model-free coverage, deterministic -source-to-bundle comparison, and a clean consumer-directory packaging control. +source-to-bundle comparison, a clean consumer-directory packaging control, and +release-planner tests (`pnpm test:release`). The clean consumer-directory packaging control deliberately lacks artifact credentials and verifies invalid-input failure. Linux CI separately exercises the packaged Action with real Vally acquisition, native mock-executor pass/fail @@ -34,7 +35,7 @@ PR check names map directly to these commands: | Lint | `pnpm lint`: source/test lint rules. | | Type check | `pnpm typecheck`: strict TypeScript validation. | | Unit tests | `pnpm test:coverage`: input, policy, reporting, mocked GitHub, tool reuse, orchestration and real model-free native CLI tests with coverage thresholds. | -| Bundle verification | `pnpm check:package`: committed bundle freshness and a clean consumer-directory packaged entry-point test. | +| Bundle verification | `pnpm check:package`: committed bundle freshness, a clean consumer-directory packaged entry-point test, and release-planner tests. | | Action smoke test | Executes `uses: ./` on Ubuntu with actual acquisition, native mock-executor pass/fail, lint, installation reuse and artifact upload. No models run. | | evals (Copilot E2E workflow) | For relevant same-repository PRs, directly invokes the default Action on the example. This consumes organization Copilot AI credits. | @@ -102,18 +103,51 @@ capability through repository write access and branch governance. ## Release preparation -The first prerelease is [`v0.1.0`](https://github.com/github/evals-action/releases/tag/v0.1.0). -Keep published version tags unchanged. For future releases, verify the packaged -Action at the target commit and update consumer examples to the intended tag. -Action release versions are independent of the selected Vally version. - -The moving `v0` tag points to the latest approved 0.x release. After publishing -a new 0.x minor or patch release and verifying its checks, advance only `v0` -to that release's exact commit. Verify the tag target afterward. Do not move -version-specific tags, publish a separate GitHub release for the moving tag, -or use a blanket force-push of all tags. Release publication and advancing the -alias are separate steps; no automatic tag-moving workflow is configured. -Keep `v0` on the 0.x line when introducing a future `v1` release. +The [`Release` workflow](.github/workflows/release.yml) publishes the current +`main` head in two ways: + +- **Automatic patch releases** run after each successful `Model-free CI` push + run on `main`, and on a six-hourly reconciliation schedule, only while the + repository variable `AUTO_RELEASE` is `true`. They cut the next patch version + 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. +- **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. + +The verify job refuses other dispatch refs and stable releases while +`dist/bundled-dependencies.json` lists `missing-license-text` entries. It then +requires a successful `Model-free CI` push run on the exact `main` commit and +reruns `pnpm check` with a clean-tree check. If CI has not yet succeeded on the +head, an automatic run skips; that CI run's completion triggers the next check. +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 +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. +GitHub Release is marked latest only for a stable release newer than every +existing version tag. + +Keep published version tags unchanged. Consumers that pin full commit SHAs +update their pins after release. Action release versions are independent of the selected Vally version. + +The moving `v0` tag points to the latest 0.x release. The workflow +never moves version-specific tags or publishes a separate GitHub release for the +moving tag; it force-updates only the matching major alias. Keep `v0` on the 0.x +line when introducing a future `v1` release. Before proposing a release, verify supported CLI versions and their native evidence contracts, run the Linux model-free controls, and qualify the optional diff --git a/README.md b/README.md index 294e2df..79edacd 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,9 @@ sticky PR comment** with the suite, eval names, verdicts, and evidence links. Vally owns selection, execution and grading; the Action handles installation and GitHub integration. -Use `github/evals-action@v0` for the latest 0.x pilot release -(currently [v0.1.0](https://github.com/github/evals-action/releases/tag/v0.1.0)). -Use `@v0.1.0` to stay on that specific Action release. The `v0` tag advances as +Use `github/evals-action@v0` for the latest 0.x pilot release (see +[releases](https://github.com/github/evals-action/releases)). +Use an exact tag such as `@v0.2.0` to stay on a specific Action release. The `v0` tag advances as new 0.x releases are published; the interface may change during the pilot. Supported host: **Linux x64 GitHub-hosted runners**; the Action uses Node 24 without a Node setup step. Your repository's Actions policy must allow it. @@ -96,7 +96,7 @@ with: vally-version: '0.21.0' # Optional; omit for latest stable ``` -The Action version (`@v0` or `@v0.1.0`) and Vally version are independent. Selecting a +The Action version (`@v0` or an exact tag such as `@v0.2.0`) and Vally version are independent. Selecting a published Vally release does not require an Action update. New versions work while the native CLI and evidence contracts remain compatible. Unsupported behavior or malformed evidence fails explicitly; @@ -456,8 +456,9 @@ checkout and one `uses: ./` step, using the Action's defaults. In your repositor use `github/evals-action@v0` instead. The Action prerelease is not listed on Marketplace. Organizations -that require full-SHA Action references can pin the release commit -`83fa12332c3e44ad899f347eaf153a0d9b6432dc` for `v0.1.0`. +that require full-SHA Action references can pin the commit of a +[release tag](https://github.com/github/evals-action/releases), for example +`uses: github/evals-action@<40-character-sha> # v0.2.0`. ## Development and acquisition diff --git a/package.json b/package.json index 25e9b69..b57f6c5 100644 --- a/package.json +++ b/package.json @@ -16,8 +16,9 @@ "test": "vitest run", "test:coverage": "vitest run --coverage", "test:packaged": "node --test tooling/packaged.test.mjs", - "check:package": "pnpm check:dist && pnpm test:packaged", - "check": "pnpm typecheck && pnpm lint && pnpm test:coverage && pnpm check:dist && pnpm test:packaged" + "test:release": "node --test tooling/release.test.mjs", + "check:package": "pnpm check:dist && pnpm test:packaged && pnpm test:release", + "check": "pnpm typecheck && pnpm lint && pnpm test:coverage && pnpm check:dist && pnpm test:packaged && pnpm test:release" }, "dependencies": { "@actions/artifact": "6.3.1", diff --git a/tests/example.test.ts b/tests/example.test.ts index 96edefe..708311b 100644 --- a/tests/example.test.ts +++ b/tests/example.test.ts @@ -153,3 +153,65 @@ describe('real Copilot example contract', () => { expect(skill).toContain('`EVALS_ACTION_SKILL_OK`'); }); }); + +describe('release workflow contract', () => { + type Step = { id?: string; name?: string; if?: string; uses?: string; run?: string; with?: Record }; + type Job = { needs?: string; if?: string; environment?: string; permissions: Record; steps: Step[] }; + + it('publishes verified main heads automatically or by dispatch through a branch-restricted environment', async () => { + const workflow = parse(await readFile('.github/workflows/release.yml', 'utf8')) as { + on: { + workflow_run: { workflows: string[]; types: string[]; branches: string[] }; + schedule: { cron: string }[]; + workflow_dispatch: { inputs: Record }; + }; + permissions: Record; + jobs: Record; + }; + expect(Object.keys(workflow.on)).toEqual(['workflow_run', 'schedule', 'workflow_dispatch']); + expect(workflow.on.workflow_run).toEqual({ workflows: ['Model-free CI'], types: ['completed'], branches: ['main'] }); + expect(workflow.on.schedule).toHaveLength(1); + const inputs = workflow.on.workflow_dispatch.inputs; + expect(inputs.bump!.options).toEqual(['patch', 'minor', 'major']); + expect(inputs.prerelease!.default).toBe(true); + expect(inputs.dry_run!.default).toBe(true); + expect(workflow.permissions).toEqual({ contents: 'read' }); + + const verify = workflow.jobs.verify!; + expect(verify.if).toContain("vars.AUTO_RELEASE == 'true'"); + expect(verify.if).toContain("github.event.workflow_run.event == 'push'"); + expect(verify.if).toContain("github.event.workflow_run.conclusion == 'success'"); + expect(verify.permissions).toEqual({ actions: 'read', contents: 'read' }); + expect(verify.steps[0]).toMatchObject({ if: "github.event_name == 'workflow_dispatch' && github.ref != 'refs/heads/main'" }); + const runs = verify.steps.map((step) => step.run ?? ''); + const order = ['git rev-parse HEAD', 'tooling/release.mjs plan patch', 'actions/workflows/ci.yml/runs?head_sha=$SHA&event=push&branch=main&status=success', 'pnpm check', 'git status --porcelain'] + .map((text) => runs.findIndex((run) => run.includes(text))); + expect(order.every((index, position) => index >= 0 && (position === 0 || index > order[position - 1]!))).toBe(true); + for (const step of verify.steps.slice(order[3]!)) expect(step.if).toBe("steps.ci.outputs.release == 'true'"); + const checkout = verify.steps.find((step) => step.uses === 'actions/checkout@v7')!; + expect(checkout.with).toMatchObject({ ref: 'main', 'persist-credentials': false }); + + const publish = workflow.jobs.publish!; + expect(publish).toMatchObject({ needs: 'verify', if: "needs.verify.outputs.release == 'true' && inputs.dry_run != true", environment: 'release' }); + expect(publish.permissions).toEqual({ actions: 'read', contents: 'write' }); + const pinned = publish.steps.filter((step) => step.uses).map((step) => step.uses); + expect(pinned).toHaveLength(2); + expect(pinned[0]).toBe('actions/checkout@v7'); + 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 recheck = publishRuns.findIndex((run) => run.includes('tooling/release.mjs recheck')); + const firstWrite = publishRuns.findIndex((run) => run.includes('git/tags')); + expect(branchPolicy).toBe(0); + expect(recheck).toBeGreaterThan(branchPolicy); + expect(recheck).toBeLessThan(firstWrite); + const script = publishRuns.join('\n'); + expect(script).not.toContain('required_reviewers'); + expect(script).toContain('isDraft,isPrerelease'); + expect(script).toContain('gh release create "$TAG"'); + expect(script).toContain('--verify-tag'); + expect(script).toContain('refs/tags/$ALIAS'); + expect(script).not.toMatch(/git push|--tags/); + }); +}); diff --git a/tooling/release.mjs b/tooling/release.mjs new file mode 100644 index 0000000..95f5af6 --- /dev/null +++ b/tooling/release.mjs @@ -0,0 +1,129 @@ +#!/usr/bin/env node +import { execFileSync } from 'node:child_process'; +import { appendFileSync, readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +const VERSION = /^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; + +export function parseVersion(value) { + const match = VERSION.exec(value); + if (!match) throw new Error(`Release version must be vMAJOR.MINOR.PATCH, received ${JSON.stringify(value)}.`); + return match.slice(1).map(Number); +} + +function compare(left, right) { + for (let index = 0; index < 3; index += 1) if (left[index] !== right[index]) return left[index] - right[index]; + return 0; +} + +export function planRelease({ version, prerelease, tags, missingLicenseText }) { + const parsed = parseVersion(version); + if (tags.includes(version)) throw new Error(`Tag ${version} already exists; published version tags are never moved.`); + if (!prerelease && missingLicenseText > 0) { + throw new Error(`${missingLicenseText} bundled dependencies are missing-license-text; resolve them before a stable release.`); + } + const versions = tags.filter((tag) => VERSION.test(tag)).map(parseVersion); + const newest = (candidates) => candidates.every((existing) => compare(parsed, existing) > 0); + const moveAlias = newest(versions.filter(([major]) => major === parsed[0])); + return { tag: version, alias: `v${parsed[0]}`, moveAlias, prerelease, latest: !prerelease && newest(versions) }; +} + +export function nextVersion(tags, bump) { + const [major, minor, patch] = tags.filter((tag) => VERSION.test(tag)).map(parseVersion).sort(compare).at(-1) ?? [0, 0, 0]; + if (bump === 'patch') return `v${major}.${minor}.${patch + 1}`; + if (bump === 'minor') return `v${major}.${minor + 1}.0`; + if (bump === 'major') return `v${major + 1}.0.0`; + throw new Error(`Release bump must be patch, minor or major, received ${JSON.stringify(bump)}.`); +} + +const SHIPPED = [/^src\//, /^dist\//, /^action\.yml$/]; +const BREAKING_SUBJECT = /^[a-z]+(\([^)\n]*\))?!:/i; +const BREAKING_FOOTER = /^BREAKING[ -]CHANGE:/m; + +export function newestVersion(tags) { + return tags.filter((tag) => VERSION.test(tag)).sort((left, right) => compare(parseVersion(left), parseVersion(right))).at(-1); +} + +// Unattended releases ship a patch for shipped-file changes since the newest version tag. +export function planAutomatic({ tags, latestIsAncestor, changedFiles, messages }) { + const latest = newestVersion(tags) ?? 'the first commit'; + if (!latestIsAncestor) return { release: false, reason: `${latest} is not an ancestor of this commit; a newer release already covers it.` }; + if (!changedFiles.some((file) => SHIPPED.some((pattern) => pattern.test(file)))) { + return { release: false, reason: `no changes to src/, dist/ or action.yml since ${latest}.` }; + } + if (messages.some((message) => BREAKING_SUBJECT.test(message) || BREAKING_FOOTER.test(message))) { + throw new Error(`Commits since ${latest} declare a breaking change; dispatch a manual minor or major release instead of an automatic patch.`); + } + return { release: true, version: nextVersion(tags, 'patch') }; +} + +// 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) { + throw new Error(`Release plan for ${version} is stale: version tags changed after verification. Dispatch a new release run.`); + } + return plan; +} + +function flag(value, name) { + if (value !== 'true' && value !== 'false') throw new Error(`${name} must be true or false.`); + return value === 'true'; +} + +function git(...args) { + return execFileSync('git', args, { encoding: 'utf8' }); +} + +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; + } + return { + tags, + latestIsAncestor, + changedFiles: git('diff', '--name-only', '--no-renames', latest, 'HEAD').split('\n').filter(Boolean), + messages: git('log', '--format=%B%x00', `${latest}..HEAD`).split('\0').map((message) => message.trim()).filter(Boolean), + }; +} + +function emit(values) { + const output = Object.entries(values).map(([key, value]) => `${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}=${value}\n`).join(''); + if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, output); + process.stdout.write(output); +} + +function main() { + const [command, ...args] = process.argv.slice(2); + if (command !== 'plan' && command !== 'recheck') throw new Error('Usage: release.mjs plan | recheck '); + const inventory = JSON.parse(readFileSync('dist/bundled-dependencies.json', 'utf8')); + const missingLicenseText = inventory.filter((item) => item.status === 'missing-license-text').length; + if (command === 'recheck') { + const [version, prerelease, moveAlias, latest] = args; + const tags = (process.env.RELEASE_TAGS ?? '').split('\n').map((tag) => tag.trim()).filter(Boolean); + emit(recheckPlan({ version, prerelease: flag(prerelease, 'prerelease'), tags, missingLicenseText, moveAlias: flag(moveAlias, 'move-alias'), latest: flag(latest, 'latest') })); + return; + } + const [bump, prerelease, automatic] = args; + const tags = git('tag', '--list', 'v*').split('\n').filter(Boolean); + let version = nextVersion(tags, bump); + if (flag(automatic, 'automatic')) { + if (bump !== 'patch') throw new Error('Automatic releases are patch releases only.'); + const decision = planAutomatic(automaticInput(tags)); + if (!decision.release) { + process.stdout.write(`::notice::Skipping automatic release: ${decision.reason}\n`); + emit({ release: false }); + return; + } + version = decision.version; + } + emit({ release: true, ...planRelease({ version, prerelease: flag(prerelease, 'prerelease'), tags, missingLicenseText }) }); + if (missingLicenseText > 0) process.stdout.write(`::warning::${missingLicenseText} bundled dependencies remain missing-license-text (prerelease only).\n`); +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) main(); diff --git a/tooling/release.test.mjs b/tooling/release.test.mjs new file mode 100644 index 0000000..0e5e95b --- /dev/null +++ b/tooling/release.test.mjs @@ -0,0 +1,104 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +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'; + +test('accepts only plain vMAJOR.MINOR.PATCH release tags', () => { + assert.deepEqual(parseVersion('v0.3.0'), [0, 3, 0]); + assert.deepEqual(parseVersion('v12.0.7'), [12, 0, 7]); + for (const value of ['0.3.0', 'v0', 'v0.3', 'v0.3.0-rc.1', 'v01.2.3', ' v0.3.0', 'v0.3.0\n', 'v0.3.0;rm']) { + assert.throws(() => parseVersion(value), /vMAJOR\.MINOR\.PATCH/, value); + } +}); + +test('plans a new release and advances its major alias', () => { + assert.deepEqual(planRelease({ version: 'v0.3.0', prerelease: true, tags: ['v0', 'v0.1.0', 'v0.2.0'], missingLicenseText: 3 }), { + tag: 'v0.3.0', alias: 'v0', moveAlias: true, prerelease: true, latest: false, + }); + assert.deepEqual(planRelease({ version: 'v1.0.0', prerelease: false, tags: ['v0', 'v0.9.0'], missingLicenseText: 0 }), { + tag: 'v1.0.0', alias: 'v1', moveAlias: true, prerelease: false, latest: true, + }); +}); + +test('never overwrites a version tag', () => { + assert.throws(() => planRelease({ version: 'v0.2.0', prerelease: true, tags: ['v0', 'v0.2.0'], missingLicenseText: 0 }), /already exists/); +}); + +test('keeps the alias on the newest release of its major line', () => { + const plan = planRelease({ version: 'v0.2.1', prerelease: true, tags: ['v0', 'v0.2.0', 'v0.3.0', 'v1.0.0'], missingLicenseText: 0 }); + assert.equal(plan.alias, 'v0'); + assert.equal(plan.moveAlias, false); + assert.equal(plan.latest, false); + assert.equal(planRelease({ version: 'v0.4.0', prerelease: true, tags: ['v0.3.0', 'v1', 'v1.0.0'], missingLicenseText: 0 }).moveAlias, true); + assert.deepEqual(planRelease({ version: 'v0.9.1', prerelease: false, tags: ['v0.9.0', 'v1.0.0'], missingLicenseText: 0 }), + { tag: 'v0.9.1', alias: 'v0', moveAlias: true, prerelease: false, latest: false }); +}); + +test('refuses stable releases while bundled license text is unresolved', () => { + assert.throws(() => planRelease({ version: 'v1.0.0', prerelease: false, tags: [], missingLicenseText: 3 }), /missing-license-text/); + assert.doesNotThrow(() => planRelease({ version: 'v0.3.0', prerelease: true, tags: [], missingLicenseText: 3 })); +}); + +test('rechecks retried publications against current tags', () => { + const base = { version: 'v0.3.0', prerelease: false, missingLicenseText: 0, moveAlias: true, latest: true }; + assert.equal(recheckPlan({ ...base, tags: ['v0', 'v0.2.0', 'v0.3.0'] }).moveAlias, true); + assert.throws(() => recheckPlan({ ...base, tags: ['v0', 'v0.2.0', 'v0.3.0', 'v0.4.0'] }), /stale/); + 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'); + assert.equal(nextVersion(tags, 'minor'), 'v0.11.0'); + assert.equal(nextVersion(tags, 'major'), 'v1.0.0'); + assert.equal(nextVersion([], 'patch'), 'v0.0.1'); + assert.throws(() => nextVersion(tags, 'prerelease'), /patch, minor or major/); +}); + +test('automatically releases a patch only when shipped files changed', () => { + const base = { tags: ['v0', 'v0.2.0'], latestIsAncestor: true, messages: ['fix: handle empty report'] }; + for (const file of ['src/main.ts', 'dist/index.js', 'action.yml']) { + assert.deepEqual(planAutomatic({ ...base, changedFiles: ['README.md', file] }), { release: true, version: 'v0.2.1' }); + } + const skipped = planAutomatic({ ...base, changedFiles: ['README.md', 'tests/a.test.ts', '.github/workflows/ci.yml', 'src.md'] }); + assert.equal(skipped.release, false); + assert.match(skipped.reason, /no changes to src\/, dist\/ or action\.yml since v0\.2\.0/); +}); + +test('skips commits already covered by a newer release tag', () => { + const plan = planAutomatic({ tags: ['v0.2.0'], latestIsAncestor: false, changedFiles: ['src/main.ts'], messages: [] }); + assert.equal(plan.release, false); + assert.match(plan.reason, /not an ancestor/); +}); + +test('refuses to auto-release breaking changes as a patch', () => { + const base = { tags: ['v0.2.0'], latestIsAncestor: true, changedFiles: ['src/main.ts'] }; + for (const message of ['feat!: drop input', 'FEAT!: drop input', 'Refactor(report)!: rename output', 'fix: x\n\nBREAKING CHANGE: removed y', 'fix: x\n\nBREAKING-CHANGE: removed y']) { + assert.throws(() => planAutomatic({ ...base, messages: ['docs: ok', message] }), /manual minor or major release/, message); + } + assert.doesNotThrow(() => planAutomatic({ ...base, messages: ['fix: mention breaking change handling', 'feat: add! marker'] })); +}); + +test('plan releases a patch when a shipped file moves out of a shipped path', (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('tag', 'v0.1.0'); + mkdirSync(join(repo, 'lib')); + git('mv', 'src/index.js', 'lib/index.js'); + git('commit', '-q', '-m', 'refactor: move entry point'); + 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); +}); \ No newline at end of file