// Zero-dependency release-PR updater. // // Reads the conventional commits since the latest tag, decides the next // semver bump, and creates or updates a draft "release PR" against the // default branch. The PR body is a generated changelog plus a contributor // list pulled from the GitHub API. // // Env: // GITHUB_TOKEN required for PR create/update; optional for read-only // contributor + PR lookups (public endpoints work // unauthenticated against public repos, just with a // 60 req/hr ceiling). // GITHUB_REPOSITORY "owner/repo" (set automatically inside Actions) // DRY_RUN if set, skip git push and GitHub writes // RELEASE_BASE override base branch (default: current branch) // PACKAGES newline-separated list of publishable workspace // paths/globs; when set, the release bumps every // resolved workspace's package.json in lockstep // PRERELEASE one-shot prerelease identifier (e.g. "beta", "rc", // "0"); when set, the release cuts or continues a // prerelease instead of a stable version // MODE "lockstep" (default) or "independent"; independent // mode computes a per-package release plan instead of // bumping every workspace to one shared version // SCOPES newline-separated ": ..." // overrides for routing commit scopes to workspaces // in independent mode // TITLE release PR title and commit message template, with // `{version}` in lockstep mode and `{count}` / // `{packages}` in independent mode // PR_NOTES Markdown kept in a marked block of the release PR // preamble and refreshed on every run, with `{base}` // and, in lockstep mode, `{version}` import process from 'node:process' import { execFileSync } from 'node:child_process' import { Buffer } from 'node:buffer' import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { runMain } from './_cli.ts' import { makePkgFormatter } from './pkg-format.ts' import { buildScopeMap, compareSemver, isPrerelease, parseScopesInput, prereleaseIdentifier, resolveCurrentVersion, resolveWorkspaces, type Workspace } from './_workspaces.ts' import { buildDependencyGraph, DEPENDENCY_FIELDS, propagateReleases, type BumpLevel } from './_dependency-graph.ts' export interface Commit { hash: string shortHash: string message: string type: string scope: string description: string isBreaking: boolean author: { name: string, email: string } references: string[] /** Hash of the commit this one reverts, when its body names one. */ revert?: string } interface Contributor { name: string username: string isFirstTime: boolean } const TYPE_TITLES: Record = { feat: '🚀 Enhancements', perf: '🔥 Performance', fix: '🩹 Fixes', refactor: '💅 Refactors', docs: '📖 Documentation', build: '📦 Build', types: '🌊 Types', chore: '🏡 Chore', examples: '🏀 Examples', test: '✅ Tests', style: '🎨 Styles', ci: '🤖 CI', revert: '⏪ Reverts', } const KNOWN_TYPES = new Set(Object.keys(TYPE_TITLES)) const isReleaseWorthy = (c: Commit) => KNOWN_TYPES.has(c.type) && !(c.type === 'chore' && c.scope === 'deps') const MAX_BUFFER = 256 * 1024 * 1024 const git = (...args: string[]) => execFileSync('git', args, { encoding: 'utf8', maxBuffer: MAX_BUFFER }).trim() function getRepo (): { owner: string, repo: string } { const env = process.env.GITHUB_REPOSITORY if (env && env.includes('/')) { const [owner, repo] = env.split('/') return { owner: owner!, repo: repo! } } const url = git('remote', 'get-url', 'origin') const match = url.match(/[/:]([^/:]+)\/([^/]+?)(?:\.git)?$/) if (!match) throw new Error(`Cannot parse repo from remote url: ${url}`) return { owner: match[1]!, repo: match[2]! } } function getCurrentBranch (): string { return process.env.RELEASE_BASE || git('rev-parse', '--abbrev-ref', 'HEAD') } export interface Tag { name: string, ref: string } export function getAllTags (): string[] { try { return execFileSync( 'git', ['for-each-ref', '--sort=-creatordate', '--format=%(refname:strip=2)', 'refs/tags'], { encoding: 'utf8', maxBuffer: MAX_BUFFER }, ).split('\n').map(s => s.trim()).filter(Boolean) } catch { return [] } } function getLatestTag (): Tag | null { // Pick the most recent semver-shaped tag by creation date. We deliberately // don't use `git describe`, which only finds tags reachable from HEAD; the // previous release tag isn't always an ancestor of HEAD (e.g. release // branches that were never merged back). // // We return both the short name (for display / URLs) and the fully // qualified ref (`refs/tags/...`) so subsequent git calls aren't confused // by branches sharing the tag name. const name = getAllTags().find(t => /^v?\d+\.\d+\.\d+/.test(t)) return name ? { name, ref: `refs/tags/${name}` } : null } // Numeric semver comparison over the `X.Y.Z` core, with a bare version // sorting above any suffixed one (prerelease or build metadata) at the // same core. Suffixes at the same core version are not further ordered; // tag selection only needs "highest stable wins", not full semver // precedence. function compareVersions (a: string, b: string): number { const parse = (v: string) => { const m = v.match(/^(\d+)\.(\d+)\.(\d+)(.*)$/)! return { core: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] !== '' } } const pa = parse(a) const pb = parse(b) for (let i = 0; i < 3; i++) { if (pa.core[i]! !== pb.core[i]!) return pa.core[i]! - pb.core[i]! } return Number(pb.pre) - Number(pa.pre) } function highestVersionTag (tags: string[], extractVersion: (tag: string) => string | null): Tag | null { let best: { name: string, version: string } | null = null for (const tag of tags) { const version = extractVersion(tag) if (version === null) continue if (!best || compareVersions(version, best.version) > 0) best = { name: tag, version } } return best ? { name: best.name, ref: `refs/tags/${best.name}` } : null } /** * Latest release tag for a specific package, using the `@X.Y.Z` * convention (`fontaine@0.8.0`, `@nuxt/kit@5.0.0`). "Latest" means the * highest version by numeric semver comparison, regardless of the order * `tags` is supplied in: tag creation date can diverge from version order * (retagging, backported releases, tag imports). Bare version-shaped tags * (`0.2.3`) and lockstep tags (`v0.6.0`) never match a package. */ export function latestTagForPackage (pkgName: string, tags: string[]): Tag | null { const escaped = pkgName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') const re = new RegExp(`^${escaped}@(\\d+\\.\\d+\\.\\d+(?:[-+].*)?)$`) return highestVersionTag(tags, tag => tag.match(re)?.[1] ?? null) } /** * Latest lockstep `vX.Y.Z` tag. Used as the commit-range fallback for a * package with no `@*` tag yet, i.e. the first independent release * after a lockstep history. "Latest" is the highest version by numeric * semver comparison, not list order. Bare version-shaped tags are * deliberately excluded: they can't be attributed to any package or * release mode. */ export function latestLockstepTag (tags: string[]): Tag | null { return highestVersionTag(tags, tag => tag.match(/^v(\d+\.\d+\.\d+(?:[-+].*)?)$/)?.[1] ?? null) } function parseCommit (raw: string): Commit | null { const [hash, shortHash, authorName, authorEmail, subject, body] = raw.split('\x1f') if (!hash || !shortHash || !subject) return null const revert = (body || '').match(/\breverts\s+(?:commit\s+)?([0-9a-f]{7,40})\b/i)?.[1]?.toLowerCase() // `git revert` and GitLab generate `Revert ""`; treat it // as a `revert:` commit carrying the original's scope and description. const reverted = subject.match(/^Revert "(.+)"$/)?.[1] const header = (reverted ?? subject).match(/^(\w+)(?:\(([^)]+)\))?(!)?:\s*(.+)$/) if (!header) { return { hash, shortHash, message: subject, type: reverted ? 'revert' : '', scope: '', description: reverted ?? subject, isBreaking: false, author: { name: authorName || '', email: authorEmail || '' }, references: [], revert, } } const [, parsedType, scope = '', bang, rawDescription] = header const type = reverted ? 'revert' : parsedType!.toLowerCase() const isBreaking = Boolean(bang) || /BREAKING[ -]CHANGE/.test(body || '') const references: string[] = [] for (const m of (body || '').matchAll(/(?:closes?|fixes?|resolves?)\s+#(\d+)/gi)) { references.push(`#${m[1]}`) } for (const m of subject.matchAll(/\(#(\d+)\)/g)) { references.push(`#${m[1]}`) } // Drop trailing `(#nnn)` PR refs from the description: we'll re-attach them // in the rendered changelog from the deduped `references` list. const description = rawDescription!.replace(/\s*\(#\d+\)\s*$/, '').trim() return { hash, shortHash, message: subject, type, scope, description, isBreaking, author: { name: authorName || '', email: authorEmail || '' }, references: [...new Set(references)], revert, } } /** * Collapse revert pairs: a revert whose target is in the same range drops * out along with the target, since together they change nothing. A chain of * reverts resolves to the commit it ultimately targets, which survives when * an even number of reverts leaves it applied. A revert whose target shipped * earlier is kept and rendered as an ordinary entry. */ export function dropRevertedCommits (commits: Commit[]): Commit[] { const find = (prefix: string) => commits.find(c => c.hash.startsWith(prefix)) const paired = new Set() const revertCount = new Map() for (const commit of commits) { if (commit.type !== 'revert' || !commit.revert) continue let root = find(commit.revert) if (!root) continue const seen = new Set([commit.hash]) while (root.type === 'revert' && root.revert && !seen.has(root.hash)) { seen.add(root.hash) const next = find(root.revert) if (!next) break root = next } paired.add(commit.hash) revertCount.set(root.hash, (revertCount.get(root.hash) ?? 0) + 1) } if (!paired.size) return commits return commits.filter(c => !paired.has(c.hash) && (revertCount.get(c.hash) ?? 0) % 2 === 0, ) } /** * Drop commits whose subject already appears on the other side of a * diverged range. The previous release tag is not always an ancestor of * HEAD (a `4.x` maintenance line tagged after `main` moved on to `5.0`), * so `tag..HEAD` includes everything since the branches diverged, most of * which shipped already as cherry-picks. Subjects are matched exactly: * a cherry-pick keeps its subject but not its hash or patch id. */ export function dropAlreadyReleased (commits: Commit[], releasedSubjects: Set): Commit[] { if (releasedSubjects.size === 0) return commits return commits.filter(c => !releasedSubjects.has(c.message)) } /** Subjects of commits reachable from `ref` but not from HEAD. */ function subjectsOnlyOn (ref: string): Set { try { const stdout = execFileSync( 'git', ['log', `HEAD..${ref}`, '--pretty=format:%s'], { encoding: 'utf8', maxBuffer: MAX_BUFFER }, ) return new Set(stdout.split('\n').map(s => s.trim()).filter(Boolean)) } catch { return new Set() } } /** Committer date of the commit a tag points at, as an ISO 8601 string. */ function tagDate (ref: string): string { return execFileSync('git', ['log', '-1', '--format=%cI', ref], { encoding: 'utf8', maxBuffer: MAX_BUFFER }).trim() } function getCommitsSince (tag: Tag | null): Commit[] { const range = tag ? `${tag.ref}..HEAD` : 'HEAD' // Merging the base branch into a release branch (or a tag that isn't an // ancestor of HEAD) puts commits older than the tag inside `tag..HEAD`; // they shipped in an earlier release, so cut the range at the tag's date. const since = tag ? tagDate(tag.ref) : null const stdout = execFileSync( 'git', ['log', range, ...(since ? ['--since', since] : []), `--pretty=format:%H%x1f%h%x1f%an%x1f%ae%x1f%s%x1f%b%x1e`], { encoding: 'utf8', maxBuffer: MAX_BUFFER }, ) const commits = stdout .split('\x1e') .map(s => s.replace(/^\n/, '')) .filter(Boolean) .map(parseCommit) .filter((c): c is Commit => c !== null) return dropRevertedCommits(tag ? dropAlreadyReleased(commits, subjectsOnlyOn(tag.ref)) : commits) } export function determineBump (commits: Commit[]): BumpLevel { if (commits.some(c => c.isBreaking)) return 'major' if (commits.some(c => c.type === 'feat')) return 'minor' return 'patch' } export function incVersion (version: string, bump: 'major' | 'minor' | 'patch', prerelease?: string): string { const match = version.match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9a-zA-Z.-]+))?$/) if (!match) { throw new Error( `Cannot bump version "${version}": expected strict "X.Y.Z" semver, optionally with a prerelease suffix. uppt does not support build-metadata versions.`, ) } let [x, y, z] = match.slice(1, 4).map(Number) as [number, number, number] const currentPre = match[4] const bumpBase = () => { if (x === 0) { if (bump === 'major') { bump = 'minor' } else if (bump === 'minor') { bump = 'patch' } } if (bump === 'major') { x += 1; y = 0; z = 0 } else if (bump === 'minor') { y += 1; z = 0 } else { z += 1 } } if (prerelease === undefined) { // A prerelease already reserved its target version, so graduating it // drops the suffix without a further bump: `feat:` on `5.0.0-0` must // produce `5.0.0`, not `5.1.0`. if (currentPre === undefined) bumpBase() return `${x}.${y}.${z}` } // The identifier flows into branch/ref names and, downstream, gh argv; // pin it to a safe alphabet to rule out flag injection and ref confusion. if (!/^[a-z0-9][a-z0-9.-]*$/.test(prerelease)) { throw new Error( `Invalid prerelease identifier "${prerelease}": expected lowercase alphanumerics, "." or "-" after the first character (e.g. "beta", "rc", "0").`, ) } const isBareNumber = /^\d+$/.test(prerelease) if (currentPre === undefined) { bumpBase() return isBareNumber ? `${x}.${y}.${z}-0` : `${x}.${y}.${z}-${prerelease}.0` } // A bare-number identifier is a style selector for the `-N` form, not a // counter seed: new lines always start at 0. if (isBareNumber) { return /^\d+$/.test(currentPre) ? `${x}.${y}.${z}-${Number(currentPre) + 1}` : `${x}.${y}.${z}-0` } const dot = currentPre.lastIndexOf('.') const head = dot === -1 ? currentPre : currentPre.slice(0, dot) const tail = dot === -1 ? '' : currentPre.slice(dot + 1) if (head === prerelease && /^\d+$/.test(tail)) { return `${x}.${y}.${z}-${prerelease}.${Number(tail) + 1}` } return `${x}.${y}.${z}-${prerelease}.0` } export interface PackageRelease { /** Package name, as declared in its `package.json`. */ name: string /** The resolved workspace record. */ workspace: Workspace /** * The tag this package's changelog range starts from: its latest * `@X.Y.Z` tag, else the latest lockstep `vX.Y.Z` tag, else * `null` when the repo has neither (full history). */ fromTag: Tag | null /** Version in the workspace `package.json` right now. */ currentVersion: string /** Version this release bumps the package to. */ newVersion: string bump: BumpLevel /** * `true` when the package releases on its own routed commits; * `false` when it releases only because a `workspace:` dependency * was bumped. */ ownCommits: boolean /** Commits routed to this package. Empty for propagated-only releases. */ commits: Commit[] /** Commit scopes that route to this package, including its own name. */ scopes: string[] } export interface IndependentReleasePlan { /** Packages to release, in topological (publish) order. */ releases: PackageRelease[] /** Commits with no scope, or a scope no package claims. They bump nothing. */ unrouted: Commit[] } /** * Compute the per-package release plan for independent-versioning mode. * * `commits` is the union commit range covering every package's last * release; `isCommitSince` narrows it per package (a commit already * shipped in `fontaine@0.8.0` must not count toward fontaine again just * because fontless released longer ago). When omitted, every commit * counts for every package. */ export function computeIndependentPlan (opts: { workspaces: Workspace[] /** `scopes:` input overrides, from `parseScopesInput`. */ scopeOverrides: Map /** All tag names, sorted newest-first. */ tags: string[] /** Commits over the union range, already filtered to release-worthy types. */ commits: Commit[] isCommitSince?: (commit: Commit, tag: Tag) => boolean prerelease?: string }): IndependentReleasePlan { const scopeMap = buildScopeMap(opts.workspaces, opts.scopeOverrides) const routed = new Map(opts.workspaces.map(ws => [ws.name, []])) const unrouted: Commit[] = [] for (const commit of opts.commits) { const matched = commit.scope ? scopeMap.resolveAll(commit.scope) : [] if (!matched.length) unrouted.push(commit) for (const ws of matched) routed.get(ws.name)!.push(commit) } const lockstepTag = latestLockstepTag(opts.tags) const fromTags = new Map() const planned: Array<{ name: string, bump: BumpLevel }> = [] for (const ws of opts.workspaces) { const fromTag = latestTagForPackage(ws.name, opts.tags) ?? lockstepTag fromTags.set(ws.name, fromTag) const commits = (fromTag && opts.isCommitSince) ? routed.get(ws.name)!.filter(c => opts.isCommitSince!(c, fromTag)) : routed.get(ws.name)! routed.set(ws.name, commits) if (commits.length) planned.push({ name: ws.name, bump: determineBump(commits) }) } const scopesByName = new Map( scopeMap.entries().map(({ workspace, scopes }) => [workspace.name, [...new Set([workspace.name, ...scopes])]]), ) const graph = buildDependencyGraph(opts.workspaces) const byName = new Map(opts.workspaces.map(ws => [ws.name, ws])) const releases = propagateReleases(graph, planned).map((release) => { const workspace = byName.get(release.name)! if (!workspace.version) { throw new Error(`Cannot release "${release.name}": its package.json has no \`version\` field.`) } return { name: release.name, workspace, fromTag: fromTags.get(release.name)!, currentVersion: workspace.version, newVersion: incVersion(workspace.version, release.bump, opts.prerelease), bump: release.bump, ownCommits: release.ownCommits, commits: release.ownCommits ? routed.get(release.name)! : [], scopes: scopesByName.get(release.name)!, } }) return { releases, unrouted } } export function formatChangelog ( commits: Commit[], opts: { owner: string repo: string fromRef: Tag | null toRef: string /** * Scopes that route to the package this changelog section belongs to. * A commit whose only scope is one of these has it dropped from the * rendered line: the section heading already names the package. */ packageScopes?: string[] }, ): string { const grouped = new Map() for (const c of commits) { if (!isReleaseWorthy(c)) continue const list = grouped.get(c.type) || [] list.push(c) grouped.set(c.type, list) } const lines: string[] = [] if (opts.fromRef) { const compareUrl = `https://github.com/${opts.owner}/${opts.repo}/compare/${opts.fromRef.name}...${opts.toRef}` lines.push(`[compare changes](${compareUrl})`, '') } const commitUrl = (sha: string) => `https://github.com/${opts.owner}/${opts.repo}/commit/${sha}` for (const type of Object.keys(TYPE_TITLES)) { const items = grouped.get(type) if (!items?.length) continue lines.push(`### ${TYPE_TITLES[type]}`, '') for (const c of items) { const ownScopes = c.scope.split(',').map(s => s.trim()).filter(Boolean) const redundant = ownScopes.length === 1 && Boolean(opts.packageScopes?.includes(ownScopes[0]!)) const scope = c.scope && !redundant ? `**${c.scope}:** ` : '' const breaking = c.isBreaking ? '⚠️ ' : '' // Prefer PR references; fall back to a link to the commit itself so // every line is traceable to something on GitHub. const trailer = c.references.length ? ` (${c.references.join(', ')})` : ` ([\`${c.shortHash}\`](${commitUrl(c.shortHash)}))` lines.push(`- ${breaking}${scope}${c.description}${trailer}`) } lines.push('') } return lines.join('\n').trim() } async function gh (path: string, rest: RequestInit = {}): Promise { const token = process.env.GITHUB_TOKEN const res = await fetch(`https://api.github.com${path}`, { ...rest, headers: { 'Accept': 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', ...(token ? { Authorization: `Bearer ${token}` } : {}), 'User-Agent': 'release-pr-updater', ...(rest.body ? { 'Content-Type': 'application/json' } : {}), ...(rest.headers as Record | undefined), }, }) if (!res.ok) { throw new Error(`GitHub ${rest.method || 'GET'} ${path} -> ${res.status} ${res.statusText}: ${await res.text()}`) } const text = await res.text() return (text ? JSON.parse(text) : undefined) as T } async function getContributors ( commits: Commit[], repo: { owner: string, repo: string }, cutoff: string | null, ): Promise { const out: Contributor[] = [] const seenEmails = new Set() const seenUsers = new Set() for (const commit of commits) { if (commit.author.name === 'renovate[bot]') continue if (seenEmails.has(commit.author.email)) continue seenEmails.add(commit.author.email) let login: string | undefined try { const data = await gh<{ author: { login: string } | null }>( `/repos/${repo.owner}/${repo.repo}/commits/${commit.shortHash}`, ) login = data.author?.login } catch { continue } if (!login || seenUsers.has(login)) continue seenUsers.add(login) // First-time contributor = no commits authored by them before the cutoff // (the previous release tag's commit date). If we have no previous tag // every contributor is, by definition, first-time. let isFirstTime = true if (cutoff) { try { const prior = await gh( `/repos/${repo.owner}/${repo.repo}/commits?author=${encodeURIComponent(login)}&until=${encodeURIComponent(cutoff)}&per_page=1`, ) isFirstTime = prior.length === 0 } catch { isFirstTime = false } } out.push({ name: commit.author.name, username: login, isFirstTime }) } return out } interface OpenPR { number: number body: string | null head: { ref: string, repo: { full_name: string } | null } base: { ref: string } created_at: string updated_at: string } /** Open PRs against `baseBranch`, newest first, stopping at a page that reaches `since` (epoch ms). */ async function listOpenPRs (repo: { owner: string, repo: string }, baseBranch: string, since?: number | null): Promise { const prs: OpenPR[] = [] for (let page = 1; ; page++) { const batch = await gh( `/repos/${repo.owner}/${repo.repo}/pulls?state=open&sort=created&direction=desc&per_page=100&page=${page}&base=${encodeURIComponent(baseBranch)}`, ) prs.push(...batch) if (batch.length < 100) return prs if (since != null && batch.some(pr => Date.parse(pr.created_at) < since)) return prs } } /** * Close open release PRs on `baseBranch` that `isStale` matches, deleting * their branches. Returns the preamble of the most recently updated stale * PR (if any) so the maintainer's intro text can be carried over. */ async function closeSupersededPRs ( repo: { owner: string, repo: string }, baseBranch: string, isStale: (headRef: string) => boolean, since?: number | null, ): Promise { let seedPreamble: string | null = null const openReleasePRs = await listOpenPRs(repo, baseBranch, since) const sameRepo = `${repo.owner}/${repo.repo}` const stale = openReleasePRs .filter(pr => pr.head.repo?.full_name === sameRepo && isStale(pr.head.ref) && pr.base.ref === baseBranch, ) .sort((a, b) => b.updated_at.localeCompare(a.updated_at)) for (const pr of stale) { console.log(`Closing superseded release PR #${pr.number} (${pr.head.ref})`) const preamble = extractPreamble(pr.body) if (preamble && !seedPreamble) seedPreamble = preamble await gh(`/repos/${repo.owner}/${repo.repo}/pulls/${pr.number}`, { method: 'PATCH', body: JSON.stringify({ state: 'closed' }), }) try { await gh(`/repos/${repo.owner}/${repo.repo}/git/refs/heads/${pr.head.ref}`, { method: 'DELETE', }) } catch (err) { console.warn(` could not delete branch ${pr.head.ref}:`, err) } } return seedPreamble } /** * Whether an open release PR's head branch is superseded by the branch this * run is building. Prerelease and stable targets are separate tracks: a * `release/v5.0.0-beta.0` PR must survive the next ordinary push (which * targets `release/v5.0.0`), and vice versa. */ export function isSupersededReleaseBranch (headRef: string, opts: { releaseBranch: string baseBranch: string prerelease: boolean }): boolean { if (headRef === opts.releaseBranch) return false if (headRef === `release/${opts.baseBranch}-pending`) return true if (!headRef.startsWith('release/v')) return false const isPrereleaseBranch = headRef.slice('release/v'.length).includes('-') return isPrereleaseBranch === opts.prerelease } async function findOpenPR ( repo: { owner: string, repo: string }, branch: string, ): Promise<{ number: number, body: string | null } | undefined> { const existing = await gh>( `/repos/${repo.owner}/${repo.repo}/pulls?head=${repo.owner}:${branch}&state=open`, ) return existing[0] } /** * GitHub rejects issue/PR bodies longer than 65536 characters with a 422. * Repos with very long changelogs (thousands of commits since the last tag) * hit this, so trim on a line boundary and say so in the body. */ export function truncateBody (body: string, limit = 65536): string { if (body.length <= limit) return body const notice = '\n\n_Changelog truncated: it exceeded GitHub\'s 65536 character limit._' const budget = limit - notice.length const cut = body.slice(0, budget) const lastBreak = cut.lastIndexOf('\n') return (lastBreak > 0 ? cut.slice(0, lastBreak) : cut).trimEnd() + notice } /** Update `currentPR` in place, or open a new draft PR when there is none. */ async function upsertReleasePR ( repo: { owner: string, repo: string }, opts: { currentPR?: { number: number }, title: string, head: string, base: string, body: string }, ): Promise { const body = truncateBody(opts.body) if (opts.currentPR) { await gh(`/repos/${repo.owner}/${repo.repo}/pulls/${opts.currentPR.number}`, { method: 'PATCH', body: JSON.stringify({ title: opts.title, body }), }) console.log(`Updated PR #${opts.currentPR.number}`) } else { const created = await gh<{ number: number, html_url: string }>( `/repos/${repo.owner}/${repo.repo}/pulls`, { method: 'POST', body: JSON.stringify({ title: opts.title, head: opts.head, base: opts.base, body, draft: true, }), }, ) console.log(`Created PR #${created.number}: ${created.html_url}`) } } /** Create a tree layering `files` over `baseTree`, returning its sha. */ async function createTree ( repo: { owner: string, repo: string }, baseTree: string, files: FileToCommit[], ): Promise { const blobs = await Promise.all(files.map(async (file) => { const blob = await gh<{ sha: string }>( `/repos/${repo.owner}/${repo.repo}/git/blobs`, { method: 'POST', body: JSON.stringify({ content: Buffer.from(file.content, 'utf8').toString('base64'), encoding: 'base64', }), }, ) return { path: file.path, sha: blob.sha } })) const tree = await gh<{ sha: string }>( `/repos/${repo.owner}/${repo.repo}/git/trees`, { method: 'POST', body: JSON.stringify({ base_tree: baseTree, tree: blobs.map(b => ({ path: b.path, mode: '100644', type: 'blob', sha: b.sha })), }), }, ) return tree.sha } interface FileToCommit { /** Path relative to the repo root, using forward slashes. */ path: string /** Raw UTF-8 contents to write at that path. */ content: string } export interface BranchDivergence { /** Files the branch changes relative to its merge base with the target base. */ changed: Set mergeBase: string behindBy: number /** Messages of the commits the branch has on top of its merge base. */ commitMessages?: string[] } /** * Decide whether `opts.branch` still represents `opts.files` correctly, or * has to be rebuilt. Returns `null` when the branch is fine as it stands. * * A branch that is simply behind base is left alone: the diff it carries is * still the diff we want, and GitHub can merge it. Rebuilding is only needed * when the branch's own diff no longer matches the plan, or when base has * since touched one of the same files (which would conflict on merge). */ export function releaseBranchDrift (opts: { /** `null` when the branch doesn't exist yet. */ divergence: BranchDivergence | null /** Desired file contents, keyed by repo-relative path. */ desired: Map /** Current contents of those same paths on the branch. */ branchContents: Map /** Desired paths that base has changed since the merge base. */ baseTouched: string[] keepOtherChanges?: boolean /** Defaults to exact equality. */ isCurrent?: (branch: string | null, desired: string) => boolean /** Desired message for a branch made of a single commit. */ message?: string }): string | null { if (!opts.divergence) return 'branch does not exist' const desiredPaths = [...opts.desired.keys()] const changed = opts.divergence.changed const missing = desiredPaths.some(path => !changed.has(path)) if (missing || (!opts.keepOtherChanges && changed.size !== desiredPaths.length)) { return `branch changes ${[...changed].join(', ') || 'nothing'}, plan changes ${desiredPaths.join(', ')}` } const isCurrent = opts.isCurrent ?? ((branch, desired) => branch === desired) for (const path of desiredPaths) { if (!isCurrent(opts.branchContents.get(path)!, opts.desired.get(path)!)) return `${path} differs from the plan` } if (opts.baseTouched.length) return `base has since changed ${opts.baseTouched.join(', ')}` const messages = opts.divergence.commitMessages if (opts.message !== undefined && messages?.length === 1 && messages[0] !== opts.message) { return 'commit message differs from the plan' } return null } /** * Make `opts.branch` carry `opts.files` as its diff against `opts.base`, * rebuilding it as a single commit on the base tip only when that isn't * already true (see `releaseBranchDrift`). With `keepOtherChanges`, a branch * that also changes other files is never rebuilt. Resolves to whether the * branch carries the plan. A rebuild always * force-updates the ref straight to the new commit rather than resetting to * base first: a branch that momentarily equals its base makes GitHub close * the open PR as having nothing to merge. */ async function syncReleaseBranch ( repo: { owner: string, repo: string }, opts: { base: string branch: string message: string files: FileToCommit[] keepOtherChanges?: boolean isCurrent?: (branch: string | null, desired: string) => boolean }, ): Promise { /* v8 ignore next 3 -- unreachable: callers never pass an empty plan. */ if (!opts.files.length) { throw new Error('syncReleaseBranch: refusing to commit with no files') } const desired = new Map(opts.files.map(file => [file.path, file.content])) let divergence: BranchDivergence | null = null try { const cmp = await gh<{ files?: Array<{ filename: string }>, commits?: Array<{ commit: { message: string } }>, merge_base_commit: { sha: string }, behind_by: number }>( `/repos/${repo.owner}/${repo.repo}/compare/${encodeURIComponent(opts.base)}...${encodeURIComponent(opts.branch)}`, ) divergence = { changed: new Set((cmp.files ?? []).map(file => file.filename)), mergeBase: cmp.merge_base_commit.sha, behindBy: cmp.behind_by, commitMessages: cmp.commits?.map(c => c.commit.message), } } catch (err) { if (!(err instanceof Error) || !/-> 404\b/.test(err.message)) throw err } const branchContents = new Map() const baseTouched: string[] = [] if (divergence) { for (const path of desired.keys()) { branchContents.set(path, await getFileContent(repo, path, opts.branch)) } if (divergence.behindBy > 0) { const baseCmp = await gh<{ files?: Array<{ filename: string }> }>( `/repos/${repo.owner}/${repo.repo}/compare/${divergence.mergeBase}...${encodeURIComponent(opts.base)}`, ) for (const file of baseCmp.files ?? []) { if (desired.has(file.filename)) baseTouched.push(file.filename) } } } const drift = releaseBranchDrift({ divergence, desired, branchContents, baseTouched, keepOtherChanges: opts.keepOtherChanges, isCurrent: opts.isCurrent, message: opts.message, }) if (!drift) { console.log(`Branch ${opts.branch} already carries the release plan; leaving it untouched.`) return true } const others = opts.keepOtherChanges ? [...divergence?.changed ?? []].filter(path => !desired.has(path)) : [] if (others.length) { console.log(`::warning::Cannot rebuild ${opts.branch} (${drift}) without discarding its changes to ${others.join(', ')}.`) return !releaseBranchDrift({ divergence, desired, branchContents, baseTouched: [], keepOtherChanges: true, isCurrent: opts.isCurrent, }) } if (!process.env.GITHUB_TOKEN) { throw new Error('GITHUB_TOKEN is required to create the release branch') } console.log(`Rebuilding ${opts.branch} on ${opts.base}: ${drift}`) const baseInfo = await gh<{ commit: { sha: string } }>( `/repos/${repo.owner}/${repo.repo}/branches/${encodeURIComponent(opts.base)}`, ) const baseSha = baseInfo.commit.sha const baseCommit = await gh<{ tree: { sha: string } }>( `/repos/${repo.owner}/${repo.repo}/git/commits/${baseSha}`, ) const tree = await createTree(repo, baseCommit.tree.sha, opts.files) const commit = await gh<{ sha: string }>( `/repos/${repo.owner}/${repo.repo}/git/commits`, { method: 'POST', body: JSON.stringify({ message: opts.message, tree, parents: [baseSha] }), }, ) if (divergence) { await gh(`/repos/${repo.owner}/${repo.repo}/git/refs/heads/${opts.branch}`, { method: 'PATCH', body: JSON.stringify({ sha: commit.sha, force: true }), }) } else { await gh(`/repos/${repo.owner}/${repo.repo}/git/refs`, { method: 'POST', body: JSON.stringify({ ref: `refs/heads/${opts.branch}`, sha: commit.sha }), }) } return true } async function getFileContent ( repo: { owner: string, repo: string }, path: string, ref: string, ): Promise { try { const data = await gh<{ content?: string, encoding?: string }>( `/repos/${repo.owner}/${repo.repo}/contents/${path.split('/').map(encodeURIComponent).join('/')}?ref=${encodeURIComponent(ref)}`, ) if (data.encoding !== 'base64' || typeof data.content !== 'string') return null return Buffer.from(data.content, 'base64').toString('utf8') } catch (err) { if (err instanceof Error && /-> 404\b/.test(err.message)) return null throw err } } async function isReleaseMergeCommit ( repo: { owner: string, repo: string }, sha: string, ): Promise { // We don't want to update the changelog when a `release/vX.Y.Z` PR is merged. try { const prs = await gh>( `/repos/${repo.owner}/${repo.repo}/commits/${sha}/pulls`, ) return prs.some(pr => pr.merged_at && (pr.head.ref.startsWith('release/v') || /^release\/.+-pending$/.test(pr.head.ref))) } catch { return false } } /** * Build the set of `package.json` files to write in the release commit. * * Single-package mode: just the root, bumped to `newVersion`. * * Monorepo mode: every listed workspace is rewritten to `newVersion`. * The root is included only if its current `version` exactly matches * the lockstep version; otherwise it's left untouched (it might be * `0.0.0`, absent, or deliberately frozen, and none of those are uppt's * business). */ export function buildBumpFileSet (opts: { monorepo: boolean workspaces: Workspace[] rootPkg: Record rootPkgSource: string currentVersion: string newVersion: string }): Array<{ path: string, content: string }> { const files: Array<{ path: string, content: string }> = [] const formatRootPkg = makePkgFormatter(opts.rootPkgSource) if (!opts.monorepo) { const updated = { ...opts.rootPkg, version: opts.newVersion } files.push({ path: 'package.json', content: formatRootPkg(updated) }) return files } let rootCoveredByWorkspaces = false for (const ws of opts.workspaces) { const wsPkg = { ...ws.pkg, version: opts.newVersion } const path = ws.relDir === '.' ? 'package.json' : `${ws.relDir}/package.json` if (path === 'package.json') rootCoveredByWorkspaces = true files.push({ path, content: makePkgFormatter(ws.source)(wsPkg) }) } if (!rootCoveredByWorkspaces && opts.rootPkg.version === opts.currentVersion) { const updated = { ...opts.rootPkg, version: opts.newVersion } files.push({ path: 'package.json', content: formatRootPkg(updated) }) } return files } /** * Build the set of `package.json` files to write in an independent-mode * release commit: exactly the planned releases' manifests, each bumped * to its own `newVersion`. `workspace:` specifiers are left as-is (the * package manager resolves them at pack time), and the root manifest is * only included if it is itself a planned release. */ export function buildIndependentBumpFileSet (plan: IndependentReleasePlan): FileToCommit[] { return plan.releases.map((release) => { const pkg = { ...release.workspace.pkg, version: release.newVersion } const path = release.workspace.relDir === '.' ? 'package.json' : `${release.workspace.relDir}/package.json` return { path, content: makePkgFormatter(release.workspace.source)(pkg) } }) } /** * Maintainer-editable preamble of a release PR body: everything above * the first generated `## 👉` heading. Returns `null` when the body is * empty or starts with a generated heading. */ export function extractPreamble (body: string | null | undefined): string | null { if (!body) return null const match = body.match(/^## 👉 .*$/m) const preamble = (match ? body.slice(0, match.index) : body).trim() return preamble || null } /** Timetable line seeded into a fresh release PR preamble. */ export const TIMETABLE_PLACEHOLDER = '> **Timetable**: to be announced.' /** Remove the unedited timetable line, and its blockquote spacer, from a PR body. */ export function stripPlaceholderTimetable (body: string): string { return body .replaceAll(`\n>\n${TIMETABLE_PLACEHOLDER}`, '') .replaceAll(`\n${TIMETABLE_PLACEHOLDER}`, '') } const PR_NOTES_START = '' const PR_NOTES_END = '' const PR_NOTES_RE = /\n*[\s\S]*?\n*/ /** * Replace the marked notes block in a release PR body with `notes`, or * remove it when `notes` is empty. A body without the block gets one * appended only when `append` is set. */ export function setPrNotes (body: string, notes: string, append = false): string { const block = notes && `${PR_NOTES_START}\n${notes}\n${PR_NOTES_END}` if (!PR_NOTES_RE.test(body)) return append && block ? `${body}\n\n${block}` : body return body.replace(PR_NOTES_RE, (match: string, offset: number) => { const before = offset > 0 ? '\n\n' : '' const after = offset + match.length < body.length ? '\n\n' : '' if (block) return before + block + after return before && after ? '\n\n' : '' }) } /** Remove the marked notes block from a release PR body. */ export function stripPrNotes (body: string): string { return setPrNotes(body, '') } function prNotes (vars: { base: string, version?: string }): string { return (process.env.PR_NOTES ?? '').replace(/^\s*\n/, '').trimEnd() .replace(/\{(base|version)\}/g, (match, key: 'base' | 'version') => vars[key] ?? match) } function bumpBetween (from: string, to: string): BumpLevel { const core = (v: string) => v.split(/[-+]/)[0]!.split('.').map(Number) const [a, b] = [core(from), core(to)] if (a[0] !== b[0]) return 'major' if (a[1] !== b[1]) return 'minor' return 'patch' } /** Hand-set version on a lockstep release branch, or `null` if none is usable. */ export function resolvePinnedVersion (opts: { headRef: string branchVersions: Array currentVersion: string prerelease: boolean /** Prerelease identifier of this run. */ identifier?: string }): string | null { const nameVersion = opts.headRef.slice('release/v'.length) if (opts.identifier !== undefined && prereleaseIdentifier(nameVersion) !== opts.identifier) return null const edited = [...new Set(opts.branchVersions.filter((v): v is string => typeof v === 'string' && v !== nameVersion))] if (edited.length > 1) { console.log(`::warning::Ignoring hand-edited versions on ${opts.headRef}: manifests disagree (${edited.join(', ')}).`) return null } const pinned = edited[0] if (!pinned) return null if (!/^\d+\.\d+\.\d+(?:-[0-9a-zA-Z.-]+)?$/.test(pinned)) { console.log(`::warning::Ignoring hand-edited version "${pinned}" on ${opts.headRef}: expected strict "X.Y.Z" semver.`) return null } if (compareSemver(pinned, opts.currentVersion) <= 0) { console.log(`::warning::Ignoring hand-edited version "${pinned}" on ${opts.headRef}: not above the current version ${opts.currentVersion}.`) return null } if (isPrerelease(pinned) !== opts.prerelease) { console.log(`::warning::Ignoring hand-edited version "${pinned}" on ${opts.headRef}: this run cuts a ${opts.prerelease ? 'prerelease' : 'stable release'}.`) return null } return pinned } async function findTrackReleasePR ( repo: { owner: string, repo: string }, opts: { baseBranch: string, prerelease: boolean, since: number | null }, ): Promise<{ number: number, head: string } | undefined> { const prs = await listOpenPRs(repo, opts.baseBranch, opts.since) const pr = prs .filter(pr => pr.head.repo?.full_name === `${repo.owner}/${repo.repo}` && pr.base.ref === opts.baseBranch && pr.head.ref.startsWith('release/v') && pr.head.ref.slice('release/v'.length).includes('-') === opts.prerelease, ) .sort((a, b) => b.updated_at.localeCompare(a.updated_at))[0] return pr && { number: pr.number, head: pr.head.ref } } function sameManifest (a: string | null, b: string): boolean { try { return JSON.stringify(JSON.parse(a!)) === JSON.stringify(JSON.parse(b)) } catch { return false } } function readVersion (source: string | null): string | undefined { try { const version = (JSON.parse(source!) as { version?: unknown }).version return typeof version === 'string' ? version : undefined } catch { return undefined } } function propagationCauses (release: PackageRelease, releasedNames: Set): string[] { const causes = new Set() for (const field of DEPENDENCY_FIELDS) { const deps = release.workspace.pkg[field] if (!deps || typeof deps !== 'object') continue for (const [dep, spec] of Object.entries(deps as Record)) { if (typeof spec !== 'string' || !spec.startsWith('workspace:')) continue if (dep !== release.name && releasedNames.has(dep)) causes.add(dep) } } return [...causes] } /** * Render the full body of an independent-mode release PR from the plan. * The body is regenerated wholesale on every push (only the preamble * carries over), so packages that drop out of the plan disappear. */ export function buildIndependentBody ( plan: IndependentReleasePlan, opts: { owner: string repo: string preamble: string contributors?: Contributor[] }, ): string { const releasedNames = new Set(plan.releases.map(r => r.name)) const lines: string[] = [opts.preamble, '', '## 👉 Changelog', ''] for (const release of plan.releases) { lines.push(`### ${release.name} (${release.currentVersion} → ${release.newVersion})`, '') if (release.ownCommits) { lines.push(formatChangelog(release.commits, { owner: opts.owner, repo: opts.repo, fromRef: release.fromTag, toRef: `${release.name}@${release.newVersion}`, packageScopes: release.scopes, }), '') } else { const causes = propagationCauses(release, releasedNames) /* v8 ignore start -- unreachable for a plan built by `computeIndependentPlan`: a release with `ownCommits: false` exists only because `propagateReleases` found a released `workspace:` dependency, and `propagationCauses` re-derives that same edge with the same predicate. Kept because `buildIndependentBody` is exported and could be handed a plan assembled by other means. */ if (!causes.length) { lines.push('_Released because a `workspace:` dependency was bumped; no direct changes._', '') continue } /* v8 ignore stop */ lines.push(`_Released because ${causes.map(c => `\`${c}\``).join(' and ')} was bumped; no direct changes._`, '') } } if (plan.unrouted.length) { const commitUrl = (sha: string) => `https://github.com/${opts.owner}/${opts.repo}/commit/${sha}` lines.push('### 📝 Other commits', '', '_These commits were not routed to any package and do not bump any version._', '') for (const c of plan.unrouted) { lines.push(`- ${c.message} ([\`${c.shortHash}\`](${commitUrl(c.shortHash)}))`) } lines.push('') } if (opts.contributors) { const newContributors = opts.contributors.filter(c => c.isFirstTime) if (newContributors.length) { lines.push('### 🎉 New Contributors', '', newContributors.map(c => `- ${c.name} (@${c.username})`).join('\n'), '') } lines.push( '### ❤️ Contributors', '', opts.contributors.length ? opts.contributors.map(c => `- ${c.name} (@${c.username})`).join('\n') : '_no contributors yet_', ) } return lines.join('\n').trimEnd() } function renderTitle (template: string, vars: Record): string { return template.replace(/\{([^{}]*)\}/g, (match, key: string) => { if (!Object.hasOwn(vars, key)) { const known = Object.keys(vars).map(k => `\`{${k}}\``).join(', ') throw new Error(`Unknown placeholder \`${match}\` in the \`title\` input; expected ${known}.`) } return vars[key]! }) } export async function main () { const dryRun = Boolean(process.env.DRY_RUN) const repo = getRepo() const baseBranch = getCurrentBranch() const headSha = git('rev-parse', 'HEAD') if (await isReleaseMergeCommit(repo, headSha)) { console.log(`HEAD (${headSha.slice(0, 7)}) is the merge of a release PR; skipping.`) return } const packagesInput = process.env.PACKAGES?.trim() ?? '' const monorepo = packagesInput.length > 0 const mode = process.env.MODE?.trim() || 'lockstep' if (mode !== 'lockstep' && mode !== 'independent') { throw new Error(`Invalid \`mode\` input "${mode}": expected "lockstep" or "independent".`) } if (mode === 'independent') { if (!monorepo) { throw new Error('`mode: independent` requires the `packages` input.') } await runIndependent(packagesInput) return } const latestTag = getLatestTag() const commits = getCommitsSince(latestTag).filter(isReleaseWorthy) if (!commits.length) { console.log('No release-worthy commits since', latestTag?.name ?? 'repo root') return } const workspaces: Workspace[] = monorepo ? resolveWorkspaces(process.cwd(), packagesInput) : [] const rootPkgPath = resolve(process.cwd(), 'package.json') const rootPkgSource = readFileSync(rootPkgPath, 'utf8') const rootPkg = JSON.parse(rootPkgSource) const currentVersion = resolveCurrentVersion(process.cwd(), packagesInput) const prerelease = process.env.PRERELEASE?.trim() || undefined const computedVersion = incVersion(currentVersion, determineBump(commits), prerelease) const bumpPaths = buildBumpFileSet({ monorepo, workspaces, rootPkg, rootPkgSource, currentVersion, newVersion: computedVersion }) .map(file => file.path) let pinned: { version: string, pr: { number: number, head: string } } | null = null const stableTag = getAllTags().find(t => /^v?\d+\.\d+\.\d+$/.test(t)) const releasedAt = stableTag ? Number(git('log', '-1', '--format=%ct', `refs/tags/${stableTag}`)) * 1000 : null const trackPR = await findTrackReleasePR(repo, { baseBranch, prerelease: Boolean(prerelease), since: releasedAt }) if (trackPR) { const branchVersions: Array = [] for (const path of bumpPaths) branchVersions.push(readVersion(await getFileContent(repo, path, trackPR.head))) const version = resolvePinnedVersion({ headRef: trackPR.head, branchVersions, currentVersion, prerelease: Boolean(prerelease), identifier: prerelease ?? '', }) if (version) pinned = { version, pr: trackPR } } if (pinned && compareVersions(computedVersion.split('-')[0]!, pinned.version.split('-')[0]!) > 0) { console.log(`::warning::Unreleased commits call for v${computedVersion}, above the hand-set v${pinned.version} on #${pinned.pr.number}.`) } const newVersion = pinned?.version ?? computedVersion const title = renderTitle(process.env.TITLE?.trim() || 'v{version}', { version: newVersion }) const bump = pinned ? bumpBetween(currentVersion, newVersion) : determineBump(commits) const releaseBranch = pinned?.pr.head ?? `release/v${newVersion}` const changelog = formatChangelog(commits, { owner: repo.owner, repo: repo.repo, fromRef: latestTag, toRef: `v${newVersion}`, }) console.log(`Current: ${currentVersion} -> ${newVersion} (${bump}${pinned ? `, pinned on #${pinned.pr.number}` : ''})`) if (monorepo) { console.log(`Workspaces (${workspaces.length}): ${workspaces.map(ws => ws.name).join(', ')}`) } console.log(`Base branch: ${baseBranch}`) console.log(`Release branch: ${releaseBranch}`) console.log(`Commits: ${commits.length}`) // Close any open release PRs that don't match the new target version, // scoped to PRs targeting the *same* base branch. Repos with maintenance // branches (e.g. nuxt's `main`, `4.x`, `3.x`) have a release PR per base; // a `feat:` landing on `main` must not close the `4.x`-base PR. The common // single-branch case: a patch PR (`release/v1.0.1`) gets superseded by a // `feat:` that bumps the target to `release/v1.1.0`. We close the stale PR, // lift its preamble (so the maintainer's intro text isn't lost), and // delete its branch. Prerelease PRs are a separate track and survive // stable runs (and vice versa). let seedPreamble: string | null = null if (!dryRun && process.env.GITHUB_TOKEN) { seedPreamble = await closeSupersededPRs(repo, baseBranch, headRef => isSupersededReleaseBranch(headRef, { releaseBranch, baseBranch, prerelease: Boolean(prerelease) }), releasedAt) } if (!dryRun) { const synced = await syncReleaseBranch(repo, { base: baseBranch, branch: releaseBranch, message: title, files: buildBumpFileSet({ monorepo, workspaces, rootPkg, rootPkgSource, currentVersion, newVersion }), keepOtherChanges: true, isCurrent: (branch, desired) => sameManifest(branch, desired), }) if (!synced) { console.log(`::warning::Leaving the release PR for ${releaseBranch} unchanged until the branch can be rebuilt.`) return } } const hasToken = Boolean(process.env.GITHUB_TOKEN) if (!hasToken && !dryRun) throw new Error('GITHUB_TOKEN is required to create or update the PR') const cutoff = latestTag ? git('log', '-1', '--format=%aI', latestTag.ref) : null // Contributor + existing-PR lookups hit public endpoints, so they work // unauthenticated against public repos. We still benefit from a token // (5000 req/h vs 60), but don't require one for previews. const contributors = await getContributors(commits, repo, cutoff) const newContributors = contributors.filter(c => c.isFirstTime) const currentPR = await findOpenPR(repo, releaseBranch) const intro = `> v${newVersion} is the next ${bump} release.` const currentPreamble = extractPreamble(currentPR?.body) const existingPreamble = (currentPreamble || seedPreamble) ?.replace(/^> v\S+ is the next (?:major|minor|patch) release\.$/m, intro) const preamble = setPrNotes( existingPreamble || `${intro}\n>\n${TIMETABLE_PLACEHOLDER}`, prNotes({ base: baseBranch, version: newVersion }), !currentPreamble, ) const body = [ preamble, '', '## 👉 Changelog', '', changelog, ...(newContributors.length ? [ '', '### 🎉 New Contributors', '', newContributors.map(c => `- ${c.name} (@${c.username})`).join('\n'), ] : []), '', '### ❤️ Contributors', '', contributors.length ? contributors.map(c => `- ${c.name} (@${c.username})`).join('\n') : '_no contributors yet_', ].join('\n') if (dryRun) { console.log('\n--- DRY RUN: PR body ---\n') console.log(body) return } await upsertReleasePR(repo, { currentPR, title, head: releaseBranch, base: baseBranch, body }) } async function runIndependent (packagesInput: string): Promise { const workspaces = resolveWorkspaces(process.cwd(), packagesInput) const scopeOverrides = parseScopesInput(process.env.SCOPES ?? '') const tags = getAllTags() const lockstepTag = latestLockstepTag(tags) const fromTags = workspaces.map(ws => latestTagForPackage(ws.name, tags) ?? lockstepTag) // One `git log` over the union range: the oldest per-package boundary, // i.e. the highest index in the newest-first tag list. Any package with // no boundary at all forces full history. let unionFrom: Tag | null = null if (fromTags.every(t => t !== null)) { let oldestIndex = -1 for (const tag of fromTags) { const index = tags.indexOf(tag!.name) if (index > oldestIndex) { oldestIndex = index unionFrom = tag } } } const commits = getCommitsSince(unionFrom).filter(isReleaseWorthy) const sinceSets = new Map>() const isCommitSince = (commit: Commit, tag: Tag): boolean => { let set = sinceSets.get(tag.ref) if (!set) { set = new Set(git('rev-list', `${tag.ref}..HEAD`).split('\n').filter(Boolean)) sinceSets.set(tag.ref, set) } return set.has(commit.hash) } const plan = computeIndependentPlan({ workspaces, scopeOverrides, tags, commits, isCommitSince, prerelease: process.env.PRERELEASE?.trim() || undefined, }) if (plan.unrouted.length) { console.log(`Other commits (${plan.unrouted.length}, bump nothing):`) for (const commit of plan.unrouted) { console.log(` ${commit.shortHash} ${commit.message}`) } } if (!plan.releases.length) { console.log('Independent release plan: no packages to release.') return } console.log(`Independent release plan (${plan.releases.length} package${plan.releases.length === 1 ? '' : 's'}):`) for (const release of plan.releases) { const reason = release.ownCommits ? `${release.commits.length} commit${release.commits.length === 1 ? '' : 's'}` : 'dependency bump only' const from = release.fromTag ? ` since ${release.fromTag.name}` : '' console.log(` ${release.name}: ${release.currentVersion} -> ${release.newVersion} (${release.bump}, ${reason}${from})`) } const dryRun = Boolean(process.env.DRY_RUN) const repo = getRepo() const baseBranch = getCurrentBranch() const releaseBranch = `release/${baseBranch}-pending` const title = renderTitle(process.env.TITLE?.trim() || 'chore: release {count} {packages}', { count: String(plan.releases.length), packages: plan.releases.length === 1 ? 'package' : 'packages', }) console.log(`Base branch: ${baseBranch}`) console.log(`Release branch: ${releaseBranch}`) // A stale lockstep PR (`release/vX.Y.Z`) on the same base means the repo // switched to independent mode with a lockstep release still open; the two // would bump the same manifests to conflicting versions, so close it and // lift its preamble into the pending PR. let seedPreamble: string | null = null if (!dryRun && process.env.GITHUB_TOKEN) { seedPreamble = await closeSupersededPRs(repo, baseBranch, headRef => headRef.startsWith('release/v')) } if (!dryRun) { // The pending branch name never changes, but the plan behind it does // (packages join and drop as commits land on base), so the branch has to // end up carrying exactly the current plan and nothing stale. await syncReleaseBranch(repo, { base: baseBranch, branch: releaseBranch, message: title, files: buildIndependentBumpFileSet(plan), }) } const ownCommits = plan.releases.flatMap(r => r.commits) const seen = new Set() const uniqueCommits = ownCommits.filter(c => !seen.has(c.hash) && Boolean(seen.add(c.hash))) const cutoff = unionFrom ? git('log', '-1', '--format=%aI', unionFrom.ref) : null const contributors = await getContributors(uniqueCommits, repo, cutoff) const currentPR = await findOpenPR(repo, releaseBranch) const currentPreamble = extractPreamble(currentPR?.body) const preamble = setPrNotes( currentPreamble || seedPreamble || `> The next set of package releases, covering all packages with unreleased changes.\n>\n${TIMETABLE_PLACEHOLDER}`, prNotes({ base: baseBranch }), !currentPreamble, ) const body = buildIndependentBody(plan, { owner: repo.owner, repo: repo.repo, preamble, contributors, }) if (dryRun) { console.log('\n--- DRY RUN: PR body ---\n') console.log(body) return } await upsertReleasePR(repo, { currentPR, title, head: releaseBranch, base: baseBranch, body }) } runMain(import.meta.url, main)