diff --git a/.github/actions/build-cli-tarball/action.yml b/.github/actions/build-cli-tarball/action.yml new file mode 100644 index 00000000000..a9a9f040902 --- /dev/null +++ b/.github/actions/build-cli-tarball/action.yml @@ -0,0 +1,53 @@ +name: 'Build the @shopify/cli tarball' +description: 'Builds the @shopify/cli tarball that a release of the checked-out commit would publish, and uploads it as an artifact' +inputs: + artifact-name: + required: true + description: 'Name of the artifact to upload the tarball as' +outputs: + tarball: + description: 'File name of the tarball in packages/cli' + value: ${{ steps.pack.outputs.tarball }} + version: + description: 'Version of @shopify/cli in the tarball' + value: ${{ steps.pack.outputs.version }} +runs: + using: 'composite' + steps: + - 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 + shell: bash + 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 + shell: bash + 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: ${{ inputs.artifact-name }} + path: packages/cli/${{ steps.pack.outputs.tarball }} + if-no-files-found: error + # The tarball is already compressed. + compression-level: 0 diff --git a/.github/scripts/smoke-test-cli.sh b/.github/scripts/smoke-test-cli.sh new file mode 100755 index 00000000000..dc8c7cd22d8 --- /dev/null +++ b/.github/scripts/smoke-test-cli.sh @@ -0,0 +1,93 @@ +#!/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 +} + +# A command's JSON output schema names its own result type beside the shared error and event types. +check_schema() { + node -e 'const schema = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")); if (!schema.definitions?.Result) process.exit(1)' "$1" || + fail "$1 isn't the command's JSON output schema" +} + +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" + +for TOPIC in app theme hydrogen; do + start_case "shopify $TOPIC --help" + shopify "$TOPIC" --help +done + +# Help comes from the oclif manifest, so it doesn't load a command's code. --json-schema does, from +# the plugin that provides the command, and needs no Shopify account or project. +start_case "shopify hydrogen check --json-schema" +shopify hydrogen check --json-schema > hydrogen-check-schema.json +check_schema hydrogen-check-schema.json + +start_case "shopify app info --json-schema" +shopify app info --json-schema > app-info-schema.json +check_schema app-info-schema.json + +# A pinned Skeleton release, so a newer one can't fail an older line's theme check. A URL with a +# tag 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#v1.0.0 +[ -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..dd9d53b390f --- /dev/null +++ b/.github/workflows/patch-provenance.yml @@ -0,0 +1,636 @@ +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. 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/**' + +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, 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 + } + } + 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 + } + } + // Fetches main until its first-parent chain reaches `cut`, and returns main's head. A merge base + // alone isn't enough: a branch based before the cut and merged later reaches it sooner. + function fetchMainSince(cut) { + const main = 'refs/remotes/origin/main' + for (const depth of [50, 200, 1000, 5000]) { + git('fetch', '--quiet', '--no-tags', `--depth=${depth}`, 'origin', `+refs/heads/main:${main}`) + if (git('rev-list', '--first-parent', main).split('\n').includes(cut)) return git('rev-parse', main) + } + fail(`${BASE_REF}'s cut ${cut} isn't in the last 5000 commits of main's first-parent history, so this check can't tell which commits reached main after it.`) + } + 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('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}`) + } + } + // The commits, newest first, that changed `path` in the history of `ref`. + function commitsChanging(ref, path) { + const endpoint = `repos/${repository}/commits?sha=${ref}&path=${encodeURIComponent(path)}&per_page=100` + try { + return run('gh', ['api', '--paginate', endpoint, '--jq', '.[].sha']).split('\n').filter(Boolean) + } catch (error) { + fail(`Reading ${endpoint} 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 = {} + 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', '.') + // 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}.`) + 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}`) { + 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() { + 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.") + 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 cut = api(`repos/${repository}/compare/main...${encodeURIComponent(BASE_REF)}`).merge_base_commit?.sha + if (!cut) fail(`Couldn't find where ${BASE_REF} was cut from main.`) + const mainHead = fetchMainSince(cut) + // 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 !== '' && fileAt(commit, path) !== undefined && fileAt(`${commit}^1`, path) === undefined) + 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 = commitsChanging(lineHead, path) + .reverse() + .find((commit) => !['behind', 'identical'].includes(api(`repos/${repository}/compare/${cut}...${commit}`).status)) + 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 changedOnLine = new Set(changedFiles(lineHead, mergedTree).map(({path}) => path)) + const leftOut = [...changedOnLine].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.`) + } + // Every change main's commit makes must be new to the line. One the line already has means + // the fix, or part of it, is already there, perhaps from a backport by hand under another + // changeset, which a release may have shipped. + const alreadyOnLine = [...changedByOrigin].filter((path) => !changedOnLine.has(path)) + if (alreadyOnLine.length > 0) { + fail(`${BASE_REF} already has main's ${origin} changes to ${alreadyOnLine.join(', ')}, so the line already has this fix or part of it, perhaps from a backport by hand that a release may have shipped.`) + } + // 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 !== '' && fileAt(commit, path) === undefined) + 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 + } + + // main's head still has the origin's change: applying the origin to it changes nothing outside + // its changesets, and every file the origin added is still there, whatever main has since done + // to it. A revert, or a later change to the same lines, leaves it unclear whether the line + // should take the fix, so a maintainer decides. + function checkMainStillHas(origin, mainHead) { + const merged = spawnSync('git', ['merge-tree', '--write-tree', '--name-only', '--no-messages', `--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.trim().split('\n') + const notOnMain = changedFiles(`${origin}^1`, origin) + .filter(({path}) => !changesetPath(path)) + .filter(({status, path}) => (status === 'A' ? entryAt(mainHead, path) === '' : conflicted.includes(path) || entryAt(mergedTree, path) !== entryAt(mainHead, path))) + .map(({path}) => path) + if (notOnMain.length > 0) { + fail(`main's head ${mainHead} doesn't have all of main's ${origin}: ${notOnMain.join(', ')} were reverted or changed in the same lines since, so a maintainer decides whether ${BASE_REF} takes this fix.`) + } + } + SCRIPT + node check.mjs diff --git a/.github/workflows/patch-qa.yml b/.github/workflows/patch-qa.yml new file mode 100644 index 00000000000..0cf3e9db53e --- /dev/null +++ b/.github/workflows/patch-qa.yml @@ -0,0 +1,240 @@ +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. +# +# `edited` covers a pull request retargeted to a stable line. It runs on every edit: skipping a job +# on the others would record a skipped "Patch QA", which counts as passing and replaces the last run. +on: + pull_request: + types: [opened, synchronize, reopened, edited] + 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.build.outputs.tarball }} + version: ${{ steps.build.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: Build the release tarball + id: build + uses: ./.github/actions/build-cli-tarball + with: + artifact-name: shopify-cli-${{ github.event.pull_request.head.sha }} + + # 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, and a different + # count alone only warns: a real patch can split the bundle differently. + compare: + name: Compare the files with the line's last release + needs: package + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - 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: Compare the files + working-directory: tarball + env: + TARBALL: ${{ needs.package.outputs.tarball }} + VERSION: ${{ needs.package.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 + ONLY_CHUNKS=true + while IFS= read -r LINE; do + case "$LINE" in + "" | *"-[hash].js") ;; + *) ONLY_CHUNKS=false ;; + esac + done <<< "$ADDED + $REMOVED" + if [ "$ONLY_CHUNKS" = true ]; then + LEVEL=warning + MESSAGE="$VERSION has $CURRENT_COUNT files and $PREVIOUS had $PREVIOUS_COUNT: only the number of bundle chunks differs. + Added (count, file): + ${ADDED:-none} + Removed (count, file): + ${REMOVED:-none}" + else + LEVEL=error + 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}" + fi + # Annotations are one line: escape % and encode newlines. + NEWLINE=$'\n' + PERCENT=% + MESSAGE=${MESSAGE//$PERCENT/%25} + MESSAGE=${MESSAGE//$NEWLINE/%0A} + echo "::$LEVEL::$MESSAGE" + if [ "$LEVEL" = error ]; then exit 1; fi + + 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, compare, install] + if: always() + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Verify the tarball, its files and every platform passed + if: needs.package.result != 'success' || needs.compare.result != 'success' || needs.install.result != 'success' + run: exit 1 diff --git a/.github/workflows/release-qa-package.yml b/.github/workflows/release-qa-package.yml index f913413f5fa..d23b9e23cf0 100644 --- a/.github/workflows/release-qa-package.yml +++ b/.github/workflows/release-qa-package.yml @@ -60,48 +60,34 @@ jobs: exit 1 fi - - name: Setup deps - uses: ./.github/actions/setup-cli-deps + # The build action comes from this workflow's own commit, so a run from main can build a line + # that doesn't have it, such as stable/4.9. It still builds the requested commit, with that + # commit's own dependency setup. + - name: Check out the build action + uses: actions/checkout@v6 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) - echo "tarball=$TARBALL" >> "$GITHUB_OUTPUT" + ref: ${{ github.workflow_sha }} + path: .release-qa-package + persist-credentials: false + sparse-checkout: .github/actions/build-cli-tarball + sparse-checkout-cone-mode: false - - name: Upload the tarball - uses: actions/upload-artifact@v4 + - name: Build the release tarball + id: build + uses: ./.release-qa-package/.github/actions/build-cli-tarball with: - name: shopify-cli-${{ inputs.sha }} - path: packages/cli/${{ steps.pack.outputs.tarball }} - if-no-files-found: error - # The tarball is already compressed. - compression-level: 0 + artifact-name: shopify-cli-${{ inputs.sha }} - name: Summarize working-directory: packages/cli env: SHA: ${{ inputs.sha }} - TARBALL: ${{ steps.pack.outputs.tarball }} + TARBALL: ${{ steps.build.outputs.tarball }} + VERSION: ${{ steps.build.outputs.version }} ARTIFACT: shopify-cli-${{ inputs.sha }} run: | set -euo pipefail CHECKSUM=$(sha256sum "$TARBALL" | cut -d ' ' -f 1) - VERSION=$(tar -xzOf "$TARBALL" package/package.json | node -p 'JSON.parse(require("node:fs").readFileSync(0, "utf8")).version') { echo "### @shopify/cli $VERSION" echo diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2c0916f4ffe..f44b951257d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -351,6 +351,68 @@ 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 }} + # Up to 30 minutes waiting for npm, then the install and the smoke tests. + timeout-minutes: 60 + 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