From 3bcf17eddb24b67c6989655d1c316a23113a081c Mon Sep 17 00:00:00 2001 From: mintaka Date: Sat, 10 Oct 2026 18:37:03 -0400 Subject: [PATCH] ci(release): mint v* tags by App and guard publish.yml (RIG-4983) The root package.json version is the release source, in the owned shape X.Y.Z or X.Y.Z-rc.N. A pull request that changes it must move past the latest tag. On main, the automation App mints v at the commit that set it. publish.yml publishes only a tag push whose commit is on main and whose package.json matches the tag, and the npm dist-tag comes from that resolved version. Co-authored-by: Matt Wilkinson --- .github/workflows/publish.yml | 46 +++- .github/workflows/release-tag.yaml | 63 +++++ package.json | 3 +- scripts/release-tag.ts | 304 +++++++++++++++++++++++ test/release-tag.test.ts | 382 +++++++++++++++++++++++++++++ 5 files changed, 793 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/release-tag.yaml create mode 100755 scripts/release-tag.ts create mode 100644 test/release-tag.test.ts diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 7c0bbde..344ba36 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -6,18 +6,54 @@ permissions: on: push: tags: - - "v*" + - "v*.*.*" workflow_dispatch: jobs: + resolve: + if: github.event_name == 'push' + runs-on: ubuntu-latest + outputs: + tag: ${{ steps.resolve.outputs.tag }} + sha: ${{ steps.resolve.outputs.sha }} + version: ${{ steps.resolve.outputs.version }} + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + fetch-depth: 0 + fetch-tags: true + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + # renovate: datasource=github-releases depName=oven-sh/bun + bun-version: "1.3.14" + no-cache: true + - name: Resolve release tag + id: resolve + env: + RELEASE_TAG: ${{ github.ref_name }} + RELEASE_SHA: ${{ github.sha }} + run: | + bun scripts/release-tag.ts resolve "$RELEASE_TAG" "$RELEASE_SHA" + { + echo "tag=$RELEASE_TAG" + echo "sha=$RELEASE_SHA" + echo "version=${RELEASE_TAG#v}" + } >> "$GITHUB_OUTPUT" publish: + needs: resolve + if: github.event_name == 'push' runs-on: ubuntu-latest steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ needs.resolve.outputs.sha }} + persist-credentials: false - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: # renovate: datasource=github-releases depName=oven-sh/bun bun-version: "1.3.14" + no-cache: true - run: bun install --frozen-lockfile - run: bun run lint - run: bun run typecheck @@ -25,13 +61,15 @@ jobs: - run: bun run build - name: Resolve npm dist-tag from version id: disttag + env: + VERSION: ${{ needs.resolve.outputs.version }} run: | - version=$(node -p "require('./package.json').version") - if [[ "$version" == *-* ]]; then + if [[ "$VERSION" == *-* ]]; then echo "tag=next" >> "$GITHUB_OUTPUT" else echo "tag=latest" >> "$GITHUB_OUTPUT" fi - - run: bun publish --access public --tag ${{ steps.disttag.outputs.tag }} + - run: bun publish --access public --tag "$NPM_TAG" env: + NPM_TAG: ${{ steps.disttag.outputs.tag }} NPM_CONFIG_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.github/workflows/release-tag.yaml b/.github/workflows/release-tag.yaml new file mode 100644 index 0000000..455f76f --- /dev/null +++ b/.github/workflows/release-tag.yaml @@ -0,0 +1,63 @@ +name: release-tag +'on': + pull_request: + branches: [main] + push: + branches: [main] + workflow_dispatch: +permissions: + contents: read +jobs: + check: + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + fetch-depth: 0 + fetch-tags: true + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + # renovate: datasource=github-releases depName=oven-sh/bun + bun-version: "1.3.14" + - name: Validate a changed release version + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: bun scripts/release-tag.ts check + mint: + if: github.event_name != 'pull_request' + runs-on: ubuntu-latest + environment: main + steps: + - name: Require main-branch dispatch + if: github.event_name == 'workflow_dispatch' && github.ref != 'refs/heads/main' + run: | + echo '::error::workflow_dispatch is only allowed from main' >&2 + exit 1 + - name: Checkout + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + fetch-depth: 0 + fetch-tags: true + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + # renovate: datasource=github-releases depName=oven-sh/bun + bun-version: "1.3.14" + - name: Create scoped automation App token + id: app-token + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 + with: + client-id: ${{ vars.AUTOMATION_APP_CLIENT_ID }} + private-key: ${{ secrets.AUTOMATION_APP_PRIVATE_KEY }} + permission-contents: write + repositories: solid-markdown + - name: Mint release tag if needed + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + RELEASE_SHA: ${{ github.sha }} + RELEASE_REPOSITORY: ${{ github.repository }} + run: bun scripts/release-tag.ts mint diff --git a/package.json b/package.json index ff442e0..2deb8f6 100644 --- a/package.json +++ b/package.json @@ -105,9 +105,10 @@ "dev": "vite serve dev", "build": "bun run build.ts && bun run smoke", "smoke": "bun run scripts/smoke-dist.ts", - "test": "bun run test:client && bun run test:ssr", + "test": "bun run test:client && bun run test:ssr && bun run test:release", "test:client": "SOLID_GENERATE=dom bun --conditions=browser --conditions=development test test/client.test.tsx", "test:ssr": "SOLID_GENERATE=ssr bun --conditions=development test test/server.test.tsx", + "test:release": "bun test test/release-tag.test.ts", "typecheck": "tsc --noEmit", "lint": "biome check .", "format": "biome format --write ." diff --git a/scripts/release-tag.ts b/scripts/release-tag.ts new file mode 100755 index 0000000..ef7c83d --- /dev/null +++ b/scripts/release-tag.ts @@ -0,0 +1,304 @@ +#!/usr/bin/env bun + +interface CommandResult { + exitCode: number; + stdout: string; + stderr: string; +} + +interface Version { + major: bigint; + minor: bigint; + patch: bigint; + rc: bigint | null; +} + +const VERSION_PATTERN = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-rc\.(0|[1-9]\d*))?$/; + +function run(args: readonly string[]): CommandResult { + const result = Bun.spawnSync({ + cmd: [...args], + stdout: "pipe", + stderr: "pipe", + }); + return { + exitCode: result.exitCode, + stdout: new TextDecoder().decode(result.stdout), + stderr: new TextDecoder().decode(result.stderr), + }; +} + +function checked(args: readonly string[]): CommandResult { + const result = run(args); + if (result.exitCode !== 0) { + const detail = [result.stderr.trim(), result.stdout.trim()] + .filter(Boolean) + .join("; "); + throw new Error( + `${args[0]} ${args.slice(1).join(" ")} failed${detail ? `: ${detail}` : ""}`, + ); + } + return result; +} + +function requiredEnv(name: string): string { + const value = process.env[name]; + if (!value) throw new Error(`${name} is required`); + return value; +} + +function parseVersion(value: string): Version | null { + if (!VERSION_PATTERN.test(value)) return null; + const [major, minor, patch, rc] = value.split(/\.|-rc\./); + if (major === undefined || minor === undefined || patch === undefined) + return null; + return { + major: BigInt(major), + minor: BigInt(minor), + patch: BigInt(patch), + rc: rc === undefined ? null : BigInt(rc), + }; +} + +function compareVersions(left: Version, right: Version): number { + const components: ReadonlyArray = [ + [left.major, right.major], + [left.minor, right.minor], + [left.patch, right.patch], + ]; + for (const [leftPart, rightPart] of components) { + if (leftPart !== rightPart) return leftPart < rightPart ? -1 : 1; + } + if (left.rc === null) return right.rc === null ? 0 : 1; + if (right.rc === null) return -1; + return left.rc === right.rc ? 0 : left.rc < right.rc ? -1 : 1; +} + +function requireValidVersion(value: string): Version { + const version = parseVersion(value); + if (!version) { + throw new Error( + `Invalid owned version '${value}'; expected X.Y.Z or X.Y.Z-rc.N with canonical non-negative integers`, + ); + } + return version; +} + +function readVersionAt(commit: string): string | null { + const exists = run(["git", "cat-file", "-e", `${commit}:package.json`]); + if (exists.exitCode !== 0) { + const validCommit = run([ + "git", + "rev-parse", + "--verify", + "--quiet", + `${commit}^{commit}`, + ]); + if (validCommit.exitCode !== 0) { + throw new Error(`Invalid commit '${commit}'`); + } + return null; + } + + const contents = checked(["git", "show", `${commit}:package.json`]).stdout; + const parsed: unknown = JSON.parse(contents); + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + throw new Error(`package.json at ${commit} must be a JSON object`); + } + if (!("version" in parsed) || typeof parsed.version !== "string") { + throw new Error( + `package.json at ${commit} must have a string version field`, + ); + } + return parsed.version; +} + +function latestTag(): { tag: string; version: Version } | null { + const tags = checked(["git", "tag", "--list", "v*"]).stdout.split("\n"); + let latest: { tag: string; version: Version } | null = null; + for (const tag of tags) { + if (!tag.startsWith("v")) continue; + const version = parseVersion(tag.slice(1)); + if (!version) continue; + if (latest === null || compareVersions(version, latest.version) > 0) { + latest = { tag, version }; + } + } + return latest; +} + +function requireGreaterThanLatest(value: string, version: Version): void { + const latest = latestTag(); + if (latest && compareVersions(version, latest.version) <= 0) { + throw new Error( + `Invalid version '${value}'; expected a version greater than ${latest.tag}`, + ); + } +} + +function checkVersion(): void { + const baseSha = requiredEnv("BASE_SHA"); + const headSha = requiredEnv("HEAD_SHA"); + const baseVersion = readVersionAt(baseSha); + const headVersion = readVersionAt(headSha); + if (baseVersion === null || headVersion === null) { + throw new Error("package.json must exist at both BASE_SHA and HEAD_SHA"); + } + if (baseVersion === headVersion) { + console.log("package.json version unchanged; check skipped."); + return; + } + + const version = requireValidVersion(headVersion); + requireGreaterThanLatest(headVersion, version); + console.log(`Version ${headVersion} is valid.`); +} + +function mintTag(): void { + const releaseSha = requiredEnv("RELEASE_SHA"); + const repository = requiredEnv("RELEASE_REPOSITORY"); + const releaseVersion = readVersionAt(releaseSha); + if (releaseVersion === null) { + throw new Error(`Could not read package.json at ${releaseSha}`); + } + const tag = `v${releaseVersion}`; + if ( + run(["git", "show-ref", "--verify", "--quiet", `refs/tags/${tag}`]) + .exitCode === 0 + ) { + console.log(`Tag ${tag} already exists; nothing to mint.`); + return; + } + + const version = requireValidVersion(releaseVersion); + requireGreaterThanLatest(releaseVersion, version); + + let target: string | null = null; + const commits = checked(["git", "rev-list", "--first-parent", releaseSha]) + .stdout.trim() + .split("\n"); + for (const commit of commits) { + if (!commit) continue; + const versionAtCommit = readVersionAt(commit); + if (versionAtCommit === null || versionAtCommit !== releaseVersion) break; + target = commit; + } + if (target === null) { + throw new Error( + `Could not find the first-parent commit that set ${releaseVersion}`, + ); + } + + const response = run([ + "gh", + "api", + `repos/${repository}/git/refs`, + "--method", + "POST", + "-f", + `ref=refs/tags/${tag}`, + "-f", + `sha=${target}`, + ]); + if (response.exitCode === 0) { + console.log(`Created ${tag} at ${target}.`); + return; + } + + const detail = [response.stderr.trim(), response.stdout.trim()] + .filter(Boolean) + .join("; "); + if (/\b422\b/.test(detail) && /Reference already exists/i.test(detail)) { + const existing = run([ + "gh", + "api", + `repos/${repository}/git/ref/tags/${tag}`, + "--jq", + ".object.sha", + ]); + if (existing.exitCode !== 0) { + throw new Error( + `Could not verify existing ${tag}: ${existing.stderr.trim() || existing.stdout.trim()}`, + ); + } + const actual = existing.stdout.trim(); + if (actual === target) { + console.log(`Tag ${tag} was created concurrently at ${target}.`); + return; + } + throw new Error( + `Tag ${tag} already exists at ${actual}, expected ${target}`, + ); + } + throw new Error( + `Could not create ${tag}: ${detail || `gh exited ${response.exitCode}`}`, + ); +} + +function resolveTag(args: readonly string[]): void { + if (args.length !== 3) + throw new Error("Usage: release-tag.ts resolve "); + const tag = args[1]; + const sha = args[2]; + if ( + tag === undefined || + sha === undefined || + !tag.startsWith("v") || + !parseVersion(tag.slice(1)) + ) { + throw new Error( + `Invalid release tag '${tag ?? ""}'; expected vX.Y.Z or vX.Y.Z-rc.N`, + ); + } + + const ancestry = run([ + "git", + "merge-base", + "--is-ancestor", + sha, + "origin/main", + ]); + if (ancestry.exitCode === 1) + throw new Error(`${sha} is not reachable from origin/main`); + if (ancestry.exitCode !== 0) { + throw new Error( + `Could not verify that ${sha} is reachable from origin/main: ${ancestry.stderr.trim()}`, + ); + } + const versionAtCommit = readVersionAt(sha); + if (versionAtCommit === null) + throw new Error(`Could not read package.json at ${sha}`); + requireValidVersion(versionAtCommit); + if (tag !== `v${versionAtCommit}`) { + throw new Error( + `Tag ${tag} does not match package.json at ${sha} (v${versionAtCommit})`, + ); + } + console.log(`Resolved ${tag} at ${sha}.`); +} + +function main(args: readonly string[]): void { + const command = args[0]; + if (command === "check" && args.length === 1) { + checkVersion(); + return; + } + if (command === "mint" && args.length === 1) { + mintTag(); + return; + } + if (command === "resolve") { + resolveTag(args); + return; + } + throw new Error("Usage: release-tag.ts {check|mint|resolve }"); +} + +try { + main(process.argv.slice(2)); +} catch (error) { + const message = error instanceof Error ? error.message : String(error); + console.error(`::error::${message.replace(/[\r\n]+/g, " ")}`); + process.exitCode = 1; +} diff --git a/test/release-tag.test.ts b/test/release-tag.test.ts new file mode 100644 index 0000000..cd8e00d --- /dev/null +++ b/test/release-tag.test.ts @@ -0,0 +1,382 @@ +import { afterEach, describe, expect, it } from "bun:test"; +import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const script = join(import.meta.dir, "../scripts/release-tag.ts"); +const directories: string[] = []; + +interface CommandResult { + exitCode: number; + stdout: string; + stderr: string; +} + +async function scratchDirectory(): Promise { + const directory = await mkdtemp( + join(tmpdir(), "solid-markdown-release-tag-"), + ); + directories.push(directory); + return directory; +} + +function command( + args: readonly string[], + options: { cwd?: string; env?: Record } = {}, +): CommandResult { + const result = Bun.spawnSync({ + cmd: [...args], + cwd: options.cwd, + env: { ...process.env, ...options.env }, + stdout: "pipe", + stderr: "pipe", + }); + return { + exitCode: result.exitCode, + stdout: new TextDecoder().decode(result.stdout), + stderr: new TextDecoder().decode(result.stderr), + }; +} + +function git(repository: string, ...args: string[]): string { + const result = command(["git", ...args], { cwd: repository }); + if (result.exitCode !== 0) { + throw new Error(`git ${args.join(" ")} failed: ${result.stderr}`); + } + return result.stdout.trim(); +} + +async function createRepository( + directory: string, + version: string, + name = "base", +): Promise { + const repository = join(directory, "repo"); + await mkdir(repository, { recursive: true }); + git(repository, "init", "-q", "-b", "main"); + git(repository, "config", "user.name", "Release Tag Test"); + git(repository, "config", "user.email", "release-tag@example.invalid"); + await writePackage(repository, version, name); + git(repository, "add", "package.json"); + git(repository, "commit", "-q", "-m", `set ${version}`); + return repository; +} + +async function writePackage( + repository: string, + version: string, + name = "base", +): Promise { + await writeFile( + join(repository, "package.json"), + `${JSON.stringify({ name, version }, null, 2)}\n`, + ); +} + +async function commitPackage( + repository: string, + version: string, + name = version, +): Promise { + await writePackage(repository, version, name); + git(repository, "add", "package.json"); + git(repository, "commit", "-q", "-m", `set ${version}`); + return git(repository, "rev-parse", "HEAD"); +} + +async function commitFile( + repository: string, + file: string, + contents: string, +): Promise { + await writeFile(join(repository, file), contents); + git(repository, "add", file); + git(repository, "commit", "-q", "-m", `update ${file}`); + return git(repository, "rev-parse", "HEAD"); +} + +async function createGhStub( + directory: string, +): Promise<{ path: string; calls: string }> { + const bin = join(directory, "bin"); + await mkdir(bin, { recursive: true }); + const path = join(bin, "gh"); + const calls = join(directory, "gh-calls.log"); + await writeFile( + path, + `#!/bin/sh +printf '%s\\n' "$*" >> "$GH_CALL_LOG" +case "$*" in + *"git/refs --method POST"*) + if [ "$GH_MODE" = same ] || [ "$GH_MODE" = different ]; then + echo 'HTTP 422: Reference already exists' >&2 + exit 1 + fi + echo created + ;; + *"git/ref/tags/"*) + printf '%s\\n' "$GH_EXISTING_SHA" + ;; + *) + echo "unexpected gh call: $*" >&2 + exit 2 + ;; +esac +`, + ); + await chmod(path, 0o755); + return { path: bin, calls }; +} + +function envForGh( + stub: { path: string; calls: string }, + extra: Record = {}, +): Record { + return { + PATH: `${stub.path}:${process.env.PATH ?? ""}`, + GH_CALL_LOG: stub.calls, + GH_MODE: "create", + GH_EXISTING_SHA: "", + ...extra, + }; +} + +function runScript( + repository: string, + args: readonly string[], + env: Record = {}, +): CommandResult { + return command(["bun", script, ...args], { cwd: repository, env }); +} + +afterEach(async () => { + await Promise.all( + directories + .splice(0) + .map((directory) => rm(directory, { recursive: true, force: true })), + ); +}); + +describe("release tag minting", () => { + it("targets the oldest first-parent commit that set the version", async () => { + const directory = await scratchDirectory(); + const repository = await createRepository(directory, "0.8.0"); + const base = git(repository, "rev-parse", "HEAD"); + const target = await commitPackage(repository, "0.9.0"); + const tip = await commitFile(repository, "later.txt", "later change\n"); + git(repository, "tag", "v0.8.0", base); + const stub = await createGhStub(directory); + + const result = runScript( + repository, + ["mint"], + envForGh(stub, { + RELEASE_SHA: tip, + RELEASE_REPOSITORY: "RigelBuild/solid-markdown", + }), + ); + + expect(result.exitCode).toBe(0); + expect(await Bun.file(stub.calls).text()).toContain(`sha=${target}`); + expect(await Bun.file(stub.calls).text()).not.toContain(`sha=${tip}`); + }); + + it("does not call GitHub when the local tag already exists", async () => { + const directory = await scratchDirectory(); + const repository = await createRepository(directory, "0.9.0"); + const tip = git(repository, "rev-parse", "HEAD"); + git(repository, "tag", "v0.9.0", tip); + const stub = await createGhStub(directory); + + const result = runScript( + repository, + ["mint"], + envForGh(stub, { + RELEASE_SHA: tip, + RELEASE_REPOSITORY: "RigelBuild/solid-markdown", + }), + ); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain("already exists; nothing to mint"); + expect(await Bun.file(stub.calls).exists()).toBe(false); + }); + + it("accepts a concurrent 422 tag creation at the expected target", async () => { + const directory = await scratchDirectory(); + const repository = await createRepository(directory, "0.8.0"); + const base = git(repository, "rev-parse", "HEAD"); + const target = await commitPackage(repository, "0.9.0"); + git(repository, "tag", "v0.8.0", base); + const stub = await createGhStub(directory); + + const result = runScript( + repository, + ["mint"], + envForGh(stub, { + GH_MODE: "same", + GH_EXISTING_SHA: target, + RELEASE_SHA: target, + RELEASE_REPOSITORY: "RigelBuild/solid-markdown", + }), + ); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain("created concurrently"); + expect( + (await Bun.file(stub.calls).text()).split("\n").filter(Boolean), + ).toHaveLength(2); + }); + + it("rejects a concurrent 422 tag creation at a different target", async () => { + const directory = await scratchDirectory(); + const repository = await createRepository(directory, "0.8.0"); + const base = git(repository, "rev-parse", "HEAD"); + const target = await commitPackage(repository, "0.9.0"); + git(repository, "tag", "v0.8.0", base); + const stub = await createGhStub(directory); + + const result = runScript( + repository, + ["mint"], + envForGh(stub, { + GH_MODE: "different", + GH_EXISTING_SHA: base, + RELEASE_SHA: target, + RELEASE_REPOSITORY: "RigelBuild/solid-markdown", + }), + ); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain(`expected ${target}`); + }); +}); + +describe("release version check", () => { + it("skips when only other package metadata changed", async () => { + const directory = await scratchDirectory(); + const repository = await createRepository(directory, "1.0.0", "before"); + const base = git(repository, "rev-parse", "HEAD"); + const head = await commitPackage(repository, "1.0.0", "after"); + + const result = runScript(repository, ["check"], { + BASE_SHA: base, + HEAD_SHA: head, + }); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain("version unchanged; check skipped"); + }); + + it("accepts a changed version greater than the latest tag", async () => { + const directory = await scratchDirectory(); + const repository = await createRepository(directory, "1.0.0"); + const base = git(repository, "rev-parse", "HEAD"); + git(repository, "tag", "v1.0.0", base); + const head = await commitPackage(repository, "1.1.0"); + + const result = runScript(repository, ["check"], { + BASE_SHA: base, + HEAD_SHA: head, + }); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain("Version 1.1.0 is valid"); + }); + + it("rejects an equal or lower version than the latest tag", async () => { + for (const version of ["1.0.0", "0.9.9"]) { + const directory = await scratchDirectory(); + const repository = await createRepository(directory, "0.8.0"); + const base = git(repository, "rev-parse", "HEAD"); + git(repository, "tag", "v1.0.0", base); + const head = await commitPackage(repository, version); + + const result = runScript(repository, ["check"], { + BASE_SHA: base, + HEAD_SHA: head, + }); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("expected a version greater than v1.0.0"); + } + }); + + it("orders release candidates before their final release and compares rc numbers", async () => { + const cases = [ + { candidate: "3.0.0-rc.1", latest: "3.0.0-rc.0", succeeds: true }, + { candidate: "3.0.0", latest: "3.0.0-rc.9", succeeds: true }, + { candidate: "3.0.0-rc.0", latest: "2.9.9", succeeds: true }, + ]; + for (const { candidate, latest, succeeds } of cases) { + const directory = await scratchDirectory(); + const repository = await createRepository(directory, "2.0.0"); + const base = git(repository, "rev-parse", "HEAD"); + git(repository, "tag", `v${latest}`, base); + const head = await commitPackage(repository, candidate); + + const result = runScript(repository, ["check"], { + BASE_SHA: base, + HEAD_SHA: head, + }); + + expect(result.exitCode === 0).toBe(succeeds); + } + }); + + it("rejects beta labels and leading-zero components", async () => { + for (const version of ["3.0.0-beta.1", "03.0.0"]) { + const directory = await scratchDirectory(); + const repository = await createRepository(directory, "2.0.0"); + const base = git(repository, "rev-parse", "HEAD"); + const head = await commitPackage(repository, version); + + const result = runScript(repository, ["check"], { + BASE_SHA: base, + HEAD_SHA: head, + }); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("Invalid owned version"); + } + }); +}); + +describe("release tag resolution", () => { + it("resolves a matching tag whose commit is on origin/main", async () => { + const directory = await scratchDirectory(); + const repository = await createRepository(directory, "1.2.3-rc.4"); + const sha = git(repository, "rev-parse", "HEAD"); + git(repository, "update-ref", "refs/remotes/origin/main", sha); + + const result = runScript(repository, ["resolve", "v1.2.3-rc.4", sha]); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain(`Resolved v1.2.3-rc.4 at ${sha}`); + }); + + it("rejects a tag that does not match the commit package version", async () => { + const directory = await scratchDirectory(); + const repository = await createRepository(directory, "1.2.3"); + const sha = git(repository, "rev-parse", "HEAD"); + git(repository, "update-ref", "refs/remotes/origin/main", sha); + + const result = runScript(repository, ["resolve", "v1.2.4", sha]); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("does not match package.json"); + }); + + it("rejects a matching-version commit that is not an ancestor of origin/main", async () => { + const directory = await scratchDirectory(); + const repository = await createRepository(directory, "1.2.3"); + const mainSha = git(repository, "rev-parse", "HEAD"); + git(repository, "update-ref", "refs/remotes/origin/main", mainSha); + const branchSha = await commitPackage(repository, "2.0.0"); + + const result = runScript(repository, ["resolve", "v2.0.0", branchSha]); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("is not reachable from origin/main"); + }); +});