Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 52 additions & 19 deletions .github/workflows/release-start.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ on:
type: string
required: true
cli-dev:
description: "How this repository runs cli-dev, e.g. `pnpm exec cli-dev` or `npx -y -p @wirecat/cli-base@x.y.z cli-dev`"
description: "How this repository runs cli-dev (cli-base 0.98.0 or later), e.g. `pnpm exec cli-dev` or `npx -y -p @wirecat/cli-base@x.y.z cli-dev`"
type: string
default: pnpm exec cli-dev
unreleased:
Expand All @@ -24,7 +24,7 @@ on:
type: string
default: ""
after-raise:
description: "Shell run after the version number changes, before it is committed; $VERSION is the new one"
description: "Shell run once after the version number changes, before it is committed; $VERSION is the new one"
type: string
default: ""
release-inputs:
Expand Down Expand Up @@ -113,31 +113,49 @@ jobs:
exit 1
fi

from=$version
# Asked once: a version that reaches npm during the run must not be folded into and then raised as taken.
taken=""
if published "$version"; then taken=1; fi
$CLI_DEV changelog restore --unreleased "$UNRELEASED"
published "$version" || $CLI_DEV changelog fold --version "$version" --unreleased "$UNRELEASED"
[ -n "$taken" ] || $CLI_DEV changelog fold --version "$version" --unreleased "$UNRELEASED"

