Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

👷 fix(ci): align test checkouts with workflow revisions (#23146)

AmAzing-3531bd1f3cef
diff --git a/.github/scripts/testCheckout.test.mjs b/.github/scripts/testCheckout.test.mjs
new file mode 100644
index 00000000000..34f86743129
--- /dev/null
+++ b/.github/scripts/testCheckout.test.mjs
@@ -0,0 +1,216 @@
+import assert from 'node:assert/strict';
+import { execFile } from 'node:child_process';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { test } from 'node:test';
+import { promisify } from 'node:util';
+import { runInNewContext } from 'node:vm';
+
+const exec = promisify(execFile);
+const workflows = await Promise.all(
+ ['test', 'e2e'].map(async (name) => ({
+ name,
+ source: await readFile(new URL(`../workflows/${name}.yml`, import.meta.url), 'utf8'),
+ })),
+);
+
+// These checks run before dependency installation, so use only Node builtins.
+function steps(source, name) {
+ return source
+ .split(` - name: ${name}\n`)
+ .slice(1)
+ .map((part) => part.split(/\n(?: {6}- | {2}[\w-]+:)/)[0]);
+}
+
+function runBlock(step) {
+ const block = step.match(/ {8}run: \|\n((?: .*\n|\n)*)/);
+ assert.ok(block, 'step has a shell script');
+ return block[1].replaceAll(/^ {10}/gm, '');
+}
+
+function checkoutEnv(step, context) {
+ const expressions = {
+ 'github.sha': context.sha,
+ 'github.repository': 'fixture/upstream',
+ "github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha":
+ context.event === 'pull_request' ? context.head : context.sha,
+ "github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || github.repository":
+ context.event === 'pull_request' ? context.repository : 'fixture/upstream',
+ };
+ return Object.fromEntries(
+ ['REF_SHA', 'REPOSITORY'].map((key) => {
+ const expression = step.match(new RegExp(` ${key}: \\$\\{\\{ (.+) \\}\\}`))?.[1];
+ assert.ok(Object.hasOwn(expressions, expression), `known ${key} expression: ${expression}`);
+ return [key, expressions[expression]];
+ }),
+ );
+}
+
+async function fixture(t) {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'ci-checkout-'));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const upstream = path.join(root, 'upstream.git');
+ const env = {
+ ...process.env,
+ GIT_CONFIG_NOSYSTEM: '1',
+ GIT_CONFIG_GLOBAL: path.join(root, 'gitconfig'),
+ GIT_AUTHOR_NAME: 'Fixture',
+ GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Fixture',
+ GIT_COMMITTER_EMAIL: '[email protected]',
+ };
+ await writeFile(
+ env.GIT_CONFIG_GLOBAL,
+ [
+ '[commit]',
+ ' gpgsign = false',
+ '[core]',
+ ' hooksPath = /dev/null',
+ `[url "file://${root}/"]`,
+ ' insteadOf = https://github.com/fixture/',
+ '',
+ ].join('\n'),
+ );
+ const git = async (cwd, ...args) => (await exec('git', args, { cwd, env })).stdout.trim();
+ await mkdir(upstream);
+ await git(upstream, 'init', '-q', '-b', 'canary');
+ await writeFile(path.join(upstream, '.gitignore'), 'node_modules/\n');
+ await writeFile(path.join(upstream, 'shared.txt'), 'original\n');
+ await git(upstream, 'add', '.');
+ await git(upstream, 'commit', '-qm', 'common ancestor');
+ const base = await git(upstream, 'rev-parse', 'HEAD');
+ await git(upstream, 'checkout', '-qb', 'feature');
+ await writeFile(path.join(upstream, 'feature.txt'), 'PR change\n');
+ await git(upstream, 'add', '.');
+ await git(upstream, 'commit', '-qm', 'PR head');
+ const head = await git(upstream, 'rev-parse', 'HEAD');
+ await git(root, 'clone', '--bare', upstream, path.join(root, 'fork.git'));
+ await git(upstream, 'checkout', 'canary');
+ await mkdir(path.join(upstream, 'packages/new-package'), { recursive: true });
+ await writeFile(
+ path.join(upstream, 'packages/new-package/package.json'),
+ '{"name":"new-package"}\n',
+ );
+ await writeFile(path.join(upstream, 'shared.txt'), 'base-only update\n');
+ await git(upstream, 'add', '.');
+ await git(upstream, 'commit', '-qm', 'base adds a workspace package');
+ const push = await git(upstream, 'rev-parse', 'HEAD');
+ await git(upstream, 'merge', '--no-ff', '-m', 'PR merge', 'feature');
+ const merge = await git(upstream, 'rev-parse', 'HEAD');
+ return { base, env, git, head, merge, push, root };
+}
+
+const checkouts = workflows.flatMap(({ name, source }) =>
+ steps(source, 'Checkout')
+ .filter((step) => step.includes('run:'))
+ .map((step, index) => ({
+ label: `${name} checkout ${index + 1}`,
+ step,
+ })),
+);
+
+for (const scenario of ['same-repository PR', 'fork PR', 'push']) {
+ test(`${scenario}: every anonymous checkout uses the workflow revision`, async (t) => {
+ const f = await fixture(t);
+ const context = {
+ event: scenario === 'push' ? 'push' : 'pull_request',
+ head: f.head,
+ repository: scenario === 'fork PR' ? 'fixture/fork' : 'fixture/upstream',
+ sha: scenario === 'push' ? f.push : f.merge,
+ };
+ for (const { label, step } of checkouts) {
+ await t.test(label, async () => {
+ const cwd = path.join(f.root, label);
+ await mkdir(cwd);
+ await exec('bash', ['-e', '-o', 'pipefail', '-c', runBlock(step)], {
+ cwd,
+ env: { ...f.env, ...checkoutEnv(step, context) },
+ });
+ assert.equal(await f.git(cwd, 'rev-parse', 'HEAD'), context.sha);
+ assert.equal(
+ JSON.parse(await readFile(path.join(cwd, 'packages/new-package/package.json'))).name,
+ 'new-package',
+ );
+ if (scenario !== 'push') {
+ assert.equal(await readFile(path.join(cwd, 'feature.txt'), 'utf8'), 'PR change\n');
+ }
+ assert.equal(
+ await f.git(cwd, 'remote', 'get-url', 'origin'),
+ `file://${f.root}/upstream.git`,
+ );
+ assert.equal(
+ (await exec('git', ['config', '--local', '--list'], { cwd, env: f.env })).stdout.includes(
+ 'extraheader',
+ ),
+ false,
+ );
+ });
+ }
+ });
+}
+
+test('ALint restores PR head before exposing only PR changes, retaining installed dependencies', async (t) => {
+ const f = await fixture(t);
+ const cwd = path.join(f.root, 'alint');
+ await f.git(f.root, 'clone', '--depth=1', `file://${f.root}/upstream.git`, cwd);
+ const bin = path.join(f.root, 'bin');
+ await mkdir(bin);
+ await writeFile(path.join(bin, 'gh'), '#!/bin/sh\nprintf "%s\\n" "$FIXTURE_MERGE_BASE"\n', {
+ mode: 0o755,
+ });
+ await mkdir(path.join(cwd, 'node_modules'));
+ await writeFile(path.join(cwd, 'node_modules/installed'), 'keep');
+ const step = steps(
+ workflows[0].source,
+ 'alint · expose the diff against the base as dirty changes',
+ )[0];
+ await exec('bash', ['-e', '-o', 'pipefail', '-c', runBlock(step)], {
+ cwd,
+ env: {
+ ...f.env,
+ BASE: f.push,
+ FIXTURE_MERGE_BASE: f.base,
+ GITHUB_REPOSITORY: 'fixture/upstream',
+ HEAD_SHA: f.head,
+ PATH: `${bin}:${process.env.PATH}`,
+ },
+ });
+ assert.equal(await f.git(cwd, 'rev-parse', 'HEAD'), f.base);
+ assert.equal(await f.git(cwd, 'status', '--porcelain'), '?? feature.txt');
+ assert.equal(await readFile(path.join(cwd, 'shared.txt'), 'utf8'), 'original\n');
+ assert.equal(await readFile(path.join(cwd, 'node_modules/installed'), 'utf8'), 'keep');
+});
+
+test('ALint consumers do not run if preparation of the PR-only working tree fails', () => {
+ const source = workflows[0].source;
+ assert.match(
+ steps(source, 'alint · expose the diff against the base as dirty changes')[0],
+ /id: alint_diff/,
+ );
+ for (const name of [
+ 'restore cache',
+ 'lint changed files',
+ 'calibrate rule fixtures (when rules or fixtures changed)',
+ ]) {
+ assert.match(steps(source, `alint · ${name}`)[0], /steps\.alint_diff\.outcome == 'success'/);
+ }
+});
+
+test('E2E size baselines use the tested merge revision rather than the stale PR head', async () => {
+ for (const name of [
+ 'Find latest canary baseline run',
+ 'Find latest canary entry-graph baseline run',
+ ]) {
+ const step = steps(workflows[1].source, name)[0];
+ const script = step.split(' script: |\n')[1];
+ assert.ok(script);
+ let target;
+ const require = () => async (args) => {
+ target = args.targetSha;
+ };
+ const context = { sha: 'merge-sha', payload: { pull_request: { head: { sha: 'head-sha' } } } };
+ await runInNewContext(`(async () => { ${script} })()`, { require, github: {}, context });
+ assert.equal(target, context.sha);
+ }
+});
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index 31018487805..0a011951a81 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -75,8 +75,10 @@ jobs:
steps:
- name: Checkout
env:
- REF_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
- REPOSITORY: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || github.repository }}
+ # Match the workflow's revision: PR merge commit, or the pushed commit.
+ # Keep fetching anonymously; PR tests must not need checkout credentials.
+ REF_SHA: ${{ github.sha }}
+ REPOSITORY: ${{ github.repository }}
run: |
git init .
git remote add origin "https://github.com/${REPOSITORY}.git"
@@ -121,7 +123,7 @@ jobs:
context,
workflowId: 'e2e.yml',
artifactName: 'bundle-size-baseline-web',
- targetSha: context.payload.pull_request?.head.sha ?? context.sha,
+ targetSha: context.sha,
});
- name: Download web dist size baseline
@@ -165,7 +167,7 @@ jobs:
context,
workflowId: 'e2e.yml',
artifactName: 'bundle-size-baseline-entry-graph',
- targetSha: context.payload.pull_request?.head.sha ?? context.sha,
+ targetSha: context.sha,
});
- name: Download entry-graph baseline
@@ -284,8 +286,10 @@ jobs:
steps:
- name: Checkout
env:
- REF_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
- REPOSITORY: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || github.repository }}
+ # Match the workflow's revision: PR merge commit, or the pushed commit.
+ # Keep fetching anonymously; PR tests must not need checkout credentials.
+ REF_SHA: ${{ github.sha }}
+ REPOSITORY: ${{ github.repository }}
run: |
git init .
git remote add origin "https://github.com/${REPOSITORY}.git"
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 24e7e936a7e..bf215cf406a 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -50,8 +50,10 @@ jobs:
steps:
- name: Checkout
env:
- REF_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
- REPOSITORY: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || github.repository }}
+ # Match the workflow's revision: PR merge commit, or the pushed commit.
+ # Keep fetching anonymously; PR tests must not need checkout credentials.
+ REF_SHA: ${{ github.sha }}
+ REPOSITORY: ${{ github.repository }}
run: |
git init .
git remote add origin "https://github.com/${REPOSITORY}.git"
@@ -66,6 +68,7 @@ jobs:
.github/scripts/size-gate-comment.test.cjs \
.github/scripts/pr-admission-check.test.cjs \
.github/scripts/mergeAllowBuilds.test.mjs \
+ .github/scripts/testCheckout.test.mjs \
.github/scripts/desktopRelease*.test.mjs \
.github/scripts/desktop-core-gate.test.mjs
@@ -204,8 +207,10 @@ jobs:
steps:
- name: Checkout
env:
- REF_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
- REPOSITORY: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || github.repository }}
+ # Match the workflow's revision: PR merge commit, or the pushed commit.
+ # Keep fetching anonymously; PR tests must not need checkout credentials.
+ REF_SHA: ${{ github.sha }}
+ REPOSITORY: ${{ github.repository }}
run: |
git init .
git remote add origin "https://github.com/${REPOSITORY}.git"
@@ -280,8 +285,10 @@ jobs:
steps:
- name: Checkout
env:
- REF_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
- REPOSITORY: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || github.repository }}
+ # Match the workflow's revision: PR merge commit, or the pushed commit.
+ # Keep fetching anonymously; PR tests must not need checkout credentials.
+ REF_SHA: ${{ github.sha }}
+ REPOSITORY: ${{ github.repository }}
run: |
git init .
git remote add origin "https://github.com/${REPOSITORY}.git"
@@ -337,6 +344,7 @@ jobs:
run: echo "::notice::ALint skipped for this ${ALINT_SKIP_REASON}"
- name: alint · expose the diff against the base as dirty changes
+ id: alint_diff
if: ${{ !cancelled() && env.ALINT_API_KEY != '' && env.ALINT_SKIP_REASON == '' }}
continue-on-error: true
env:
@@ -344,6 +352,10 @@ jobs:
BASE: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || 'canary' }}
HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
run: |
+ # Tests use the merge commit, but inline lint findings must describe
+ # only the PR head. Preserve installed dependencies for alint below.
+ git fetch --no-tags --depth=1 origin "${HEAD_SHA}"
+ git checkout --force --detach "${HEAD_SHA}"
MERGE_BASE=$(gh api "repos/${GITHUB_REPOSITORY}/compare/${BASE}...${HEAD_SHA}" --jq .merge_base_commit.sha)
echo "merge base: ${MERGE_BASE}"
git fetch --no-tags --depth=1 origin "${MERGE_BASE}"
@@ -354,7 +366,7 @@ jobs:
git status --short | head -50
- name: alint · restore cache
- if: ${{ !cancelled() && env.ALINT_API_KEY != '' && env.ALINT_SKIP_REASON == '' }}
+ if: ${{ !cancelled() && steps.alint_diff.outcome == 'success' }}
continue-on-error: true
uses: actions/cache@v4
with:
@@ -367,7 +379,7 @@ jobs:
alint-
- name: alint · lint changed files
- if: ${{ !cancelled() && env.ALINT_API_KEY != '' && env.ALINT_SKIP_REASON == '' }}
+ if: ${{ !cancelled() && steps.alint_diff.outcome == 'success' }}
continue-on-error: true
env:
GITHUB_TOKEN: ${{ github.token }}
@@ -385,7 +397,7 @@ jobs:
bun packages/alint/report.ts alint-output.json
- name: alint · calibrate rule fixtures (when rules or fixtures changed)
- if: ${{ !cancelled() && env.ALINT_API_KEY != '' && env.ALINT_SKIP_REASON == '' }}
+ if: ${{ !cancelled() && steps.alint_diff.outcome == 'success' }}
continue-on-error: true
run: |
if git status --porcelain -- alint.config.toml packages/alint ':(glob)packages/*/alint/**' | grep -q .; then
@@ -408,8 +420,10 @@ jobs:
steps:
- name: Checkout
env:
- REF_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
- REPOSITORY: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || github.repository }}
+ # Match the workflow's revision: PR merge commit, or the pushed commit.
+ # Keep fetching anonymously; PR tests must not need checkout credentials.
+ REF_SHA: ${{ github.sha }}
+ REPOSITORY: ${{ github.repository }}
run: |
git init .
git remote add origin "https://github.com/${REPOSITORY}.git"
@@ -446,8 +460,10 @@ jobs:
steps:
- name: Checkout
env:
- REF_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
- REPOSITORY: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || github.repository }}
+ # Match the workflow's revision: PR merge commit, or the pushed commit.
+ # Keep fetching anonymously; PR tests must not need checkout credentials.
+ REF_SHA: ${{ github.sha }}
+ REPOSITORY: ${{ github.repository }}
run: |
git init .
git remote add origin "https://github.com/${REPOSITORY}.git"
@@ -507,8 +523,10 @@ jobs:
steps:
- name: Checkout
env:
- REF_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
- REPOSITORY: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || github.repository }}
+ # Match the workflow's revision: PR merge commit, or the pushed commit.
+ # Keep fetching anonymously; PR tests must not need checkout credentials.
+ REF_SHA: ${{ github.sha }}
+ REPOSITORY: ${{ github.repository }}
run: |
git init .
git remote add origin "https://github.com/${REPOSITORY}.git"