diff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.ts index 4254ad51..6206ea12 100644 --- a/packages/cli/src/commands/index.ts +++ b/packages/cli/src/commands/index.ts @@ -14,6 +14,8 @@ 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 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'; @@ -28,4 +30,6 @@ export const commands: ((program: Command) => void)[] = [ requirements, changeset, deploy, + promote, + release, ]; diff --git a/packages/cli/src/commands/promote.test.ts b/packages/cli/src/commands/promote.test.ts new file mode 100644 index 00000000..8e70db70 --- /dev/null +++ b/packages/cli/src/commands/promote.test.ts @@ -0,0 +1,275 @@ +import assert from 'node:assert/strict'; +import { mkdirSync, 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}`); +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'); +}); + +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); + 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/promote.ts b/packages/cli/src/commands/promote.ts new file mode 100644 index 00000000..f90f374d --- /dev/null +++ b/packages/cli/src/commands/promote.ts @@ -0,0 +1,30 @@ +// 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. 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 +// 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/cli/src/commands/release.test.ts b/packages/cli/src/commands/release.test.ts new file mode 100644 index 00000000..09adb3ec --- /dev/null +++ b/packages/cli/src/commands/release.test.ts @@ -0,0 +1,481 @@ +import assert from 'node:assert/strict'; +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, + 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]); + +/** 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); + ghReleased(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', + finished: false, + }); + const calls = ghCalls(); + assert.deepEqual(calls[0], ['auth', 'status']); + 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 () => { + 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().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|--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 () => { + 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).filter((r) => r.startsWith('refs/heads'))]; + 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'), /'huge' is invalid for argument 'step'/); + 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); +}); + +/** `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 { + 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.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`/); + 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'); + 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); + return 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'), + [], + ); +}); + +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, 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))); + 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/); +}); + +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}`], + ); +}); + +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/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/cli/src/testing/forge.ts b/packages/cli/src/testing/forge.ts new file mode 100644 index 00000000..56fd37ad --- /dev/null +++ b/packages/cli/src/testing/forge.ts @@ -0,0 +1,160 @@ +// 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 } { + ghReleased(); + 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 +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 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; } + echo "$3" >> "$FAKE_GH_LOG.releases" + 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: the arguments of each call. */ +export function ghCalls(): string[][] { + let text = ''; + try { + text = readFileSync(log, 'utf8'); + } catch {} + writeFileSync(log, ''); + return text + .split('\x1e') + .filter(Boolean) + .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 { + 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 = ''; + 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; + } +} + +/** 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}`); +} 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"] } 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/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/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/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'); +}); 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/index.ts b/packages/lib/src/index.ts index 2e70cfa2..470bde1c 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'; @@ -160,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, @@ -182,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/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, + ); +}); diff --git a/packages/lib/src/io.ts b/packages/lib/src/io.ts index bfb29c8d..1e5a7f15 100644 --- a/packages/lib/src/io.ts +++ b/packages/lib/src/io.ts @@ -218,7 +218,14 @@ 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; 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); + } }), readFile: (path) => readFile(path, 'utf8'), writeFile: (path, content) => writeFile(path, content), 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) => diff --git a/packages/lib/src/promote.ts b/packages/lib/src/promote.ts new file mode 100644 index 00000000..815595fd --- /dev/null +++ b/packages/lib/src/promote.ts @@ -0,0 +1,126 @@ +// 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. 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, 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. */ +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, as far as the checkout's history goes. */ + commits: number; + outcome: 'created' | 'fast-forwarded' | 'unchanged'; +} + +const head = (branch: string) => `refs/heads/${branch}`; +const tracking = (branch: string) => `refs/remotes/${REMOTE}/${branch}`; + +/** 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 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); + if (!environment) + throw new UsageError( + `${name} is no declared environment; the repo declares ${declared.environments.map((e) => e.name).join(', ')}`, + ); + const { branch, source } = environment; + + const there = await remoteRefs(ctx, root, [head(source), head(branch)]); + if (!there.has(head(source))) + throw new Error( + environment.promotesFrom === source + ? `${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 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 ((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, + branch, + source, + from, + to, + commits, + outcome: from === null ? 'created' : 'fast-forwarded', + }; + + const n = `${commits} ${commits === 1 ? 'commit' : 'commits'}`; + ctx.say( + 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}:${head(branch)}`], { cwd: root })]); + 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'})`; +} diff --git a/packages/lib/src/release.ts b/packages/lib/src/release.ts new file mode 100644 index 00000000..7bea9560 --- /dev/null +++ b/packages/lib/src/release.ts @@ -0,0 +1,208 @@ +// 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. 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. 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`, 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 +// 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 +// --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, and for the first release only say that it is the first; where +// 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 +// 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, ExecError } from './io.ts'; +import { fetchRefs, REMOTE, remoteRefs } from './remote.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'; +/** 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; + +/** 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; + /** 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. */ +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; the first release lists none. */ +export const releaseNotes = (previous: string | null, subjects: string[]): string => + [ + 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.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 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 { 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, + (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`); + 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 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'}`, + ); + 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, 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} ${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). */ +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)}); run plx release again`); + }); + return url?.trim() || null; +} + +/** + * 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; 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, finished: true }; +} 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]), + ); +} 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); 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"