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.

⚑️ perf: reduce PR test and coverage latency (#19823)

YuTengjing5d9ebcb71c9c
diff --git a/.agents/skills/testing/SKILL.md b/.agents/skills/testing/SKILL.md
index cfe27784776..740bd040f94 100644
--- a/.agents/skills/testing/SKILL.md
+++ b/.agents/skills/testing/SKILL.md
@@ -41,6 +41,7 @@ cd packages/database && TEST_SERVER_DB=1 bunx vitest run --silent='passed-only'
1. **Prefer `vi.spyOn` over `vi.mock`** - More targeted, easier to maintain. The root Vitest configs do not restore mocks automatically; restore spies in test cleanup with `vi.restoreAllMocks()`.
2. **Test behavior, not implementation details**
+ - Keep native `node:test` CI checks under `.github/scripts/`, outside the app Vitest discovery paths. When mixing test runners, verify both the intended runner and the owning Vitest project's file discovery before pushing.
3. **Regression tests for bug fixes** - Include a regression test that fails without the fix and passes with it; write the failing test first when the failure is easy to reproduce. **Skip** pure style/CSS fixes (selector, hover, mask, spacing, color) when the only practical assertion would be source-string matching on the stylesheet β€” that is not a regression test worth shipping.
4. **No new component tests** - Only update existing React component tests. Complex logic should be extracted into hooks and tested there instead
diff --git a/.github/scripts/vercel-ignored-build-step.test.cjs b/.github/scripts/vercel-ignored-build-step.test.cjs
new file mode 100644
index 00000000000..f338527e7d5
--- /dev/null
+++ b/.github/scripts/vercel-ignored-build-step.test.cjs
@@ -0,0 +1,206 @@
+const assert = require('node:assert/strict');
+const { execFile } = require('node:child_process');
+const { copyFile, mkdir, mkdtemp, rm, writeFile } = require('node:fs/promises');
+const os = require('node:os');
+const path = require('node:path');
+const { promisify } = require('node:util');
+const { test } = require('node:test');
+
+const execFileAsync = promisify(execFile);
+const sourceScript = path.resolve(__dirname, '../../scripts/vercelIgnoredBuildStep.js');
+
+const runGit = (repoRoot, args) =>
+ execFileAsync('git', args, {
+ cwd: repoRoot,
+ encoding: 'utf8',
+ });
+
+const commit = async (repoRoot, message) => {
+ await runGit(repoRoot, ['add', '--all']);
+ await runGit(repoRoot, ['commit', '-q', '-m', message]);
+ const { stdout } = await runGit(repoRoot, ['rev-parse', 'HEAD']);
+ return stdout.trim();
+};
+
+const writeRepoFile = async (repoRoot, relativePath, contents) => {
+ const filePath = path.join(repoRoot, relativePath);
+ await mkdir(path.dirname(filePath), { recursive: true });
+ await writeFile(filePath, contents);
+};
+
+const createRepository = async (t) => {
+ const repoRoot = await mkdtemp(path.join(os.tmpdir(), 'vercel-ignore-step-'));
+ t.after(() => rm(repoRoot, { force: true, recursive: true }));
+
+ await runGit(repoRoot, ['init', '-q']);
+ await runGit(repoRoot, ['config', 'user.email', '[email protected]']);
+ await runGit(repoRoot, ['config', 'user.name', 'Test']);
+ await mkdir(path.join(repoRoot, 'scripts'), { recursive: true });
+ await copyFile(sourceScript, path.join(repoRoot, 'scripts/vercelIgnoredBuildStep.js'));
+ await writeRepoFile(repoRoot, 'src/app.js', 'export const app = true;\n');
+ const baseSha = await commit(repoRoot, 'base');
+
+ return { baseSha, repoRoot };
+};
+
+const createShallowRepository = async (t, changedPath, contents) => {
+ const remoteRoot = await mkdtemp(path.join(os.tmpdir(), 'vercel-ignore-remote-'));
+ const cloneParent = await mkdtemp(path.join(os.tmpdir(), 'vercel-ignore-clone-'));
+ t.after(() =>
+ Promise.all([
+ rm(remoteRoot, { force: true, recursive: true }),
+ rm(cloneParent, { force: true, recursive: true }),
+ ]),
+ );
+
+ await runGit(remoteRoot, ['init', '-q']);
+ await runGit(remoteRoot, ['config', 'user.email', '[email protected]']);
+ await runGit(remoteRoot, ['config', 'user.name', 'Test']);
+ await mkdir(path.join(remoteRoot, 'scripts'), { recursive: true });
+ await copyFile(sourceScript, path.join(remoteRoot, 'scripts/vercelIgnoredBuildStep.js'));
+ await writeRepoFile(remoteRoot, 'src/app.js', 'export const app = true;\n');
+ const baseSha = await commit(remoteRoot, 'base');
+ await commitFile(remoteRoot, changedPath, contents, 'change');
+
+ await runGit(cloneParent, ['clone', '-q', '--depth=1', `file://${remoteRoot}`, 'repo']);
+
+ return { baseSha, repoRoot: path.join(cloneParent, 'repo') };
+};
+
+const commitFile = async (repoRoot, relativePath, contents, message) => {
+ await writeRepoFile(repoRoot, relativePath, contents);
+ return commit(repoRoot, message);
+};
+
+const runIgnoreStep = async (repoRoot, env = {}) => {
+ try {
+ const result = await execFileAsync(process.execPath, ['scripts/vercelIgnoredBuildStep.js'], {
+ cwd: repoRoot,
+ encoding: 'utf8',
+ env: {
+ PATH: process.env.PATH,
+ VERCEL_ENV: 'preview',
+ ...env,
+ },
+ });
+
+ return { code: 0, ...result };
+ } catch (error) {
+ return {
+ code: error.code,
+ stderr: error.stderr,
+ stdout: error.stdout,
+ };
+ }
+};
+
+test('skips preview deployments for CI-only and root Markdown changes', async (t) => {
+ const { baseSha, repoRoot } = await createRepository(t);
+
+ await commitFile(repoRoot, '.github/workflows/test.yml', 'name: Test\n', 'CI change');
+ let result = await runIgnoreStep(repoRoot, { VERCEL_GIT_PREVIOUS_SHA: baseSha });
+ assert.equal(result.code, 0);
+ assert.match(result.stdout, /shouldBuild: false/);
+
+ await commitFile(repoRoot, 'README.md', '# Docs\n', 'Docs change');
+ result = await runIgnoreStep(repoRoot, { VERCEL_GIT_PREVIOUS_SHA: baseSha });
+ assert.equal(result.code, 0);
+ assert.match(result.stdout, /shouldBuild: false/);
+});
+
+test('builds when a source change is followed by a CI-only commit', async (t) => {
+ const { baseSha, repoRoot } = await createRepository(t);
+
+ await commitFile(repoRoot, 'src/app.js', 'export const app = false;\n', 'Source change');
+ await commitFile(repoRoot, '.github/workflows/test.yml', 'name: Test\n', 'CI change');
+
+ const result = await runIgnoreStep(repoRoot, { VERCEL_GIT_PREVIOUS_SHA: baseSha });
+ assert.equal(result.code, 1);
+ assert.match(result.stdout, /shouldBuild: true/);
+});
+
+test('builds when a runtime file is renamed into an ignored directory', async (t) => {
+ const { baseSha, repoRoot } = await createRepository(t);
+
+ await mkdir(path.join(repoRoot, '.github'), { recursive: true });
+ await runGit(repoRoot, ['mv', 'src/app.js', '.github/app.js']);
+ await commit(repoRoot, 'Move runtime file');
+
+ const result = await runIgnoreStep(repoRoot, { VERCEL_GIT_PREVIOUS_SHA: baseSha });
+ assert.equal(result.code, 1);
+ assert.match(result.stdout, /shouldBuild: true/);
+});
+
+test('builds for runtime scripts and Vercel configuration changes', async (t) => {
+ const { baseSha, repoRoot } = await createRepository(t);
+
+ await commitFile(repoRoot, 'scripts/build.js', 'console.log("build");\n', 'Build script change');
+ let result = await runIgnoreStep(repoRoot, { VERCEL_GIT_PREVIOUS_SHA: baseSha });
+ assert.equal(result.code, 1);
+ assert.match(result.stdout, /shouldBuild: true/);
+
+ await commitFile(
+ repoRoot,
+ 'vercel.json',
+ '{"buildCommand":"next build"}\n',
+ 'Vercel config change',
+ );
+ result = await runIgnoreStep(repoRoot, { VERCEL_GIT_PREVIOUS_SHA: baseSha });
+ assert.equal(result.code, 1);
+ assert.match(result.stdout, /shouldBuild: true/);
+});
+
+test('builds when the previous deployment baseline is missing, invalid, or unavailable', async (t) => {
+ const { repoRoot } = await createRepository(t);
+ await commitFile(repoRoot, '.github/workflows/test.yml', 'name: Test\n', 'CI change');
+
+ let result = await runIgnoreStep(repoRoot);
+ assert.equal(result.code, 1);
+ assert.match(result.stdout, /shouldBuild: true/);
+
+ result = await runIgnoreStep(repoRoot, { VERCEL_GIT_PREVIOUS_SHA: 'not-a-commit' });
+ assert.equal(result.code, 1);
+ assert.match(result.stdout, /shouldBuild: true/);
+
+ result = await runIgnoreStep(repoRoot, {
+ VERCEL_GIT_PREVIOUS_SHA: '0000000000000000000000000000000000000000',
+ });
+ assert.equal(result.code, 1);
+ assert.match(result.stdout, /shouldBuild: true/);
+});
+
+test('fetches a missing baseline before skipping CI-only changes', async (t) => {
+ const { baseSha, repoRoot } = await createShallowRepository(
+ t,
+ '.github/workflows/test.yml',
+ 'name: Test\n',
+ );
+
+ const result = await runIgnoreStep(repoRoot, { VERCEL_GIT_PREVIOUS_SHA: baseSha });
+ assert.equal(result.code, 0);
+ assert.match(result.stdout, /shouldBuild: false/);
+});
+
+test('fetches a missing baseline before building for runtime changes', async (t) => {
+ const { baseSha, repoRoot } = await createShallowRepository(
+ t,
+ 'src/app.js',
+ 'export const app = false;\n',
+ );
+
+ const result = await runIgnoreStep(repoRoot, { VERCEL_GIT_PREVIOUS_SHA: baseSha });
+ assert.equal(result.code, 1);
+ assert.match(result.stdout, /shouldBuild: true/);
+});
+
+test('always builds production deployments', async (t) => {
+ const { baseSha, repoRoot } = await createRepository(t);
+ await commitFile(repoRoot, '.github/workflows/test.yml', 'name: Test\n', 'CI change');
+
+ const result = await runIgnoreStep(repoRoot, {
+ VERCEL_ENV: 'production',
+ VERCEL_GIT_PREVIOUS_SHA: baseSha,
+ });
+ assert.equal(result.code, 1);
+ assert.match(result.stdout, /shouldBuild: true/);
+});
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index 8c6899fc9c4..e1c0d29077b 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -2,6 +2,9 @@ name: E2E CI
on:
push:
+ branches:
+ - main
+ - canary
paths-ignore:
- '**/*.md'
- 'docs/**'
@@ -31,7 +34,7 @@ on:
- '.github/workflows/bundle-analyzer.yml'
permissions:
- actions: write
+ actions: read
contents: read
pull-requests: write
@@ -40,9 +43,9 @@ concurrency:
cancel-in-progress: true
env:
- # Same-repo PRs get their pull_request run skipped as a duplicate of the push run,
- # so the size gates must also run on pushes to feature branches.
- SIZE_GATE_ENABLED: ${{ github.event_name == 'pull_request' || (github.event_name == 'push' && github.ref != 'refs/heads/canary' && github.ref != 'refs/heads/main') }}
+ # Size gates run on every PR. Main/canary pushes run the full E2E job and publish
+ # their baselines, while the PR run owns the comparison gate.
+ SIZE_GATE_ENABLED: ${{ github.event_name == 'pull_request' }}
APP_URL: http://localhost:3006
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/postgres
DATABASE_DRIVER: node
@@ -56,24 +59,7 @@ env:
S3_ENDPOINT: https://e2e-mock-s3.localhost
jobs:
- # Check for duplicate runs
- check-duplicate-run:
- name: Check Duplicate Run
- runs-on: ubuntu-latest
- outputs:
- should_skip: ${{ steps.skip_check.outputs.should_skip }}
- steps:
- - id: skip_check
- uses: fkirc/skip-duplicate-actions@v5
- with:
- concurrent_skipping: 'same_content_newer'
- skip_after_successful_duplicate: 'true'
- do_not_skip: '["workflow_dispatch", "schedule"]'
-
e2e:
- needs: check-duplicate-run
- if: >-
- github.ref == 'refs/heads/main' || github.ref == 'refs/heads/canary' || needs.check-duplicate-run.outputs.should_skip != 'true'
name: Test Web App
runs-on: ubuntu-latest
services:
diff --git a/.github/workflows/fts-search-mapping-history.yml b/.github/workflows/fts-search-mapping-history.yml
index c3f17ad870a..1f09ed07f57 100644
--- a/.github/workflows/fts-search-mapping-history.yml
+++ b/.github/workflows/fts-search-mapping-history.yml
@@ -8,11 +8,14 @@ permissions:
contents: read
concurrency:
- group: fts-search-mapping-history-${{ github.event.pull_request.number }}
+ # Metadata-only edits must not cancel a queued or running history check.
+ group: fts-search-mapping-history-${{ github.event.pull_request.number }}-${{ github.event.action == 'edited' && !github.event.changes.base.ref.from && github.run_id || 'verify' }}
cancel-in-progress: true
jobs:
verify:
+ # Retargeting changes the comparison baseline; title/body edits do not.
+ if: github.event.action != 'edited' || github.event.changes.base.ref.from
name: Verify Append-Only History
runs-on: ubuntu-latest
steps:
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 627a5e4b442..21ce9ae7cba 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -2,6 +2,9 @@ name: Test CI
on:
push:
+ branches:
+ - main
+ - canary
paths-ignore:
- '**/*.md'
- 'docs/**'
@@ -31,7 +34,7 @@ on:
- '.github/workflows/bundle-analyzer.yml'
permissions:
- actions: write
+ actions: read
contents: read
concurrency:
@@ -39,24 +42,8 @@ concurrency:
cancel-in-progress: true
jobs:
- # Check for duplicate runs
- check-duplicate-run:
- name: Check Duplicate Run
- runs-on: ubuntu-latest
- outputs:
- should_skip: ${{ steps.skip_check.outputs.should_skip }}
- steps:
- - id: skip_check
- uses: fkirc/skip-duplicate-actions@v5
- with:
- concurrent_skipping: 'same_content_newer'
- skip_after_successful_duplicate: 'true'
- do_not_skip: '["workflow_dispatch", "schedule"]'
-
# Package tests - all packages in single job to save runner resources
test-packages:
- needs: check-duplicate-run
- if: needs.check-duplicate-run.outputs.should_skip != 'true'
runs-on: ubuntu-latest
name: Test Packages
env:
@@ -73,6 +60,9 @@ jobs:
git fetch --no-tags --depth=1 origin "${REF_SHA}"
git checkout --force FETCH_HEAD
+ - name: Verify preview build filtering
+ run: node --test .github/scripts/vercel-ignored-build-step.test.cjs
+
- name: Setup environment
uses: ./.github/actions/setup-env
@@ -100,6 +90,8 @@ jobs:
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
run: |
+ set -euo pipefail
+
curl -Os https://cli.codecov.io/latest/linux/codecov
chmod +x codecov
@@ -123,6 +115,37 @@ jobs:
COMMON_ARGS="$COMMON_ARGS -t $CODECOV_TOKEN"
fi
+ upload_coverage() {
+ local dir="$1"
+ local flag="$2"
+
+ echo "Uploading coverage for $dir as $flag..."
+ ./codecov upload-coverage \
+ $COMMON_ARGS \
+ --file "./packages/$dir/coverage/lcov.info" \
+ --flag "$flag" \
+ --disable-search
+ }
+
+ pids=()
+ labels=()
+ failed=0
+
+ reap_one() {
+ local pid="${pids[0]}"
+ local label="${labels[0]}"
+
+ if wait "$pid"; then
+ echo "Coverage upload completed for $label."
+ else
+ echo "::error::Coverage upload failed for $label."
+ failed=1
+ fi
+
+ pids=("${pids[@]:1}")
+ labels=("${labels[@]:1}")
+ }
+
for package in $PACKAGES; do
dir="${package#@lobechat/}"
if [ -f "./packages/$dir/coverage/lcov.info" ]; then
@@ -138,23 +161,30 @@ jobs:
;;
esac
- echo "Uploading coverage for $dir as $flag..."
- ./codecov upload-coverage \
- $COMMON_ARGS \
- --file ./packages/$dir/coverage/lcov.info \
- --flag "$flag" \
- --disable-search
+ while [ "${#pids[@]}" -ge 4 ]; do
+ reap_one
+ done
+
+ upload_coverage "$dir" "$flag" &
+ pids+=("$!")
+ labels+=("$dir")
fi
done
+ while [ "${#pids[@]}" -gt 0 ]; do
+ reap_one
+ done
+
+ if [ "$failed" -ne 0 ]; then
+ exit 1
+ fi
+
# App tests - run sharded tests
test-app:
- needs: check-duplicate-run
- if: needs.check-duplicate-run.outputs.should_skip != 'true'
strategy:
matrix:
- shard: [1, 2]
- name: Test App (shard ${{ matrix.shard }}/2)
+ shard: [1, 2, 3]
+ name: Test App (shard ${{ matrix.shard }}/3)
runs-on: ubuntu-latest
steps:
- name: Checkout
@@ -174,56 +204,16 @@ jobs:
run: pnpm install
- name: Run tests
- run: bunx vitest --coverage --silent='passed-only' --reporter=default --reporter=blob --project app --shard=${{ matrix.shard }}/2
-
- - name: Upload blob report
- if: ${{ !cancelled() }}
- uses: actions/upload-artifact@v6
- with:
- name: blob-report-${{ matrix.shard }}
- path: .vitest/blob
- include-hidden-files: true
- retention-days: 1
-
- # Merge sharded test reports and upload coverage
- merge-app-coverage:
- needs: test-app
- if: ${{ !cancelled() && needs.test-app.result == 'success' }}
- name: Merge and Upload App Coverage
- runs-on: ubuntu-latest
- 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 }}
- run: |
- git init .
- git remote add origin "https://github.com/${REPOSITORY}.git"
- git fetch --no-tags --depth=1 origin "${REF_SHA}"
- git checkout --force FETCH_HEAD
-
- - name: Setup environment
- uses: ./.github/actions/setup-env
-
- - name: Install deps
- run: pnpm install
-
- - name: Download blob reports
- uses: actions/download-artifact@v7
- with:
- path: .vitest/blob
- pattern: blob-report-*
- merge-multiple: true
-
- - name: Merge reports
- run: bunx vitest --merge-reports --reporter=default --coverage
+ run: bunx vitest --coverage --silent='passed-only' --reporter=default --project app --shard=${{ matrix.shard }}/3
- name: Upload App Coverage to Codecov
+ if: success()
uses: codecov/codecov-action@v5
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: ./coverage/app/lcov.info
flags: app
+ name: app-shard-${{ matrix.shard }}
# Windows-only verification of the local shell execution strategy.
# The unit tests mock process.platform and fs.existsSync, so they prove
@@ -232,8 +222,6 @@ jobs:
# detection cascade against real install paths. The driver script only needs
# node builtins, so this job skips the monorepo install entirely.
test-windows-shell:
- needs: check-duplicate-run
- if: needs.check-duplicate-run.outputs.should_skip != 'true'
name: Test Windows Shell
runs-on: windows-latest
@@ -251,8 +239,6 @@ jobs:
run: bun run packages/local-file-shell/scripts/verify-windows-shell.ts
test-desktop:
- needs: check-duplicate-run
- if: needs.check-duplicate-run.outputs.should_skip != 'true'
name: ALint & Test Desktop App
runs-on: ubuntu-latest
@@ -356,8 +342,6 @@ jobs:
fi
test-server:
- needs: check-duplicate-run
- if: needs.check-duplicate-run.outputs.should_skip != 'true'
strategy:
matrix:
shard: [1, 2]
@@ -383,60 +367,18 @@ jobs:
run: pnpm install
- name: Test Server Coverage
- run: bunx vitest --coverage --silent='passed-only' --reporter=default --reporter=blob --coverage.reportsDirectory=./apps/server/coverage --project server --shard=${{ matrix.shard }}/2
-
- - name: Upload blob report
- if: ${{ !cancelled() }}
- uses: actions/upload-artifact@v6
- with:
- name: server-blob-report-${{ matrix.shard }}
- path: .vitest/blob
- include-hidden-files: true
- retention-days: 1
-
- # Merge sharded test reports and upload coverage
- merge-server-coverage:
- needs: test-server
- if: ${{ !cancelled() && needs.test-server.result == 'success' }}
- name: Merge and Upload Server Coverage
- runs-on: ubuntu-latest
- 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 }}
- run: |
- git init .
- git remote add origin "https://github.com/${REPOSITORY}.git"
- git fetch --no-tags --depth=1 origin "${REF_SHA}"
- git checkout --force FETCH_HEAD
-
- - name: Setup environment
- uses: ./.github/actions/setup-env
-
- - name: Install deps
- run: pnpm install
-
- - name: Download blob reports
- uses: actions/download-artifact@v7
- with:
- path: .vitest/blob
- pattern: server-blob-report-*
- merge-multiple: true
-
- - name: Merge reports
- run: bunx vitest --merge-reports --reporter=default --coverage --coverage.reportsDirectory=./apps/server/coverage
+ run: bunx vitest --coverage --silent='passed-only' --reporter=default --coverage.reportsDirectory=./apps/server/coverage --project server --shard=${{ matrix.shard }}/2
- - name: Upload Server coverage to Codecov
+ - name: Upload Server Coverage to Codecov
+ if: success()
uses: codecov/codecov-action@v5
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: ./apps/server/coverage/lcov.info
flags: server
+ name: server-shard-${{ matrix.shard }}
test-databsae:
- needs: check-duplicate-run
- if: needs.check-duplicate-run.outputs.should_skip != 'true'
name: Test Database
runs-on: ubuntu-latest
diff --git a/scripts/vercelIgnoredBuildStep.js b/scripts/vercelIgnoredBuildStep.js
index 480904825b8..d8a9bdecaa6 100644
--- a/scripts/vercelIgnoredBuildStep.js
+++ b/scripts/vercelIgnoredBuildStep.js
@@ -1,46 +1,104 @@
-const { execSync } = require('node:child_process');
-
-// Get current branch name
-const branchName = process.env.VERCEL_GIT_COMMIT_REF || '';
-
-function shouldProceedBuild() {
- // If the branch is 'lighthouse' or starts with a skip prefix, cancel the build
- if (
- branchName === 'lighthouse' ||
- ['gru', 'automatic', 'reproduction'].some((item) =>
- branchName.startsWith(`${item.toLowerCase()}/`),
- )
- ) {
+/* eslint-disable @typescript-eslint/no-require-imports */
+const { execFile } = require('node:child_process');
+const { promisify } = require('node:util');
+
+const execFileAsync = promisify(execFile);
+const GIT_FETCH_TIMEOUT_MS = 15_000;
+
+const isValidCommitSha = (value) => /^[0-9a-f]{7,64}$/i.test(value);
+
+const isNonRuntimePath = (filePath) =>
+ filePath === '.github' ||
+ filePath.startsWith('.github/') ||
+ (!filePath.includes('/') && /\.md$/i.test(filePath));
+
+const runGit = async (args) => {
+ try {
+ const { stdout } = await execFileAsync('git', args, { encoding: 'utf8' });
+ return stdout.trim();
+ } catch {
+ return null;
+ }
+};
+
+const hasGitObject = async (revision) => {
+ try {
+ await execFileAsync('git', ['cat-file', '-e', `${revision}^{commit}`]);
+ return true;
+ } catch {
return false;
}
+};
+const fetchGitObject = async (revision) => {
try {
- // Check file changes, excluding specific files and directories
- const diffCommand =
- 'git diff HEAD^ HEAD --quiet -- \
- ":!./*.md" \
- ":!./Dockerfile" \
- ":!./.github" \
- ":!./.githooks" \
- ":!./scripts"';
+ await execFileAsync('git', ['fetch', '--no-tags', '--depth=1', 'origin', revision], {
+ encoding: 'utf8',
+ timeout: GIT_FETCH_TIMEOUT_MS,
+ });
+ return hasGitObject(revision);
+ } catch {
+ return false;
+ }
+};
- execSync(diffCommand);
+const buildConservatively = (message) => {
+ console.log(message);
+ return true;
+};
- return false;
- } catch {
- return true;
+/**
+ * Compare with the last successful deployment, fetching its tree for shallow checkouts.
+ * Missing comparison data must build; HEAD^ can hide source changes behind a later CI commit.
+ * https://vercel.com/docs/environment-variables/system-environment-variables#vercel_git_previous_sha
+ */
+const shouldProceedBuild = async () => {
+ if (process.env.VERCEL_ENV !== 'preview') return true;
+
+ const previousSha = process.env.VERCEL_GIT_PREVIOUS_SHA;
+ if (!previousSha || !isValidCommitSha(previousSha)) {
+ return buildConservatively('No valid previous deployment baseline; building conservatively.');
}
-}
-const shouldBuild = shouldProceedBuild();
+ const currentSha = await runGit(['rev-parse', '--verify', 'HEAD']);
+ if (!currentSha)
+ return buildConservatively('Current commit unavailable; building conservatively.');
-console.log('shouldBuild:', shouldBuild);
-if (shouldBuild) {
- console.log('βœ… - Build can proceed');
+ const previousCommitAvailable =
+ (await hasGitObject(previousSha)) || (await fetchGitObject(previousSha));
+ if (!previousCommitAvailable) {
+ return buildConservatively(
+ 'Previous deployment baseline unavailable; building conservatively.',
+ );
+ }
+
+ try {
+ const { stdout } = await execFileAsync(
+ 'git',
+ [
+ 'diff',
+ '--no-renames',
+ '--name-only',
+ '--diff-filter=ACDMRTUXB',
+ '-z',
+ previousSha,
+ currentSha,
+ '--',
+ ],
+ { encoding: 'utf8' },
+ );
+ const changedFiles = stdout.split('\0').filter(Boolean);
- process.exit(1);
-} else {
- console.log('πŸ›‘ - Build cancelled');
+ return changedFiles.some((filePath) => !isNonRuntimePath(filePath));
+ } catch {
+ return buildConservatively('Unable to inspect deployment diff; building conservatively.');
+ }
+};
- process.exit(0);
-}
+shouldProceedBuild()
+ .catch(() => buildConservatively('Unable to inspect deployment diff; building conservatively.'))
+ .then((shouldBuild) => {
+ console.log('shouldBuild:', shouldBuild);
+ console.log(shouldBuild ? 'βœ… - Build can proceed' : 'πŸ›‘ - Build cancelled');
+ process.exitCode = shouldBuild ? 1 : 0;
+ });
diff --git a/vercel.json b/vercel.json
index 6f50f6f508b..87b15720eb0 100644
--- a/vercel.json
+++ b/vercel.json
@@ -49,6 +49,7 @@
]
}
],
+ "ignoreCommand": "node scripts/vercelIgnoredBuildStep.js",
"installCommand": "npx [email protected] install",
"rewrites": [
{