From 45e9ca0b6781c021f51b234bd46ab8a16caff5e2 Mon Sep 17 00:00:00 2001 From: jdalton Date: Wed, 2 Dec 2026 12:43:48 -0500 Subject: [PATCH] chore(release): prepare Socket CLI 2.1.0-rc.0 Prepare the native release without changelog entries. Validate release metadata and reserve changelog entries for stable releases. --- .claude/skills/bump-socket/SKILL.md | 6 +- .../bump-socket/references/release-lanes.md | 10 +- .github/workflows/publish-npm.yml | 2 +- .github/workflows/release-github.yml | 18 +- package.json | 4 +- scripts/release/open-release-pr.mts | 35 ++-- scripts/release/prepare.mts | 158 ++++++++++-------- scripts/release/release-branch.mts | 23 ++- test/release-open-pr.test.mts | 103 ++++++++++-- test/release-prepare.test.mts | 97 +++++++++-- test/release-workflow.test.mts | 9 +- 11 files changed, 335 insertions(+), 130 deletions(-) diff --git a/.claude/skills/bump-socket/SKILL.md b/.claude/skills/bump-socket/SKILL.md index 863130c11..43011a712 100644 --- a/.claude/skills/bump-socket/SKILL.md +++ b/.claude/skills/bump-socket/SKILL.md @@ -25,7 +25,7 @@ gh workflow run publish-npm.yml --ref v1.x \ -f mode=release-pr -f dry-run=true -f release-lane=v2-rc ``` -Review the proposed version and changelog output. If the requested task is to -prepare the release PR, rerun with `dry-run=false`; do not ask again for that -authorization. Do not dispatch `mode=publish` as part of bump preparation. +Review the proposed versions and the changelog output for the stable lane, +when selected. If the requested task is to prepare the release PR, rerun with +`dry-run=false`; do not ask again for that authorization. Do not dispatch `mode=publish` as part of bump preparation. Report the workflow run and resulting PR. diff --git a/.claude/skills/bump-socket/references/release-lanes.md b/.claude/skills/bump-socket/references/release-lanes.md index 7101e558f..d654c2068 100644 --- a/.claude/skills/bump-socket/references/release-lanes.md +++ b/.claude/skills/bump-socket/references/release-lanes.md @@ -16,8 +16,14 @@ dist-tag. Never publish an RC as `latest` or promote this track to stable. The `release-pr` workflow derives the next patch or minor version for v1.x unless `release-as` is required for a breaking release. A dry run prints the -proposed versions and changelog. Set `dry-run=false` when the user asks to -create the release preparation PR. +proposed versions and the stable changelog, when selected. Set `dry-run=false` +when the user asks to create the release preparation PR. + +Keep changelog entries for stable releases. An RC-only preparation updates +`socketCliPrereleaseVersion` in `package.json` and leaves `CHANGELOG.md` +untouched. A paired preparation adds a changelog section for the stable +version only. GitHub finalizes native RCs with a version tag and no release +notes. After merging, dispatch `mode=publish` with the same `release-lane` on `v1.x`. Publishing selects the latest merged preparation for that lane. diff --git a/.github/workflows/publish-npm.yml b/.github/workflows/publish-npm.yml index 1eaf8e1b8..ac3afeec7 100644 --- a/.github/workflows/publish-npm.yml +++ b/.github/workflows/publish-npm.yml @@ -694,7 +694,7 @@ jobs: - *setup-firewall - *install-dependencies - - name: Prepare version and changelog + - name: Prepare release metadata id: bump env: RELEASE_AS: ${{ inputs.release-as }} diff --git a/.github/workflows/release-github.yml b/.github/workflows/release-github.yml index 1bd6d23ed..091a84b67 100644 --- a/.github/workflows/release-github.yml +++ b/.github/workflows/release-github.yml @@ -110,18 +110,20 @@ jobs: gh release view "${TAG}" --json databaseId --jq '.databaseId' > "$RUNNER_TEMP/release-id" 2>/dev/null || true RELEASE_ID="$(cat "$RUNNER_TEMP/release-id" 2>/dev/null || true)" if [[ ! "$RELEASE_ID" =~ ^[0-9]+$ ]]; then - awk -v version="$VERSION" 'index($0, "## [" version "]") == 1 { found=1; print; next } found && /^## / { exit } found { print }' \ - "$GITHUB_WORKSPACE/CHANGELOG.md" > "$RUNNER_TEMP/release-notes.md" - if [ ! -s "$RUNNER_TEMP/release-notes.md" ]; then - echo "CHANGELOG.md has no section for $VERSION." >&2 - exit 1 + if [ "$IS_PRERELEASE" = true ]; then + RELEASE_FLAGS=(--prerelease --notes "") + else + awk -v version="$VERSION" 'index($0, "## [" version "]") == 1 { found=1; print; next } found && /^## / { exit } found { print }' \ + "$GITHUB_WORKSPACE/CHANGELOG.md" > "$RUNNER_TEMP/release-notes.md" + if [ ! -s "$RUNNER_TEMP/release-notes.md" ]; then + echo "CHANGELOG.md has no section for $VERSION." >&2 + exit 1 + fi + RELEASE_FLAGS=(--notes-file "$RUNNER_TEMP/release-notes.md") fi - RELEASE_FLAGS=() - if [ "$IS_PRERELEASE" = true ]; then RELEASE_FLAGS+=(--prerelease); fi gh release create "$TAG" \ --title "$TAG" \ --verify-tag \ - --notes-file "$RUNNER_TEMP/release-notes.md" \ --draft \ "${RELEASE_FLAGS[@]}" RELEASE_ID="$(gh release view "${TAG}" --json databaseId --jq '.databaseId')" diff --git a/package.json b/package.json index 6588a7027..30d9722f7 100644 --- a/package.json +++ b/package.json @@ -1,9 +1,7 @@ { "name": "socket", "version": "1.18.2", - "publishConfig": { - "tag": "rc-2.1.0" - }, + "socketCliPrereleaseVersion": "2.1.0-rc.0", "description": "CLI for Socket.dev", "contentPolicy": { "class": "dual-use" diff --git a/scripts/release/open-release-pr.mts b/scripts/release/open-release-pr.mts index d884cd420..57c0f7d44 100644 --- a/scripts/release/open-release-pr.mts +++ b/scripts/release/open-release-pr.mts @@ -21,11 +21,13 @@ import { discardReleaseBranch, openReleaseBranch, openReleasePullRequest, + requireReleaseLane, resolveReleaseEnv, } from './release-branch.mts' import { isMainModule } from '../lib/is-main-module.mts' import { runMain } from '../lib/run-main.mts' +import type { ReleaseLane } from './release-branch.mts' import type { ScriptMeta } from '../lib/run-main.mts' const execFile = promisify(execFileCallback) @@ -38,15 +40,20 @@ const rootPath = path.join( // The only files a bump may change. Anything else in the diff means the // derivation job wrote something it should not have. -const BUMP_FILES = ['CHANGELOG.md', 'package.json'] +export function bumpFiles(lane: ReleaseLane): string[] { + return lane === 'v2-rc' ? ['package.json'] : ['CHANGELOG.md', 'package.json'] +} -function readFlag(argv: readonly string[], name: string): string | undefined { +export function readFlag( + argv: readonly string[], + name: string, +): string | undefined { const index = argv.indexOf(`--${name}`) const value = index === -1 ? undefined : argv[index + 1] return value?.startsWith('--') ? undefined : value } -async function git(args: readonly string[]): Promise { +export async function git(args: readonly string[]): Promise { const { stdout } = await execFile('git', [...args], { cwd: rootPath, maxBuffer: 64 * 1024 * 1024, @@ -54,14 +61,18 @@ async function git(args: readonly string[]): Promise { return stdout } -export function assertBumpOnly(changedFiles: readonly string[]): void { +export function assertBumpOnly( + changedFiles: readonly string[], + lane: ReleaseLane, +): void { + const expected = bumpFiles(lane) const sorted = [...changedFiles].sort() if ( - sorted.length !== BUMP_FILES.length || - sorted.some((file, i) => file !== BUMP_FILES[i]) + sorted.length !== expected.length || + sorted.some((file, i) => file !== expected[i]) ) { throw new Error( - '[open-release-pr] the bump must change exactly CHANGELOG.md and package.json.\n' + + `[open-release-pr] the bump must change exactly ${expected.join(' and ')}.\n` + " Where: the working tree after applying the derivation job's patch.\n" + ` Saw: ${sorted.join(', ') || '(no changes)'}.\n` + ' Fix: re-dispatch with mode release-pr. If it repeats, inspect prepare.mts.', @@ -69,18 +80,19 @@ export function assertBumpOnly(changedFiles: readonly string[]): void { } } -async function main(): Promise { - const version = readFlag(process.argv.slice(2), 'version') +export async function main(argv = process.argv.slice(2)): Promise { + const version = readFlag(argv, 'version') if (!version) { throw new Error( '[open-release-pr] --version is required.\n' + " Fix: pass the derivation job's version output through.", ) } + const lane = requireReleaseLane(process.env['RELEASE_LANE']) const changed = (await git(['diff', '--name-only', 'HEAD'])) .split('\n') .filter(Boolean) - assertBumpOnly(changed) + assertBumpOnly(changed, lane) const manifest = JSON.parse( readFileSync(path.join(rootPath, 'package.json'), 'utf8'), ) as { version?: string; socketCliPrereleaseVersion?: string } @@ -94,7 +106,6 @@ async function main(): Promise { ) } - const lane = process.env['RELEASE_LANE'] const pairedVersion = process.env['PAIRED_VERSION'] || undefined if ( (lane === 'paired' && !pairedVersion) || @@ -111,7 +122,7 @@ async function main(): Promise { const env = resolveReleaseEnv() const parentSha = (await git(['rev-parse', 'HEAD'])).trim() const baseTreeSha = (await git(['rev-parse', 'HEAD^{tree}'])).trim() - const files = BUMP_FILES.map(relPath => ({ + const files = bumpFiles(lane).map(relPath => ({ content: readFileSync(path.join(rootPath, relPath), 'utf8'), path: relPath, })) diff --git a/scripts/release/prepare.mts b/scripts/release/prepare.mts index 0c938d130..01db3f97b 100644 --- a/scripts/release/prepare.mts +++ b/scripts/release/prepare.mts @@ -25,6 +25,7 @@ import { readTaggedPrereleaseVersions, } from './history.mts' import { readPublishedVersion, readPublishedVersions } from './registry.mts' +import { requireReleaseLane } from './release-branch.mts' import { deriveNextVersion, maxPrereleaseVersion, @@ -37,6 +38,7 @@ import { readReleasePolicy } from '../../src/sea/version.mts' import { isMainModule } from '../lib/is-main-module.mts' import { runMain } from '../lib/run-main.mts' +import type { ConventionalCommit } from './version.mts' import type { ScriptMeta } from '../lib/run-main.mts' const rootPath = path.join( @@ -45,6 +47,8 @@ const rootPath = path.join( '..', ) +const STABLE_RELEASE_MAJOR = 1 + const VERSION_FIELD_PATTERN = /("version":\s*")[^"]+(")/ interface PackageJsonShape { @@ -127,57 +131,80 @@ function parseArgs(argv: readonly string[]): { return { dryRun, releaseAs } } +export function prepareStableChangelog(opts: { + changelog: string + commits: readonly ConventionalCommit[] + date: string + repositoryUrl?: string | undefined + version: string +}) { + const heading = changelogHeading( + opts.version, + opts.date, + repoBaseUrl(opts.repositoryUrl), + ) + return promoteChangelog({ + changelog: opts.changelog, + derivedSection: generateChangelogSection({ + commits: opts.commits, + heading, + }), + heading, + }) +} + async function main( argv = process.argv.slice(2), root = rootPath, ): Promise { const { dryRun, releaseAs } = parseArgs(argv) - const releaseLane = process.env['SOCKET_CLI_RELEASE_LANE'] - if ( - releaseLane && - releaseLane !== 'paired' && - releaseLane !== 'v1.x' && - releaseLane !== 'v2-rc' - ) { - throw new Error(`Unknown release lane: ${releaseLane}.`) - } - const releaseMajorValue = releaseLane - ? releaseLane === 'v2-rc' - ? '2' - : '1' - : process.env['SOCKET_CLI_RELEASE_MAJOR'] - const releaseMajor = releaseMajorValue - ? Number.parseInt(releaseMajorValue, 10) - : undefined - if ( - releaseMajorValue && - (releaseMajor === undefined || - !Number.isInteger(releaseMajor) || - releaseMajor < 1 || - String(releaseMajor) !== releaseMajorValue) - ) { - throw new Error( - `SOCKET_CLI_RELEASE_MAJOR must be a positive integer; received ${releaseMajorValue}`, - ) - } + const laneValue = process.env['SOCKET_CLI_RELEASE_LANE'] + const releaseLane = laneValue ? requireReleaseLane(laneValue) : undefined const manifest = readPackageJson(root) const releasePolicy = readReleasePolicy(root) - if (releaseLane === 'v2-rc' && releasePolicy.mode !== 'prerelease-only') { - throw new Error('The v2-rc lane requires a prerelease-only policy.') - } const manifestVersion = manifest.parsed.version ?? '0.0.0' + const prereleasePolicy = + releasePolicy.mode === 'prerelease-only' ? releasePolicy : undefined + const prereleaseMajor = prereleasePolicy + ? Number(prereleasePolicy.versionHint.split('.')[0]) + : undefined + + let releaseMajor: number | undefined + if (releaseLane === 'v2-rc') { + if (prereleaseMajor === undefined) { + throw new Error('The v2-rc lane requires a prerelease-only policy.') + } + releaseMajor = prereleaseMajor + } else if (releaseLane) { + releaseMajor = STABLE_RELEASE_MAJOR + } else { + const legacyMajor = process.env['SOCKET_CLI_RELEASE_MAJOR'] + if (legacyMajor) { + releaseMajor = Number.parseInt(legacyMajor, 10) + if ( + !Number.isInteger(releaseMajor) || + releaseMajor < 1 || + String(releaseMajor) !== legacyMajor + ) { + throw new Error( + `SOCKET_CLI_RELEASE_MAJOR must be a positive integer; received ${legacyMajor}`, + ) + } + } + } + const selectedReleaseMajor = releaseMajor ?? Number(manifestVersion.split('.')[0]) const prereleaseTrack = - releasePolicy.mode === 'prerelease-only' && - selectedReleaseMajor === Number(releasePolicy.versionHint.split('.')[0]) - ? releasePolicy + releaseLane === 'v2-rc' || + (releaseLane === undefined && selectedReleaseMajor === prereleaseMajor) + ? prereleasePolicy : undefined const pairedTrack = - selectedReleaseMajor === 1 && - releaseLane !== 'v1.x' && - releasePolicy.mode === 'prerelease-only' - ? releasePolicy + !prereleaseTrack && + selectedReleaseMajor === STABLE_RELEASE_MAJOR && + releaseLane !== 'v1.x' + ? prereleasePolicy : undefined const nativeTrack = prereleaseTrack ?? pairedTrack const [publishedVersion, publishedVersions, taggedPrereleases] = @@ -206,7 +233,7 @@ async function main( releaseVersionsForLine( publishedVersions, manifestVersion, - prereleaseTrack ? 1 : selectedReleaseMajor, + prereleaseTrack ? STABLE_RELEASE_MAJOR : selectedReleaseMajor, ), ) const latestStableBaseline = prereleaseTrack @@ -264,20 +291,22 @@ async function main( } log(`${derived.base} → ${derived.version} (${derived.reason}).`) - const repoUrl = repoBaseUrl( - typeof manifest.parsed.repository === 'string' - ? manifest.parsed.repository - : manifest.parsed.repository?.url, - ) - const date = new Date().toISOString().slice(0, 10) - const heading = changelogHeading(derived.version, date, repoUrl) const changelogPath = path.join(root, 'CHANGELOG.md') - const promoted = promoteChangelog({ - changelog: readFileSync(changelogPath, 'utf8'), - derivedSection: generateChangelogSection({ commits, heading }), - heading, - }) - log(`changelog section taken from the ${promoted.source} entries.`) + const promoted = prereleaseTrack + ? undefined + : prepareStableChangelog({ + changelog: readFileSync(changelogPath, 'utf8'), + commits, + date: new Date().toISOString().slice(0, 10), + repositoryUrl: + typeof manifest.parsed.repository === 'string' + ? manifest.parsed.repository + : manifest.parsed.repository?.url, + version: derived.version, + }) + if (promoted) { + log(`changelog section taken from the ${promoted.source} entries.`) + } const pairedVersion = pairedTrack ? nextPrereleaseVersion(pairedTrack, [ @@ -287,22 +316,13 @@ async function main( ...taggedPrereleases, ]) : undefined - let pairedSection: string | undefined - let changelog = promoted.changelog let rawManifest = prereleaseTrack && - manifestVersion.startsWith('1.') && + manifestVersion.startsWith(`${STABLE_RELEASE_MAJOR}.`) && !manifestVersion.includes('-') ? writePairedPrerelease(manifest.raw, derived.version) : writeManifestVersion(manifest.raw, derived.version) if (pairedVersion) { - const nativeHeading = changelogHeading(pairedVersion, date, repoUrl) - pairedSection = nativeHeading + promoted.section.slice(heading.length) - changelog = promoteChangelog({ - changelog, - derivedSection: pairedSection, - heading: nativeHeading, - }).changelog rawManifest = writePairedPrerelease(rawManifest, pairedVersion) log(`paired native prerelease ${pairedVersion}.`) } @@ -313,16 +333,20 @@ async function main( } if (dryRun) { log(`dry run — would release ${derived.version}. Nothing written.`) - process.stdout.write( - [promoted.section, pairedSection].filter(Boolean).join('\n\n') + '\n', - ) + if (promoted) { + process.stdout.write(`${promoted.section}\n`) + } emitOutputs(outputs) return } writeFileSync(path.join(root, 'package.json'), rawManifest) - writeFileSync(changelogPath, changelog) - log(`wrote ${derived.version} to package.json and CHANGELOG.md.`) + if (promoted) { + writeFileSync(changelogPath, promoted.changelog) + } + log( + `wrote ${derived.version} to package.json${promoted ? ' and CHANGELOG.md' : ''}.`, + ) emitOutputs(outputs) } diff --git a/scripts/release/release-branch.mts b/scripts/release/release-branch.mts index 2ef6d658a..20b71c6e2 100644 --- a/scripts/release/release-branch.mts +++ b/scripts/release/release-branch.mts @@ -16,6 +16,15 @@ import { import type { PullRequest } from './github-api.mts' +export type ReleaseLane = 'paired' | 'v1.x' | 'v2-rc' + +export function requireReleaseLane(value: string | undefined): ReleaseLane { + if (value === 'paired' || value === 'v1.x' || value === 'v2-rc') { + return value + } + throw new Error(`Unknown release lane: ${value ?? '(missing)'}.`) +} + export interface ReleaseEnv { // The branch the release PR targets, i.e. the dispatch branch. readonly releaseLine: string @@ -107,7 +116,7 @@ export async function openReleaseBranch( */ export async function openReleasePullRequest( releaseBranch: ReleaseBranch, - lane?: string, + lane: ReleaseLane, pairedVersion?: string, ): Promise { const { branch, env, version } = releaseBranch @@ -128,15 +137,19 @@ function releaseVersionLabel(version: string, pairedVersion?: string): string { export function releasePullRequestBody( releaseLine: string, version: string, - lane = version.includes('-') ? 'v2-rc' : 'paired', + lane: ReleaseLane, pairedVersion?: string, ): string { + const stable = lane !== 'v2-rc' return [ - `Records ${releaseVersionLabel(version, pairedVersion)} in package.json and CHANGELOG.md.`, + `Records ${releaseVersionLabel(version, pairedVersion)} in package.json.` + + (stable ? ' Updates CHANGELOG.md for the stable version.' : ''), '', 'To release:', '', - '1. Review the release versions and CHANGELOG sections, then squash-merge this PR.', + stable + ? '1. Review the release versions and stable changelog, then squash-merge this PR.' + : '1. Review the RC version, then squash-merge this PR.', `2. Dispatch **Publish to npm registry** on \`${releaseLine}\` with \`release-lane: ${lane}\` and \`dry-run: false\`. It reserves the prepared versions and stages their npm packages.`, '3. Approve each package with `pnpm run approve:npm `. Approve the RC launcher after its platform packages. GitHub releases are finalized after the packages for each version become public.', '', @@ -149,7 +162,7 @@ export function releasePullRequestBody( */ export async function closeSupersededReleasePullRequests( releaseBranch: ReleaseBranch, - lane = releaseBranch.version.includes('-') ? 'v2-rc' : 'v1.x', + lane: ReleaseLane, ): Promise { const { branch, env } = releaseBranch return await closeSupersededPullRequests({ diff --git a/test/release-open-pr.test.mts b/test/release-open-pr.test.mts index 2bc38d787..1a331ac12 100644 --- a/test/release-open-pr.test.mts +++ b/test/release-open-pr.test.mts @@ -4,11 +4,18 @@ import { closeSupersededPullRequests, upsertPullRequest, } from '../scripts/release/github-api.mts' -import { assertBumpOnly } from '../scripts/release/open-release-pr.mts' +import { + assertBumpOnly, + bumpFiles, + git, + main, + readFlag, +} from '../scripts/release/open-release-pr.mts' import { closeSupersededReleasePullRequests, openReleaseBranch, releasePullRequestBody, + requireReleaseLane, } from '../scripts/release/release-branch.mts' const PR_CONFIG = { @@ -27,11 +34,58 @@ function jsonResponse(body: unknown, status = 200): Response { afterEach(() => { vi.unstubAllGlobals() + vi.unstubAllEnvs() +}) + +describe('release lane', () => { + it.each(['v1.x', 'paired'] as const)( + 'includes the stable changelog in %s', + lane => { + expect(bumpFiles(requireReleaseLane(lane))).toEqual([ + 'CHANGELOG.md', + 'package.json', + ]) + }, + ) + + it('expects only the manifest in v2-rc', () => { + expect(bumpFiles(requireReleaseLane('v2-rc'))).toEqual(['package.json']) + }) + + it.each([undefined, '', 'preview', 'v2-rc-extra'])( + 'rejects invalid lane %s', + lane => { + expect(() => requireReleaseLane(lane)).toThrow(/Unknown release lane/) + }, + ) + + it('rejects an invalid dispatch before opening a PR', async () => { + vi.stubEnv('RELEASE_LANE', 'preview') + await expect(main(['--version', '2.1.0-rc.0'])).rejects.toThrow( + 'Unknown release lane: preview.', + ) + }) + + it('reports a missing version flag', async () => { + await expect(main([])).rejects.toThrow('--version is required') + }) + + it('reads a populated flag and ignores a following flag', () => { + expect(readFlag(['--version', '2.1.0-rc.0'], 'version')).toBe('2.1.0-rc.0') + expect(readFlag(['--version', '--other'], 'version')).toBeUndefined() + expect(readFlag([], 'version')).toBeUndefined() + }) + + it('runs Git from the repository root', async () => { + expect((await git(['rev-parse', '--show-prefix'])).trim()).toBe('') + }) }) describe('assertBumpOnly', () => { it('accepts exactly the changelog and the manifest in any order', () => { - expect(() => assertBumpOnly(['package.json', 'CHANGELOG.md'])).not.toThrow() + expect(() => + assertBumpOnly(['package.json', 'CHANGELOG.md'], 'paired'), + ).not.toThrow() }) it.each([ @@ -40,7 +94,14 @@ describe('assertBumpOnly', () => { [['CHANGELOG.md', 'package.json', 'scripts/release/prepare.mts']], [['CHANGELOG.md', 'pnpm-lock.yaml']], ])('refuses %j', files => { - expect(() => assertBumpOnly(files)).toThrow(/exactly CHANGELOG.md/) + expect(() => assertBumpOnly(files, 'v1.x')).toThrow(/exactly CHANGELOG.md/) + }) + + it('permits only the manifest for a prerelease', () => { + expect(() => assertBumpOnly(['package.json'], 'v2-rc')).not.toThrow() + expect(() => + assertBumpOnly(['CHANGELOG.md', 'package.json'], 'v2-rc'), + ).toThrow(/exactly package.json/) }) }) @@ -217,16 +278,19 @@ describe('closing superseded lane preparations', () => { vi.stubGlobal('fetch', fetchMock) expect( - await closeSupersededReleasePullRequests({ - branch: 'npm-publish-v1.6.0', - created: false, - env: { - releaseLine: PR_CONFIG.base, - repo: PR_CONFIG.repo, - token: PR_CONFIG.token, + await closeSupersededReleasePullRequests( + { + branch: 'npm-publish-v1.6.0', + created: false, + env: { + releaseLine: PR_CONFIG.base, + repo: PR_CONFIG.repo, + token: PR_CONFIG.token, + }, + version: '1.6.0', }, - version: '1.6.0', - }), + 'v1.x', + ), ).toEqual([1]) expect(fetchMock).toHaveBeenCalledTimes(3) }) @@ -234,7 +298,7 @@ describe('closing superseded lane preparations', () => { describe('releasePullRequestBody', () => { it('tells the reviewer how to publish from the release line', () => { - const body = releasePullRequestBody('v1.x', '1.5.1') + const body = releasePullRequestBody('v1.x', '1.5.1', 'paired') expect(body).toContain('1.5.1') expect(body).toContain('squash-merge') expect(body).toContain('`v1.x`') @@ -242,12 +306,17 @@ describe('releasePullRequestBody', () => { expect(body).toContain('`release-lane: paired`') }) - it.each(['v1.x', 'v2-rc'])( + it.each(['v1.x', 'v2-rc'] as const)( 'tells reviewers to publish on the %s lane', lane => { - expect(releasePullRequestBody('v1.x', '1.5.1', lane)).toContain( - `\`release-lane: ${lane}\``, - ) + const version = lane === 'v2-rc' ? '2.1.0-rc.0' : '1.5.1' + const body = releasePullRequestBody('v1.x', version, lane) + expect(body).toContain(`\`release-lane: ${lane}\``) + if (lane === 'v2-rc') { + expect(body).not.toContain('CHANGELOG.md') + } else { + expect(body).toContain('CHANGELOG.md') + } }, ) }) diff --git a/test/release-prepare.test.mts b/test/release-prepare.test.mts index 082fbc03c..d764d1f8f 100644 --- a/test/release-prepare.test.mts +++ b/test/release-prepare.test.mts @@ -17,6 +17,7 @@ import { } from '../scripts/release/history.mts' import { prepareRelease, + prepareStableChangelog, writeManifestVersion, writePairedPrerelease, } from '../scripts/release/prepare.mts' @@ -112,6 +113,47 @@ const stableNext = '1.18.1' const originalChangelog = '# Changelog\n\n## [Unreleased]\n\n### Fixed\n- Handle a missing executable.\n' +describe('prepareStableChangelog', () => { + const options = { + date: '2026-12-02', + repositoryUrl: 'git+https://github.com/SocketDev/socket-cli.git', + version: stableNext, + commits: [ + { + breaking: false, + description: 'repair the launcher', + hash: '1234567', + scope: undefined, + type: 'fix', + }, + ], + } + + it('promotes handwritten notes with the stable release heading', () => { + const result = prepareStableChangelog({ + ...options, + changelog: originalChangelog, + }) + + expect(result.source).toBe('unreleased') + expect(result.section).toBe( + '## [1.18.1](https://github.com/SocketDev/socket-cli/releases/tag/v1.18.1) - 2026-12-02\n\n### Fixed\n- Handle a missing executable.', + ) + expect(result.changelog).not.toContain('[Unreleased]') + }) + + it('uses commit-derived notes when no handwritten notes exist', () => { + const result = prepareStableChangelog({ + ...options, + changelog: '# Changelog\n\n## [1.18.0]\n', + }) + + expect(result.source).toBe('derived') + expect(result.section).toContain('### Fixed\n- repair the launcher') + expect(result.changelog).toContain('## [1.18.0]') + }) +}) + function registryVersions(versions: readonly string[]) { vi.stubGlobal( 'fetch', @@ -170,7 +212,7 @@ describe('prepareRelease', () => { rmSync(root, { recursive: true, force: true }) }) - it('prepares stable and the first native RC in the same manifest and changelog', async () => { + it('prepares both versions and writes only the stable changelog', async () => { await prepareRelease([], root) expect(JSON.parse(readFileSync(manifestPath, 'utf8'))).toEqual({ @@ -179,11 +221,12 @@ describe('prepareRelease', () => { socketCliPrereleaseVersion: '2.1.0-rc.0', }) const sections = readFileSync(changelogPath, 'utf8').split(/^## /mu) - for (const version of [stableNext, '2.1.0-rc.0']) { - expect( - sections.find(section => section.startsWith(`[${version}]`)), - ).toContain('- Handle a missing executable.') - } + expect( + sections.find(section => section.startsWith(`[${stableNext}]`)), + ).toContain('- Handle a missing executable.') + expect(sections.some(section => section.startsWith('[2.1.0-rc.'))).toBe( + false, + ) expect(sections.some(section => section.startsWith('[Unreleased]'))).toBe( false, ) @@ -222,7 +265,13 @@ describe('prepareRelease', () => { await prepareRelease(['--dry-run'], root) expect(process.stdout.write).toHaveBeenCalledWith( - expect.stringMatching(/## \[1\.18\.1\][\s\S]*## \[2\.1\.0-rc\.0\]/u), + expect.stringMatching(/## \[1\.18\.1\]/u), + ) + expect(process.stdout.write).toHaveBeenCalledWith( + expect.stringContaining('paired native prerelease 2.1.0-rc.0'), + ) + expect(process.stdout.write).not.toHaveBeenCalledWith( + expect.stringContaining('## [2.1.0-rc.0]'), ) expect(readFileSync(manifestPath, 'utf8')).toBe(originalManifest) expect(readFileSync(changelogPath, 'utf8')).toBe(originalChangelog) @@ -262,8 +311,36 @@ describe('prepareRelease', () => { version: stable, socketCliPrereleaseVersion: '2.1.0-rc.0', }) - const changelog = readFileSync(changelogPath, 'utf8') - expect(changelog).toContain('## [2.1.0-rc.0]') - expect(changelog).not.toContain(`## [${stableNext}]`) + expect(readFileSync(changelogPath, 'utf8')).toBe(originalChangelog) + }) + + it('takes the native major from the configured prerelease hint', async () => { + vi.stubEnv('SOCKET_CLI_RELEASE_LANE', 'v2-rc') + vi.stubEnv('SOCKET_CLI_RELEASE_MAJOR', '2') + writeFileSync( + path.join(root, '.config', 'release.json'), + JSON.stringify({ + mode: 'prerelease-only', + versionHint: '3.4.0', + identifier: 'rc', + distTag: 'rc-3.4.0', + }), + ) + vi.mocked(readTaggedPrereleaseVersions).mockResolvedValue(['3.4.0-rc.1']) + + await prepareRelease([], root) + + expect(readReleaseHistory).toHaveBeenCalledWith(root, stable, 3, stable) + expect(readTaggedPrereleaseVersions).toHaveBeenCalledWith( + root, + '3.4.0', + 'rc', + ) + expect(JSON.parse(readFileSync(manifestPath, 'utf8'))).toEqual({ + name: 'socket', + version: stable, + socketCliPrereleaseVersion: '3.4.0-rc.2', + }) + expect(readFileSync(changelogPath, 'utf8')).toBe(originalChangelog) }) }) diff --git a/test/release-workflow.test.mts b/test/release-workflow.test.mts index 35d9394f7..2e82025ff 100644 --- a/test/release-workflow.test.mts +++ b/test/release-workflow.test.mts @@ -18,6 +18,7 @@ import { npmDistTagForRelease } from '../scripts/release/validate-npm-policy.mts import { SEA_RELEASE_POLICY } from '../src/sea/version.mts' interface ReleaseStep { + id?: string if?: string env?: Record name?: string @@ -531,6 +532,10 @@ console.log(JSON.stringify({ stage: { name, version, stageId: '12345678-1234-412 'gh release view "${TAG}" --json databaseId', ) expect(finalize?.run).not.toContain('releases/tags/${TAG}') + expect(finalize?.run).toContain('RELEASE_FLAGS=(--prerelease --notes "")') + expect(finalize?.run).toContain( + 'RELEASE_FLAGS=(--notes-file "$RUNNER_TEMP/release-notes.md")', + ) }) it('publishes the native CLI for the configured prerelease policy', () => { @@ -551,7 +556,7 @@ console.log(JSON.stringify({ stage: { name, version, stageId: '12345678-1234-412 expect(versionGuardIndex).toBeLessThan(buildIndex) const prepareStep = workflow.jobs.prepare.steps.find( - step => step.name === 'Prepare version and changelog', + step => step.id === 'bump', ) expect(prepareStep?.env?.SOCKET_CLI_RELEASE_LANE).toBe( '${{ env.RELEASE_LANE }}', @@ -592,7 +597,7 @@ console.log(JSON.stringify({ stage: { name, version, stageId: '12345678-1234-412 expect(npmDistTagForRelease(manifest.version, SEA_RELEASE_POLICY)).toBe( isStableV1 ? 'latest' : SEA_RELEASE_POLICY.distTag, ) - expect(manifest.publishConfig?.tag).toBe(releasePolicy.distTag) + expect(manifest.publishConfig?.tag).toBeUndefined() expect(workflow.on.workflow_dispatch.inputs['release-lane']).toMatchObject({ default: 'paired', options: ['paired', 'v1.x', 'v2-rc'],