name: Patch provenance # Passes only for the two kinds of pull request that bring a stable line nothing main doesn't have: # - a backport of a fix that main has and the line doesn't: its tree is the landing on main that # added its changesets, applied whole to the line's head, and it carries only patch changesets for # the fixed version group, which main still has as patches unless a release consumed them; # - the line's Version Packages pull request: one commit on top of the line's head that only versions # the packages, one patch up within the line's X.Y, and consumes only patch changesets. # Any other pull request into a stable line fails this check, and a maintainer reviews and merges it. # # It runs on pull_request, so each stable line runs its own copy of this file. It never checks out # or runs the pull request's code: it only reads commits, anonymously with git, so it doesn't # depend on GitHub's API, which can refuse requests from GitHub-hosted runners. A pull request that # changes .github/ runs its own version of the checks there, this one included, so they vouch for # nothing on it: a maintainer reviews it, and the release bot never merges a pull request that # changes .github/. on: pull_request: types: [opened, synchronize, reopened, edited] branches: - 'stable/**' # The repository is public and the check reads it anonymously, so its token needs no permissions. permissions: {} concurrency: group: patch-provenance-${{ github.event.pull_request.number }} cancel-in-progress: true jobs: provenance: name: Patch provenance runs-on: ubuntu-latest timeout-minutes: 15 steps: - name: Check where the pull request's changes come from env: PR_NUMBER: ${{ github.event.pull_request.number }} BASE_REF: ${{ github.event.pull_request.base.ref }} HEAD_REF: ${{ github.event.pull_request.head.ref }} HEAD_SHA: ${{ github.event.pull_request.head.sha }} HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }} run: | set -euo pipefail mkdir "$RUNNER_TEMP/provenance" cd "$RUNNER_TEMP/provenance" cat > check.mjs <<'SCRIPT' import {execFileSync, spawnSync} from 'node:child_process' import {appendFileSync, writeFileSync} from 'node:fs' import {resolve} from 'node:path' import {pathToFileURL} from 'node:url' const {GITHUB_REPOSITORY: repository, PR_NUMBER, BASE_REF, HEAD_REF, HEAD_SHA, HEAD_REPO} = process.env // Paths the public repository keeps for itself and main's mirrored history never changes. const KEPT_PATHS = ['.github/', '.spin/', 'dev.yml', 'TORRENT_WORKFLOW.md', 'AGENTS.md', '.agents/', '.claude/', '.cursor/'] const DEPENDENCY_FIELDS = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'] const VERSION_FILE = 'packages/cli-kit/src/public/common/version.ts' const run = (command, args) => execFileSync(command, args, {encoding: 'utf8', maxBuffer: 512 * 1024 * 1024}) const git = (...args) => run('git', args).trimEnd() const gitSucceeds = (...args) => { try { execFileSync('git', args, {stdio: 'ignore'}) return true } catch { return false } } // A git command that talks to GitHub. Its failure fails the check with git's message, as the // other refusals do, instead of ending the job with a stack trace and no summary. const network = (what, ...args) => { try { return git(...args) } catch (error) { fail(`${what} failed: ${error.stderr?.toString().trim() || error.message}`) } } // Whether a commit has a path. The fetch below brings every commit and tree, so this reads no // file. `git ls-tree` prints nothing for a missing path and fails on a failed read, which fails // the check: like a file's text, a failed read never reads as a missing file. const hasFile = (commit, path) => { try { return run('git', ['--literal-pathspecs', 'ls-tree', '--full-tree', commit, '--', path]) !== '' } catch (error) { fail(`Reading ${commit}'s tree for ${path} failed: ${error.stderr?.toString().trim() || error.message}`) } } // A file's text at a commit, or undefined when the commit doesn't have it. Git fetches the // text from GitHub on first read, and a failed fetch fails the check: it never reads as a // missing file. const fileAt = (commit, path) => { if (!hasFile(commit, path)) return undefined try { return run('git', ['cat-file', 'blob', `${commit}:${path}`]) } catch (error) { fail(`Reading ${path} at ${commit} failed: ${error.stderr?.toString().trim() || error.message}`) } } const summary = (text) => appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${text}\n`) // Workflow commands are one line, and file names come from the pull request. const commandData = (text) => text.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A') function fail(reason) { console.log(`::error::${commandData(reason)}`) summary(`### Patch provenance failed\n\n${reason}\n\nA maintainer reviews and merges this pull request.`) process.exit(1) } function pass(text) { console.log(text) summary(`### Patch provenance passed\n\n${text}`) process.exit(0) } const changesetPath = (path) => /^\.changeset\/[^/]+\.md$/.test(path) && path !== '.changeset/README.md' // [{status, path, oldMode, newMode}] for base..head, without rename detection, and with paths // exactly as stored. function changedFiles(base, head) { const fields = run('git', ['diff', '--raw', '--no-renames', '--no-abbrev', '-z', base, head]).split('\0') const changes = [] for (let index = 0; index + 1 < fields.length; index += 2) { const [oldMode, newMode, , , status] = fields[index].replace(/^:/, '').split(' ') changes.push({status, path: fields[index + 1], oldMode, newMode}) } return changes } // " " for a path at a commit, or '' when it isn't there. const entryAt = (commit, path) => git('--literal-pathspecs', 'ls-tree', '--full-tree', commit, '--', path).split('\t')[0] // {name: {directory, version, manifest}} for the workspace packages at a commit. function packagesAt(commit) { const packages = {} for (const directory of git('ls-tree', '--name-only', `${commit}:packages`).split('\n').filter(Boolean)) { const text = fileAt(commit, `packages/${directory}/package.json`) if (text === undefined) continue const manifest = JSON.parse(text) packages[manifest.name] = {directory, version: manifest.version, manifest} } return packages } const fixedGroup = (commit) => new Set(JSON.parse(fileAt(commit, '.changeset/config.json')).fixed.flat()) // The bumps a changeset file declares, as [[package, bump]], from its front matter. function changesetBumps(text) { const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text) if (!match) return undefined return match[1] .split(/\r?\n/) .filter((line) => line.trim() !== '') .map((line) => /^\s*['"]?([^'":\s]+)['"]?\s*:\s*['"]?(patch|minor|major)['"]?\s*$/.exec(line)) .map((parsed) => (parsed ? [parsed[1], parsed[2]] : [undefined, undefined])) } const isPatchOf = (version, previous) => { const [major, minor, patch] = previous.split('.').map(Number) return version === `${major}.${minor}.${patch + 1}` } git('init', '--quiet', '.') // A fetch can start background maintenance, which would compete with the check's own git // commands for locks. git('config', 'maintenance.auto', 'false') git('config', 'gc.auto', '0') git('remote', 'add', 'origin', `https://github.com/${repository}`) // ls-remote matches the end of ref names, so a branch such as a/refs/heads/ matches too: // only the exact ref is the line's head. const lineHead = network(`Reading the head of ${BASE_REF}`, 'ls-remote', 'origin', `refs/heads/${BASE_REF}`) .split('\n') .map((line) => line.split('\t')) .find(([, ref]) => ref === `refs/heads/${BASE_REF}`)?.[0] if (!/^[0-9a-f]{40}$/.test(lineHead ?? '')) fail(`Couldn't read the head of ${BASE_REF}.`) // Every commit and tree of the line, the pull request and main, without file contents, so // merge bases and histories are exact. network(`Fetching ${BASE_REF}, the pull request and main`, 'fetch', '--quiet', '--no-tags', '--filter=blob:none', 'origin', lineHead, HEAD_SHA, '+refs/heads/main:refs/remotes/origin/main') if (!gitSucceeds('merge-base', lineHead, HEAD_SHA)) fail(`${HEAD_SHA} doesn't share history with ${BASE_REF}.`) if (HEAD_REF === `changeset-release/${BASE_REF}`) { await checkVersionPackages() } else { checkBackport() } // The line's Version Packages pull request: one commit on the line's head that only moves every // package in the fixed group up one patch version and consumes the line's pending changesets. async function checkVersionPackages() { if (HEAD_REPO !== repository) fail(`A Version Packages pull request comes from ${repository}, not ${HEAD_REPO}.`) const lineConfig = JSON.parse(fileAt(lineHead, '.changeset/config.json')) if (lineConfig.changelog !== './changelog.cjs') { fail(`This check doesn't support ${BASE_REF}: its .changeset/config.json sets "changelog" to ${JSON.stringify(lineConfig.changelog)}, and the check can only rebuild the changelogs of a line that writes them with its own "./changelog.cjs".`) } const parents = git('rev-list', '--parents', '-n', '1', HEAD_SHA).split(' ').slice(1) if (parents.length !== 1 || parents[0] !== lineHead) { fail(`${HEAD_SHA} isn't one commit on top of ${BASE_REF}'s head ${lineHead}. Let Version Packages version the line's current head.`) } const fixed = fixedGroup(lineHead) const before = packagesAt(lineHead) const after = packagesAt(HEAD_SHA) if (Object.keys(before).sort().join() !== Object.keys(after).sort().join()) fail('The set of workspace packages changed.') const newVersion = after['@shopify/cli-kit'].version // A line releases only its own X.Y. A new line starts with the previous line's versions, and // its first release, the minor, is a maintainer's. const lineVersion = /^stable\/(\d+)\.(\d+)$/.exec(BASE_REF) if (!lineVersion) fail(`${BASE_REF} isn't named stable/X.Y, so this check can't tell which versions it releases.`) if (!newVersion.startsWith(`${lineVersion[1]}.${lineVersion[2]}.`)) { fail(`The bump releases ${newVersion}, and ${BASE_REF} releases only ${lineVersion[1]}.${lineVersion[2]}.z versions.`) } for (const [name, {version}] of Object.entries(before)) { if (fixed.has(name)) { if (!isPatchOf(after[name].version, version) || after[name].version !== newVersion) { fail(`${name} goes from ${version} to ${after[name].version}; every package in the fixed group must move up one patch, to the same version.`) } } else if (after[name].version !== version) { fail(`${name} isn't in the fixed group, and its version changed from ${version} to ${after[name].version}.`) } } const pending = git('ls-tree', '--name-only', `${lineHead}:.changeset`) .split('\n') .map((name) => `.changeset/${name}`) .filter(changesetPath) if (pending.length === 0) fail(`${BASE_REF} has no pending changesets, so there's nothing to release.`) const deleted = new Set() const changes = changedFiles(lineHead, HEAD_SHA) const changesets = consumedChangesets(changes.filter(({status, path}) => changesetPath(path) && status === 'D').map(({path}) => path)) for (const {id, releases} of changesets) { for (const {name, type} of releases) { if (type !== 'patch') fail(`.changeset/${id}.md bumps ${name} ${type}, and a patch release consumes only patch changesets.`) if (!after[name] || after[name].version === before[name].version) fail(`.changeset/${id}.md names ${name}, which the bump doesn't release.`) } } const release = {changesets, formatter: await lineFormatter(), prettier: lineConfig.prettier !== false, before, after} const changelogs = new Set() for (const {status, path, oldMode, newMode} of changes) { const directory = /^packages\/([^/]+)\//.exec(path)?.[1] const packageName = Object.keys(after).find((name) => after[name].directory === directory) if (changesetPath(path) && status === 'D') { deleted.add(path) } else if (status !== 'M') { fail(`${path} is ${status === 'A' ? 'added' : 'deleted'}; a version bump only edits files and deletes changesets.`) } else if (oldMode !== '100644' || newMode !== '100644') { fail(`${path} changes mode from ${oldMode} to ${newMode}; a version bump only edits regular files.`) } else if (packageName && path === `packages/${directory}/package.json`) { checkPackageManifest(path, packageName, before, after) } else if (packageName && path === `packages/${directory}/CHANGELOG.md`) { await checkChangelog(path, packageName, release) changelogs.add(packageName) } else if (packageName && path === `packages/${directory}/oclif.manifest.json`) { checkOclifManifest(path, after[packageName].version) } else if (path === VERSION_FILE) { if (fileAt(HEAD_SHA, path) !== `export const CLI_KIT_VERSION = '${newVersion}'\n`) fail(`${path} must only set CLI_KIT_VERSION to ${newVersion}.`) } else if (path === 'pnpm-lock.yaml') { checkLockfile(before, after) } else { fail(`${path} changed, and a version bump doesn't change it.`) } } checkReportedVersions(newVersion, after) for (const name of Object.keys(after)) checkPins(name, before, after) checkLockfileLinks(after) const kept = pending.filter((path) => !deleted.has(path)) if (kept.length > 0) fail(`The bump leaves changesets pending: ${kept.join(', ')}.`) const withoutSection = Object.keys(after).filter((name) => after[name].version !== before[name].version && !changelogs.has(name)) if (withoutSection.length > 0) fail(`The bump doesn't add a changelog section for ${withoutSection.join(', ')}.`) pass(`#${PR_NUMBER} releases ${newVersion}: one commit on ${BASE_REF}'s head ${lineHead} that only versions the packages and consumes ${deleted.size} changeset(s).`) } // The file keeps every line, and only lines matching `pattern` change. A JSON comparison alone // would miss what JSON.parse normalizes away, such as a duplicated key. function checkChangedLines(path, pattern) { const old = fileAt(lineHead, path).split('\n') const next = fileAt(HEAD_SHA, path).split('\n') const changed = old.length === next.length && old.every((line, index) => line === next[index] || (pattern.test(line) && pattern.test(next[index]))) if (!changed) fail(`${path} changes lines other than versions.`) } // A package.json may change only its version and its exact dependencies on workspace packages. function checkPackageManifest(path, packageName, before, after) { checkChangedLines(path, /^\s*"(version|@shopify\/[a-z0-9-]+)": "\d+\.\d+\.\d+",?$/) const old = before[packageName].manifest const next = after[packageName].manifest const stripped = (manifest) => { const copy = structuredClone(manifest) delete copy.version for (const field of DEPENDENCY_FIELDS) { for (const name of Object.keys(copy[field] ?? {})) { if (before[name]) copy[field][name] = '' } } return JSON.stringify(copy) } if (stripped(old) !== stripped(next)) fail(`${path} changes more than versions.`) } // Each workspace package's dependencies on the others, changed or not. `changeset version` moves // every pin of a package it releases to the new version: a pin left behind would publish the // package with the old version of its dependency. function checkPins(packageName, before, after) { const path = `packages/${after[packageName].directory}/package.json` const old = before[packageName].manifest const next = after[packageName].manifest for (const field of DEPENDENCY_FIELDS) { for (const [name, value] of Object.entries(next[field] ?? {})) { if (!before[name]) continue const pin = old[field]?.[name] if (after[name].version === before[name].version) { if (value !== pin) fail(`${path} moves ${name} from ${pin} to ${value}, and the bump doesn't release ${name}.`) } else if (pin !== before[name].version || value !== after[name].version) { fail(`${path} must move ${name} from ${before[name].version} to ${after[name].version}, as \`changeset version\` does, and it has ${pin} before the bump and ${value} after it.`) } } } } // The importers' entries in a pnpm lockfile, as {"\n\n": {specifier, version}}. function lockfileImporters(text) { const entries = {} const unquote = (key) => key.replace(/^'(.*)'$/, '$1') let inImporters = false let importer let field let entry for (const line of text.split('\n')) { if (/^\S/.test(line)) inImporters = line === 'importers:' if (!inImporters) continue const key = /^( *)(\S.*):$/.exec(line) const value = /^ {8}(specifier|version): (.+)$/.exec(line) if (key?.[1].length === 2) { importer = unquote(key[2]) entry = undefined } else if (key?.[1].length === 4) { field = key[2] entry = undefined } else if (key?.[1].length === 6) { entry = {} entries[`${importer}\n${field}\n${unquote(key[2])}`] = entry } else if (value && entry) { entry[value[1]] = value[2] } } return entries } // The lockfile links every workspace package as its dependents' package.json files pin it, so // an install of the release resolves what the manifests say. function checkLockfileLinks(after) { const importers = lockfileImporters(fileAt(HEAD_SHA, 'pnpm-lock.yaml') ?? '') for (const {directory, manifest} of Object.values(after)) { for (const field of ['dependencies', 'devDependencies', 'optionalDependencies']) { for (const [name, pin] of Object.entries(manifest[field] ?? {})) { if (!after[name]) continue const entry = importers[`packages/${directory}\n${field}\n${name}`] if (entry?.specifier !== pin || entry?.version !== `link:../${after[name].directory}`) { fail(`pnpm-lock.yaml doesn't link ${name} into packages/${directory}'s ${field} at ${pin}, as its package.json pins it.`) } } } } } // The consumed changesets as `changeset version` reads them from the line's head. function consumedChangesets(paths) { return paths.map((path) => { const text = fileAt(lineHead, path) ?? '' const bumps = changesetBumps(text) // @changesets/parse's pattern, so the summary is the text changesets passes to the formatter. const summary = /\s*---([^]*?)\n\s*---(\s*(?:\n|$)[^]*)/.exec(text)?.[2] if (!bumps || bumps.length === 0 || bumps.some(([name]) => name === undefined) || summary === undefined) { fail(`${path} has front matter this check can't read.`) } return {id: path.slice('.changeset/'.length, -'.md'.length), summary: summary.trim(), releases: bumps.map(([name, type]) => ({name, type}))} }) } // The changelog formatter `changeset version` loads from the line's "changelog" setting, read // from the line's head and never from the pull request. async function lineFormatter() { writeFileSync('line-changelog.cjs', fileAt(lineHead, '.changeset/changelog.cjs') ?? '') const {default: formatter} = await import(pathToFileURL(resolve('line-changelog.cjs')).href) if (typeof formatter?.getReleaseLine !== 'function' || typeof formatter?.getDependencyReleaseLine !== 'function') { fail(`${BASE_REF}'s .changeset/changelog.cjs doesn't export getReleaseLine and getDependencyReleaseLine.`) } return formatter } // The section `changeset version` adds for a package, assembled as @changesets/apply-release-plan's // getChangelogEntry does: the formatter's line for each consumed changeset that names the package, // grouped by bump type, then the formatter's line for the workspace dependencies it updates. Changesets // orders the changesets as it reads them from disk and the dependencies as it plans their releases, // so both follow the order they have in `actual`, and every other character must match. async function expectedChangelogSection(packageName, {changesets, formatter, prettier, before, after}, actual) { const position = (text) => (actual.includes(text) ? actual.indexOf(text) : actual.length) const releaseLines = [] for (const changeset of changesets) { const {type} = changeset.releases.find(({name}) => name === packageName) ?? {} if (type) releaseLines.push({type, line: await formatter.getReleaseLine(changeset, type, null)}) } releaseLines.sort((first, second) => position(`\n${first.line}\n`) - position(`\n${second.line}\n`)) const manifest = before[packageName].manifest const dependencies = [] for (const [name, {version}] of Object.entries(before)) { // Changesets reads the range from dependencies, then peerDependencies, and lists it whenever an // exact range no longer matches. const range = manifest.dependencies?.[name] || manifest.peerDependencies?.[name] if (!range || after[name].version === version) continue if (!/^\d+\.\d+\.\d+$/.test(range)) fail(`${packageName} depends on ${name} at ${range}, and this check only rebuilds changelogs for exact workspace versions.`) const ids = changesets.filter(({releases}) => releases.some((release) => release.name === name)).map(({id}) => id) dependencies.push({name, type: 'patch', oldVersion: version, newVersion: after[name].version, changesets: ids}) } dependencies.sort((first, second) => position(`${first.name}@${first.newVersion}`) - position(`${second.name}@${second.newVersion}`)) const dependencyChangesets = changesets.filter(({id}) => dependencies.some((dependency) => dependency.changesets.includes(id))) const dependencyLine = await formatter.getDependencyReleaseLine(dependencyChangesets, dependencies, null) const groups = ['major', 'minor', 'patch'].map((type) => { const lines = [...releaseLines.filter((line) => line.type === type).map(({line}) => line), ...(type === 'patch' ? [dependencyLine] : [])].filter(Boolean) return lines.length > 0 ? `### ${type[0].toUpperCase()}${type.slice(1)} Changes\n\n${lines.join('\n')}\n` : undefined }) const section = [`## ${after[packageName].version}`, ...groups].filter(Boolean).join('\n').trim() // `changeset version` formats the changelog with Prettier, which puts a blank line after each heading. return `${prettier ? section.replace(/^(#{1,6} .*)\n(?!\n)/gm, '$1\n\n') : section}\n\n` } // A changelog only gains, at the top, the section `changeset version` writes for the new version. async function checkChangelog(path, packageName, release) { const {before, after} = release const version = after[packageName].version if (version === before[packageName].version) fail(`${path} changes, and the bump doesn't release ${packageName}.`) const old = fileAt(lineHead, path) const next = fileAt(HEAD_SHA, path) const title = /^# [^\n]*\n\n/.exec(old)?.[0] const rest = old.slice(title?.length ?? 0) const added = next.slice(title?.length ?? 0, next.length - rest.length) if (!title || !next.startsWith(title) || !next.endsWith(rest) || !added.startsWith(`## ${version}\n`)) { fail(`${path} must only gain a "## ${version}" section at the top.`) } const expected = await expectedChangelogSection(packageName, release, added) if (added === expected) return const addedLines = added.split('\n') const expectedLines = expected.split('\n') let index = 0 while (addedLines[index] === expectedLines[index]) index++ const describe = (line) => (line === undefined ? 'the end of the section' : JSON.stringify(line.slice(0, 120))) fail(`${path}'s new section isn't what ${BASE_REF}'s changelog formatter writes for the consumed changesets and dependency updates: line ${index + 3} is ${describe(addedLines[index])}, where it writes ${describe(expectedLines[index])}.`) } // The versions the release reports at run time, whether or not the bump changed their files: // cli-kit's CLI_KIT_VERSION and each package's oclif manifest. A file the bump leaves behind // would publish the release reporting the previous version. function checkReportedVersions(newVersion, after) { if (fileAt(HEAD_SHA, VERSION_FILE) !== `export const CLI_KIT_VERSION = '${newVersion}'\n`) { fail(`${VERSION_FILE} must be exactly "export const CLI_KIT_VERSION = '${newVersion}'", the version the bump releases.`) } for (const {directory, version} of Object.values(after)) { const path = `packages/${directory}/oclif.manifest.json` const text = fileAt(HEAD_SHA, path) if (text === undefined) continue const manifestVersion = JSON.parse(text).version if (manifestVersion !== version) fail(`${path} has version ${manifestVersion}, and the bump releases its package at ${version}.`) } } // An oclif manifest only changes its version. function checkOclifManifest(path, version) { checkChangedLines(path, /^\s*"version": "\d+\.\d+\.\d+",?$/) const old = JSON.parse(fileAt(lineHead, path)) const next = JSON.parse(fileAt(HEAD_SHA, path)) if (next.version !== version || JSON.stringify({...old, version}) !== JSON.stringify(next)) fail(`${path} must only change its version to ${version}.`) } // The lockfile only changes the specifiers of links to workspace packages, each from that package's // old version to its new one. function checkLockfile(before, after) { const old = fileAt(lineHead, 'pnpm-lock.yaml').split('\n') const next = fileAt(HEAD_SHA, 'pnpm-lock.yaml').split('\n') if (old.length !== next.length) fail('pnpm-lock.yaml gains or loses lines; a version bump only changes the specifiers of workspace links.') for (let index = 0; index < old.length; index++) { if (old[index] === next[index]) continue const name = /^\s+'?([^'\s]+?)'?:$/.exec(old[index - 1] ?? '')?.[1] const oldSpecifier = /^(\s+)specifier: (\S+)$/.exec(old[index]) const newSpecifier = /^(\s+)specifier: (\S+)$/.exec(next[index]) const link = /^\s+version: link:/.test(next[index + 1] ?? '') && next[index + 1] === old[index + 1] if ( !name || !before[name] || old[index - 1] !== next[index - 1] || !oldSpecifier || !newSpecifier || oldSpecifier[1] !== newSpecifier[1] || !link || oldSpecifier[2] !== before[name].version || newSpecifier[2] !== after[name].version ) { fail(`pnpm-lock.yaml line ${index + 1} changes more than a workspace link's specifier.`) } } } // A backport: it builds on the line's head, carries only patch changesets for the fixed group, // and its tree is exactly the landing on main that added its changesets, applied to the line's // head. All of that landing, because part of it could ship a fix without its code, or one of // several changes batched in one commit without the changeset that makes it a minor. That // landing must have reached main after the line was cut from it: an older one could carry files // the line has since fixed. None of it can be on the line already, so a fix is never released // twice, and it must change more than changesets, since a changeset alone doesn't say which // change it describes. function checkBackport() { if (!gitSucceeds('merge-base', '--is-ancestor', lineHead, HEAD_SHA)) { fail(`${HEAD_SHA} doesn't build on ${BASE_REF}'s head ${lineHead}. Update the branch.`) } const changes = changedFiles(lineHead, HEAD_SHA) if (changes.length === 0) fail('The pull request changes nothing.') const kept = changes.filter(({path}) => KEPT_PATHS.some((prefix) => (prefix.endsWith('/') ? path.startsWith(prefix) : path === prefix))) if (kept.length > 0) fail(`It changes files main's backports never change: ${kept.map(({path}) => path).join(', ')}.`) const changesets = changes.filter(({path}) => changesetPath(path)) const otherChangesets = changesets.filter(({status}) => status !== 'A') if (otherChangesets.length > 0) fail(`It edits or deletes changesets: ${otherChangesets.map(({path}) => path).join(', ')}.`) if (changesets.length === 0) fail("It adds no changeset, so it isn't a backport of a fix.") const fixed = fixedGroup(lineHead) for (const {path} of changesets) { if (!/^\.changeset\/[A-Za-z0-9._-]+\.md$/.test(path)) fail(`Unexpected changeset name: ${path}.`) const bumps = changesetBumps(fileAt(HEAD_SHA, path)) if (!bumps || bumps.length === 0 || bumps.some(([name]) => name === undefined)) fail(`${path} has front matter this check can't read.`) for (const [name, bump] of bumps) { if (bump !== 'patch' || !fixed.has(name)) fail(`${path} bumps ${name} ${bump}; a backport carries only patch changesets for the fixed group.`) } } const mainHead = git('rev-parse', 'refs/remotes/origin/main') const cut = spawnSync('git', ['merge-base', mainHead, lineHead], {encoding: 'utf8'}).stdout.trim() if (!/^[0-9a-f]{40}$/.test(cut)) fail(`Couldn't find where ${BASE_REF} was cut from main.`) // The line was cut from one of main's landings, so main's first-parent commits after the // cut are the landings the line doesn't have. if (!git('rev-list', '--first-parent', mainHead).split('\n').includes(cut)) { fail(`${BASE_REF}'s cut ${cut} isn't on main's first-parent history, so this check can't tell which commits reached main after it.`) } // The commit on main's first-parent chain since the cut that added each changeset: a landing, // compared with main before it. A merged pull request's own commits never count, because one // of them can carry a changeset its merge changed. One backport brings one change, so they // must all be the same commit. const additions = new Map() const origins = new Set() for (const {path} of changesets) { const added = git('log', '--first-parent', '--reverse', '--format=%H', `${cut}..${mainHead}`, '--', path) .split('\n') .filter((commit) => commit !== '' && hasFile(commit, path) && !hasFile(`${commit}^1`, path)) const [origin] = added if (!origin) fail(`main hasn't added ${path} since ${BASE_REF} was cut from it at ${cut}, so this isn't a backport of a fix main has and the line lacks.`) additions.set(path, added) origins.add(origin) } if (origins.size !== 1) fail(`Its changesets came to main in different commits: ${[...origins].join(', ')}. Backport them one at a time.`) const [origin] = origins // A changeset the line has had since its cut came with an earlier backport of the fix, and a // release may have consumed it since: a second backport would release the fix again. for (const {path} of changesets) { const [sinceCut] = git('log', '--full-history', '--reverse', '--format=%H', `${cut}..${lineHead}`, '--', path).split('\n').filter(Boolean) if (sinceCut) fail(`${BASE_REF} has had ${path} since ${sinceCut}, so the line already has this fix, and a release may have shipped it.`) } // main's commit applied to the line's head. const merged = spawnSync('git', ['merge-tree', '--write-tree', '--name-only', '--no-messages', `--merge-base=${origin}^1`, lineHead, origin], {encoding: 'utf8', maxBuffer: 64 * 1024 * 1024}) if (merged.status !== 0 && merged.status !== 1) fail(`Couldn't apply main's ${origin} to ${BASE_REF}: ${merged.stderr.trim()}`) const [mergedTree, ...conflicted] = merged.stdout.trim().split('\n') if (merged.status === 1) fail(`main's ${origin} doesn't apply cleanly to ${BASE_REF}: ${conflicted.join(', ')}.`) const changedByOrigin = new Set(changedFiles(`${origin}^1`, origin).map(({path}) => path)) for (const {path} of changes) { if (!changedByOrigin.has(path)) fail(`It changes ${path}, which main's ${origin} doesn't change.`) if (entryAt(mergedTree, path) !== entryAt(HEAD_SHA, path)) fail(`Its ${path} isn't main's ${origin} applied to ${BASE_REF}.`) } const changed = new Set(changes.map(({path}) => path)) const leftOut = changedFiles(lineHead, mergedTree).map(({path}) => path).filter((path) => !changed.has(path)) if (leftOut.length > 0) { fail(`It leaves out ${leftOut.join(', ')}, which main's ${origin} also changes. A backport brings the whole commit, so a fix that reached main together with other changes needs a maintainer.`) } // Undoing the whole commit must restore the line's tree. If the line already contains // one edit, undoing it also removes that edit, even when another edit in the same file is new. let restoredTree try { restoredTree = git('merge-tree', '--write-tree', '--no-messages', `--merge-base=${origin}`, mergedTree, `${origin}^1`) } catch (error) { if (error.status === 1) fail(`Undoing main's ${origin} on the backport conflicts, so this check can't verify that the whole fix is new to ${BASE_REF}.`) fail(`Couldn't undo main's ${origin} on the backport: ${error.stderr?.toString().trim() || error.message}`) } if (restoredTree !== git('rev-parse', `${lineHead}^{tree}`)) { const paths = changedFiles(lineHead, restoredTree).map(({path}) => path) fail(`Undoing main's ${origin} would also change ${paths.join(', ')} on ${BASE_REF}. The line may already have part of this fix.`) } // A changeset that reached main on its own, such as one added after its fix landed without // it, says nothing about which change it describes or whether the line has that change. if (changes.every(({path}) => changesetPath(path))) { fail("It changes only changesets, so it can't be checked against the change they describe. A maintainer backports the fix together with its changeset.") } // main must still have the fix as a patch. A changeset main has since removed, as a revert // does, or raised above a patch would ship a change main no longer has, or a feature as a // fix. Only the bumps count, so an edited summary doesn't hold a backport. for (const {path} of changesets) { const text = fileAt(mainHead, path) if (text !== undefined) { checkPatchOnly(text, `main's copy of ${path}`, fixed) } else { const release = releaseConsuming(path, origin, mainHead) checkPatchOnly(fileAt(`${release}^1`, path), `main's last copy of ${path}, before the release in ${release} consumed it,`, fixed) } } // A changeset main added more than once since the cut was reverted and relanded, and history // can't tell which landing the backport should be. for (const [path, added] of additions) { if (added.length > 1) fail(`main added ${path} more than once since ${BASE_REF}'s cut, in ${added.join(', ')}: it reverted and relanded it, so this check can't tell which landing the backport should be.`) } checkMainStillHas(origin, mainHead) pass(`#${PR_NUMBER} backports main's ${origin}: its ${changesets.length} changeset(s) are patch changesets for the fixed group, and its tree is that commit applied to ${BASE_REF}'s head ${lineHead}.`) } // A changeset's bumps, read from main, must still be patches for the fixed group. function checkPatchOnly(text, copy, fixed) { const bumps = changesetBumps(text ?? '') if (!bumps || bumps.length === 0 || bumps.some(([name]) => name === undefined)) fail(`${copy} has front matter this check can't read.`) for (const [name, bump] of bumps) { if (bump !== 'patch' || !fixed.has(name)) fail(`${copy} bumps ${name} ${bump}; a backport carries only patch changesets for the fixed group.`) } } // The landing that removed a changeset main no longer has. The fix is still one main has only // when a release consumed it: that landing also moves cli-kit's version, as a release's catch-up // to main does. Any other deletion, a revert's or a drop of changesets without a release, fails, // and a maintainer backports such a fix to an older line. function releaseConsuming(path, origin, mainHead) { const deletion = git('log', '--first-parent', '--reverse', '--format=%H', `${origin}..${mainHead}`, '--', path) .split('\n') .find((commit) => commit !== '' && !hasFile(commit, path)) const cliKitVersion = (commit) => JSON.parse(fileAt(commit, 'packages/cli-kit/package.json') ?? '{}').version if (!deletion || cliKitVersion(deletion) === cliKitVersion(`${deletion}^1`)) { fail(`main removed ${path} in ${deletion} without a release, so this isn't a fix main still has.`) } return deletion } // Reapplying the fix must leave main's tree unchanged outside changesets. Git can apply // the fix at a new path after a rename or report a conflict in a file the fix added. function checkMainStillHas(origin, mainHead) { const merged = spawnSync('git', ['merge-tree', '--write-tree', '--name-only', '--no-messages', '-z', `--merge-base=${origin}^1`, mainHead, origin], {encoding: 'utf8', maxBuffer: 64 * 1024 * 1024}) if (merged.status !== 0 && merged.status !== 1) fail(`Couldn't apply main's ${origin} to main's head ${mainHead}: ${merged.stderr.trim()}`) const [mergedTree, ...conflicted] = merged.stdout.split('\0').filter(Boolean) const changedPaths = changedFiles(mainHead, mergedTree).map(({path}) => path) const notOnMain = [...new Set([...changedPaths, ...conflicted])].filter((path) => !changesetPath(path)) if (notOnMain.length > 0) { fail(`Reapplying main's ${origin} to ${mainHead} changes or conflicts with ${notOnMain.join(', ')}. A maintainer decides whether ${BASE_REF} takes this fix.`) } } SCRIPT node check.mjs