From 03de0925b7a4a4ad8311cee1038da7635cc761ca Mon Sep 17 00:00:00 2001 From: Craig Martin Date: Wed, 25 Nov 2026 08:29:13 -0500 Subject: [PATCH 1/3] Check stable-line pull requests with Patch QA and Patch provenance Patch QA builds the @shopify/cli tarball a release of the pull request's head would publish, installs it on Linux, Windows and macOS (x64 and arm64), runs the checks that need no Shopify account, and fails if its files differ from the line's last release. Patch provenance passes only for a backport whose changes main already has (pinned to the main commit that added its patch changesets) and for the line's Version Packages pull request when it only versions the packages on top of the line's head. It runs from the stable line's own copy of the workflow and reads commits without running the pull request's code. After a release publishes, release.yml installs it from npm on Linux, Windows and macOS and runs the same checks. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 70e53331ae405304dabb801611439e3d986f5867) --- .github/scripts/smoke-test-cli.sh | 81 +++++++ .github/workflows/patch-provenance.yml | 313 +++++++++++++++++++++++++ .github/workflows/patch-qa.yml | 230 ++++++++++++++++++ .github/workflows/release.yml | 61 +++++ 4 files changed, 685 insertions(+) create mode 100755 .github/scripts/smoke-test-cli.sh create mode 100644 .github/workflows/patch-provenance.yml create mode 100644 .github/workflows/patch-qa.yml diff --git a/.github/scripts/smoke-test-cli.sh b/.github/scripts/smoke-test-cli.sh new file mode 100755 index 00000000000..162555c5bdd --- /dev/null +++ b/.github/scripts/smoke-test-cli.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# Runs the checks that need no Shopify account against the globally installed `shopify`. +# Works on Linux, macOS and Git Bash on Windows. +# +# Usage: smoke-test-cli.sh +set -euo pipefail + +if [ "$#" -ne 1 ] || [ -z "$1" ]; then + echo "Usage: $0 " >&2 + exit 2 +fi +EXPECTED_VERSION="$1" + +# No color codes in the output, no prompts, no analytics, and no auto-upgrade, which the CLI skips +# when CI is set. +export NO_COLOR=1 +export SHOPIFY_CLI_NO_ANALYTICS=1 +export CI=1 + +WORK_DIR=$(mktemp -d) +trap 'rm -rf "$WORK_DIR"' EXIT +cd "$WORK_DIR" + +CURRENT_CASE="" +trap 'echo "::error::Smoke test failed: $CURRENT_CASE"' ERR + +start_case() { + CURRENT_CASE="$1" + echo + echo "=== $1" +} + +fail() { + echo "::error::$CURRENT_CASE: $1" + exit 1 +} + +start_case "Turn off auto-upgrade" +shopify config autoupgrade off + +start_case "shopify version is $EXPECTED_VERSION" +VERSION_OUTPUT=$(shopify version) +echo "$VERSION_OUTPUT" +# Exact match on one whitespace-separated token, so 5.1.1 doesn't match 5.1.10. +if ! tr -s ' \t\r' '\n' <<< "$VERSION_OUTPUT" | grep -Fxq "$EXPECTED_VERSION"; then + fail "expected version $EXPECTED_VERSION, got: $VERSION_OUTPUT" +fi + +start_case "shopify help" +shopify help + +start_case "shopify commands" +COMMANDS_OUTPUT=$(shopify commands) +echo "Listed $(wc -l <<< "$COMMANDS_OUTPUT" | tr -d ' ') lines of commands" + +# Each topic's help loads the plugin that provides it. +for TOPIC in app theme hydrogen; do + start_case "shopify $TOPIC --help" + shopify "$TOPIC" --help +done + +# --latest checks out the repository's latest tag without prompting. The explicit URL takes the +# Git-only path: the default Skeleton URL looks up its release through the GitHub API, whose +# unauthenticated rate limit is shared by every machine behind the same address. +start_case "shopify theme init" +shopify theme init qa-theme --clone-url https://github.com/Shopify/skeleton-theme --latest +[ -f qa-theme/config/settings_schema.json ] || fail "qa-theme/config/settings_schema.json is missing" + +# The default fail level, error, lets warnings and suggestions pass. +start_case "shopify theme check" +shopify theme check --path qa-theme --fail-level error + +start_case "shopify theme package" +shopify theme package --path qa-theme +ZIPS=$(find qa-theme -maxdepth 1 -name '*.zip') +[ -n "$ZIPS" ] || fail "no .zip file in qa-theme" +echo "Packaged $ZIPS" + +CURRENT_CASE="" +echo +echo "All smoke tests passed for @shopify/cli $EXPECTED_VERSION" diff --git a/.github/workflows/patch-provenance.yml b/.github/workflows/patch-provenance.yml new file mode 100644 index 00000000000..37be6f5af14 --- /dev/null +++ b/.github/workflows/patch-provenance.yml @@ -0,0 +1,313 @@ +name: Patch provenance + +# Passes only for the two kinds of pull request that bring a stable line nothing main doesn't have: +# - a backport whose changes main already has: everything it changes matches the main commit that +# added its changesets, and it carries only patch changesets for the fixed version group; +# - the line's Version Packages pull request: one commit on top of the line's head that only versions +# the packages. +# Any other pull request into a stable line fails this check, and a maintainer reviews and merges it. +# +# It runs on pull_request_target, so this file comes from the stable line, not from the pull request, +# and it never checks out or runs the pull request's code: it only reads commits. +on: + pull_request_target: + types: [opened, synchronize, reopened, edited] + branches: + - 'stable/**' + +permissions: + contents: read + +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: + GH_TOKEN: ${{ github.token }} + 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} from 'node:child_process' + import {appendFileSync} from 'node:fs' + + 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 + } + } + const fileAt = (commit, path) => { + try { + return execFileSync('git', ['show', `${commit}:${path}`], {encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore']}) + } catch { + return undefined + } + } + 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) + } + // Fetches more history until `commit` reaches `base`, so merge bases are found in a shallow repository. + function deepen(ref, base) { + for (const depth of [50, 200, 1000, 5000]) { + git('fetch', '--quiet', '--no-tags', `--depth=${depth}`, 'origin', ref) + if (base === undefined || gitSucceeds('merge-base', base, ref)) return + } + } + const changesetPath = (path) => /^\.changeset\/[^/]+\.md$/.test(path) && path !== '.changeset/README.md' + // [{status, path}] for base..head, without rename detection, and with paths exactly as stored. + function changedFiles(base, head) { + const fields = run('git', ['diff', '--name-status', '--no-renames', '-z', base, head]).split('\0') + const changes = [] + for (let index = 0; index + 1 < fields.length; index += 2) changes.push({status: fields[index], path: fields[index + 1]}) + return changes + } + // {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', '.') + git('remote', 'add', 'origin', `https://github.com/${repository}`) + const lineHead = git('ls-remote', 'origin', `refs/heads/${BASE_REF}`).split('\t')[0] + if (!/^[0-9a-f]{40}$/.test(lineHead)) fail(`Couldn't read the head of ${BASE_REF}.`) + deepen(lineHead) + deepen(HEAD_SHA, lineHead) + if (!gitSucceeds('merge-base', lineHead, HEAD_SHA)) fail(`${HEAD_SHA} doesn't share history with ${BASE_REF}.`) + + if (HEAD_REF === `changeset-release/${BASE_REF}`) { + 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. + function checkVersionPackages() { + if (HEAD_REPO !== repository) fail(`A Version Packages pull request comes from ${repository}, not ${HEAD_REPO}.`) + 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 + 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() + for (const {status, path} of changedFiles(lineHead, HEAD_SHA)) { + 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 (packageName && path === `packages/${directory}/package.json`) { + checkPackageManifest(path, packageName, before, after) + } else if (packageName && path === `packages/${directory}/CHANGELOG.md`) { + checkChangelog(path, after[packageName].version) + } 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.`) + } + } + const kept = pending.filter((path) => !deleted.has(path)) + if (kept.length > 0) fail(`The bump leaves changesets pending: ${kept.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).`) + } + + // A package.json may change only its version and its exact dependencies on workspace packages, + // each moving from that package's old version to its new one. + function checkPackageManifest(path, packageName, before, after) { + 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.`) + for (const field of DEPENDENCY_FIELDS) { + for (const [name, value] of Object.entries(next[field] ?? {})) { + if (!before[name] || value === old[field][name]) continue + if (old[field][name] !== before[name].version || value !== after[name].version) { + fail(`${path} moves ${name} from ${old[field][name]} to ${value}, not from ${before[name].version} to ${after[name].version}.`) + } + } + } + } + + // A changelog only gains a section for the new version at the top. + function checkChangelog(path, version) { + 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`) || /^## /m.test(added.slice(1))) { + fail(`${path} must only gain a "## ${version}" section at the top.`) + } + } + + // An oclif manifest only changes its version. + function checkOclifManifest(path, version) { + 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 carries only patch changesets for the fixed group, changes only paths that come + // from main's mirrored history, and everything it changes is already in the main commit that + // added its changesets. + function checkBackport() { + const mergeBase = git('merge-base', lineHead, HEAD_SHA) + const changes = changedFiles(mergeBase, 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) fail(`${path} declares no package bumps.`) + for (const [name, bump] of bumps) { + if (bump !== 'patch' || !fixed.has(name)) fail(`${path} bumps ${name ?? 'an unreadable entry'} ${bump ?? ''}; a backport carries only patch changesets for the fixed group.`) + } + } + // The first commit on main that added each changeset. One backport brings one change, so they + // must all be the same commit. + const origins = new Set() + for (const {path} of changesets) { + const commits = run('gh', ['api', '--paginate', `repos/${repository}/commits?sha=main&path=${encodeURIComponent(path)}&per_page=100`, '--jq', '.[].sha']) + .split('\n') + .filter(Boolean) + .reverse() + const origin = commits.find((commit) => { + git('fetch', '--quiet', '--no-tags', '--depth=2', 'origin', commit) + return fileAt(commit, path) !== undefined && fileAt(`${commit}^1`, path) === undefined + }) + if (!origin) fail(`main has never added ${path}, so this isn't a backport of a change main already has.`) + 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 + // Merging the backport into that main commit, from the backport's own base, must leave the + // commit unchanged: then every change the backport makes is already on main. + let mergedTree + try { + mergedTree = run('git', ['merge-tree', '--write-tree', '--no-messages', `--merge-base=${mergeBase}`, origin, HEAD_SHA]).split('\n')[0] + } catch { + fail(`Its changes conflict with main's ${origin}, so they aren't the same changes.`) + } + if (mergedTree !== git('rev-parse', `${origin}^{tree}`)) { + fail(`It changes things that main's ${origin} doesn't have.`) + } + pass(`#${PR_NUMBER} backports main's ${origin}: its ${changesets.length} changeset(s) are patch changesets for the fixed group, and everything it changes since ${mergeBase} is already in ${origin}.`) + } + SCRIPT + node check.mjs diff --git a/.github/workflows/patch-qa.yml b/.github/workflows/patch-qa.yml new file mode 100644 index 00000000000..47b835560c8 --- /dev/null +++ b/.github/workflows/patch-qa.yml @@ -0,0 +1,230 @@ +name: Patch QA + +# Tests every pull request into a stable line with the @shopify/cli tarball that a release of its +# head would publish: installs it on each supported platform, runs the checks that need no Shopify +# account, and compares its files with the line's last release. Nothing is published. +on: + pull_request: + branches: + - 'stable/**' + +permissions: + contents: read + +concurrency: + group: patch-qa-${{ github.event.pull_request.number }} + cancel-in-progress: true + +env: + PNPM_VERSION: '10.11.1' + +jobs: + package: + name: Build the release tarball + runs-on: ubuntu-latest + timeout-minutes: 40 + outputs: + tarball: ${{ steps.pack.outputs.tarball }} + version: ${{ steps.pack.outputs.version }} + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + + - name: Verify the checked-out commit + env: + SHA: ${{ github.event.pull_request.head.sha }} + run: | + set -euo pipefail + HEAD_SHA=$(git rev-parse HEAD) + if [ "$HEAD_SHA" != "$SHA" ]; then + echo "::error::Checked out $HEAD_SHA instead of $SHA." + exit 1 + fi + + - name: Setup deps + uses: ./.github/actions/setup-cli-deps + with: + node-version: 24.22.1 + + # The same build the release runs, before it publishes. + - name: Bundle + run: pnpm bundle-for-release + env: + SHOPIFY_CLI_BUILD_REPO: ${{ github.repository }} + + # The release's prepack also generates the manifest and copies the README. Its error-reporting + # source map upload is left out, and the tarball excludes source maps either way. + - name: Pack @shopify/cli + id: pack + working-directory: packages/cli + run: | + set -euo pipefail + pnpm oclif manifest + cp ../../README.md README.md + TARBALL=$(npm pack --ignore-scripts | tail -n 1) + VERSION=$(tar -xzOf "$TARBALL" package/package.json | node -p 'JSON.parse(require("node:fs").readFileSync(0, "utf8")).version') + { + echo "tarball=$TARBALL" + echo "version=$VERSION" + } >> "$GITHUB_OUTPUT" + + - name: Upload the tarball + uses: actions/upload-artifact@v4 + with: + name: shopify-cli-${{ github.event.pull_request.head.sha }} + path: packages/cli/${{ steps.pack.outputs.tarball }} + if-no-files-found: error + # The tarball is already compressed. + compression-level: 0 + + # A patch release should ship the same files as the release before it. Bundle chunk names carry + # a content hash, which changes with any code change, so they're compared by count only. + - name: Compare the files with the line's last release + working-directory: packages/cli + env: + TARBALL: ${{ steps.pack.outputs.tarball }} + VERSION: ${{ steps.pack.outputs.version }} + run: | + set -euo pipefail + # The highest release of this major.minor that isn't newer than this version. A pull + # request that doesn't change the version compares with the release of that version. + PREVIOUS=$(npm view @shopify/cli versions --json --registry=https://registry.npmjs.org/ | node -e ' + const [major, minor, patch] = process.argv[1].split(".").map(Number) + const versions = JSON.parse(require("node:fs").readFileSync(0, "utf8")) + const previous = versions + .filter((version) => /^\d+\.\d+\.\d+$/.test(version)) + .map((version) => version.split(".").map(Number)) + .filter((parts) => parts[0] === major && parts[1] === minor && parts[2] <= patch) + .sort((a, b) => b[2] - a[2])[0] + console.log(previous ? previous.join(".") : "") + ' "$VERSION") + if [ -z "$PREVIOUS" ]; then + echo "::notice::No earlier ${VERSION%.*} release on npm, so there's nothing to compare $VERSION's files with." + { + echo "### @shopify/cli $VERSION files" + echo + echo "No earlier ${VERSION%.*} release to compare with." + } >> "$GITHUB_STEP_SUMMARY" + exit 0 + fi + + PREVIOUS_URL=$(npm view "@shopify/cli@$PREVIOUS" dist.tarball --registry=https://registry.npmjs.org/) + curl --fail --silent --show-error --location --retry 3 --output "$RUNNER_TEMP/previous.tgz" "$PREVIOUS_URL" + + # esbuild names chunks like dist/chunk-2AW3KBTP.js: an 8-character hash before .js. + list_files() { + tar -tzf "$1" | sed -E 's/-[A-Z0-9]{8}\.js$/-[hash].js/' | LC_ALL=C sort + } + list_files "$TARBALL" > "$RUNNER_TEMP/current-files.txt" + list_files "$RUNNER_TEMP/previous.tgz" > "$RUNNER_TEMP/previous-files.txt" + CURRENT_COUNT=$(wc -l < "$RUNNER_TEMP/current-files.txt" | tr -d ' ') + PREVIOUS_COUNT=$(wc -l < "$RUNNER_TEMP/previous-files.txt" | tr -d ' ') + # comm on sorted lists pairs repeated lines one to one, so this compares them as multisets. + ADDED=$(LC_ALL=C comm -13 "$RUNNER_TEMP/previous-files.txt" "$RUNNER_TEMP/current-files.txt" | uniq -c) + REMOVED=$(LC_ALL=C comm -23 "$RUNNER_TEMP/previous-files.txt" "$RUNNER_TEMP/current-files.txt" | uniq -c) + + if [ -z "$ADDED" ] && [ -z "$REMOVED" ]; then + RESULT="Same files" + else + RESULT="Different files" + fi + { + echo "### @shopify/cli $VERSION files" + echo + echo "| | |" + echo "| --- | --- |" + echo "| Version | \`$VERSION\` |" + echo "| Compared with | \`$PREVIOUS\` |" + echo "| Files in $VERSION | $CURRENT_COUNT |" + echo "| Files in $PREVIOUS | $PREVIOUS_COUNT |" + echo "| Result | $RESULT |" + if [ "$RESULT" != "Same files" ]; then + echo + echo "Added (count, file):" + echo + echo '```' + echo "${ADDED:-none}" + echo '```' + echo + echo "Removed (count, file):" + echo + echo '```' + echo "${REMOVED:-none}" + echo '```' + fi + } >> "$GITHUB_STEP_SUMMARY" + + if [ "$RESULT" = "Same files" ]; then + echo "$VERSION has the same $CURRENT_COUNT files as $PREVIOUS, apart from chunk hashes." + exit 0 + fi + MESSAGE="$VERSION's files differ from $PREVIOUS's ($CURRENT_COUNT files, was $PREVIOUS_COUNT). A patch release should ship the same files. + Added (count, file): + ${ADDED:-none} + Removed (count, file): + ${REMOVED:-none}" + # Annotations are one line: escape % and encode newlines. + NEWLINE=$'\n' + PERCENT=% + MESSAGE=${MESSAGE//$PERCENT/%25} + MESSAGE=${MESSAGE//$NEWLINE/%0A} + echo "::error::$MESSAGE" + exit 1 + + install: + name: Patch QA on ${{ matrix.os }} + needs: package + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, ubuntu-24.04-arm, windows-latest, windows-11-arm, macos-latest] + steps: + # Only the smoke test script, so no project files affect the global install. + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + sparse-checkout: .github/scripts/smoke-test-cli.sh + sparse-checkout-cone-mode: false + + - name: Install Node.js + uses: actions/setup-node@v6 + with: + node-version: 24.22.1 + + - name: Download the tarball + uses: actions/download-artifact@v4 + with: + name: shopify-cli-${{ github.event.pull_request.head.sha }} + path: tarball + + - name: Install @shopify/cli globally + shell: bash + env: + TARBALL: ${{ needs.package.outputs.tarball }} + run: | + set -euo pipefail + npm install -g "./tarball/$TARBALL" --registry=https://registry.npmjs.org/ + + - name: Run the smoke tests + shell: bash + env: + VERSION: ${{ needs.package.outputs.version }} + run: | + set -euo pipefail + bash .github/scripts/smoke-test-cli.sh "$VERSION" + + gate: + name: Patch QA + needs: [package, install] + if: always() + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Verify the tarball and every platform passed + if: needs.package.result != 'success' || needs.install.result != 'success' + run: exit 1 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2c0916f4ffe..91e3d667d6c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -351,6 +351,67 @@ jobs: -f make_latest=legacy >/dev/null echo "Created release $TAG" + # Installs the release from the public registry, as users get it, and runs the checks that need + # no Shopify account. + smoke: + name: Smoke test the published release on ${{ matrix.os }} + needs: [check, publish] + if: ${{ !cancelled() && needs.publish.result == 'success' }} + runs-on: ${{ matrix.os }} + timeout-minutes: 40 + permissions: + contents: read + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + steps: + # Only the smoke test script, so no project files affect the global install. + - uses: actions/checkout@v6 + with: + ref: ${{ github.sha }} + persist-credentials: false + sparse-checkout: .github/scripts/smoke-test-cli.sh + sparse-checkout-cone-mode: false + + - name: Install Node.js + uses: actions/setup-node@v6 + with: + node-version: 24.22.1 + + # A new version can take a few minutes to appear in the registry's metadata. + - name: Wait for the release on npm + shell: bash + env: + VERSION: ${{ needs.check.outputs.version }} + run: | + set -euo pipefail + for attempt in $(seq 1 60); do + if [ "$(npm view "@shopify/cli@$VERSION" version --prefer-online --registry=https://registry.npmjs.org/ 2>/dev/null || true)" = "$VERSION" ]; then + echo "@shopify/cli $VERSION is on npm" + exit 0 + fi + if [ "$attempt" != 60 ]; then sleep 30; fi + done + echo "::error::@shopify/cli $VERSION didn't appear on npm within 30 minutes." + exit 1 + + - name: Install @shopify/cli globally + shell: bash + env: + VERSION: ${{ needs.check.outputs.version }} + run: | + set -euo pipefail + npm install -g "@shopify/cli@$VERSION" --prefer-online --registry=https://registry.npmjs.org/ + + - name: Run the smoke tests + shell: bash + env: + VERSION: ${{ needs.check.outputs.version }} + run: | + set -euo pipefail + bash .github/scripts/smoke-test-cli.sh "$VERSION" + # A scheduled nightly of an unchanged main would publish the same code again under a new version. nightly-changes: name: Check for changes since the last nightly From bbff8b07a8c3a6cdfd9b3e40fbf56fc79734487b Mon Sep 17 00:00:00 2001 From: Craig Martin Date: Wed, 25 Nov 2026 08:31:04 -0500 Subject: [PATCH 2/3] Check versioned files line by line in Patch provenance A JSON comparison of package.json and oclif manifests misses changes that parsing normalizes away, such as a duplicated key. Require the same lines, with only version lines changed. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 74e567d2449fd3416cc10c553f143051d6798486) --- .github/workflows/patch-provenance.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.github/workflows/patch-provenance.yml b/.github/workflows/patch-provenance.yml index 37be6f5af14..6792e6da9cc 100644 --- a/.github/workflows/patch-provenance.yml +++ b/.github/workflows/patch-provenance.yml @@ -190,9 +190,19 @@ jobs: 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, // each moving from that package's old version to its new one. 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) => { @@ -230,6 +240,7 @@ jobs: // 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}.`) From 3e4f8efba09f7c4ae1f148eb8077faeb62a2da28 Mon Sep 17 00:00:00 2001 From: Craig Martin Date: Wed, 25 Nov 2026 08:48:04 -0500 Subject: [PATCH 3/3] Tighten Patch provenance for backports and Version Packages changelogs A backport now has to build on the line's head, and each file it changes has to be, whole, what the main commit that added its changesets does to that file when applied to the line. That commit must have reached main after the line's cut. Before, a backport could reuse an old changeset to bring back old main code, or apply only part of a main commit's change. A Version Packages pull request's new changelog section may only hold the consumed changesets' entries and dependency updates, and no versioned file may change mode. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 477ca190bc811b40ba42d53cbe57b499066af61c) --- .github/workflows/patch-provenance.yml | 107 ++++++++++++++++++------- 1 file changed, 80 insertions(+), 27 deletions(-) diff --git a/.github/workflows/patch-provenance.yml b/.github/workflows/patch-provenance.yml index 6792e6da9cc..1f0c16517b0 100644 --- a/.github/workflows/patch-provenance.yml +++ b/.github/workflows/patch-provenance.yml @@ -41,7 +41,7 @@ jobs: mkdir "$RUNNER_TEMP/provenance" cd "$RUNNER_TEMP/provenance" cat > check.mjs <<'SCRIPT' - import {execFileSync} from 'node:child_process' + import {execFileSync, spawnSync} from 'node:child_process' import {appendFileSync} from 'node:fs' const {GITHUB_REPOSITORY: repository, PR_NUMBER, BASE_REF, HEAD_REF, HEAD_SHA, HEAD_REPO} = process.env @@ -88,13 +88,26 @@ jobs: } } const changesetPath = (path) => /^\.changeset\/[^/]+\.md$/.test(path) && path !== '.changeset/README.md' - // [{status, path}] for base..head, without rename detection, and with paths exactly as stored. + // [{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', '--name-status', '--no-renames', '-z', base, head]).split('\0') + 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) changes.push({status: fields[index], path: fields[index + 1]}) + 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('ls-tree', '--full-tree', commit, '--', path).split('\t')[0] + function api(path) { + try { + return JSON.parse(run('gh', ['api', path])) + } catch (error) { + fail(`Reading ${path} from GitHub failed: ${error.stderr?.toString().trim() || error.message}`) + } + } // {name: {directory, version, manifest}} for the workspace packages at a commit. function packagesAt(commit) { const packages = {} @@ -123,6 +136,9 @@ jobs: } git('init', '--quiet', '.') + // Background maintenance after a fetch can hold the shallow lock while the next fetch starts. + git('config', 'maintenance.auto', 'false') + git('config', 'gc.auto', '0') git('remote', 'add', 'origin', `https://github.com/${repository}`) const lineHead = git('ls-remote', 'origin', `refs/heads/${BASE_REF}`).split('\t')[0] if (!/^[0-9a-f]{40}$/.test(lineHead)) fail(`Couldn't read the head of ${BASE_REF}.`) @@ -164,17 +180,21 @@ jobs: .filter(changesetPath) if (pending.length === 0) fail(`${BASE_REF} has no pending changesets, so there's nothing to release.`) const deleted = new Set() - for (const {status, path} of changedFiles(lineHead, HEAD_SHA)) { + const changes = changedFiles(lineHead, HEAD_SHA) + const entries = changesetEntries(changes.filter(({status, path}) => changesetPath(path) && status === 'D').map(({path}) => path)) + 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`) { - checkChangelog(path, after[packageName].version) + checkChangelog(path, after[packageName].version, entries, after) } else if (packageName && path === `packages/${directory}/oclif.manifest.json`) { checkOclifManifest(path, after[packageName].version) } else if (path === VERSION_FILE) { @@ -226,16 +246,38 @@ jobs: } } - // A changelog only gains a section for the new version at the top. - function checkChangelog(path, version) { + // The changelog lines .changeset/changelog.cjs writes for the consumed changesets. + function changesetEntries(paths) { + const lines = new Set() + for (const path of paths) { + const summary = (fileAt(lineHead, path) ?? '').replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '').trim() + const [first, ...others] = summary.split('\n').map((line) => line.trimEnd()) + lines.add(`- ${first}`) + for (const line of others) lines.add(` ${line}`) + } + return lines + } + + // A changelog only gains a section for the new version at the top, made of the consumed + // changesets' entries and the workspace dependencies at their new versions. + function checkChangelog(path, version, entries, after) { 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`) || /^## /m.test(added.slice(1))) { + if (!title || !next.startsWith(title) || !next.endsWith(rest) || !added.startsWith(`## ${version}\n`)) { fail(`${path} must only gain a "## ${version}" section at the top.`) } + const headings = new Set(['', '### Patch Changes', '- Updated dependencies']) + for (const line of added.split('\n').slice(1)) { + // ` - name@version` under "- Updated dependencies", or `- name@version` on older lines. + const dependency = /^(?: )?- (@shopify\/[a-z0-9-]+)@(\S+)$/.exec(line) + // Older lines' changelogs prefix each entry with the commit that added its changeset. + const entry = line.replace(/^- [0-9a-f]{7,40}: /, '- ') + if (headings.has(line) || entries.has(entry) || (dependency && after[dependency[1]]?.version === dependency[2])) continue + fail(`${path}'s new section has a line that no consumed changeset or dependency update writes: ${JSON.stringify(line.slice(0, 120))}`) + } } // An oclif manifest only changes its version. @@ -268,26 +310,33 @@ jobs: } } - // A backport: it carries only patch changesets for the fixed group, changes only paths that come - // from main's mirrored history, and everything it changes is already in the main commit that - // added its changesets. + // A backport: it builds on the line's head, carries only patch changesets for the fixed group, + // and every file it changes is, whole, what the main commit that added its changesets does to + // that file when applied to the line's head. That commit must have reached main after the line + // was cut from it: an older one could carry files the line has since fixed. function checkBackport() { - const mergeBase = git('merge-base', lineHead, HEAD_SHA) - const changes = changedFiles(mergeBase, HEAD_SHA) + for (const depth of [50, 200, 1000, 5000]) { + if (gitSucceeds('merge-base', '--is-ancestor', lineHead, HEAD_SHA)) break + git('fetch', '--quiet', '--no-tags', `--depth=${depth}`, 'origin', HEAD_SHA) + } + 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.') + 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) fail(`${path} declares no package bumps.`) + 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 ?? 'an unreadable entry'} ${bump ?? ''}; a backport carries only patch changesets for the fixed group.`) + if (bump !== 'patch' || !fixed.has(name)) fail(`${path} bumps ${name} ${bump}; a backport carries only patch changesets for the fixed group.`) } } // The first commit on main that added each changeset. One backport brings one change, so they @@ -307,18 +356,22 @@ jobs: } if (origins.size !== 1) fail(`Its changesets came to main in different commits: ${[...origins].join(', ')}. Backport them one at a time.`) const [origin] = origins - // Merging the backport into that main commit, from the backport's own base, must leave the - // commit unchanged: then every change the backport makes is already on main. - let mergedTree - try { - mergedTree = run('git', ['merge-tree', '--write-tree', '--no-messages', `--merge-base=${mergeBase}`, origin, HEAD_SHA]).split('\n')[0] - } catch { - fail(`Its changes conflict with main's ${origin}, so they aren't the same changes.`) + if (git('rev-list', '--parents', '-n', '1', origin).split(' ').length !== 2) fail(`main's ${origin} isn't a single-parent commit.`) + const cut = api(`repos/${repository}/compare/main...${encodeURIComponent(BASE_REF)}`).merge_base_commit?.sha + if (!cut || api(`repos/${repository}/compare/${cut}...${origin}`).status !== 'ahead') { + fail(`main's ${origin} isn't newer than ${BASE_REF}'s cut from main ${cut}, so it can't be a fix the line lacks.`) } - if (mergedTree !== git('rev-parse', `${origin}^{tree}`)) { - fail(`It changes things that main's ${origin} doesn't have.`) + // main's commit applied to the line's head, and the files it changes. + 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') + 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 (conflicted.includes(path)) fail(`main's ${origin} doesn't apply cleanly to ${path} on ${BASE_REF}.`) + if (entryAt(mergedTree, path) !== entryAt(HEAD_SHA, path)) fail(`Its ${path} isn't main's ${origin} applied to ${BASE_REF}.`) } - pass(`#${PR_NUMBER} backports main's ${origin}: its ${changesets.length} changeset(s) are patch changesets for the fixed group, and everything it changes since ${mergeBase} is already in ${origin}.`) + pass(`#${PR_NUMBER} backports main's ${origin}: its ${changesets.length} changeset(s) are patch changesets for the fixed group, and each of the ${changes.length} file(s) it changes is that commit's change applied to ${BASE_REF}'s head ${lineHead}.`) } SCRIPT node check.mjs