latest=$(npm view "$package" version --prefer-online 2>/dev/null || true)
versions=$(npm view "$package" versions --json --prefer-online 2>/dev/null || true)
# Raises $1 to $2 in package.json, src/version.ts and the CHANGELOG heading. With $3 set, npm has $1: its
# section stays as published, and the unreleased one becomes $2, or a new section the fragments fill.
# Every file is checked before any is written.
renumber() {
node -e 'const fs = require("fs"); const [o, n, taken, unreleased] = process.argv.slice(1)
const swap = (file, from, to, optional) => {
if (optional && !fs.existsSync(file)) return
const text = fs.readFileSync(file, "utf8")
const swap = (file, text, from, to) => {
if (!text.includes(from)) throw new Error(`${file} has no ${JSON.stringify(from.trim())} to raise ${o} to ${n}`)
fs.writeFileSync(file, text.replace(from, to))
return text.replace(from, to)
}
swap("package.json", `"version": "${o}"`, `"version": "${n}"`)
swap("src/version.ts", `VERSION = "${o}"`, `VERSION = "${n}"`, true)
const today = new Date().toLocaleDateString("en-GB").replaceAll("/", ".")
if (taken) swap("CHANGELOG.md", `\n## ${unreleased}\n`, `\n## ${n} — ${today}\n`)
else swap("CHANGELOG.md", `\n## ${o} — `, `\n## ${n} — `)' "$1" "$2" "$3" "$UNRELEASED"
if [ -n "$AFTER_RAISE" ]; then VERSION=$2 sh -c "$AFTER_RAISE"; fi
const writes = [["package.json", swap("package.json", fs.readFileSync("package.json", "utf8"), `"version": "${o}"`, `"version": "${n}"`)]]
if (fs.existsSync("src/version.ts")) {
writes.push(["src/version.ts", swap("src/version.ts", fs.readFileSync("src/version.ts", "utf8"), `VERSION = "${o}"`, `VERSION = "${n}"`)])
}
const log = fs.readFileSync("CHANGELOG.md", "utf8")
const top = log.match(/^## .*$/m)?.[0] ?? ""
const heading = `\n## ${n} — ${today}\n`
const section = `\n## ${unreleased}\n`
let next
if (taken && log.includes(section)) next = swap("CHANGELOG.md", log, section, heading)
else if (taken) next = swap("CHANGELOG.md", log, "\n## ", `${heading}\n## `)
else if (top.startsWith(`## ${o} — `)) next = swap("CHANGELOG.md", log, `\n## ${o} — `, `\n## ${n} — `)
else throw new Error(`CHANGELOG.md top section is ${JSON.stringify(top)} — date it as ${o} first`)
writes.push(["CHANGELOG.md", next])
for (const [file, text] of writes) fs.writeFileSync(file, text)' "$1" "$2" "$3" "$UNRELEASED"
}
unreleased() {
awk -v title="## $UNRELEASED" '/^## /{if (u) exit; u = ($0 == title); next} u && NF {found = 1; exit} END {exit !found}' CHANGELOG.md
}
count=$(find changes -maxdepth 1 -type f -name '*.md' ! -name README.md 2>/dev/null | wc -l)
# The changes/ fragments go into the version's section, which may then need a higher level (an Added is a
# minor, a stable break a major from 1.0.0 on).
fragments() {
[ -n "$(find changes -maxdepth 1 -type f -name '*.md' ! -name README.md 2>/dev/null)" ] || return 0
$CLI_DEV changelog fragments --collect "$version"
collect() {
[ "$count" -eq 0 ] || $CLI_DEV changelog fragments --collect "$version"
levelled=$($CLI_DEV changelog level --next "$version")
[ "$levelled" != "$version" ] || return 0
levelled=$($CLI_DEV next-version "$levelled" "$latest" "$versions")
Expand All @@ -146,20 +164,35 @@ jobs:
why="${why:+$why; }the changelog needs $levelled"
version=$levelled
}
next=$($CLI_DEV next-version "$version" "$latest" "$versions")
# A version npm has starts again from its patch: the entries after it, not its own section, decide the
# level. A taken x.0.0 would otherwise stay a major.
want=$version
if [ -n "$taken" ]; then
case "$version" in
*-*) ;;
*) want=$(node -p 'const [a, b, c] = process.argv[1].split(".").map(Number); `${a}.${b}.${c + 1}`' "$version") ;;
esac
fi
next=$($CLI_DEV next-version "$want" "$latest" "$versions")
why=""
if [ "$next" != "$version" ]; then
taken=""
if published "$version"; then taken=1; why="$version is already on npm"; else why="$version is not above npm's latest $latest"; fi
if [ -n "$taken" ]; then why="$version is already on npm"; else why="$version is not above npm's latest $latest"; fi
if [ -n "$taken" ] && [ "$count" -eq 0 ] && ! unreleased; then
echo "::error::$why and nothing is unreleased — add a $UNRELEASED section or a changes/ fragment first"
exit 1
fi
echo "$why — releasing $next instead"
renumber "$version" "$next" "$taken"
version=$next
collect
elif [ "$count" -gt 0 ] && [ -z "$taken" ]; then
collect
fi
fragments
if [ -n "$latest" ] && [ "${version%%.*}" != "${latest%%.*}" ] && [ "$MAJOR" != "true" ]; then
echo "::error::$version raises the major version over npm's $latest — start the release with major allowed if that is meant"
exit 1
fi
if [ "$version" != "$from" ] && [ -n "$AFTER_RAISE" ]; then VERSION=$version sh -c "$AFTER_RAISE"; fi

top=$(sed -n '/^## /{p;q;}' CHANGELOG.md)
case "$top" in
Expand Down
9 changes: 9 additions & 0 deletions changes/fix-release-start-fragments.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### Fixed

- **The shared Start release workflow agrees with `bin/release` on the `changes/` fragments.** When npm already had
the version in `package.json` and every entry was in `changes/` fragments, `release-start.yml` failed with
`CHANGELOG.md has no "## Unreleased" to raise …`. Now the new version gets a new section the fragments fill, and
the run stops only when there are no fragments and the Unreleased section is missing or empty. A
published `x.0.0` is followed by its next patch, raised only when the entries need more, so `1.0.0` with a fix
gives `1.0.1` instead of stopping at a major. Every file is checked before any is written, and `after-raise` runs
once, with the version that ships. The workflow needs cli-dev from cli-base 0.98.0 or later (#714).
9 changes: 7 additions & 2 deletions docs/dev/release-workflow.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,13 @@ Status: proposed. No repository calls it yet; `bin/release` still works and stay
2. `cli-dev changelog restore`: entries that missed the last release go back to Unreleased.
3. `cli-dev changelog fold`, when the dated version is not on npm yet: Unreleased joins it.
4. `cli-dev next-version`: when npm already has the version, or a higher one, it raises `package.json`,
`src/version.ts` (if present) and the changelog heading. An `after-raise` command runs next (whatsapp-cli syncs
its engine packages there).
`src/version.ts` (if present) and the changelog heading, as `bin/release` does. A version npm has keeps its
section as published and is followed by its next patch: the Unreleased section, or a new section, takes the new
number. `cli-dev changelog fragments --collect` puts the `changes/` fragments into it, and
`cli-dev changelog level --next` raises it only when the entries need more (`1.0.0` with a fix gives `1.0.1`,
with an Added `1.1.0`). With no fragment and no Unreleased entry the run stops. An `after-raise` command runs
once after the raise, with the version that ships (whatsapp-cli syncs its engine packages there). The `cli-dev`
the caller runs must be cli-base 0.98.0 or later, which has `changelog level`.
5. Requires a dated top section and a version that is not on npm. Runs the `check` command (for example the
live check, WC-REL-17).
6. If steps 2 to 4 changed files: one pull request `chore(release): <version>`, merged when GitHub says it can merge
Expand Down
225 changes: 225 additions & 0 deletions scripts/release-start.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
import { execFileSync, spawnSync } from "node:child_process"
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { build } from "esbuild"
import { afterAll, beforeAll, describe, expect, it } from "vitest"
import { parse } from "yaml"

const root = join(import.meta.dirname, "..")
const dirs: string[] = []
let cliDev = ""

type Step = { name?: string; run?: string }
const workflow = parse(readFileSync(join(root, ".github/workflows/release-start.yml"), "utf8")) as {
jobs: { prepare: { steps: Step[] } }
}
const settle = workflow.jobs.prepare.steps.find((step) => step.name === "settle the version")?.run ?? ""

// The test shards do not build: the dev bin is bundled from src/ instead, inside the worktree so its packages resolve.
beforeAll(async () => {
mkdirSync(join(root, "node_modules/.cache"), { recursive: true })
const dist = mkdtempSync(join(root, "node_modules/.cache/release-start-dist-"))
dirs.push(dist)
cliDev = join(dist, "bin.js")
await build({
entryPoints: [join(root, "src/dev/bin.ts")],
outfile: cliDev,
bundle: true,
platform: "node",
format: "esm",
packages: "external",
logLevel: "silent",
})
}, 60_000)
afterAll(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
})

const git = (cwd: string, ...args: string[]) =>
execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.com", ...args], { cwd, encoding: "utf8" })

type Repo = {
version: string
published: string[]
changelog: string
fragment?: string
major?: boolean
unreleased?: string
versionTs?: boolean
}

// The published versions are tagged on a first commit, without the Unreleased section, and the changelog under test
// lands on a second, as on main.
const start = ({
version,
published,
changelog,
fragment,
major = false,
unreleased = "Unreleased",
versionTs,
}: Repo) => {
const work = mkdtempSync(join(tmpdir(), "release-start-"))
dirs.push(work)
const origin = join(work, "origin.git")
const repo = join(work, "repo")
const stubs = join(work, "stubs")
mkdirSync(stubs)
git(work, "init", "-q", "--bare", "-b", "main", origin)
git(work, "clone", "-q", origin, repo)
const tagged = published.at(-1) ?? version
writeFileSync(join(repo, "package.json"), `${JSON.stringify({ name: "@wirecat/x", version: tagged }, null, 2)}\n`)
writeFileSync(
join(repo, "CHANGELOG.md"),
changelog.replace(new RegExp(`^## ${unreleased}\n[\\s\\S]*?(?=^## )`, "m"), ""),
)
if (versionTs) {
mkdirSync(join(repo, "src"))
writeFileSync(join(repo, "src/version.ts"), `export const VERSION = "${version}"\n`)
}
git(repo, "add", "-A")
git(repo, "commit", "-q", "-m", "init")
for (const tag of published) git(repo, "tag", `v${tag}`)
writeFileSync(join(repo, "package.json"), `${JSON.stringify({ name: "@wirecat/x", version }, null, 2)}\n`)
writeFileSync(join(repo, "CHANGELOG.md"), changelog)
if (fragment) {
mkdirSync(join(repo, "changes"))
writeFileSync(join(repo, "changes/feat-x.md"), fragment)
}
git(repo, "add", "-A")
git(repo, "commit", "-q", "--allow-empty", "-m", "next")
git(repo, "push", "-q", "--tags", "origin", "main")

const latest = published.at(-1) ?? ""
const views = published.map((one) => `"view @wirecat/x@${one} version "*`).join("|")
writeFileSync(
join(stubs, "npm"),
[
"#!/bin/sh",
'case "$*" in',
` *" versions "*) echo '${JSON.stringify(published)}' ;;`,
` "view @wirecat/x version "*) echo ${latest} ;;`,
...(views ? [` ${views}) echo yes ;;`] : []),
" *) exit 1 ;;",
"esac",
"",
].join("\n"),
)
chmodSync(join(stubs, "npm"), 0o755)
const output = join(work, "output")
writeFileSync(output, "")
const run = spawnSync("sh", ["-c", settle], {
cwd: repo,
encoding: "utf8",
env: {
...process.env,
PATH: `${stubs}:${process.env.PATH}`,
CLI_DEV: `node ${cliDev}`,
UNRELEASED: unreleased,
AFTER_RAISE: 'echo "$VERSION" >> raised.log',
CHECK: "",
MAJOR: String(major),
GITHUB_OUTPUT: output,
},
})
const read = (file: string) => (existsSync(join(repo, file)) ? readFileSync(join(repo, file), "utf8") : "")
return { run, read, output: readFileSync(output, "utf8") }
}

const PUBLISHED = "# Changelog\n\n## 0.131.0 — 22.11.2026\n\n### Fixed\n\n- **Old.** Shipped in 0.131.0.\n"
const above = (section: string) => PUBLISHED.replace("## 0.131.0", `${section}\n\n## 0.131.0`)

// Each run starts node several times; a loaded machine takes seconds for each.
describe("release-start.yml settles the version as bin/release does", { timeout: 60_000 }, () => {
it("finds the step's script", () => {
expect(settle).toContain("changelog level --next")
})

it("gives fragments a new section and leaves the published one as npm has it", () => {
const { run, read, output } = start({
version: "0.131.0",
published: ["0.131.0"],
changelog: PUBLISHED,
fragment: "### Fixed\n\n- **New.** Merged after 0.131.0.\n",
})
expect(run.status).toBe(0)
expect(output).toContain("version=0.131.1\n")
expect(JSON.parse(read("package.json")).version).toBe("0.131.1")
const log = read("CHANGELOG.md")
expect(log).toMatch(/## 0\.131\.1 — [\d.]+\n\n### Fixed\n\n- \*\*New\.\*\*/)
expect(log).toContain("## 0.131.0 — 22.11.2026\n\n### Fixed\n\n- **Old.** Shipped in 0.131.0.\n")
expect(log.split("\n## 0.131.0")[0]).not.toContain("Old")
expect(read("changes/feat-x.md")).toBe("")
})

it("follows a published 1.0.0 with a patch when only a fix is unreleased", () => {
const { run, read, output } = start({
version: "1.0.0",
published: ["0.131.0", "1.0.0"],
changelog: above(
"## Unreleased\n\n### Fixed\n\n- **Fix.** After 1.0.0.\n\n## 1.0.0 — 23.11.2026\n\n### Added\n\n- **One.** A.",
),
})
expect(run.status).toBe(0)
expect(output).toContain("version=1.0.1\n")
expect(read("CHANGELOG.md")).toMatch(/## 1\.0\.1 — [\d.]+\n\n### Fixed\n\n- \*\*Fix\.\*\*/)
})

it("follows a published 1.0.0 with a minor when a fragment adds something", () => {
const { run, read, output } = start({
version: "1.0.0",
published: ["0.131.0", "1.0.0"],
changelog: above("## 1.0.0 — 23.11.2026\n\n### Added\n\n- **One.** A."),
fragment: "### Added\n\n- **Pages.** Pages are written.\n",
})
expect(run.status).toBe(0)
expect(output).toContain("version=1.1.0\n")
expect(read("CHANGELOG.md")).toMatch(/## 1\.1\.0 — [\d.]+\n\n### Added\n\n- \*\*Pages\.\*\*/)
expect(read("CHANGELOG.md")).not.toContain("## 1.0.1")
})

it("raises src/version.ts under a custom title and runs after-raise once, with the version that ships", () => {
const { run, read, output } = start({
version: "1.0.0",
published: ["0.131.0", "1.0.0"],
changelog: above("## Next\n\n### Added\n\n- **Two.** B.\n\n## 1.0.0 — 23.11.2026\n\n### Added\n\n- **One.** A."),
unreleased: "Next",
versionTs: true,
})
expect(run.status).toBe(0)
expect(output).toContain("version=1.1.0\n")
expect(read("src/version.ts")).toBe('export const VERSION = "1.1.0"\n')
expect(read("raised.log")).toBe("1.1.0\n")
expect(read("CHANGELOG.md")).toMatch(/## 1\.1\.0 — [\d.]+\n\n### Added\n\n- \*\*Two\.\*\*/)
})

it("refuses an empty Unreleased section on a published version", () => {
const { run, read } = start({ version: "0.131.0", published: ["0.131.0"], changelog: above("## Unreleased") })
expect(run.status).toBe(1)
expect(run.stdout).toContain("0.131.0 is already on npm and nothing is unreleased")
expect(JSON.parse(read("package.json")).version).toBe("0.131.0")
})

it("refuses a published version with nothing unreleased instead of renaming its section", () => {
const { run, read } = start({ version: "0.131.0", published: ["0.131.0"], changelog: PUBLISHED })
expect(run.status).toBe(1)
expect(run.stdout).toContain("0.131.0 is already on npm and nothing is unreleased")
expect(read("CHANGELOG.md")).toBe(PUBLISHED)
})

it("stops a major the fragments need unless major is allowed", () => {
const repo = {
version: "1.0.0",
published: ["0.131.0", "1.0.0"],
changelog: above("## 1.0.0 — 23.11.2026\n\n### Added\n\n- **One.** A."),
fragment: "### Removed\n\n- **Gone.** A stable name is removed.\n",
}
const refused = start(repo)
expect(refused.run.status).toBe(1)
expect(refused.run.stdout).toContain("2.0.0 raises the major version over npm's 1.0.0")
const allowed = start({ ...repo, major: true })
expect(allowed.run.status).toBe(0)
expect(allowed.output).toContain("version=2.0.0\n")
})
})