From a9f0cf283f892c034cfb775ff8c00560a3fb6afd Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:50:44 +0100 Subject: [PATCH 01/20] Move codeSpan to lib, where plx release uses it beside ship Co-Authored-By: Claude Sonnet 5.5 --- packages/dev/src/ship.ts | 14 +------------- .../src/ship.test.ts => lib/src/codeSpan.test.ts} | 2 +- packages/lib/src/codeSpan.ts | 14 ++++++++++++++ packages/lib/src/index.ts | 1 + 4 files changed, 17 insertions(+), 14 deletions(-) rename packages/{dev/src/ship.test.ts => lib/src/codeSpan.test.ts} (94%) create mode 100644 packages/lib/src/codeSpan.ts diff --git a/packages/dev/src/ship.ts b/packages/dev/src/ship.ts index 0890197a..950ae24f 100644 --- a/packages/dev/src/ship.ts +++ b/packages/dev/src/ship.ts @@ -75,6 +75,7 @@ import { COMPENDIUM, type Context, checkRepo, + codeSpan, compareVersions, type FetchVersion, frontmatterField, @@ -392,19 +393,6 @@ async function releaseNotes(ctx: Context, repo: VersionedRepo, next: string, ref return [`Plexus ${next}: the commits ${since}.`, '', ...subjects.map((s) => `- ${codeSpan(s)}`)].join('\n'); } -/** - * A commit subject as a Markdown code span, so that nothing in it is live on - * the forge: no `@scope/package` mention, no `#` heading or reference, no - * emphasis or link. The fence is one backtick longer than the longest run in - * the subject, padded with a space where the subject begins or ends with one. - */ -export function codeSpan(text: string): string { - const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length)); - const fence = '`'.repeat(longest + 1); - const pad = text.startsWith('`') || text.endsWith('`') ? ' ' : ''; - return `${fence}${pad}${text}${pad}${fence}`; -} - /** * Between the phases: tooling's release workflow publishes the three * Plexus-versioned packages, and phase two pins them. Polled with the same diff --git a/packages/dev/src/ship.test.ts b/packages/lib/src/codeSpan.test.ts similarity index 94% rename from packages/dev/src/ship.test.ts rename to packages/lib/src/codeSpan.test.ts index 61ce176e..bf03fc48 100644 --- a/packages/dev/src/ship.test.ts +++ b/packages/lib/src/codeSpan.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'node:test'; -import { codeSpan } from './ship.ts'; +import { codeSpan } from './codeSpan.ts'; test('a commit subject in the release notes is a code span: no mention, reference or markup is live', () => { assert.equal(codeSpan('fix(deps): bump @plexus-ms/lib'), '`fix(deps): bump @plexus-ms/lib`'); diff --git a/packages/lib/src/codeSpan.ts b/packages/lib/src/codeSpan.ts new file mode 100644 index 00000000..72d1ce30 --- /dev/null +++ b/packages/lib/src/codeSpan.ts @@ -0,0 +1,14 @@ +// A commit subject as it goes into release notes. + +/** + * A commit subject as a Markdown code span, so that nothing in it is live on + * the forge: no `@scope/package` mention, no `#` heading or reference, no + * emphasis or link. The fence is one backtick longer than the longest run in + * the subject, padded with a space where the subject begins or ends with one. + */ +export function codeSpan(text: string): string { + const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length)); + const fence = '`'.repeat(longest + 1); + const pad = text.startsWith('`') || text.endsWith('`') ? ' ' : ''; + return `${fence}${pad}${text}${pad}${fence}`; +} diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index 2e70cfa2..7084a277 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -28,6 +28,7 @@ export { readChangeset, workspaceGlobs, } from './changeset.ts'; +export { codeSpan } from './codeSpan.ts'; export { commitVersion } from './commitVersion.ts'; export { type Compose, declaresHealthcheck, type Mapping, parseCompose } from './compose.ts'; export { filesWithConflictMarkers, hasConflictMarkers, hasUnmergedEntries } from './conflicts.ts'; From 182fc32a0362b902324fb02a849acec4dd371889 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:52:11 +0100 Subject: [PATCH 02/20] Test: plx promote against local bare repositories Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/commands/promote.test.ts | 159 ++++++++++++++++++++++ packages/cli/src/testing/forge.ts | 125 +++++++++++++++++ packages/cli/tsconfig.json | 2 +- 3 files changed, 285 insertions(+), 1 deletion(-) create mode 100644 packages/cli/src/commands/promote.test.ts create mode 100644 packages/cli/src/testing/forge.ts diff --git a/packages/cli/src/commands/promote.test.ts b/packages/cli/src/commands/promote.test.ts new file mode 100644 index 00000000..7c7b261d --- /dev/null +++ b/packages/cli/src/commands/promote.test.ts @@ -0,0 +1,159 @@ +import assert from 'node:assert/strict'; +import { writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import { commit, dir, fixture, git, plx, refs, snapshot } from '../testing/forge.ts'; + +const ref = (origin: string, branch: string) => git(origin, 'rev-parse', '-q', '--verify', `refs/heads/${branch}`); +const promote = (repo: string, ...args: string[]) => plx('-y', '--json', 'promote', ...args, '-C', repo); + +test('promote creates env/ on the remote at the head of main when it does not exist', async () => { + const { repo, origin } = fixture('creates'); + const head = git(origin, 'rev-parse', 'main'); + const { code, stdout } = await promote(repo, 'staging'); + assert.equal(code, 0); + assert.equal(ref(origin, 'env/staging'), head); + assert.deepEqual(JSON.parse(stdout), { + environment: 'staging', + branch: 'env/staging', + source: 'main', + from: null, + to: head, + commits: 1, + outcome: 'created', + }); +}); + +test('promote fast-forwards env/ to the head of its source, and the commits it moves over are counted', async () => { + const { repo, origin } = fixture('forwards'); + await promote(repo, 'staging'); + const before = ref(origin, 'env/staging'); + commit(repo, 'second'); + const head = commit(repo, 'third'); + git(repo, 'push', '-q', 'origin', 'main'); + const { stdout } = await promote(repo, 'staging'); + assert.equal(ref(origin, 'env/staging'), head); + assert.deepEqual(JSON.parse(stdout), { + environment: 'staging', + branch: 'env/staging', + source: 'main', + from: before, + to: head, + commits: 2, + outcome: 'fast-forwarded', + }); +}); + +test('promote takes the source from the remote: a main that is not pushed is not promoted', async () => { + const { repo, origin } = fixture('unpushed'); + commit(repo, 'local only'); + await promote(repo, 'staging'); + assert.equal(ref(origin, 'env/staging'), git(origin, 'rev-parse', 'main')); + assert.notEqual(ref(origin, 'env/staging'), git(repo, 'rev-parse', 'HEAD')); +}); + +test('promote of an environment whose source is another one moves it to where that one is on the remote', async () => { + const { repo, origin } = fixture('chain'); + await promote(repo, 'staging'); + commit(repo, 'not yet in staging'); + git(repo, 'push', '-q', 'origin', 'main'); + const { stdout } = await promote(repo, 'production'); + assert.equal(ref(origin, 'env/production'), ref(origin, 'env/staging')); + assert.equal(JSON.parse(stdout).source, 'env/staging'); + assert.notEqual(ref(origin, 'env/production'), git(origin, 'rev-parse', 'main')); +}); + +test('promote refuses an environment whose source branch is not on the remote yet, and says to promote that one first', async () => { + const { repo, origin } = fixture('source-missing'); + const before = refs(origin); + await assert.rejects(promote(repo, 'production'), /env\/staging.*not on the remote.*promote staging first/s); + assert.deepEqual(refs(origin), before); +}); + +test('promote refuses a move that is no fast-forward, and leaves the branch where it is', async () => { + const { repo, origin } = fixture('diverged'); + await promote(repo, 'staging'); + // Someone put a commit of their own on the environment's branch. + const other = join(dir, 'diverged-other'); + git(dir, 'clone', '-q', origin, other); + git(other, 'checkout', '-q', 'env/staging'); + const theirs = commit(other, 'a hotfix on the branch'); + git(other, 'push', '-q', 'origin', 'env/staging'); + commit(repo, 'next'); + git(repo, 'push', '-q', 'origin', 'main'); + const before = refs(origin); + await assert.rejects(promote(repo, 'staging'), /env\/staging is not an ancestor of main.*fast-forward/s); + assert.deepEqual(refs(origin), before); + assert.equal(ref(origin, 'env/staging'), theirs); +}); + +test('promote of a branch already at its source pushes nothing and says so', async () => { + const { repo, origin } = fixture('unchanged'); + await promote(repo, 'staging'); + const before = refs(origin); + const { code, stdout } = await plx('-y', 'promote', 'staging', '-C', repo); + assert.equal(code, 0); + assert.deepEqual(refs(origin), before); + assert.match(stdout, /^✓ env\/staging is at main already/); + assert.equal(JSON.parse((await promote(repo, 'staging')).stdout).outcome, 'unchanged'); +}); + +test('promote refuses an undeclared name, naming the declared ones', async () => { + const { repo, origin } = fixture('undeclared'); + const before = refs(origin); + await assert.rejects(promote(repo, 'qa'), /qa is no declared environment.*staging, production/s); + await assert.rejects(promote(repo, 'main'), /main is no declared environment/); + assert.deepEqual(refs(origin), before); +}); + +test('promote refuses an invalid declaration, and a repo that declares nothing', async () => { + const invalid = fixture('invalid', '---\nenvironments:\n staging:\n promotes_from: develop\n---\n'); + await assert.rejects(promote(invalid.repo, 'staging'), /invalid.*develop/s); + const none = fixture('none', '---\n---\n'); + await assert.rejects(promote(none.repo, 'staging'), /declares no environment/); + assert.deepEqual(refs(invalid.origin), [`refs/heads/main ${git(invalid.origin, 'rev-parse', 'main')}`]); +}); + +test('promote takes the one name and no other argument', async () => { + const { repo, origin } = fixture('arguments'); + const before = refs(origin); + await assert.rejects(promote(repo, 'staging', 'production'), /too many arguments/); + await assert.rejects(promote(repo, 'staging', '--force'), /unknown option '--force'/); + await assert.rejects(plx('-y', 'promote', '-C', repo), /missing required argument 'name'/); + assert.deepEqual(refs(origin), before); +}); + +test('promote changes nothing of the checkout: not its branch, head, branches or files, wherever it stands and however dirty', async () => { + const { repo, origin } = fixture('checkout'); + git(repo, 'checkout', '-q', '-b', 'topic'); + commit(repo, 'topic work'); + writeFileSync(join(repo, 'notes.txt'), 'edited, not committed\n'); + writeFileSync(join(repo, 'untracked.txt'), 'x\n'); + const before = snapshot(repo); + await promote(repo, 'staging'); + assert.deepEqual(snapshot(repo), before); + assert.equal(ref(origin, 'env/staging'), git(origin, 'rev-parse', 'main')); +}); + +test('promote asks before it pushes, and off a terminal without --yes it is an error that pushes nothing', async () => { + const { repo, origin } = fixture('asks'); + const before = refs(origin); + await assert.rejects(plx('promote', 'staging', '-C', repo), /cannot ask .* without a terminal; pass --yes/); + assert.deepEqual(refs(origin), before); +}); + +test('promote --dry-run prints what it would push and pushes nothing', async () => { + const { repo, origin } = fixture('dry'); + const before = refs(origin); + const { code, stderr } = await plx('--dry-run', 'promote', 'staging', '-C', repo); + assert.equal(code, 0); + assert.match(stderr, /\[dry-run\] \$ \(cd .*git push --no-verify origin [0-9a-f]{40}:refs\/heads\/env\/staging/); + assert.deepEqual(refs(origin), before); +}); + +test('promote --quiet narrates nothing and --json prints the result alone', async () => { + const { repo } = fixture('quiet'); + const { stdout, stderr } = await plx('-y', '-q', '--json', 'promote', 'staging', '-C', repo); + assert.equal(stderr, ''); + assert.equal(JSON.parse(stdout).outcome, 'created'); +}); diff --git a/packages/cli/src/testing/forge.ts b/packages/cli/src/testing/forge.ts new file mode 100644 index 00000000..3aa5cddf --- /dev/null +++ b/packages/cli/src/testing/forge.ts @@ -0,0 +1,125 @@ +// A scratch forge for the tests of `plx promote` and `plx release`: a bare repository as origin, a checkout of it +// whose root marker declares two environments, `plx` run through the program with its output captured, and a +// stand-in for `gh` on the PATH that records what it was asked and creates nothing. Not shipped (excluded in +// tsconfig). No git configuration of the machine is read: the identity given here is the only one. +import { execFileSync } from 'node:child_process'; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { after } from 'node:test'; +import { buildProgram } from '../program.ts'; + +process.env.GIT_CONFIG_GLOBAL = '/dev/null'; +process.env.GIT_CONFIG_NOSYSTEM = '1'; + +export const dir = realpathSync(mkdtempSync(join(tmpdir(), 'plx-forge-'))); +after(() => rmSync(dir, { recursive: true, force: true })); + +export const git = (repo: string, ...args: string[]): string => + execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@example.org', ...args], { cwd: repo, stdio: 'pipe' }) + .toString() + .trim(); + +/** The declaration of the checkout's root marker: `staging` from `main`, and `production` from `staging`. */ +export const MARKER = `--- +environments: + staging: + promotes_from: main + auto_promote: true + production: + promotes_from: staging +--- + +The repo. +`; + +/** Commit `file` with `text` in the checkout, on its current branch, as the one commit `subject`. */ +export function commit(repo: string, subject: string, file = 'notes.txt'): string { + writeFileSync(join(repo, file), `${subject}\n`); + git(repo, 'add', '-A'); + git(repo, 'commit', '-q', '-m', subject); + return git(repo, 'rev-parse', 'HEAD'); +} + +/** A bare origin and a checkout of it on `main` with one commit, which is pushed. */ +export function fixture(name: string, marker = MARKER): { repo: string; origin: string } { + const origin = join(dir, `${name}.git`); + execFileSync('git', ['init', '-q', '--bare', '-b', 'main', origin]); + const repo = join(dir, name); + mkdirSync(repo); + git(repo, 'init', '-q', '-b', 'main'); + writeFileSync(join(repo, 'PLEXUS.md'), marker); + git(repo, 'add', '-A'); + git(repo, 'commit', '-q', '-m', 'born'); + git(repo, 'remote', 'add', 'origin', origin); + git(repo, 'push', '-q', 'origin', 'main'); + return { repo, origin }; +} + +/** Every ref of the remote, as ` ` lines. */ +export const refs = (origin: string): string[] => + git(origin, 'for-each-ref', '--format=%(refname) %(objectname)').split('\n').filter(Boolean); + +/** What a checkout shows of itself: its branch, its head, its branches, its tags and its status. */ +export const snapshot = (repo: string): string[] => [ + git(repo, 'rev-parse', '--abbrev-ref', 'HEAD'), + git(repo, 'rev-parse', 'HEAD'), + git(repo, 'for-each-ref', '--format=%(refname) %(objectname)', 'refs/heads'), + git(repo, 'status', '--porcelain'), +]; + +const GH = `#!/bin/sh +printf '%s\\n' "$*" >> "$FAKE_GH_LOG" +case "$1 $2" in + "auth status") [ -z "$FAKE_GH_LOGGED_OUT" ] || { echo "not logged in" >&2; exit 1; } ;; + "release create") + [ -z "$FAKE_GH_REFUSE" ] || { echo "refused" >&2; exit 1; } + echo "https://example.com/acme/shop/releases/tag/$3" ;; +esac +`; + +const bin = join(dir, 'bin'); +mkdirSync(bin); +writeFileSync(join(bin, 'gh'), GH); +chmodSync(join(bin, 'gh'), 0o755); +const log = join(dir, 'gh.log'); +process.env.FAKE_GH_LOG = log; +process.env.PATH = `${bin}:${process.env.PATH}`; + +/** What the stand-in `gh` was asked since the last call to this, one line per call. */ +export function ghCalls(): string[] { + let text = ''; + try { + text = readFileSync(log, 'utf8'); + } catch {} + writeFileSync(log, ''); + return text.split('\n').filter(Boolean); +} + +/** Runs `plx` with `args`, returning what it printed and the exit code it asked for; a refusal rejects, as bin.ts catches it. */ +export async function plx(...args: string[]): Promise<{ stdout: string; stderr: string; code: number }> { + let stdout = ''; + const write = process.stdout.write; + process.stdout.write = ((chunk: string | Uint8Array, ...rest: unknown[]) => { + if (typeof chunk !== 'string') return (write as (...a: unknown[]) => boolean).call(process.stdout, chunk, ...rest); + stdout += chunk; + return true; + }) as typeof process.stdout.write; + let stderr = ''; + const err = process.stderr.write; + process.stderr.write = ((chunk: string | Uint8Array) => { + stderr += Buffer.from(chunk).toString(); + return true; + }) as typeof process.stderr.write; + process.exitCode = undefined; + try { + const program = buildProgram().exitOverride(); + for (const command of program.commands) command.exitOverride(); + await program.parseAsync(args, { from: 'user' }); + return { stdout, stderr, code: process.exitCode ?? 0 }; + } finally { + process.stdout.write = write; + process.stderr.write = err; + process.exitCode = undefined; + } +} diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.json index 442142ad..f7b3ce57 100644 --- a/packages/cli/tsconfig.json +++ b/packages/cli/tsconfig.json @@ -12,5 +12,5 @@ "erasableSyntaxOnly": true }, "include": ["src"], - "exclude": ["dist", "node_modules", "**/*.test.ts"] + "exclude": ["dist", "node_modules", "**/*.test.ts", "src/testing"] } From 226e51db8c9cd0671d59d20db4fa48e5d290a6ba Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:53:42 +0100 Subject: [PATCH 03/20] plx promote: fast-forward env/ on the remote to the head of its declared source Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/commands/index.ts | 2 + packages/cli/src/commands/promote.ts | 28 +++++++ packages/lib/src/index.ts | 1 + packages/lib/src/promote.ts | 110 +++++++++++++++++++++++++++ 4 files changed, 141 insertions(+) create mode 100644 packages/cli/src/commands/promote.ts create mode 100644 packages/lib/src/promote.ts diff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.ts index 4254ad51..77c790d5 100644 --- a/packages/cli/src/commands/index.ts +++ b/packages/cli/src/commands/index.ts @@ -14,6 +14,7 @@ import { register as deploy } from './deploy.ts'; import { register as doctor } from './doctor.ts'; import { register as newSite } from './new.ts'; import { register as overview } from './overview.ts'; +import { register as promote } from './promote.ts'; import { register as requirements } from './requirements.ts'; import { register as umbrella } from './umbrella.ts'; import { register as update } from './update.ts'; @@ -28,4 +29,5 @@ export const commands: ((program: Command) => void)[] = [ requirements, changeset, deploy, + promote, ]; diff --git a/packages/cli/src/commands/promote.ts b/packages/cli/src/commands/promote.ts new file mode 100644 index 00000000..aa3e2164 --- /dev/null +++ b/packages/cli/src/commands/promote.ts @@ -0,0 +1,28 @@ +// plx promote : fast-forward `env/` on the remote to the head of +// its declared source, `main` or another environment's branch, and create the +// branch when it does not exist (§ 6.8 Decisions). lib's `promote` does the +// work, and its header says how, in order; this file maps the arguments and +// prints the result. It takes no other argument and has no override. The +// checkout is read for its root marker alone and is never changed. +// +// plx promote staging +// plx -y promote production # without a terminal +// plx -n promote staging -C ../shop # print what would be pushed +import { resolve } from 'node:path'; +import { promote, renderPromoted } from '@plexus-ms/lib'; +import type { Command } from 'commander'; +import { contextOf } from '../program.ts'; + +export function register(program: Command): void { + program + .command('promote') + .description( + 'fast-forward env/ on the remote to where its declared source is, creating the branch when it does not exist', + ) + .argument('', 'a declared environment') + .option('-C, --dir ', 'the checkout to read the declaration from', '.') + .action(async (name: string, opts: { dir: string }, command: Command) => { + const ctx = contextOf(command); + ctx.result(await promote(ctx, resolve(opts.dir), name), renderPromoted); + }); +} diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index 7084a277..8141560c 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -161,6 +161,7 @@ export { } from './need.ts'; export { type Created, type NewOptions, newSite } from './newSite.ts'; export { overview, PRUNED, type ScanOptions } from './overview.ts'; +export { type Promoted, promote, renderPromoted } from './promote.ts'; export { askForReviews, needsAHand, diff --git a/packages/lib/src/promote.ts b/packages/lib/src/promote.ts new file mode 100644 index 00000000..f78f5440 --- /dev/null +++ b/packages/lib/src/promote.ts @@ -0,0 +1,110 @@ +// promote: move `env/` on the remote to where its declared source is +// (§ 6.8 Decisions; § 3 PLX-Delivery). The environments, their branches and +// their sources are the declaration's (declaredEnvironments.ts); nothing here +// spells a branch or knows a name. +// +// In order: +// 1. read the declaration of the checkout's root marker, and refuse one that +// is invalid or empty, and a name it does not declare +// 2. fetch `origin` (its branches, pruned), which is the one change to the +// checkout, and to its remote-tracking refs alone, also under --dry-run +// 3. find the head of the source on the remote: `origin/main`, or +// `origin/env/`, which must exist already (promote that one first) +// 4. find the head of `env/` on the remote, if it exists; refuse where +// it is no ancestor of the source's head (no fast-forward), and stop where +// it is the source's head already +// 5. say what will be pushed, ask, and push that commit to +// `refs/heads/env/` of origin, with no force and past the hooks +// +// The checkout's files, its branches and its checked-out branch are neither +// read nor changed, whichever branch it stands on and however dirty it is; +// only its root marker is read, as it is. The commit to push is named by its +// hash, so no local branch is made. The remote's own refusal of a push that +// is no fast-forward stands behind step 4, should the branch have moved in +// between. An `env/` branch takes no commit of its own and has no +// override (§ 6.3 Decisions): nothing here forces anything. +import type { Context } from './context.ts'; +import { declarationRefusal, readDeclaredEnvironments } from './declaredEnvironments.ts'; +import { run } from './effects.ts'; +import { UsageError } from './version.ts'; + +/** What a promotion did, or would do under --dry-run. */ +export interface Promoted { + environment: string; + /** `env/`. */ + branch: string; + /** The branch it promotes from. */ + source: string; + /** Where the branch was on the remote: null where it did not exist. */ + from: string | null; + /** Where it is now: the head of the source. */ + to: string; + /** The commits the move adds to the branch. */ + commits: number; + outcome: 'created' | 'fast-forwarded' | 'unchanged'; +} + +const REMOTE = 'origin'; + +/** The commit a remote branch is at in the checkout's remote-tracking refs, or null where there is none. */ +async function remoteHead(ctx: Context, dir: string, branch: string): Promise { + return ctx + .read('git', ['rev-parse', '-q', '--verify', `refs/remotes/${REMOTE}/${branch}^{commit}`], { cwd: dir }) + .then((out) => out.trim()) + .catch(() => null); +} + +/** Move `env/` of the checkout at `dir` on the remote to the head of its source. */ +export async function promote(ctx: Context, dir: string, name: string): Promise { + const declared = await readDeclaredEnvironments(ctx, dir); + const refusal = declarationRefusal(declared); + if (refusal) throw new Error(refusal); + const environment = declared.environments.find((e) => e.name === name); + if (!environment) + throw new UsageError( + `${name} is no declared environment; the repo declares ${declared.environments.map((e) => e.name).join(', ')}`, + ); + const { branch, source } = environment; + + await ctx.stage(run('git', ['fetch', '--quiet', '--prune', REMOTE], { cwd: dir })); + const to = await remoteHead(ctx, dir, source); + if (to === null) + throw new Error( + environment.promotesFrom === source + ? `${REMOTE}/${source} not found: push the repo's default branch first` + : `${source}, the source of ${branch}, is not on the remote yet; promote ${environment.promotesFrom} first`, + ); + const from = await remoteHead(ctx, dir, branch); + const count = async (range: string) => + Number((await ctx.read('git', ['rev-list', '--count', range], { cwd: dir })).trim()); + if (from === to) return { environment: name, branch, source, from, to, commits: 0, outcome: 'unchanged' }; + if (from !== null && (await count(`${to}..${from}`)) > 0) + throw new Error( + `${branch} is not an ancestor of ${source} on the remote, so moving it is no fast-forward: it holds commits ${source} does not; an \`env/\` branch only ever fast-forwards, so look at them with git before anything else`, + ); + const commits = await count(from === null ? to : `${from}..${to}`); + const result: Promoted = { + environment: name, + branch, + source, + from, + to, + commits, + outcome: from === null ? 'created' : 'fast-forwarded', + }; + + ctx.say( + `${from === null ? `create ${branch} on ${REMOTE}` : `move ${branch} on ${REMOTE} from ${from.slice(0, 7)}`} at ${to.slice(0, 7)}, the head of ${source}: ${commits} ${commits === 1 ? 'commit' : 'commits'}`, + ); + if (!(await ctx.confirm(`push ${branch}?`))) throw new Error('aborted; nothing was pushed'); + await ctx.apply([run('git', ['push', '--no-verify', REMOTE, `${to}:refs/heads/${branch}`], { cwd: dir })]); + return result; +} + +/** The result line of a promotion. */ +export function renderPromoted(p: Promoted): string { + const at = p.to.slice(0, 7); + if (p.outcome === 'unchanged') return `✓ ${p.branch} is at ${p.source} already (${at})`; + const verb = p.outcome === 'created' ? 'created' : 'moved to'; + return `✓ ${p.branch} ${verb} ${at}, the head of ${p.source} (${p.commits} ${p.commits === 1 ? 'commit' : 'commits'})`; +} From 720b057cfc77d125ff7b314a90b7f6a49a67b093 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:54:47 +0100 Subject: [PATCH 04/20] Test: plx release against local bare repositories and a stand-in for gh Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/commands/promote.test.ts | 12 ++ packages/cli/src/commands/release.test.ts | 249 ++++++++++++++++++++++ packages/cli/src/testing/forge.ts | 22 +- 3 files changed, 279 insertions(+), 4 deletions(-) create mode 100644 packages/cli/src/commands/release.test.ts diff --git a/packages/cli/src/commands/promote.test.ts b/packages/cli/src/commands/promote.test.ts index 7c7b261d..e6360182 100644 --- a/packages/cli/src/commands/promote.test.ts +++ b/packages/cli/src/commands/promote.test.ts @@ -2,6 +2,8 @@ import assert from 'node:assert/strict'; import { writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { test } from 'node:test'; +import * as lib from '@plexus-ms/lib'; +import { Context, realIo } from '@plexus-ms/lib'; import { commit, dir, fixture, git, plx, refs, snapshot } from '../testing/forge.ts'; const ref = (origin: string, branch: string) => git(origin, 'rev-parse', '-q', '--verify', `refs/heads/${branch}`); @@ -157,3 +159,13 @@ test('promote --quiet narrates nothing and --json prints the result alone', asyn assert.equal(stderr, ''); assert.equal(JSON.parse(stdout).outcome, 'created'); }); + +test('promote pushes nothing when the answer to the question is no, and asks it once, naming the branch', async () => { + const { repo, origin } = fixture('declined'); + const asked: string[] = []; + const ctx = new Context({ quiet: true }, { ...realIo(), prompt: async (question) => (asked.push(question), false) }); + const before = refs(origin); + await assert.rejects(lib.promote(ctx, repo, 'staging'), /aborted; nothing was pushed/); + assert.deepEqual(asked, ['push env/staging?']); + assert.deepEqual(refs(origin), before); +}); diff --git a/packages/cli/src/commands/release.test.ts b/packages/cli/src/commands/release.test.ts new file mode 100644 index 00000000..f3e07a09 --- /dev/null +++ b/packages/cli/src/commands/release.test.ts @@ -0,0 +1,249 @@ +import assert from 'node:assert/strict'; +import { writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { test } from 'node:test'; +import * as lib from '@plexus-ms/lib'; +import { commit, dir, fixture, ghCalls, git, plx, refs, snapshot, tag, tags } from '../testing/forge.ts'; + +const release = (repo: string, ...args: string[]) => plx('-y', '--json', 'release', ...args, '-C', repo); +const names = (origin: string) => tags(origin).map((t) => t.split(' ')[0]); + +/** A repo whose main holds the commits `subjects`, each pushed, the first one tagged `version`. */ +function released(name: string, version: string, ...subjects: string[]) { + const f = fixture(name); + tag(f.repo, version); + for (const subject of subjects) commit(f.repo, subject); + git(f.repo, 'push', '-q', 'origin', 'main'); + ghCalls(); + return f; +} + +test('release of a repo without tags is 0.1.0: it tags origin/main, pushes the tag and creates the release', async () => { + const { repo, origin } = fixture('first'); + const head = git(origin, 'rev-parse', 'main'); + const { code, stdout } = await release(repo); + assert.equal(code, 0); + assert.deepEqual(tags(origin), [`0.1.0 ${head}`]); + assert.deepEqual(JSON.parse(stdout), { + version: '0.1.0', + previous: null, + commit: head, + commits: 1, + url: 'https://example.com/acme/shop/releases/tag/0.1.0', + }); + const calls = ghCalls(); + assert.deepEqual(calls[0], ['auth', 'status']); + assert.deepEqual(calls[1]?.slice(0, 5), ['release', 'create', '0.1.0', '--verify-tag', '--title']); + assert.equal(calls.length, 2); +}); + +test('the first release is 0.1.0 whichever step is given', async () => { + for (const step of ['major', 'minor', 'patch']) { + const { repo, origin } = fixture(`first-${step}`); + await release(repo, step); + assert.deepEqual(names(origin), ['0.1.0'], step); + } +}); + +test('release bumps the version of origin/main by the step, minor by default', async () => { + for (const [step, next] of [ + [undefined, '1.3.0'], + ['patch', '1.2.4'], + ['minor', '1.3.0'], + ['major', '2.0.0'], + ] as const) { + const { repo, origin } = released(`step-${step}`, '1.2.3', 'a change'); + const head = git(origin, 'rev-parse', 'main'); + const { stdout } = await release(repo, ...(step ? [step] : [])); + assert.deepEqual( + tags(origin).filter((t) => t.startsWith(next)), + [`${next} ${head}`], + `${step}`, + ); + assert.equal(JSON.parse(stdout).previous, '1.2.3'); + } +}); + +test('release counts the plain tags only: changeset tags and tags of other forms are ignored', async () => { + const { repo, origin } = released('changesets', '1.2.3', 'a change'); + tag(repo, '@acme/lib@9.9.9'); + tag(repo, 'v7.0.0'); + tag(repo, '1.2.3-rc.1'); + await release(repo, 'patch'); + assert.ok(names(origin).includes('1.2.4'), names(origin).join()); +}); + +test('release goes by the highest version reachable from origin/main, not by the newest tag', async () => { + const { repo, origin } = released('reachable', '1.2.3', 'a change'); + // 3.0.0 is on a side branch that main does not hold. + git(repo, 'checkout', '-q', '-b', 'side'); + commit(repo, 'on the side'); + tag(repo, '3.0.0'); + git(repo, 'checkout', '-q', 'main'); + await release(repo); + assert.ok(names(origin).includes('1.3.0')); +}); + +test('the release lists the subjects since the previous tag, oldest first, each a code span', async () => { + const { repo } = released('notes', '1.0.0', 'fix: the first', 'feat: use `@acme/ui` #12'); + await release(repo); + const [, create] = ghCalls(); + const notes = create?.[create.indexOf('--notes') + 1] ?? ''; + assert.match(notes, /the commits since 1\.0\.0/); + assert.deepEqual( + notes.split('\n').filter((l) => l.startsWith('- ')), + ['- `fix: the first`', '- ``feat: use `@acme/ui` #12``'], + ); + assert.deepEqual(create?.slice(0, 5), ['release', 'create', '1.1.0', '--verify-tag', '--title']); + assert.ok(!create?.some((a) => /immutable|draft|prerelease/.test(a)), 'a normal release'); +}); + +test('release refuses where nothing is new since the last tag, and pushes and creates nothing', async () => { + const { repo, origin } = released('nothing', '1.0.0'); + const before = [refs(origin), tags(origin)]; + await assert.rejects(release(repo), /nothing to release: origin\/main is at 1\.0\.0 already/); + assert.deepEqual([refs(origin), tags(origin)], before); + assert.deepEqual( + ghCalls().filter((c) => c[1] === 'create'), + [], + ); +}); + +test('release refuses a version whose tag exists already, on a commit main does not hold', async () => { + const { repo, origin } = released('exists', '1.0.0', 'a change'); + git(repo, 'checkout', '-q', '-b', 'side'); + commit(repo, 'on the side'); + tag(repo, '1.1.0'); + git(repo, 'checkout', '-q', 'main'); + const before = tags(origin); + await assert.rejects(release(repo), /1\.1\.0 exists already/); + assert.deepEqual(tags(origin), before); +}); + +test('release works from origin/main, not from the checkout: behind it, on another branch, dirty, with a main of its own', async () => { + const { repo, origin } = released('behind', '1.0.0', 'on the remote'); + // The checkout is one commit behind, on a topic branch with work and an unpushed local main. + git(repo, 'checkout', '-q', '-b', 'topic', 'HEAD~1'); + commit(repo, 'topic work'); + writeFileSync(join(repo, 'notes.txt'), 'dirty\n'); + const head = git(origin, 'rev-parse', 'main'); + const before = snapshot(repo); + await release(repo); + assert.deepEqual( + tags(origin).filter((t) => t.startsWith('1.1.0')), + [`1.1.0 ${head}`], + ); + assert.deepEqual(snapshot(repo), before); +}); + +test('release sees a tag that is on the remote and not yet in the checkout', async () => { + const { origin } = released('unfetched', '1.0.0', 'a change'); + const other = join(dir, 'unfetched-other'); + git(dir, 'clone', '-q', origin, other); + git(other, 'checkout', '-q', '--detach', 'main'); + // Remove the tags the clone got, as a checkout that never fetched them. + for (const t of git(other, 'tag', '--list').split('\n').filter(Boolean)) git(other, 'tag', '-d', t); + await release(other); + assert.ok(names(origin).includes('1.1.0')); +}); + +test('release moves no branch, touches no file, and makes no tag of its own in the checkout', async () => { + const { repo, origin } = released('inert', '1.0.0', 'a change'); + const before = [snapshot(repo), refs(origin)]; + await release(repo); + assert.deepEqual(snapshot(repo), before[0]); + assert.deepEqual( + refs(origin).filter((r) => r.startsWith('refs/heads')), + before[1], + ); + assert.ok(!git(repo, 'tag', '--list').split('\n').includes('1.1.0')); +}); + +test('release refuses a step that is none of major, minor and patch, and any other argument', async () => { + const { repo, origin } = released('steps', '1.0.0', 'a change'); + const before = tags(origin); + await assert.rejects(release(repo, 'huge'), /argument 'huge' is invalid/); + await assert.rejects(release(repo, 'patch', 'minor'), /too many arguments/); + assert.deepEqual(tags(origin), before); +}); + +test('release asks before it pushes: off a terminal without --yes it is an error that pushes nothing', async () => { + const { repo, origin } = released('asks', '1.0.0', 'a change'); + const before = tags(origin); + await assert.rejects(plx('release', '-C', repo), /cannot ask .* without a terminal; pass --yes/); + assert.deepEqual(tags(origin), before); + assert.deepEqual( + ghCalls().filter((c) => c[1] === 'create'), + [], + ); +}); + +test('release --dry-run says what it would do and does none of it', async () => { + const { repo, origin } = released('dry', '1.0.0', 'a change'); + const before = tags(origin); + const { code, stderr } = await plx('--dry-run', 'release', '-C', repo); + assert.equal(code, 0); + assert.match(stderr, /\[dry-run\] \$ \(cd .*git push --no-verify origin [0-9a-f]{40}:refs\/tags\/1\.1\.0/); + assert.match(stderr, /\[dry-run\] \$ \(cd .*gh release create 1\.1\.0 --verify-tag/); + assert.deepEqual(tags(origin), before); + assert.deepEqual( + ghCalls().filter((c) => c[1] === 'create'), + [], + ); +}); + +test('release is refused before it pushes where gh is not logged in', async () => { + const { repo, origin } = released('logged-out', '1.0.0', 'a change'); + const before = tags(origin); + process.env.FAKE_GH_LOGGED_OUT = '1'; + try { + await assert.rejects(release(repo), /gh is not logged in/); + } finally { + delete process.env.FAKE_GH_LOGGED_OUT; + } + assert.deepEqual(tags(origin), before); +}); + +test('a release that gh refuses leaves the pushed tag and names the command that finishes it', async () => { + const { repo, origin } = released('refused', '1.0.0', 'a change'); + process.env.FAKE_GH_REFUSE = '1'; + try { + await assert.rejects(release(repo), /tag 1\.1\.0 is pushed.*gh release create 1\.1\.0 --verify-tag/s); + } finally { + delete process.env.FAKE_GH_REFUSE; + } + assert.ok(names(origin).includes('1.1.0')); +}); + +test('release refuses a shallow clone, which cannot see the tags', async () => { + const { origin } = released('shallow', '1.0.0', 'a change'); + const clone = join(dir, 'shallow-clone'); + git(dir, 'clone', '-q', '--depth', '1', `file://${origin}`, clone); + const before = tags(origin); + await assert.rejects(release(clone), /shallow clone/); + assert.deepEqual(tags(origin), before); +}); + +test('release --quiet narrates nothing, and --json prints the result alone', async () => { + const { repo } = released('quiet', '1.0.0', 'a change'); + const { stdout, stderr } = await plx('-y', '-q', '--json', 'release', '-C', repo); + assert.equal(stderr, ''); + assert.equal(JSON.parse(stdout).version, '1.1.0'); +}); + +test('release pushes and creates nothing when the answer to the question is no, and asks it once, naming the version', async () => { + const { repo, origin } = released('declined', '1.0.0', 'a change'); + const asked: string[] = []; + const ctx = new lib.Context( + { quiet: true }, + { ...lib.realIo(), prompt: async (question) => (asked.push(question), false) }, + ); + const before = tags(origin); + await assert.rejects(lib.release(ctx, repo, 'minor'), /aborted; nothing was pushed/); + assert.deepEqual(asked, ['tag origin/main as 1.1.0, push the tag and create its release?']); + assert.deepEqual(tags(origin), before); + assert.deepEqual( + ghCalls().filter((c) => c[1] === 'create'), + [], + ); +}); diff --git a/packages/cli/src/testing/forge.ts b/packages/cli/src/testing/forge.ts index 3aa5cddf..340323d7 100644 --- a/packages/cli/src/testing/forge.ts +++ b/packages/cli/src/testing/forge.ts @@ -69,7 +69,8 @@ export const snapshot = (repo: string): string[] => [ ]; const GH = `#!/bin/sh -printf '%s\\n' "$*" >> "$FAKE_GH_LOG" +for a in "$@"; do printf '%s\\037' "$a" >> "$FAKE_GH_LOG"; done +printf '\\036' >> "$FAKE_GH_LOG" case "$1 $2" in "auth status") [ -z "$FAKE_GH_LOGGED_OUT" ] || { echo "not logged in" >&2; exit 1; } ;; "release create") @@ -86,14 +87,17 @@ const log = join(dir, 'gh.log'); process.env.FAKE_GH_LOG = log; process.env.PATH = `${bin}:${process.env.PATH}`; -/** What the stand-in `gh` was asked since the last call to this, one line per call. */ -export function ghCalls(): string[] { +/** What the stand-in `gh` was asked since the last call to this: the arguments of each call. */ +export function ghCalls(): string[][] { let text = ''; try { text = readFileSync(log, 'utf8'); } catch {} writeFileSync(log, ''); - return text.split('\n').filter(Boolean); + return text + .split('\x1e') + .filter(Boolean) + .map((call) => call.split('\x1f').slice(0, -1)); } /** Runs `plx` with `args`, returning what it printed and the exit code it asked for; a refusal rejects, as bin.ts catches it. */ @@ -123,3 +127,13 @@ export async function plx(...args: string[]): Promise<{ stdout: string; stderr: process.exitCode = undefined; } } + +/** The tags of the remote, as ` ` lines. */ +export const tags = (origin: string): string[] => + git(origin, 'for-each-ref', '--format=%(refname:short) %(objectname)', 'refs/tags').split('\n').filter(Boolean); + +/** Tag `ref` (the checkout's HEAD by default) in the checkout, lightweight, and push the tag. */ +export function tag(repo: string, name: string, ref = 'HEAD'): void { + git(repo, 'tag', name, ref); + git(repo, 'push', '-q', 'origin', `refs/tags/${name}`); +} From e5caf2166fa0649f44311518976abb6b98df2a43 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:56:18 +0100 Subject: [PATCH 05/20] plx release: tag origin/main with the next version and create its release Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/commands/index.ts | 2 + packages/cli/src/commands/release.test.ts | 6 +- packages/cli/src/commands/release.ts | 28 +++++ packages/lib/src/index.ts | 7 ++ packages/lib/src/release.ts | 127 ++++++++++++++++++++++ 5 files changed, 167 insertions(+), 3 deletions(-) create mode 100644 packages/cli/src/commands/release.ts create mode 100644 packages/lib/src/release.ts diff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.ts index 77c790d5..6206ea12 100644 --- a/packages/cli/src/commands/index.ts +++ b/packages/cli/src/commands/index.ts @@ -15,6 +15,7 @@ import { register as doctor } from './doctor.ts'; import { register as newSite } from './new.ts'; import { register as overview } from './overview.ts'; import { register as promote } from './promote.ts'; +import { register as release } from './release.ts'; import { register as requirements } from './requirements.ts'; import { register as umbrella } from './umbrella.ts'; import { register as update } from './update.ts'; @@ -30,4 +31,5 @@ export const commands: ((program: Command) => void)[] = [ changeset, deploy, promote, + release, ]; diff --git a/packages/cli/src/commands/release.test.ts b/packages/cli/src/commands/release.test.ts index f3e07a09..ba700c87 100644 --- a/packages/cli/src/commands/release.test.ts +++ b/packages/cli/src/commands/release.test.ts @@ -89,7 +89,7 @@ test('the release lists the subjects since the previous tag, oldest first, each await release(repo); const [, create] = ghCalls(); const notes = create?.[create.indexOf('--notes') + 1] ?? ''; - assert.match(notes, /the commits since 1\.0\.0/); + assert.match(notes, /commits since 1\.0\.0/); assert.deepEqual( notes.split('\n').filter((l) => l.startsWith('- ')), ['- `fix: the first`', '- ``feat: use `@acme/ui` #12``'], @@ -149,7 +149,7 @@ test('release sees a tag that is on the remote and not yet in the checkout', asy test('release moves no branch, touches no file, and makes no tag of its own in the checkout', async () => { const { repo, origin } = released('inert', '1.0.0', 'a change'); - const before = [snapshot(repo), refs(origin)]; + const before = [snapshot(repo), refs(origin).filter((r) => r.startsWith('refs/heads'))]; await release(repo); assert.deepEqual(snapshot(repo), before[0]); assert.deepEqual( @@ -162,7 +162,7 @@ test('release moves no branch, touches no file, and makes no tag of its own in t test('release refuses a step that is none of major, minor and patch, and any other argument', async () => { const { repo, origin } = released('steps', '1.0.0', 'a change'); const before = tags(origin); - await assert.rejects(release(repo, 'huge'), /argument 'huge' is invalid/); + await assert.rejects(release(repo, 'huge'), /'huge' is invalid for argument 'step'/); await assert.rejects(release(repo, 'patch', 'minor'), /too many arguments/); assert.deepEqual(tags(origin), before); }); diff --git a/packages/cli/src/commands/release.ts b/packages/cli/src/commands/release.ts new file mode 100644 index 00000000..5508b236 --- /dev/null +++ b/packages/cli/src/commands/release.ts @@ -0,0 +1,28 @@ +// plx release [major|minor|patch]: tag `origin/main` with the repo's next +// version, push the tag and create a GitHub release that lists the commit +// subjects since the previous tag (§ 7.9 Decisions). lib's `release` does the +// work, and its header says how, in order; this file maps the arguments and +// prints the result. `minor` where no step is given. It moves no branch and +// deploys nothing: the order is release, then `plx promote`. +// +// plx release # the next minor +// plx release patch -C ../shop +// plx -y --json release major # without a terminal +import { resolve } from 'node:path'; +import { RELEASE_STEPS, type ReleaseStep, release, renderReleased } from '@plexus-ms/lib'; +import { Argument, type Command } from 'commander'; +import { contextOf } from '../program.ts'; + +export function register(program: Command): void { + program + .command('release') + .description( + 'tag origin/main with the next version, push the tag and create a GitHub release listing the commits since the last', + ) + .addArgument(new Argument('[step]', 'how far the version moves').choices(RELEASE_STEPS).default('minor')) + .option('-C, --dir ', 'the checkout of the repo', '.') + .action(async (step: ReleaseStep, opts: { dir: string }, command: Command) => { + const ctx = contextOf(command); + ctx.result(await release(ctx, resolve(opts.dir), step), renderReleased); + }); +} diff --git a/packages/lib/src/index.ts b/packages/lib/src/index.ts index 8141560c..470bde1c 100644 --- a/packages/lib/src/index.ts +++ b/packages/lib/src/index.ts @@ -184,6 +184,13 @@ export { versionBranch, } from './pull.ts'; export { type RecursiveOptions, updateRecursive } from './recursive.ts'; +export { + RELEASE_STEPS, + type Released, + type ReleaseStep, + release, + renderReleased, +} from './release.ts'; export { type CompendiumCheck, checkCommitMessage, diff --git a/packages/lib/src/release.ts b/packages/lib/src/release.ts new file mode 100644 index 00000000..cd6c8316 --- /dev/null +++ b/packages/lib/src/release.ts @@ -0,0 +1,127 @@ +// release: tag `origin/main` with the next version of the repo and create a +// GitHub release of it (§ 7.9 Decisions; § 3 PLX-Delivery). The version of a +// commit is the highest plain semver tag reachable from it (commitVersion.ts); +// no file of the repo holds one. +// +// In order: +// 1. check that `gh` is logged in, before anything else +// 2. fetch `origin` with its tags, which changes the checkout's +// remote-tracking refs and adds the remote's tags to it, also under +// --dry-run: the version is only as true as the tags the checkout has +// 3. find the head of `origin/main` and its version (0.0.0 where there is +// no tag), and refuse where `origin/main` holds no commit since that tag: +// a release lists the commits since the previous one and would be empty +// 4. compute the next version, a step of that version (`minor` by default; +// the first release of a repo without tags is 0.1.0 whichever the step), +// and refuse where its tag exists already +// 5. say what will be done, ask, and push the head of `origin/main` to +// `refs/tags/` of origin, past the hooks +// 6. create the release with `gh release create --verify-tag`: a +// normal release (not a draft, no immutability asked for) whose notes +// list the subjects of the commits since the previous tag, each a code +// span; where gh fails, the tag stays and the error names the command +// that finishes the release +// +// It moves no branch and touches no file, wherever the checkout stands and +// however dirty it is: only `origin/main` is read, never the checked-out +// branch, and no tag is made in the checkout, the push naming the commit. +// Deploying is no part of it: the order is release, then promote. + +import { codeSpan } from './codeSpan.ts'; +import { commitVersion } from './commitVersion.ts'; +import type { Context } from './context.ts'; +import { DEFAULT_BRANCH } from './declaredEnvironments.ts'; +import { run } from './effects.ts'; +import { preflightForge } from './version.ts'; + +/** How far the version moves. */ +export const RELEASE_STEPS = ['major', 'minor', 'patch'] as const; +export type ReleaseStep = (typeof RELEASE_STEPS)[number]; + +/** The first version of a repo without one, whichever the step. */ +const FIRST = '0.1.0'; +const NONE = '0.0.0'; +const REMOTE = 'origin'; + +/** What a release did, or would do under --dry-run. */ +export interface Released { + version: string; + /** The version of `origin/main` before: null where there was none. */ + previous: string | null; + /** The commit tagged. */ + commit: string; + /** The commits since the previous version. */ + commits: number; + /** The release's page, as gh printed it: null where none was created. */ + url: string | null; +} + +/** The version after `version` by `step`, for numbers of any length. */ +export function nextVersion(version: string, step: ReleaseStep): string { + if (version === NONE) return FIRST; + const [major = 0n, minor = 0n, patch = 0n] = version.split('.').map((p) => BigInt(p)); + switch (step) { + case 'major': + return `${major + 1n}.0.0`; + case 'minor': + return `${major}.${minor + 1n}.0`; + case 'patch': + return `${major}.${minor}.${patch + 1n}`; + } +} + +/** The release notes: the subjects since the previous version, each a code span. */ +export const releaseNotes = (previous: string | null, subjects: string[]): string => + [ + previous === null ? 'The commits of the first release.' : `The commits since ${previous}.`, + '', + ...subjects.map((s) => `- ${codeSpan(s)}`), + ].join('\n'); + +/** Release `origin/main` of the checkout at `dir` by `step`. */ +export async function release(ctx: Context, dir: string, step: ReleaseStep): Promise { + const main = `${REMOTE}/${DEFAULT_BRANCH}`; + await preflightForge(ctx); + await ctx.stage(run('git', ['fetch', '--quiet', '--tags', REMOTE], { cwd: dir })); + const read = (args: string[]) => ctx.read('git', args, { cwd: dir }).then((out) => out.trim()); + const commit = await read(['rev-parse', '-q', '--verify', `refs/remotes/${main}^{commit}`]).catch(() => { + throw new Error(`${main} not found: push the repo's default branch first`); + }); + const last = await commitVersion(ctx, dir, main); + const previous = last === NONE ? null : last; + const since = previous === null ? commit : `refs/tags/${previous}..${commit}`; + const commits = Number(await read(['rev-list', '--count', since])); + if (previous !== null && commits === 0) + throw new Error(`nothing to release: ${main} is at ${previous} already, with no commit since`); + const version = nextVersion(last, step); + const held = await read(['rev-parse', '-q', '--verify', `refs/tags/${version}^{commit}`]).catch(() => null); + if (held !== null) + throw new Error( + `${version} exists already, at ${held.slice(0, 7)}, a commit ${main} does not hold: ${step} would reuse it; move or delete that tag, or take a larger step`, + ); + const subjects = (await read(['log', '--reverse', '--format=%s', since])).split('\n').filter(Boolean); + const notes = releaseNotes(previous, subjects); + + ctx.say( + `tag ${main} (${commit.slice(0, 7)}) as ${version}${previous === null ? ', the first version' : `, ${step} of ${previous}`}: ${commits} ${commits === 1 ? 'commit' : 'commits'}`, + ); + for (const subject of subjects) ctx.say(` ${subject}`); + if (!(await ctx.confirm(`tag ${main} as ${version}, push the tag and create its release?`))) + throw new Error('aborted; nothing was pushed'); + await ctx.apply([run('git', ['push', '--no-verify', REMOTE, `${commit}:refs/tags/${version}`], { cwd: dir })]); + const create = run('gh', ['release', 'create', version, '--verify-tag', '--title', version, '--notes', notes], { + cwd: dir, + }); + const url = await ctx.effect(create).catch((error: unknown) => { + throw new Error( + `the tag ${version} is pushed and its release is not (${error instanceof Error ? error.message : String(error)}): create it with \`gh release create ${version} --verify-tag --title ${version}\` and the notes of the commits since ${previous ?? 'the start'}`, + ); + }); + return { version, previous, commit, commits, url: url?.trim() || null }; +} + +/** The result line of a release. */ +export function renderReleased(r: Released): string { + const n = `${r.commits} ${r.commits === 1 ? 'commit' : 'commits'}`; + return `✓ ${r.version} tagged on ${r.commit.slice(0, 7)} (${n}${r.previous === null ? '' : ` since ${r.previous}`})${r.url === null ? '' : `: ${r.url}`}`; +} From 227af7bf6c8784ff3b80099b597f046e72817a2b Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:56:53 +0100 Subject: [PATCH 06/20] Test: a repo renders no promote or release task Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/repoTurbo.test.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/packages/lib/src/repoTurbo.test.ts b/packages/lib/src/repoTurbo.test.ts index 8ac4a5d3..f4d6a0e9 100644 --- a/packages/lib/src/repoTurbo.test.ts +++ b/packages/lib/src/repoTurbo.test.ts @@ -239,6 +239,15 @@ test('a repo has the six verbs as root tasks, each taking an optional name, and } }); +test('a repo renders no task for deploy, promote or release: they are commands of plx', async () => { + for (const answers of SHAPES) { + const mise = textOf(await render(answers), 'mise.toml'); + for (const task of ['deploy', 'promote', 'release']) + assert.ok(!tasksOf(mise).includes(task), `${task} ${JSON.stringify(answers)}`); + assert.doesNotMatch(mise, /git push origin/); + } +}); + test('no rendered file mentions verify', async () => { for (const answers of SHAPES) { const result = await render(answers); From 8dc43c703267d0604a4080d66589dd356997bdd4 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 05:57:18 +0100 Subject: [PATCH 07/20] The repo-turbo template renders no promote task: plx promote and plx release are commands Co-Authored-By: Claude Sonnet 5.5 --- templates/repo-turbo/files/mise.toml.jinja | 6 ------ 1 file changed, 6 deletions(-) diff --git a/templates/repo-turbo/files/mise.toml.jinja b/templates/repo-turbo/files/mise.toml.jinja index 5d554210..0837b858 100644 --- a/templates/repo-turbo/files/mise.toml.jinja +++ b/templates/repo-turbo/files/mise.toml.jinja @@ -67,12 +67,6 @@ PLX_PLATFORM = "{% raw %}{{ os() }}-{{ arch() }}{% endraw %}" PLX_POSTGRES_MAJOR = "{{ postgres.split('.')[0] }}" {%- endif %} -{% if not publishes_packages -%} -[tasks.promote] -description = "Promote staging to prod: fast-forward main to what is on develop (§ 3 PLX-Delivery); refused unless it is a fast-forward" -run = 'git fetch -q origin && git push origin origin/develop:refs/heads/main' - -{% endif -%} [tasks.dev] {%- if publishes_packages %} description = "No-op: a package repo has no development environment to start; build builds its packages and test exercises them" From e29973d9a325fe9a7178714c2768df9851f48b76 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:00:35 +0100 Subject: [PATCH 08/20] The narration of a promotion names where the branch moves from and to; a refused release names gh's own reason Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/promote.ts | 5 ++++- packages/lib/src/release.ts | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/lib/src/promote.ts b/packages/lib/src/promote.ts index f78f5440..8dfa74b2 100644 --- a/packages/lib/src/promote.ts +++ b/packages/lib/src/promote.ts @@ -93,8 +93,11 @@ export async function promote(ctx: Context, dir: string, name: string): Promise< outcome: from === null ? 'created' : 'fast-forwarded', }; + const n = `${commits} ${commits === 1 ? 'commit' : 'commits'}`; ctx.say( - `${from === null ? `create ${branch} on ${REMOTE}` : `move ${branch} on ${REMOTE} from ${from.slice(0, 7)}`} at ${to.slice(0, 7)}, the head of ${source}: ${commits} ${commits === 1 ? 'commit' : 'commits'}`, + from === null + ? `create ${branch} on ${REMOTE} at ${to.slice(0, 7)}, the head of ${source}: ${n}` + : `move ${branch} on ${REMOTE} from ${from.slice(0, 7)} to ${to.slice(0, 7)}, the head of ${source}: ${n}`, ); if (!(await ctx.confirm(`push ${branch}?`))) throw new Error('aborted; nothing was pushed'); await ctx.apply([run('git', ['push', '--no-verify', REMOTE, `${to}:refs/heads/${branch}`], { cwd: dir })]); diff --git a/packages/lib/src/release.ts b/packages/lib/src/release.ts index cd6c8316..dcb63fdf 100644 --- a/packages/lib/src/release.ts +++ b/packages/lib/src/release.ts @@ -32,6 +32,7 @@ import { commitVersion } from './commitVersion.ts'; import type { Context } from './context.ts'; import { DEFAULT_BRANCH } from './declaredEnvironments.ts'; import { run } from './effects.ts'; +import { detailOf } from './io.ts'; import { preflightForge } from './version.ts'; /** How far the version moves. */ @@ -114,7 +115,7 @@ export async function release(ctx: Context, dir: string, step: ReleaseStep): Pro }); const url = await ctx.effect(create).catch((error: unknown) => { throw new Error( - `the tag ${version} is pushed and its release is not (${error instanceof Error ? error.message : String(error)}): create it with \`gh release create ${version} --verify-tag --title ${version}\` and the notes of the commits since ${previous ?? 'the start'}`, + `the tag ${version} is pushed and its release is not (${detailOf(error)}): create it with \`gh release create ${version} --verify-tag --title ${version}\` and the notes of the commits since ${previous ?? 'the start'}`, ); }); return { version, previous, commit, commits, url: url?.trim() || null }; From a0880f14d5153a1c03c7dc4921076fbdf06e09da Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:06:28 +0100 Subject: [PATCH 09/20] The comparison with the earlier render of an app repo's mise.toml leaves out the task promote, which plx promote replaced Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/packageRepoPipeline.test.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/lib/src/packageRepoPipeline.test.ts b/packages/lib/src/packageRepoPipeline.test.ts index da22f032..30c6057a 100644 --- a/packages/lib/src/packageRepoPipeline.test.ts +++ b/packages/lib/src/packageRepoPipeline.test.ts @@ -308,11 +308,15 @@ test('no workflow of a package repo names plexus-ms/tooling or the Plexus versio }); /** - * A mise.toml without its task publish, which in an app repo makes every app's image since, and without the pin of - * crane, with which that step makes the image of a version since. + * A mise.toml without its task publish, which in an app repo makes every app's image since, without the pin of + * crane, with which that step makes the image of a version since, and without the task promote, which `plx promote` + * replaced. */ const withoutPublish = (text: string) => - text.replace(/^\[tasks\.publish\]\n[\s\S]*?(?=^\[)/m, '').replace(/^# What plx-ci image makes .*\ncrane = .*\n/m, ''); + text + .replace(/^\[tasks\.publish\]\n[\s\S]*?(?=^\[)/m, '') + .replace(/^\[tasks\.promote\]\n[\s\S]*?(?=^\[)/m, '') + .replace(/^# What plx-ci image makes .*\ncrane = .*\n/m, ''); /** An on_push.yml without the comment on its publish step's server-actions key, which says since why it is there. */ const uncommented = (text: string) => From cc0877e21efc0dfb1febc804376c164fe7874b4f Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:31:48 +0100 Subject: [PATCH 10/20] Test: a long release, the first release's notes, remote tags only, gh reaching the repo, narrow clones, subdirectories, git's own messages Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/commands/promote.test.ts | 108 ++++++++++++++++++++- packages/cli/src/commands/release.test.ts | 111 ++++++++++++++++++++-- packages/cli/src/testing/forge.ts | 11 +++ packages/lib/src/commitVersion.test.ts | 9 ++ 4 files changed, 228 insertions(+), 11 deletions(-) diff --git a/packages/cli/src/commands/promote.test.ts b/packages/cli/src/commands/promote.test.ts index e6360182..8e70db70 100644 --- a/packages/cli/src/commands/promote.test.ts +++ b/packages/cli/src/commands/promote.test.ts @@ -1,5 +1,5 @@ import assert from 'node:assert/strict'; -import { writeFileSync } from 'node:fs'; +import { mkdirSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { test } from 'node:test'; import * as lib from '@plexus-ms/lib'; @@ -163,9 +163,113 @@ test('promote --quiet narrates nothing and --json prints the result alone', asyn test('promote pushes nothing when the answer to the question is no, and asks it once, naming the branch', async () => { const { repo, origin } = fixture('declined'); const asked: string[] = []; - const ctx = new Context({ quiet: true }, { ...realIo(), prompt: async (question) => (asked.push(question), false) }); + const ctx = new Context( + { quiet: true }, + { + ...realIo(), + prompt: async (question) => { + asked.push(question); + return false; + }, + }, + ); const before = refs(origin); await assert.rejects(lib.promote(ctx, repo, 'staging'), /aborted; nothing was pushed/); assert.deepEqual(asked, ['push env/staging?']); assert.deepEqual(refs(origin), before); }); + +/** A clone of the fixture's origin as a workflow's checkout makes it: only `main`, and perhaps only the last commits. */ +function narrow(name: string, origin: string, ...options: string[]): string { + const clone = join(dir, name); + git(dir, 'clone', '-q', '--single-branch', '--branch', 'main', ...options, `file://${origin}`, clone); + return clone; +} + +/** A remote whose env/staging is `behind` commits behind main, and whose main holds `behind + 1` commits. */ +function behind(name: string, ahead: number) { + const f = fixture(name); + git(f.repo, 'push', '-q', 'origin', 'main:refs/heads/env/staging'); + for (let i = 0; i < ahead; i++) commit(f.repo, `next ${i}`); + git(f.repo, 'push', '-q', 'origin', 'main'); + return f; +} + +test('promote in a clone that fetched only main gives the answers of a full clone: it sees the branch that exists', async () => { + const { origin } = behind('single', 2); + const clone = narrow('single-clone', origin); + const staging = ref(origin, 'env/staging'); + const forwarded = JSON.parse((await promote(clone, 'staging')).stdout); + assert.equal(forwarded.outcome, 'fast-forwarded'); + assert.equal(forwarded.from, staging); + assert.equal(forwarded.commits, 2); + assert.equal(ref(origin, 'env/staging'), git(origin, 'rev-parse', 'main')); + const production = JSON.parse((await promote(clone, 'production')).stdout); + assert.equal(production.outcome, 'created', 'its source, env/staging, is on the remote'); + assert.equal(ref(origin, 'env/production'), ref(origin, 'env/staging')); + assert.equal(JSON.parse((await promote(clone, 'staging')).stdout).outcome, 'unchanged'); +}); + +test('promote in a clone that fetched only main refuses a move that is no fast-forward, as a full clone does', async () => { + const { origin } = behind('single-diverged', 1); + const other = join(dir, 'single-diverged-other'); + git(dir, 'clone', '-q', origin, other); + git(other, 'checkout', '-q', 'env/staging'); + commit(other, 'a hotfix on the branch'); + git(other, 'push', '-q', 'origin', 'env/staging'); + const before = refs(origin); + await assert.rejects(promote(narrow('single-diverged-clone', origin), 'staging'), /not an ancestor of main/); + assert.deepEqual(refs(origin), before); +}); + +test('promote in a shallow clone gives the answers of a full clone where the history it holds decides', async () => { + const { origin } = behind('shallow', 2); + const clone = narrow('shallow-clone', origin, '--depth', '5'); + const forwarded = JSON.parse((await promote(clone, 'staging')).stdout); + assert.equal(forwarded.outcome, 'fast-forwarded'); + assert.equal(forwarded.commits, 2); + assert.equal(ref(origin, 'env/staging'), git(origin, 'rev-parse', 'main')); + assert.equal(JSON.parse((await promote(clone, 'production')).stdout).outcome, 'created'); +}); + +test('promote in a shallow clone that cannot tell whether the move is a fast-forward says so and names the remedy', async () => { + const { origin } = behind('shallow-cut', 3); + const clone = narrow('shallow-cut-clone', origin, '--depth', '1'); + const before = refs(origin); + await assert.rejects(promote(clone, 'staging'), /shallow clone.*cannot tell.*git fetch --unshallow/s); + assert.deepEqual(refs(origin), before); +}); + +test('promote names what the move is in its narration: where the branch is, and where it goes', async () => { + const { repo, origin } = behind('narration', 1); + const from = ref(origin, 'env/staging').slice(0, 7); + const to = git(origin, 'rev-parse', 'main').slice(0, 7); + const moved = await plx('-y', 'promote', 'staging', '-C', repo); + assert.match( + moved.stderr, + new RegExp(`move env/staging on origin from ${from} to ${to}, the head of main: 1 commit`), + ); + const created = await plx('-y', 'promote', 'production', '-C', repo); + assert.match(created.stderr, new RegExp(`create env/production on origin at ${to}, the head of env/staging`)); +}); + +test('promote in a subdirectory of the repo reads the repo’s root marker, and outside a repo refuses', async () => { + const { repo, origin } = fixture('subdirectory'); + mkdirSync(join(repo, 'packages', 'web'), { recursive: true }); + writeFileSync(join(repo, 'packages', 'web', 'PLEXUS.md'), '---\n---\n'); + const { code } = await promote(join(repo, 'packages', 'web'), 'staging'); + assert.equal(code, 0); + assert.equal(ref(origin, 'env/staging'), git(origin, 'rev-parse', 'main')); + const outside = join(dir, 'outside'); + mkdirSync(outside); + await assert.rejects(promote(outside, 'staging'), /is not inside a git repository/); +}); + +test('promote where the remote cannot be read shows git’s own message and pushes nothing', async () => { + const { repo } = fixture('unreadable'); + git(repo, 'remote', 'set-url', 'origin', join(dir, 'there-is-no-such-remote.git')); + await assert.rejects( + promote(repo, 'staging'), + /there-is-no-such-remote\.git.*(does not appear to be a git repository|No such file)/s, + ); +}); diff --git a/packages/cli/src/commands/release.test.ts b/packages/cli/src/commands/release.test.ts index ba700c87..71914f10 100644 --- a/packages/cli/src/commands/release.test.ts +++ b/packages/cli/src/commands/release.test.ts @@ -1,9 +1,10 @@ import assert from 'node:assert/strict'; -import { writeFileSync } from 'node:fs'; +import { execFileSync } from 'node:child_process'; +import { mkdirSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { test } from 'node:test'; import * as lib from '@plexus-ms/lib'; -import { commit, dir, fixture, ghCalls, git, plx, refs, snapshot, tag, tags } from '../testing/forge.ts'; +import { commit, dir, fixture, ghCalls, ghStdin, git, plx, refs, snapshot, tag, tags } from '../testing/forge.ts'; const release = (repo: string, ...args: string[]) => plx('-y', '--json', 'release', ...args, '-C', repo); const names = (origin: string) => tags(origin).map((t) => t.split(' ')[0]); @@ -33,8 +34,9 @@ test('release of a repo without tags is 0.1.0: it tags origin/main, pushes the t }); const calls = ghCalls(); assert.deepEqual(calls[0], ['auth', 'status']); - assert.deepEqual(calls[1]?.slice(0, 5), ['release', 'create', '0.1.0', '--verify-tag', '--title']); - assert.equal(calls.length, 2); + assert.deepEqual(calls[1]?.slice(0, 2), ['repo', 'view']); + assert.deepEqual(calls[2], ['release', 'create', '0.1.0', '--verify-tag', '--title', '0.1.0', '--notes-file', '-']); + assert.equal(calls.length, 3); }); test('the first release is 0.1.0 whichever step is given', async () => { @@ -87,15 +89,15 @@ test('release goes by the highest version reachable from origin/main, not by the test('the release lists the subjects since the previous tag, oldest first, each a code span', async () => { const { repo } = released('notes', '1.0.0', 'fix: the first', 'feat: use `@acme/ui` #12'); await release(repo); - const [, create] = ghCalls(); - const notes = create?.[create.indexOf('--notes') + 1] ?? ''; + const create = ghCalls().find((c) => c[1] === 'create'); + const notes = ghStdin(); assert.match(notes, /commits since 1\.0\.0/); assert.deepEqual( notes.split('\n').filter((l) => l.startsWith('- ')), ['- `fix: the first`', '- ``feat: use `@acme/ui` #12``'], ); assert.deepEqual(create?.slice(0, 5), ['release', 'create', '1.1.0', '--verify-tag', '--title']); - assert.ok(!create?.some((a) => /immutable|draft|prerelease/.test(a)), 'a normal release'); + assert.ok(!create?.some((a) => /immutable|draft|prerelease|--notes$/.test(a)), 'a normal release, notes on stdin'); }); test('release refuses where nothing is new since the last tag, and pushes and creates nothing', async () => { @@ -208,7 +210,13 @@ test('a release that gh refuses leaves the pushed tag and names the command that const { repo, origin } = released('refused', '1.0.0', 'a change'); process.env.FAKE_GH_REFUSE = '1'; try { - await assert.rejects(release(repo), /tag 1\.1\.0 is pushed.*gh release create 1\.1\.0 --verify-tag/s); + await assert.rejects(release(repo), (error: Error) => { + assert.match(error.message, /tag 1\.1\.0 is pushed.*\(refused\)/s); + assert.match(error.message, /gh release create 1\.1\.0 --verify-tag/); + assert.match(error.message, /--notes-file -/, 'the notes are not on the command line'); + assert.ok(error.message.length < 600, 'and none of them is in the message'); + return true; + }); } finally { delete process.env.FAKE_GH_REFUSE; } @@ -236,7 +244,13 @@ test('release pushes and creates nothing when the answer to the question is no, const asked: string[] = []; const ctx = new lib.Context( { quiet: true }, - { ...lib.realIo(), prompt: async (question) => (asked.push(question), false) }, + { + ...lib.realIo(), + prompt: async (question) => { + asked.push(question); + return false; + }, + }, ); const before = tags(origin); await assert.rejects(lib.release(ctx, repo, 'minor'), /aborted; nothing was pushed/); @@ -247,3 +261,82 @@ test('release pushes and creates nothing when the answer to the question is no, [], ); }); + +test('the notes of a release reach gh on its standard input, whatever their length: 3000 subjects of 100 bytes pass', async () => { + const { repo, origin } = released('long', '1.0.0'); + const subject = (i: number) => `${String(i).padStart(4, '0')} ${'x'.repeat(100)}`; + const input = Array.from( + { length: 3000 }, + (_, i) => + `commit refs/heads/main\ncommitter t ${1700000000 + i} +0000\ndata ${subject(i).length}\n${subject(i)}\n${i === 0 ? `from ${git(repo, 'rev-parse', 'HEAD')}\n` : ''}`, + ).join('\n'); + execFileSync('git', ['fast-import', '--quiet'], { cwd: repo, input }); + git(repo, 'push', '-q', 'origin', 'main'); + ghCalls(); + const { code } = await release(repo); + assert.equal(code, 0); + const notes = ghStdin(); + assert.ok(notes.length > 300_000, `${notes.length} bytes`); + assert.ok(notes.includes(subject(2999))); + const create = ghCalls().find((c) => c[1] === 'create'); + assert.ok( + create?.every((a) => a.length < 100), + 'no argument holds the notes', + ); + assert.ok(names(origin).includes('1.1.0')); +}); + +test('the first release lists no commit: its notes say that it is the first release', async () => { + const { repo } = fixture('first-notes'); + commit(repo, 'a second commit'); + git(repo, 'push', '-q', 'origin', 'main'); + await release(repo); + const notes = ghStdin(); + assert.match(notes, /first release/i); + assert.doesNotMatch(notes, /a second commit|born/); +}); + +test('a tag that only the checkout has does not count for the version, nor is it named in the notes', async () => { + const { repo, origin } = released('local-tag', '1.0.0', 'a change'); + git(repo, 'tag', '5.0.0'); + await release(repo); + assert.deepEqual( + names(origin).filter((n) => /^[0-9]/.test(n)), + ['1.0.0', '1.1.0'], + ); + assert.match(ghStdin(), /since 1\.0\.0/); +}); + +test('release is refused before anything is pushed where gh cannot reach the repository, though it is signed in', async () => { + const { repo, origin } = released('no-repo', '1.0.0', 'a change'); + const before = tags(origin); + process.env.FAKE_GH_NOREPO = '1'; + try { + await assert.rejects(release(repo), /gh cannot reach this repository.*none of the git remotes/s); + } finally { + delete process.env.FAKE_GH_NOREPO; + } + assert.deepEqual(tags(origin), before); + assert.deepEqual( + ghCalls().filter((c) => c[1] === 'create'), + [], + ); +}); + +test('a fetch that git refuses shows git’s own message: a local tag that differs from the remote’s', async () => { + const { repo, origin } = released('clobber', '1.0.0', 'a change'); + git(repo, 'tag', '-f', '1.0.0', 'HEAD'); + const before = tags(origin); + await assert.rejects(release(repo), /would clobber existing tag|rejected/); + assert.deepEqual(tags(origin), before); +}); + +test('release in a subdirectory of the repo works from the repo’s root, and outside a repo refuses', async () => { + const { repo, origin } = released('subdirectory', '1.0.0', 'a change'); + mkdirSync(join(repo, 'packages'), { recursive: true }); + assert.equal((await release(join(repo, 'packages'))).code, 0); + assert.ok(names(origin).includes('1.1.0')); + const outside = join(dir, 'release-outside'); + mkdirSync(outside); + await assert.rejects(release(outside), /is not inside a git repository/); +}); diff --git a/packages/cli/src/testing/forge.ts b/packages/cli/src/testing/forge.ts index 340323d7..8595ca16 100644 --- a/packages/cli/src/testing/forge.ts +++ b/packages/cli/src/testing/forge.ts @@ -72,8 +72,10 @@ const GH = `#!/bin/sh for a in "$@"; do printf '%s\\037' "$a" >> "$FAKE_GH_LOG"; done printf '\\036' >> "$FAKE_GH_LOG" case "$1 $2" in + "repo view") [ -z "$FAKE_GH_NOREPO" ] || { echo "none of the git remotes point to a known GitHub host" >&2; exit 1; } ;; "auth status") [ -z "$FAKE_GH_LOGGED_OUT" ] || { echo "not logged in" >&2; exit 1; } ;; "release create") + case " $* " in *" --notes-file - "*) cat > "$FAKE_GH_LOG.stdin" ;; esac [ -z "$FAKE_GH_REFUSE" ] || { echo "refused" >&2; exit 1; } echo "https://example.com/acme/shop/releases/tag/$3" ;; esac @@ -100,6 +102,15 @@ export function ghCalls(): string[][] { .map((call) => call.split('\x1f').slice(0, -1)); } +/** What the stand-in `gh` read on its standard input in the last `release create` that asked for it. */ +export function ghStdin(): string { + try { + return readFileSync(`${log}.stdin`, 'utf8'); + } catch { + return ''; + } +} + /** Runs `plx` with `args`, returning what it printed and the exit code it asked for; a refusal rejects, as bin.ts catches it. */ export async function plx(...args: string[]): Promise<{ stdout: string; stderr: string; code: number }> { let stdout = ''; diff --git a/packages/lib/src/commitVersion.test.ts b/packages/lib/src/commitVersion.test.ts index caca0a2e..d36482a2 100644 --- a/packages/lib/src/commitVersion.test.ts +++ b/packages/lib/src/commitVersion.test.ts @@ -129,3 +129,12 @@ test('a shallow clone, which cannot see what is reachable, is refused, told to f /shallow.*whole history.*without its tags answers 0\.0\.0/s, ); }); + +test('given the tags to count, a tag that is not among them is ignored, though reachable and higher', async () => { + const { root, commits } = repo(3); + git(root, 'tag', '1.0.0', commits[0] as string); + git(root, 'tag', '5.0.0', commits[1] as string); + assert.equal(await commitVersion(ctx, root, 'HEAD', new Set(['1.0.0'])), '1.0.0'); + assert.equal(await commitVersion(ctx, root, 'HEAD', new Set()), '0.0.0'); + assert.equal(await commitVersion(ctx, root), '5.0.0', 'every tag without the option'); +}); From 205284fb28a9bcb84f40a4d07af69d4f896d5746 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:33:20 +0100 Subject: [PATCH 11/20] plx promote and plx release: explicit refspecs, remote tags only, notes on stdin, gh reaching the repo, the repo's top, git's own messages Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/commands/promote.ts | 6 +- packages/lib/src/apply.ts | 2 +- packages/lib/src/commitVersion.ts | 17 +++++- packages/lib/src/promote.ts | 85 ++++++++++++++++------------ packages/lib/src/release.ts | 75 +++++++++++++++--------- packages/lib/src/remote.ts | 38 +++++++++++++ 6 files changed, 154 insertions(+), 69 deletions(-) create mode 100644 packages/lib/src/remote.ts diff --git a/packages/cli/src/commands/promote.ts b/packages/cli/src/commands/promote.ts index aa3e2164..f90f374d 100644 --- a/packages/cli/src/commands/promote.ts +++ b/packages/cli/src/commands/promote.ts @@ -2,8 +2,10 @@ // its declared source, `main` or another environment's branch, and create the // branch when it does not exist (§ 6.8 Decisions). lib's `promote` does the // work, and its header says how, in order; this file maps the arguments and -// prints the result. It takes no other argument and has no override. The -// checkout is read for its root marker alone and is never changed. +// prints the result. It takes no other argument and has no override. Of the +// checkout it reads the root marker of the repo the directory is in; it +// changes no file, branch or checked-out branch, only the remote-tracking refs +// it fetches and their reflogs. // // plx promote staging // plx -y promote production # without a terminal diff --git a/packages/lib/src/apply.ts b/packages/lib/src/apply.ts index ae398237..1b157448 100644 --- a/packages/lib/src/apply.ts +++ b/packages/lib/src/apply.ts @@ -103,7 +103,7 @@ const AT_HEAD = 'at HEAD'; const IN_TREE = 'in the working tree'; /** The top of the repo that `dir` is inside; rejects, saying so, when it is inside none. */ -async function topOf(ctx: Context, dir: string): Promise { +export async function topOf(ctx: Context, dir: string): Promise { try { return (await ctx.read('git', ['rev-parse', '--show-toplevel'], { cwd: dir })).trim(); } catch { diff --git a/packages/lib/src/commitVersion.ts b/packages/lib/src/commitVersion.ts index 0c459de9..df2edaa1 100644 --- a/packages/lib/src/commitVersion.ts +++ b/packages/lib/src/commitVersion.ts @@ -18,13 +18,24 @@ import { compareVersions } from './version.ts'; /** A plain semver version, as a repo's tag names it: no prefix, no pre-release, no leading zero. */ const VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; -/** The version of `commit` (HEAD by default, else anything git names a commit by) in the checkout at `root`. */ -export async function commitVersion(ctx: Context, root: string, commit = 'HEAD'): Promise { +/** + * The version of `commit` (HEAD by default, else anything git names a commit by) in the checkout at `root`. Given + * `only`, the names of the tags to count, a tag the checkout has and `only` lacks is ignored: a caller that wants the + * version as a remote knows it passes the remote's tags, and a tag made here and not pushed does not move it. + */ +export async function commitVersion( + ctx: Context, + root: string, + commit = 'HEAD', + only?: ReadonlySet, +): Promise { const shallow = (await ctx.read('git', ['rev-parse', '--is-shallow-repository'], { cwd: root })).trim(); if (shallow === 'true') throw new Error( `${root} is a shallow clone, which cannot see the tags reachable from ${commit}, and so not its version: fetch the whole history with its tags (git fetch --unshallow --tags; actions/checkout with fetch-depth: 0); a full clone without its tags answers 0.0.0, so fetch them too`, ); const tags = (await ctx.read('git', ['tag', '--merged', commit], { cwd: root })).split('\n').map((t) => t.trim()); - return tags.filter((tag) => VERSION.test(tag)).reduce((a, b) => (compareVersions(a, b) >= 0 ? a : b), '0.0.0'); + return tags + .filter((tag) => VERSION.test(tag) && (only === undefined || only.has(tag))) + .reduce((a, b) => (compareVersions(a, b) >= 0 ? a : b), '0.0.0'); } diff --git a/packages/lib/src/promote.ts b/packages/lib/src/promote.ts index 8dfa74b2..815595fd 100644 --- a/packages/lib/src/promote.ts +++ b/packages/lib/src/promote.ts @@ -4,28 +4,36 @@ // spells a branch or knows a name. // // In order: -// 1. read the declaration of the checkout's root marker, and refuse one that -// is invalid or empty, and a name it does not declare -// 2. fetch `origin` (its branches, pruned), which is the one change to the -// checkout, and to its remote-tracking refs alone, also under --dry-run -// 3. find the head of the source on the remote: `origin/main`, or -// `origin/env/`, which must exist already (promote that one first) -// 4. find the head of `env/` on the remote, if it exists; refuse where -// it is no ancestor of the source's head (no fast-forward), and stop where -// it is the source's head already +// 1. find the top of the repo the directory is in, read the declaration of +// its root marker, and refuse one that is invalid or empty, and a name it +// does not declare +// 2. ask the remote which of the source and `env/` it has, and refuse +// where the source is not there: `main` must be pushed, and an +// `env/` source must be promoted first +// 3. fetch exactly those refs, by explicit refspec, into the checkout's +// remote-tracking refs (and their reflogs), also under --dry-run: a +// clone that fetches `main` alone, as a forge's checkout does, gives the +// same answers as a full one +// 4. compare the two heads: stop, pushing nothing, where `env/` is at +// the source's head; refuse where it holds a commit the source does not +// (no fast-forward); and in a shallow clone, where the history it holds +// cannot tell that, say so and name the remedy // 5. say what will be pushed, ask, and push that commit to // `refs/heads/env/` of origin, with no force and past the hooks // -// The checkout's files, its branches and its checked-out branch are neither -// read nor changed, whichever branch it stands on and however dirty it is; -// only its root marker is read, as it is. The commit to push is named by its -// hash, so no local branch is made. The remote's own refusal of a push that -// is no fast-forward stands behind step 4, should the branch have moved in -// between. An `env/` branch takes no commit of its own and has no +// The checkout's files, index, branches and checked-out branch are neither +// read nor changed, whichever branch it stands on and however dirty it is, +// and `origin/HEAD` is left alone; only its root marker is read, as it is on +// disk, while the source is read from the remote. The commit to push is named +// by its hash, so no local branch is made. The remote's own refusal of a push +// that is no fast-forward stands behind step 4, should the branch have moved +// in between. An `env/` branch takes no commit of its own and has no // override (§ 6.3 Decisions): nothing here forces anything. +import { topOf } from './apply.ts'; import type { Context } from './context.ts'; import { declarationRefusal, readDeclaredEnvironments } from './declaredEnvironments.ts'; import { run } from './effects.ts'; +import { fetchRefs, REMOTE, remoteRefs } from './remote.ts'; import { UsageError } from './version.ts'; /** What a promotion did, or would do under --dry-run. */ @@ -39,24 +47,18 @@ export interface Promoted { from: string | null; /** Where it is now: the head of the source. */ to: string; - /** The commits the move adds to the branch. */ + /** The commits the move adds to the branch, as far as the checkout's history goes. */ commits: number; outcome: 'created' | 'fast-forwarded' | 'unchanged'; } -const REMOTE = 'origin'; +const head = (branch: string) => `refs/heads/${branch}`; +const tracking = (branch: string) => `refs/remotes/${REMOTE}/${branch}`; -/** The commit a remote branch is at in the checkout's remote-tracking refs, or null where there is none. */ -async function remoteHead(ctx: Context, dir: string, branch: string): Promise { - return ctx - .read('git', ['rev-parse', '-q', '--verify', `refs/remotes/${REMOTE}/${branch}^{commit}`], { cwd: dir }) - .then((out) => out.trim()) - .catch(() => null); -} - -/** Move `env/` of the checkout at `dir` on the remote to the head of its source. */ +/** Move `env/` of the repo that `dir` is in on the remote to the head of its source. */ export async function promote(ctx: Context, dir: string, name: string): Promise { - const declared = await readDeclaredEnvironments(ctx, dir); + const root = await topOf(ctx, dir); + const declared = await readDeclaredEnvironments(ctx, root); const refusal = declarationRefusal(declared); if (refusal) throw new Error(refusal); const environment = declared.environments.find((e) => e.name === name); @@ -66,22 +68,33 @@ export async function promote(ctx: Context, dir: string, name: string): Promise< ); const { branch, source } = environment; - await ctx.stage(run('git', ['fetch', '--quiet', '--prune', REMOTE], { cwd: dir })); - const to = await remoteHead(ctx, dir, source); - if (to === null) + const there = await remoteRefs(ctx, root, [head(source), head(branch)]); + if (!there.has(head(source))) throw new Error( environment.promotesFrom === source - ? `${REMOTE}/${source} not found: push the repo's default branch first` + ? `${source} is not on the remote: push the repo's default branch first` : `${source}, the source of ${branch}, is not on the remote yet; promote ${environment.promotesFrom} first`, ); - const from = await remoteHead(ctx, dir, branch); - const count = async (range: string) => - Number((await ctx.read('git', ['rev-list', '--count', range], { cwd: dir })).trim()); + const branches = [source, ...(there.has(head(branch)) ? [branch] : [])]; + await fetchRefs( + ctx, + root, + branches.map((b) => `+${head(b)}:${tracking(b)}`), + ); + const read = (args: string[]) => ctx.read('git', args, { cwd: root }).then((out) => out.trim()); + const to = await read(['rev-parse', `${tracking(source)}^{commit}`]); + const from = there.has(head(branch)) ? await read(['rev-parse', `${tracking(branch)}^{commit}`]) : null; + const count = async (range: string) => Number(await read(['rev-list', '--count', range])); if (from === to) return { environment: name, branch, source, from, to, commits: 0, outcome: 'unchanged' }; - if (from !== null && (await count(`${to}..${from}`)) > 0) + if (from !== null && (await count(`${to}..${from}`)) > 0) { + if ((await read(['rev-parse', '--is-shallow-repository'])) === 'true') + throw new Error( + `this is a shallow clone and cannot tell whether moving ${branch} to ${source} is a fast-forward: its history does not connect them; fetch the history (git fetch --unshallow ${REMOTE}) and run it again`, + ); throw new Error( `${branch} is not an ancestor of ${source} on the remote, so moving it is no fast-forward: it holds commits ${source} does not; an \`env/\` branch only ever fast-forwards, so look at them with git before anything else`, ); + } const commits = await count(from === null ? to : `${from}..${to}`); const result: Promoted = { environment: name, @@ -100,7 +113,7 @@ export async function promote(ctx: Context, dir: string, name: string): Promise< : `move ${branch} on ${REMOTE} from ${from.slice(0, 7)} to ${to.slice(0, 7)}, the head of ${source}: ${n}`, ); if (!(await ctx.confirm(`push ${branch}?`))) throw new Error('aborted; nothing was pushed'); - await ctx.apply([run('git', ['push', '--no-verify', REMOTE, `${to}:refs/heads/${branch}`], { cwd: dir })]); + await ctx.apply([run('git', ['push', '--no-verify', REMOTE, `${to}:${head(branch)}`], { cwd: root })]); return result; } diff --git a/packages/lib/src/release.ts b/packages/lib/src/release.ts index dcb63fdf..ec17e867 100644 --- a/packages/lib/src/release.ts +++ b/packages/lib/src/release.ts @@ -4,35 +4,43 @@ // no file of the repo holds one. // // In order: -// 1. check that `gh` is logged in, before anything else -// 2. fetch `origin` with its tags, which changes the checkout's -// remote-tracking refs and adds the remote's tags to it, also under -// --dry-run: the version is only as true as the tags the checkout has -// 3. find the head of `origin/main` and its version (0.0.0 where there is -// no tag), and refuse where `origin/main` holds no commit since that tag: -// a release lists the commits since the previous one and would be empty +// 1. find the top of the repo the directory is in, and check that `gh` is +// logged in and can reach the repository (`gh repo view`), before +// anything is fetched or pushed +// 2. fetch `origin`'s `main` and its tags by explicit refspec, which changes +// the checkout's remote-tracking ref (and its reflog) and adds the +// remote's tags, also under --dry-run; a local tag that differs from the +// remote's is git's refusal, shown as git words it +// 3. find the head of `origin/main` and its version among the tags the +// remote has (0.0.0 where there is none): a tag made here and not pushed +// does not count; refuse where `origin/main` holds no commit since that +// tag, a release listing nothing // 4. compute the next version, a step of that version (`minor` by default; // the first release of a repo without tags is 0.1.0 whichever the step), // and refuse where its tag exists already // 5. say what will be done, ask, and push the head of `origin/main` to // `refs/tags/` of origin, past the hooks -// 6. create the release with `gh release create --verify-tag`: a +// 6. create the release with `gh release create --verify-tag +// --notes-file -`, the notes on standard input whatever their length: a // normal release (not a draft, no immutability asked for) whose notes // list the subjects of the commits since the previous tag, each a code -// span; where gh fails, the tag stays and the error names the command -// that finishes the release +// span, and for the first release only say that it is the first; where +// gh fails, the tag stays and the error names the command that finishes +// the release // // It moves no branch and touches no file, wherever the checkout stands and // however dirty it is: only `origin/main` is read, never the checked-out -// branch, and no tag is made in the checkout, the push naming the commit. -// Deploying is no part of it: the order is release, then promote. - +// branch, and no tag is made in the checkout, the push naming the commit. The +// tag is lightweight and unsigned. Deploying is no part of it: the order is +// release, then promote. +import { topOf } from './apply.ts'; import { codeSpan } from './codeSpan.ts'; import { commitVersion } from './commitVersion.ts'; import type { Context } from './context.ts'; import { DEFAULT_BRANCH } from './declaredEnvironments.ts'; import { run } from './effects.ts'; import { detailOf } from './io.ts'; +import { fetchRefs, REMOTE, remoteRefs } from './remote.ts'; import { preflightForge } from './version.ts'; /** How far the version moves. */ @@ -42,7 +50,6 @@ export type ReleaseStep = (typeof RELEASE_STEPS)[number]; /** The first version of a repo without one, whichever the step. */ const FIRST = '0.1.0'; const NONE = '0.0.0'; -const REMOTE = 'origin'; /** What a release did, or would do under --dry-run. */ export interface Released { @@ -71,24 +78,30 @@ export function nextVersion(version: string, step: ReleaseStep): string { } } -/** The release notes: the subjects since the previous version, each a code span. */ +/** The release notes: the subjects since the previous version, each a code span; the first release lists none. */ export const releaseNotes = (previous: string | null, subjects: string[]): string => [ - previous === null ? 'The commits of the first release.' : `The commits since ${previous}.`, - '', - ...subjects.map((s) => `- ${codeSpan(s)}`), + previous === null ? 'The first release.' : `The commits since ${previous}.`, + ...(subjects.length === 0 ? [] : ['', ...subjects.map((s) => `- ${codeSpan(s)}`)]), ].join('\n'); /** Release `origin/main` of the checkout at `dir` by `step`. */ export async function release(ctx: Context, dir: string, step: ReleaseStep): Promise { const main = `${REMOTE}/${DEFAULT_BRANCH}`; + const root = await topOf(ctx, dir); await preflightForge(ctx); - await ctx.stage(run('git', ['fetch', '--quiet', '--tags', REMOTE], { cwd: dir })); - const read = (args: string[]) => ctx.read('git', args, { cwd: dir }).then((out) => out.trim()); + await ctx.read('gh', ['repo', 'view', '--json', 'name'], { cwd: root }).catch((error: unknown) => { + throw new Error(`gh cannot reach this repository, so nothing was pushed: ${detailOf(error)}`); + }); + await fetchRefs(ctx, root, [`+refs/heads/${DEFAULT_BRANCH}:refs/remotes/${main}`, 'refs/tags/*:refs/tags/*']); + const read = (args: string[]) => ctx.read('git', args, { cwd: root }).then((out) => out.trim()); const commit = await read(['rev-parse', '-q', '--verify', `refs/remotes/${main}^{commit}`]).catch(() => { throw new Error(`${main} not found: push the repo's default branch first`); }); - const last = await commitVersion(ctx, dir, main); + const remoteTags = new Set( + [...(await remoteRefs(ctx, root, ['refs/tags/*'])).keys()].map((t) => t.slice('refs/tags/'.length)), + ); + const last = await commitVersion(ctx, root, main, remoteTags); const previous = last === NONE ? null : last; const since = previous === null ? commit : `refs/tags/${previous}..${commit}`; const commits = Number(await read(['rev-list', '--count', since])); @@ -98,9 +111,10 @@ export async function release(ctx: Context, dir: string, step: ReleaseStep): Pro const held = await read(['rev-parse', '-q', '--verify', `refs/tags/${version}^{commit}`]).catch(() => null); if (held !== null) throw new Error( - `${version} exists already, at ${held.slice(0, 7)}, a commit ${main} does not hold: ${step} would reuse it; move or delete that tag, or take a larger step`, + `${version} exists already, at ${held.slice(0, 7)}: ${step} would reuse it; move or delete that tag, or take a larger step`, ); - const subjects = (await read(['log', '--reverse', '--format=%s', since])).split('\n').filter(Boolean); + const subjects = + previous === null ? [] : (await read(['log', '--reverse', '--format=%s', since])).split('\n').filter(Boolean); const notes = releaseNotes(previous, subjects); ctx.say( @@ -109,13 +123,14 @@ export async function release(ctx: Context, dir: string, step: ReleaseStep): Pro for (const subject of subjects) ctx.say(` ${subject}`); if (!(await ctx.confirm(`tag ${main} as ${version}, push the tag and create its release?`))) throw new Error('aborted; nothing was pushed'); - await ctx.apply([run('git', ['push', '--no-verify', REMOTE, `${commit}:refs/tags/${version}`], { cwd: dir })]); - const create = run('gh', ['release', 'create', version, '--verify-tag', '--title', version, '--notes', notes], { - cwd: dir, + await ctx.apply([run('git', ['push', '--no-verify', REMOTE, `${commit}:refs/tags/${version}`], { cwd: root })]); + const create = run('gh', ['release', 'create', version, '--verify-tag', '--title', version, '--notes-file', '-'], { + cwd: root, + input: notes, }); const url = await ctx.effect(create).catch((error: unknown) => { throw new Error( - `the tag ${version} is pushed and its release is not (${detailOf(error)}): create it with \`gh release create ${version} --verify-tag --title ${version}\` and the notes of the commits since ${previous ?? 'the start'}`, + `the tag ${version} is pushed and its release is not (${detailOf(error)}): create it with \`${finish(version, previous)}\``, ); }); return { version, previous, commit, commits, url: url?.trim() || null }; @@ -126,3 +141,9 @@ export function renderReleased(r: Released): string { const n = `${r.commits} ${r.commits === 1 ? 'commit' : 'commits'}`; return `✓ ${r.version} tagged on ${r.commit.slice(0, 7)} (${n}${r.previous === null ? '' : ` since ${r.previous}`})${r.url === null ? '' : `: ${r.url}`}`; } + +/** A command that finishes a release whose tag is pushed, with its notes from a pipe or short enough to type. */ +const finish = (version: string, previous: string | null): string => + previous === null + ? `gh release create ${version} --verify-tag --title ${version} --notes 'The first release.'` + : `git log --reverse --format='- %s' ${previous}..${version} | gh release create ${version} --verify-tag --title ${version} --notes-file -`; diff --git a/packages/lib/src/remote.ts b/packages/lib/src/remote.ts new file mode 100644 index 00000000..932c3941 --- /dev/null +++ b/packages/lib/src/remote.ts @@ -0,0 +1,38 @@ +// What `promote` and `release` share of talking to the remote: its name, the fetch of explicit refs, and which refs +// it has. Each fetch names the refs it compares by refspec, whatever the clone's configured refspec is (a single-branch +// or shallow clone, as a forge's checkout makes it, fetches `main` alone), and a failure carries git's own message. +import type { Context } from './context.ts'; +import { run } from './effects.ts'; +import { ExecError } from './io.ts'; + +/** The remote of the repo. */ +export const REMOTE = 'origin'; + +/** What went wrong in a git command, in git's own words. */ +const why = (error: unknown): string => + (error instanceof ExecError ? error.stderr.trim() : '') || (error instanceof Error ? error.message : String(error)); + +/** + * Fetch `refspecs` of the remote into the checkout, also under --dry-run, where it changes remote-tracking refs and + * their reflogs, and tags that were not there, and no branch, file or checked-out branch. + */ +export async function fetchRefs(ctx: Context, dir: string, refspecs: string[]): Promise { + await ctx.stage(run('git', ['fetch', REMOTE, ...refspecs], { cwd: dir })).catch((error: unknown) => { + throw new Error(`git fetch ${REMOTE} failed: ${why(error)}`); + }); +} + +/** The refs of the remote that match `patterns` (full names, or globs such as `refs/tags/*`), by name, with their objects. */ +export async function remoteRefs(ctx: Context, dir: string, patterns: string[]): Promise> { + const out = await ctx.read('git', ['ls-remote', REMOTE, ...patterns], { cwd: dir }).catch((error: unknown) => { + throw new Error(`git ls-remote ${REMOTE} failed: ${why(error)}`); + }); + return new Map( + out + .split('\n') + .filter(Boolean) + .map((line) => line.split('\t') as [string, string]) + .filter(([, name]) => !name.endsWith('^{}')) + .map(([sha, name]) => [name, sha]), + ); +} From aeb4e9be33fc0d6bbd0ba77a08fb6007f446c568 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:35:20 +0100 Subject: [PATCH 12/20] Test: release in a clone that fetches another branch than main Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/commands/release.test.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/packages/cli/src/commands/release.test.ts b/packages/cli/src/commands/release.test.ts index 71914f10..9e596ab9 100644 --- a/packages/cli/src/commands/release.test.ts +++ b/packages/cli/src/commands/release.test.ts @@ -340,3 +340,16 @@ test('release in a subdirectory of the repo works from the repo’s root, and ou mkdirSync(outside); await assert.rejects(release(outside), /is not inside a git repository/); }); + +test('release in a clone that fetches another branch than main still tags the remote’s main', async () => { + const { repo, origin } = released('other-branch', '1.0.0', 'a change'); + git(repo, 'push', '-q', 'origin', 'main:refs/heads/side'); + const clone = join(dir, 'other-branch-clone'); + git(dir, 'clone', '-q', '--single-branch', '--branch', 'side', `file://${origin}`, clone); + const head = git(origin, 'rev-parse', 'main'); + await release(clone); + assert.deepEqual( + tags(origin).filter((t) => t.startsWith('1.1.0')), + [`1.1.0 ${head}`], + ); +}); From cd7db4be801dd2ff11a1124c03ed122e0a2d29a3 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:36:12 +0100 Subject: [PATCH 13/20] Test: the narration of a long release shows some subjects and counts the rest Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/commands/release.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/commands/release.test.ts b/packages/cli/src/commands/release.test.ts index 9e596ab9..5b342142 100644 --- a/packages/cli/src/commands/release.test.ts +++ b/packages/cli/src/commands/release.test.ts @@ -273,8 +273,10 @@ test('the notes of a release reach gh on its standard input, whatever their leng execFileSync('git', ['fast-import', '--quiet'], { cwd: repo, input }); git(repo, 'push', '-q', 'origin', 'main'); ghCalls(); - const { code } = await release(repo); + const { code, stderr } = await release(repo); assert.equal(code, 0); + assert.ok(stderr.split('\n').length < 60, 'the narration shows some of the subjects and counts the rest'); + assert.match(stderr, /and 2980 more/); const notes = ghStdin(); assert.ok(notes.length > 300_000, `${notes.length} bytes`); assert.ok(notes.includes(subject(2999))); From 438e55e93e9432375305929d95b2ff4d354af69e Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:36:28 +0100 Subject: [PATCH 14/20] plx release: the narration lists twenty subjects and counts the rest Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/release.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/lib/src/release.ts b/packages/lib/src/release.ts index ec17e867..fd716420 100644 --- a/packages/lib/src/release.ts +++ b/packages/lib/src/release.ts @@ -50,6 +50,8 @@ export type ReleaseStep = (typeof RELEASE_STEPS)[number]; /** The first version of a repo without one, whichever the step. */ const FIRST = '0.1.0'; const NONE = '0.0.0'; +/** How many subjects the narration lists before it counts the rest. */ +const SHOWN = 20; /** What a release did, or would do under --dry-run. */ export interface Released { @@ -120,7 +122,8 @@ export async function release(ctx: Context, dir: string, step: ReleaseStep): Pro ctx.say( `tag ${main} (${commit.slice(0, 7)}) as ${version}${previous === null ? ', the first version' : `, ${step} of ${previous}`}: ${commits} ${commits === 1 ? 'commit' : 'commits'}`, ); - for (const subject of subjects) ctx.say(` ${subject}`); + for (const subject of subjects.slice(0, SHOWN)) ctx.say(` ${subject}`); + if (subjects.length > SHOWN) ctx.say(` … and ${subjects.length - SHOWN} more`); if (!(await ctx.confirm(`tag ${main} as ${version}, push the tag and create its release?`))) throw new Error('aborted; nothing was pushed'); await ctx.apply([run('git', ['push', '--no-verify', REMOTE, `${commit}:refs/tags/${version}`], { cwd: root })]); From 4b9d8255e689e604650713da61a10e366dafdad9 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:37:06 +0100 Subject: [PATCH 15/20] Test: a process that exits without reading its input fails by its exit code Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/io.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/packages/lib/src/io.test.ts b/packages/lib/src/io.test.ts index b0c7af80..dcf2264d 100644 --- a/packages/lib/src/io.test.ts +++ b/packages/lib/src/io.test.ts @@ -75,3 +75,11 @@ test('SIGTERM runs what onInterrupt registered, kills a time-limited process gro assert.ok(!existsSync(scratch), 'the cleanup ran'); assert.ok(await until(() => !alive(sleeper)), 'the time-limited process group is killed'); }); + +test('a process that exits without reading its input fails by its exit code, and the write error does not crash', async () => { + for (let i = 0; i < 20; i++) + await assert.rejects( + realIo().exec('sh', ['-c', 'exit 3'], { input: 'x'.repeat(2_000_000) }), + (error: unknown) => error instanceof ExecError && error.code === 3, + ); +}); From 2bae0871190f8395e051ce4dd5710bf9c9b95088 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:37:23 +0100 Subject: [PATCH 16/20] exec: a process that exits without reading its input fails by its exit code, not by a broken pipe Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/io.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/lib/src/io.ts b/packages/lib/src/io.ts index bfb29c8d..9d13ce5d 100644 --- a/packages/lib/src/io.ts +++ b/packages/lib/src/io.ts @@ -218,7 +218,11 @@ export function realIo(prompt?: Io['prompt']): Io { else if (code === 0) resolve(stdout); else reject(new ExecError(render(command, args), code, stderr, stdout)); }); - if (options.input !== undefined) child.stdin?.end(options.input); + if (options.input !== undefined) { + // A process that exits without reading its input fails by its exit code; the broken pipe is no error of ours. + child.stdin?.on('error', () => {}); + child.stdin?.end(options.input); + } }), readFile: (path) => readFile(path, 'utf8'), writeFile: (path, content) => writeFile(path, content), From 228cdd4979dfa22c4c865da0e262e752699fa737 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:53:03 +0100 Subject: [PATCH 17/20] Test: a run of plx release finishes a release whose tag is pushed, with the notes of the first run Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/commands/release.test.ts | 114 ++++++++++++++++++++-- packages/cli/src/testing/forge.ts | 8 ++ 2 files changed, 112 insertions(+), 10 deletions(-) diff --git a/packages/cli/src/commands/release.test.ts b/packages/cli/src/commands/release.test.ts index 5b342142..4c3fa2d3 100644 --- a/packages/cli/src/commands/release.test.ts +++ b/packages/cli/src/commands/release.test.ts @@ -4,7 +4,20 @@ import { mkdirSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { test } from 'node:test'; import * as lib from '@plexus-ms/lib'; -import { commit, dir, fixture, ghCalls, ghStdin, git, plx, refs, snapshot, tag, tags } from '../testing/forge.ts'; +import { + commit, + dir, + fixture, + ghCalls, + ghReleased, + ghStdin, + git, + plx, + refs, + snapshot, + tag, + tags, +} from '../testing/forge.ts'; const release = (repo: string, ...args: string[]) => plx('-y', '--json', 'release', ...args, '-C', repo); const names = (origin: string) => tags(origin).map((t) => t.split(' ')[0]); @@ -13,6 +26,7 @@ const names = (origin: string) => tags(origin).map((t) => t.split(' ')[0]); function released(name: string, version: string, ...subjects: string[]) { const f = fixture(name); tag(f.repo, version); + ghReleased(version); for (const subject of subjects) commit(f.repo, subject); git(f.repo, 'push', '-q', 'origin', 'main'); ghCalls(); @@ -206,23 +220,103 @@ test('release is refused before it pushes where gh is not logged in', async () = assert.deepEqual(tags(origin), before); }); -test('a release that gh refuses leaves the pushed tag and names the command that finishes it', async () => { - const { repo, origin } = released('refused', '1.0.0', 'a change'); +/** `plx release`, with the stand-in `gh` refusing to create a release. */ +async function refused(repo: string, ...args: string[]) { process.env.FAKE_GH_REFUSE = '1'; try { - await assert.rejects(release(repo), (error: Error) => { - assert.match(error.message, /tag 1\.1\.0 is pushed.*\(refused\)/s); - assert.match(error.message, /gh release create 1\.1\.0 --verify-tag/); - assert.match(error.message, /--notes-file -/, 'the notes are not on the command line'); - assert.ok(error.message.length < 600, 'and none of them is in the message'); - return true; - }); + return await release(repo, ...args).then( + () => assert.fail('the release was refused'), + (error: Error) => error, + ); } finally { delete process.env.FAKE_GH_REFUSE; } +} + +test('a release that gh refuses leaves the pushed tag and says to run plx release again, with no command to assemble', async () => { + const { repo, origin } = released('refused', '1.0.0', 'a change'); + const error = await refused(repo); + assert.match(error.message, /the tag 1\.1\.0 is pushed and its release is not \(refused\); run plx release again/); + assert.doesNotMatch(error.message, /gh release create|git log/); assert.ok(names(origin).includes('1.1.0')); }); +test('plx release run again after a refused release creates the release of the pushed tag with the notes of the first run, and tags nothing', async () => { + const { repo, origin } = released('finish', '1.0.0', 'fix: one @acme/ui', 'feat: two'); + await refused(repo); + const notes = ghStdin(); + const before = [tags(origin), refs(origin)]; + ghCalls(); + const { code, stdout, stderr } = await release(repo, 'major'); + assert.equal(code, 0); + assert.match(stderr, /the tag 1\.1\.0 has no release yet/); + assert.deepEqual(JSON.parse(stdout), { + version: '1.1.0', + previous: '1.0.0', + commit: git(origin, 'rev-parse', 'main'), + commits: 2, + url: 'https://example.com/acme/shop/releases/tag/1.1.0', + }); + assert.equal(ghStdin(), notes, 'the notes of the first run'); + assert.match(notes, /- `fix: one @acme\/ui`/); + assert.deepEqual([tags(origin), refs(origin)], before, 'nothing pushed, whatever the step'); + const create = ghCalls().filter((c) => c[1] === 'create'); + assert.deepEqual( + create.map((c) => c[2]), + ['1.1.0'], + ); +}); + +test('plx release run again once the release exists says there is nothing to release', async () => { + const { repo, origin } = released('finished', '1.0.0', 'a change'); + await release(repo); + const before = tags(origin); + ghCalls(); + await assert.rejects(release(repo), /nothing to release: origin\/main is at 1\.1\.0 already/); + assert.deepEqual(tags(origin), before); + assert.deepEqual( + ghCalls().filter((c) => c[1] === 'create'), + [], + ); +}); + +test('the first release that gh refused is finished by a run again, with the first release’s notes', async () => { + const { repo, origin } = fixture('finish-first'); + commit(repo, 'a second commit'); + git(repo, 'push', '-q', 'origin', 'main'); + await refused(repo); + assert.deepEqual(names(origin), ['0.1.0']); + const { code, stdout } = await release(repo); + assert.equal(code, 0); + assert.equal(JSON.parse(stdout).version, '0.1.0'); + assert.equal(JSON.parse(stdout).previous, null); + assert.match(ghStdin(), /^The first release\.$/); + assert.deepEqual(names(origin), ['0.1.0']); +}); + +test('where gh is asked to finish a release and declines the question, nothing is created', async () => { + const { repo } = released('finish-declined', '1.0.0', 'a change'); + await refused(repo); + const asked: string[] = []; + const ctx = new lib.Context( + { quiet: true }, + { + ...lib.realIo(), + prompt: async (question) => { + asked.push(question); + return false; + }, + }, + ); + ghCalls(); + await assert.rejects(lib.release(ctx, repo, 'minor'), /aborted; nothing was created/); + assert.deepEqual(asked, ['create the release of 1.1.0?']); + assert.deepEqual( + ghCalls().filter((c) => c[1] === 'create'), + [], + ); +}); + test('release refuses a shallow clone, which cannot see the tags', async () => { const { origin } = released('shallow', '1.0.0', 'a change'); const clone = join(dir, 'shallow-clone'); diff --git a/packages/cli/src/testing/forge.ts b/packages/cli/src/testing/forge.ts index 8595ca16..dc1177fb 100644 --- a/packages/cli/src/testing/forge.ts +++ b/packages/cli/src/testing/forge.ts @@ -43,6 +43,7 @@ export function commit(repo: string, subject: string, file = 'notes.txt'): strin /** A bare origin and a checkout of it on `main` with one commit, which is pushed. */ export function fixture(name: string, marker = MARKER): { repo: string; origin: string } { + ghReleased(); const origin = join(dir, `${name}.git`); execFileSync('git', ['init', '-q', '--bare', '-b', 'main', origin]); const repo = join(dir, name); @@ -74,9 +75,11 @@ printf '\\036' >> "$FAKE_GH_LOG" case "$1 $2" in "repo view") [ -z "$FAKE_GH_NOREPO" ] || { echo "none of the git remotes point to a known GitHub host" >&2; exit 1; } ;; "auth status") [ -z "$FAKE_GH_LOGGED_OUT" ] || { echo "not logged in" >&2; exit 1; } ;; + "release view") grep -qx "$3" "$FAKE_GH_LOG.releases" 2>/dev/null || { echo "release not found" >&2; exit 1; } ;; "release create") case " $* " in *" --notes-file - "*) cat > "$FAKE_GH_LOG.stdin" ;; esac [ -z "$FAKE_GH_REFUSE" ] || { echo "refused" >&2; exit 1; } + echo "$3" >> "$FAKE_GH_LOG.releases" echo "https://example.com/acme/shop/releases/tag/$3" ;; esac `; @@ -102,6 +105,11 @@ export function ghCalls(): string[][] { .map((call) => call.split('\x1f').slice(0, -1)); } +/** The releases the stand-in `gh` holds: exactly `tags`. */ +export function ghReleased(...tags: string[]): void { + writeFileSync(`${log}.releases`, tags.map((t) => `${t}\n`).join('')); +} + /** What the stand-in `gh` read on its standard input in the last `release create` that asked for it. */ export function ghStdin(): string { try { From 6187225fe463ed4697a393a89cccf50fae4fbc2d Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 06:53:45 +0100 Subject: [PATCH 18/20] plx release finishes a release whose tag is pushed and has none, and names no command to assemble; exec ignores a broken pipe on its input and no other error Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/io.ts | 7 ++- packages/lib/src/release.ts | 92 +++++++++++++++++++++++++++---------- 2 files changed, 73 insertions(+), 26 deletions(-) diff --git a/packages/lib/src/io.ts b/packages/lib/src/io.ts index 9d13ce5d..1e5a7f15 100644 --- a/packages/lib/src/io.ts +++ b/packages/lib/src/io.ts @@ -219,8 +219,11 @@ export function realIo(prompt?: Io['prompt']): Io { else reject(new ExecError(render(command, args), code, stderr, stdout)); }); if (options.input !== undefined) { - // A process that exits without reading its input fails by its exit code; the broken pipe is no error of ours. - child.stdin?.on('error', () => {}); + // A process that exits without reading its input fails by its exit code; its broken pipe is no error of ours, + // and any other failure to write fails the call. + child.stdin?.on('error', (error: NodeJS.ErrnoException) => { + if (error.code !== 'EPIPE') reject(error); + }); child.stdin?.end(options.input); } }), diff --git a/packages/lib/src/release.ts b/packages/lib/src/release.ts index fd716420..9995cca5 100644 --- a/packages/lib/src/release.ts +++ b/packages/lib/src/release.ts @@ -13,8 +13,13 @@ // remote's is git's refusal, shown as git words it // 3. find the head of `origin/main` and its version among the tags the // remote has (0.0.0 where there is none): a tag made here and not pushed -// does not count; refuse where `origin/main` holds no commit since that -// tag, a release listing nothing +// does not count. Where `origin/main` holds no commit since that tag, +// there is nothing to release, unless the tag sits on the head and GitHub +// has no release for it (`gh release view`), as after a `gh` that failed +// in step 6: the run says the tag has no release yet and, after the same +// question, creates that release with the notes the first run wrote (the +// commits since the newest of the other tags), whatever the step, and +// tags nothing // 4. compute the next version, a step of that version (`minor` by default; // the first release of a repo without tags is 0.1.0 whichever the step), // and refuse where its tag exists already @@ -105,48 +110,87 @@ export async function release(ctx: Context, dir: string, step: ReleaseStep): Pro ); const last = await commitVersion(ctx, root, main, remoteTags); const previous = last === NONE ? null : last; - const since = previous === null ? commit : `refs/tags/${previous}..${commit}`; - const commits = Number(await read(['rev-list', '--count', since])); - if (previous !== null && commits === 0) - throw new Error(`nothing to release: ${main} is at ${previous} already, with no commit since`); + const { commits, subjects } = await since(ctx, root, previous, commit); + if (previous !== null && commits === 0) { + const tagged = await read(['rev-parse', `refs/tags/${previous}^{commit}`]); + const released = await ctx.read('gh', ['release', 'view', previous], { cwd: root }).then( + () => true, + () => false, + ); + if (tagged !== commit || released) + throw new Error(`nothing to release: ${main} is at ${previous} already, with no commit since`); + return finishRelease(ctx, root, previous, commit, new Set([...remoteTags].filter((t) => t !== previous))); + } const version = nextVersion(last, step); const held = await read(['rev-parse', '-q', '--verify', `refs/tags/${version}^{commit}`]).catch(() => null); if (held !== null) throw new Error( `${version} exists already, at ${held.slice(0, 7)}: ${step} would reuse it; move or delete that tag, or take a larger step`, ); - const subjects = - previous === null ? [] : (await read(['log', '--reverse', '--format=%s', since])).split('\n').filter(Boolean); const notes = releaseNotes(previous, subjects); ctx.say( `tag ${main} (${commit.slice(0, 7)}) as ${version}${previous === null ? ', the first version' : `, ${step} of ${previous}`}: ${commits} ${commits === 1 ? 'commit' : 'commits'}`, ); - for (const subject of subjects.slice(0, SHOWN)) ctx.say(` ${subject}`); - if (subjects.length > SHOWN) ctx.say(` … and ${subjects.length - SHOWN} more`); + listed(ctx, subjects); if (!(await ctx.confirm(`tag ${main} as ${version}, push the tag and create its release?`))) throw new Error('aborted; nothing was pushed'); await ctx.apply([run('git', ['push', '--no-verify', REMOTE, `${commit}:refs/tags/${version}`], { cwd: root })]); + const url = await createRelease(ctx, root, version, notes); + return { version, previous, commit, commits, url }; +} + +/** The result line of a release. */ +export function renderReleased(r: Released): string { + const n = `${r.commits} ${r.commits === 1 ? 'commit' : 'commits'}`; + return `✓ ${r.version} tagged on ${r.commit.slice(0, 7)} (${n}${r.previous === null ? '' : ` since ${r.previous}`})${r.url === null ? '' : `: ${r.url}`}`; +} + +/** The commits of `commit` since the version `previous` (all of them, none listed, where there is none). */ +async function since(ctx: Context, root: string, previous: string | null, commit: string) { + const read = (args: string[]) => ctx.read('git', args, { cwd: root }).then((out) => out.trim()); + const range = previous === null ? commit : `refs/tags/${previous}..${commit}`; + const commits = Number(await read(['rev-list', '--count', range])); + const subjects = + previous === null ? [] : (await read(['log', '--reverse', '--format=%s', range])).split('\n').filter(Boolean); + return { commits, subjects }; +} + +/** The first subjects of a release to the narration, and the count of the rest. */ +function listed(ctx: Context, subjects: string[]): void { + for (const subject of subjects.slice(0, SHOWN)) ctx.say(` ${subject}`); + if (subjects.length > SHOWN) ctx.say(` … and ${subjects.length - SHOWN} more`); +} + +/** `gh release create` for a tag the remote has; the tag is pushed and the release is not where it fails. */ +async function createRelease(ctx: Context, root: string, version: string, notes: string): Promise { const create = run('gh', ['release', 'create', version, '--verify-tag', '--title', version, '--notes-file', '-'], { cwd: root, input: notes, }); const url = await ctx.effect(create).catch((error: unknown) => { - throw new Error( - `the tag ${version} is pushed and its release is not (${detailOf(error)}): create it with \`${finish(version, previous)}\``, - ); + throw new Error(`the tag ${version} is pushed and its release is not (${detailOf(error)}); run plx release again`); }); - return { version, previous, commit, commits, url: url?.trim() || null }; + return url?.trim() || null; } -/** The result line of a release. */ -export function renderReleased(r: Released): string { - const n = `${r.commits} ${r.commits === 1 ? 'commit' : 'commits'}`; - return `✓ ${r.version} tagged on ${r.commit.slice(0, 7)} (${n}${r.previous === null ? '' : ` since ${r.previous}`})${r.url === null ? '' : `: ${r.url}`}`; +/** + * Create the release of the newest tag, which sits on the head of `origin/main` and has none: the notes are those + * the run that pushed the tag wrote (the commits since the newest of the other tags), and nothing is tagged. + */ +async function finishRelease( + ctx: Context, + root: string, + version: string, + commit: string, + others: ReadonlySet, +): Promise { + const last = await commitVersion(ctx, root, `${REMOTE}/${DEFAULT_BRANCH}`, others); + const previous = last === NONE ? null : last; + const { commits, subjects } = await since(ctx, root, previous, commit); + ctx.say(`the tag ${version} has no release yet: create it, with the commits since ${previous ?? 'the start'}`); + listed(ctx, subjects); + if (!(await ctx.confirm(`create the release of ${version}?`))) throw new Error('aborted; nothing was created'); + const url = await createRelease(ctx, root, version, releaseNotes(previous, subjects)); + return { version, previous, commit, commits, url }; } - -/** A command that finishes a release whose tag is pushed, with its notes from a pipe or short enough to type. */ -const finish = (version: string, previous: string | null): string => - previous === null - ? `gh release create ${version} --verify-tag --title ${version} --notes 'The first release.'` - : `git log --reverse --format='- %s' ${previous}..${version} | gh release create ${version} --verify-tag --title ${version} --notes-file -`; From 0105cc24a32f677667e79f2d62b45c283103d4c8 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 07:05:47 +0100 Subject: [PATCH 19/20] Test: a finishing run says so, a failing gh release view stops it Co-Authored-By: Claude Sonnet 5.5 --- packages/cli/src/commands/release.test.ts | 30 +++++++++++++++++++++++ packages/cli/src/testing/forge.ts | 4 ++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/commands/release.test.ts b/packages/cli/src/commands/release.test.ts index 4c3fa2d3..09adb3ec 100644 --- a/packages/cli/src/commands/release.test.ts +++ b/packages/cli/src/commands/release.test.ts @@ -45,6 +45,7 @@ test('release of a repo without tags is 0.1.0: it tags origin/main, pushes the t commit: head, commits: 1, url: 'https://example.com/acme/shop/releases/tag/0.1.0', + finished: false, }); const calls = ghCalls(); assert.deepEqual(calls[0], ['auth', 'status']); @@ -250,12 +251,15 @@ test('plx release run again after a refused release creates the release of the p const { code, stdout, stderr } = await release(repo, 'major'); assert.equal(code, 0); assert.match(stderr, /the tag 1\.1\.0 has no release yet/); + assert.match(stderr, /the tag exists on the remote and was not made by this run/); + assert.match(stderr, /the step is not used/); assert.deepEqual(JSON.parse(stdout), { version: '1.1.0', previous: '1.0.0', commit: git(origin, 'rev-parse', 'main'), commits: 2, url: 'https://example.com/acme/shop/releases/tag/1.1.0', + finished: true, }); assert.equal(ghStdin(), notes, 'the notes of the first run'); assert.match(notes, /- `fix: one @acme\/ui`/); @@ -449,3 +453,29 @@ test('release in a clone that fetches another branch than main still tags the re [`1.1.0 ${head}`], ); }); + +test('a run that only finishes a release says so in its result line, and not that it tagged', async () => { + const { repo } = released('finish-line', '1.0.0', 'a change'); + await refused(repo); + const { stdout } = await plx('-y', 'release', '-C', repo); + assert.match(stdout, /^✓ 1\.1\.0 released on [0-9a-f]{7} \(1 commit since 1\.0\.0\): https:/); + assert.doesNotMatch(stdout, /tagged/); +}); + +test('a run whose gh release view fails for any reason but "release not found" stops with gh’s words and creates nothing', async () => { + const { repo, origin } = released('view-fails', '1.0.0', 'a change'); + await refused(repo); + const before = tags(origin); + ghCalls(); + process.env.FAKE_GH_VIEW_FAIL = '1'; + try { + await assert.rejects(release(repo), /gh release view 1\.1\.0 failed: error connecting to api\.github\.com/); + } finally { + delete process.env.FAKE_GH_VIEW_FAIL; + } + assert.deepEqual(tags(origin), before); + assert.deepEqual( + ghCalls().filter((c) => c[1] === 'create'), + [], + ); +}); diff --git a/packages/cli/src/testing/forge.ts b/packages/cli/src/testing/forge.ts index dc1177fb..56fd37ad 100644 --- a/packages/cli/src/testing/forge.ts +++ b/packages/cli/src/testing/forge.ts @@ -75,7 +75,9 @@ printf '\\036' >> "$FAKE_GH_LOG" case "$1 $2" in "repo view") [ -z "$FAKE_GH_NOREPO" ] || { echo "none of the git remotes point to a known GitHub host" >&2; exit 1; } ;; "auth status") [ -z "$FAKE_GH_LOGGED_OUT" ] || { echo "not logged in" >&2; exit 1; } ;; - "release view") grep -qx "$3" "$FAKE_GH_LOG.releases" 2>/dev/null || { echo "release not found" >&2; exit 1; } ;; + "release view") + [ -z "$FAKE_GH_VIEW_FAIL" ] || { echo "error connecting to api.github.com" >&2; exit 1; } + grep -qx "$3" "$FAKE_GH_LOG.releases" 2>/dev/null || { echo "release not found" >&2; exit 1; } ;; "release create") case " $* " in *" --notes-file - "*) cat > "$FAKE_GH_LOG.stdin" ;; esac [ -z "$FAKE_GH_REFUSE" ] || { echo "refused" >&2; exit 1; } From 4104399e43b739490d960b7d51dacdcf4bd03f2a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Sun, 6 Dec 2026 07:06:22 +0100 Subject: [PATCH 20/20] plx release: a run that only finishes a release says so, and only gh's answer "release not found" counts as no release Co-Authored-By: Claude Sonnet 5.5 --- packages/lib/src/release.ts | 38 ++++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/packages/lib/src/release.ts b/packages/lib/src/release.ts index 9995cca5..7bea9560 100644 --- a/packages/lib/src/release.ts +++ b/packages/lib/src/release.ts @@ -15,11 +15,13 @@ // remote has (0.0.0 where there is none): a tag made here and not pushed // does not count. Where `origin/main` holds no commit since that tag, // there is nothing to release, unless the tag sits on the head and GitHub -// has no release for it (`gh release view`), as after a `gh` that failed -// in step 6: the run says the tag has no release yet and, after the same -// question, creates that release with the notes the first run wrote (the -// commits since the newest of the other tags), whatever the step, and -// tags nothing +// has no release for it (`gh release view`, whose answer "release not +// found" is the one that counts: any other failure stops the run, with +// gh's words), as after a `gh` that failed in step 6: the run says that +// the tag has no release yet, that it exists on the remote and was not +// made by this run, and that the step is not used, and after the same +// question creates that release with the notes the first run wrote (the +// commits since the newest of the other tags) and tags nothing // 4. compute the next version, a step of that version (`minor` by default; // the first release of a repo without tags is 0.1.0 whichever the step), // and refuse where its tag exists already @@ -30,8 +32,8 @@ // normal release (not a draft, no immutability asked for) whose notes // list the subjects of the commits since the previous tag, each a code // span, and for the first release only say that it is the first; where -// gh fails, the tag stays and the error names the command that finishes -// the release +// gh fails, the tag stays and the error says that the tag is pushed and +// the release is not, and to run `plx release` again // // It moves no branch and touches no file, wherever the checkout stands and // however dirty it is: only `origin/main` is read, never the checked-out @@ -44,7 +46,7 @@ import { commitVersion } from './commitVersion.ts'; import type { Context } from './context.ts'; import { DEFAULT_BRANCH } from './declaredEnvironments.ts'; import { run } from './effects.ts'; -import { detailOf } from './io.ts'; +import { detailOf, ExecError } from './io.ts'; import { fetchRefs, REMOTE, remoteRefs } from './remote.ts'; import { preflightForge } from './version.ts'; @@ -55,6 +57,8 @@ export type ReleaseStep = (typeof RELEASE_STEPS)[number]; /** The first version of a repo without one, whichever the step. */ const FIRST = '0.1.0'; const NONE = '0.0.0'; +/** What `gh release view` says, on its standard error, of a tag that has no release (gh's own `release not found`). */ +const NOT_FOUND = /release not found/; /** How many subjects the narration lists before it counts the rest. */ const SHOWN = 20; @@ -69,6 +73,8 @@ export interface Released { commits: number; /** The release's page, as gh printed it: null where none was created. */ url: string | null; + /** True where the run only created the release of a tag an earlier run pushed. */ + finished: boolean; } /** The version after `version` by `step`, for numbers of any length. */ @@ -115,7 +121,10 @@ export async function release(ctx: Context, dir: string, step: ReleaseStep): Pro const tagged = await read(['rev-parse', `refs/tags/${previous}^{commit}`]); const released = await ctx.read('gh', ['release', 'view', previous], { cwd: root }).then( () => true, - () => false, + (error: unknown) => { + if (error instanceof ExecError && NOT_FOUND.test(error.stderr)) return false; + throw new Error(`gh release view ${previous} failed: ${detailOf(error)}; nothing was created`); + }, ); if (tagged !== commit || released) throw new Error(`nothing to release: ${main} is at ${previous} already, with no commit since`); @@ -137,13 +146,13 @@ export async function release(ctx: Context, dir: string, step: ReleaseStep): Pro throw new Error('aborted; nothing was pushed'); await ctx.apply([run('git', ['push', '--no-verify', REMOTE, `${commit}:refs/tags/${version}`], { cwd: root })]); const url = await createRelease(ctx, root, version, notes); - return { version, previous, commit, commits, url }; + return { version, previous, commit, commits, url, finished: false }; } /** The result line of a release. */ export function renderReleased(r: Released): string { const n = `${r.commits} ${r.commits === 1 ? 'commit' : 'commits'}`; - return `✓ ${r.version} tagged on ${r.commit.slice(0, 7)} (${n}${r.previous === null ? '' : ` since ${r.previous}`})${r.url === null ? '' : `: ${r.url}`}`; + return `✓ ${r.version} ${r.finished ? 'released' : 'tagged'} on ${r.commit.slice(0, 7)} (${n}${r.previous === null ? '' : ` since ${r.previous}`})${r.url === null ? '' : `: ${r.url}`}`; } /** The commits of `commit` since the version `previous` (all of them, none listed, where there is none). */ @@ -188,9 +197,12 @@ async function finishRelease( const last = await commitVersion(ctx, root, `${REMOTE}/${DEFAULT_BRANCH}`, others); const previous = last === NONE ? null : last; const { commits, subjects } = await since(ctx, root, previous, commit); - ctx.say(`the tag ${version} has no release yet: create it, with the commits since ${previous ?? 'the start'}`); + ctx.say( + `the tag ${version} has no release yet; the tag exists on the remote and was not made by this run, which only creates its release: the step is not used and nothing is tagged`, + ); + ctx.say(`the release lists the commits since ${previous ?? 'the start'}`); listed(ctx, subjects); if (!(await ctx.confirm(`create the release of ${version}?`))) throw new Error('aborted; nothing was created'); const url = await createRelease(ctx, root, version, releaseNotes(previous, subjects)); - return { version, previous, commit, commits, url }; + return { version, previous, commit, commits, url, finished: true }; }