From d811f62e91db2ad97766d49f4b7c37204170a6cf Mon Sep 17 00:00:00 2001 From: jdalton Date: Wed, 25 Nov 2026 17:38:08 -0500 Subject: [PATCH] refactor(ci): centralize pull request context --- .gitignore | 1 + .../ci/detect-ci-pull-request-context.mts | 45 ++++++++++ src/commands/ci/handle-ci.mts | 18 +--- src/commands/ci/handle-ci.test.mts | 85 ++++++++++++++----- 4 files changed, 113 insertions(+), 36 deletions(-) create mode 100644 src/commands/ci/detect-ci-pull-request-context.mts diff --git a/.gitignore b/.gitignore index ac788ddad9..17f4bed200 100644 --- a/.gitignore +++ b/.gitignore @@ -470,6 +470,7 @@ !/src/commands/cdxgen/cmd-cdxgen.test.mts !/src/commands/ci/cmd-ci.mts !/src/commands/ci/cmd-ci.test.mts +!/src/commands/ci/detect-ci-pull-request-context.mts !/src/commands/ci/fetch-default-org-slug.mts !/src/commands/ci/fetch-default-org-slug.test.mts !/src/commands/ci/handle-ci.mts diff --git a/src/commands/ci/detect-ci-pull-request-context.mts b/src/commands/ci/detect-ci-pull-request-context.mts new file mode 100644 index 0000000000..b2d6571051 --- /dev/null +++ b/src/commands/ci/detect-ci-pull-request-context.mts @@ -0,0 +1,45 @@ +import { readFile } from 'node:fs/promises' + +import { envAsString } from '../../utils/env.mts' + +export type CiPullRequestContext = { + baseBranch: string | undefined + baseCommitHash: string | undefined + number: number + provider: 'github' | undefined +} + +export async function detectCiPullRequestContext(): Promise { + const match = /^refs\/pull\/(\d+)\//.exec( + envAsString(process.env['GITHUB_REF']), + ) + if (!match) { + return { + baseBranch: undefined, + baseCommitHash: undefined, + number: 0, + provider: undefined, + } + } + + let baseCommitHash = envAsString(process.env['GITHUB_BASE_SHA']) || undefined + const eventPath = envAsString(process.env['GITHUB_EVENT_PATH']) + if (!baseCommitHash && eventPath) { + try { + const event = JSON.parse(await readFile(eventPath, 'utf8')) + baseCommitHash = + typeof event?.pull_request?.base?.sha === 'string' + ? event.pull_request.base.sha + : undefined + } catch { + baseCommitHash = undefined + } + } + + return { + baseBranch: envAsString(process.env['GITHUB_BASE_REF']) || undefined, + baseCommitHash, + number: Number(match[1]), + provider: 'github', + } +} diff --git a/src/commands/ci/handle-ci.mts b/src/commands/ci/handle-ci.mts index 1cc43733f1..f801488ecd 100644 --- a/src/commands/ci/handle-ci.mts +++ b/src/commands/ci/handle-ci.mts @@ -1,7 +1,7 @@ +import { detectCiPullRequestContext } from './detect-ci-pull-request-context.mts' import { getDefaultOrgSlug } from './fetch-default-org-slug.mts' import constants from '../../constants.mts' import { debugDir, debugFn } from '../../utils/debug.mts' -import { envAsString } from '../../utils/env.mts' import { detectDefaultBranch, getRepoName, @@ -11,19 +11,6 @@ import { logger } from '../../utils/logger.mts' import { serializeResultJson } from '../../utils/serialize-result-json.mts' import { handleCreateNewScan } from '../scan/handle-create-new-scan.mts' -/** - * Derive the pull request number from the CI environment. GitHub Actions - * pull_request events check out `refs/pull//merge`, so the number is - * recoverable from GITHUB_REF; returns 0 outside a PR run (the API omits - * `pull_request` for falsy values). - */ -export function detectCiPullRequestNumber(): number { - const match = /^refs\/pull\/(\d+)\//.exec( - envAsString(process.env['GITHUB_REF']), - ) - return match ? Number(match[1]) : 0 -} - export async function handleCi(autoManifest: boolean): Promise { debugFn('notice', 'Starting CI scan') debugDir('inspect', { autoManifest }) @@ -42,6 +29,7 @@ export async function handleCi(autoManifest: boolean): Promise { const cwd = process.cwd() const branchName = (await gitBranch(cwd)) || (await detectDefaultBranch(cwd)) const repoName = await getRepoName(cwd) + const { number: pullRequest } = await detectCiPullRequestContext() debugFn( 'notice', @@ -62,7 +50,7 @@ export async function handleCi(autoManifest: boolean): Promise { outputKind: 'json', // When 'pendingHead' is true, it requires 'branchName' set and 'tmp' false. pendingHead: true, - pullRequest: detectCiPullRequestNumber(), + pullRequest, reach: { dynamicSbomInference: undefined, excludePaths: [], diff --git a/src/commands/ci/handle-ci.test.mts b/src/commands/ci/handle-ci.test.mts index 9688e1c2e1..85c1ed5d20 100644 --- a/src/commands/ci/handle-ci.test.mts +++ b/src/commands/ci/handle-ci.test.mts @@ -1,49 +1,92 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { detectCiPullRequestNumber } from './handle-ci.mts' +import { detectCiPullRequestContext } from './detect-ci-pull-request-context.mts' -let originalGithubRef: string | undefined +const githubEnvironmentKeys = [ + 'GITHUB_BASE_REF', + 'GITHUB_BASE_SHA', + 'GITHUB_EVENT_PATH', + 'GITHUB_REF', +] as const -describe('detectCiPullRequestNumber', () => { +let originalGithubEnvironment: Map + +describe('detectCiPullRequestContext', () => { beforeEach(() => { - originalGithubRef = process.env['GITHUB_REF'] - delete process.env['GITHUB_REF'] + originalGithubEnvironment = new Map( + githubEnvironmentKeys.map(key => [key, process.env[key]]), + ) + for (const key of githubEnvironmentKeys) { + delete process.env[key] + } }) afterEach(() => { - if (originalGithubRef === undefined) { - delete process.env['GITHUB_REF'] - } else { - process.env['GITHUB_REF'] = originalGithubRef + for (const [key, value] of originalGithubEnvironment) { + if (value === undefined) { + delete process.env[key] + } else { + process.env[key] = value + } } }) - it('derives the number from a pull request merge ref', () => { + it('derives the number from a pull request merge ref', async () => { process.env['GITHUB_REF'] = 'refs/pull/482/merge' - expect(detectCiPullRequestNumber()).toBe(482) + await expect(detectCiPullRequestContext()).resolves.toEqual({ + baseBranch: undefined, + baseCommitHash: undefined, + number: 482, + provider: 'github', + }) }) - it('derives the number from a pull request head ref', () => { + it('derives the number from a pull request head ref', async () => { process.env['GITHUB_REF'] = 'refs/pull/482/head' - expect(detectCiPullRequestNumber()).toBe(482) + await expect(detectCiPullRequestContext()).resolves.toEqual({ + baseBranch: undefined, + baseCommitHash: undefined, + number: 482, + provider: 'github', + }) }) - it('returns 0 for a branch push', () => { + it('returns 0 for a branch push', async () => { process.env['GITHUB_REF'] = 'refs/heads/feature-branch' - expect(detectCiPullRequestNumber()).toBe(0) + await expect(detectCiPullRequestContext()).resolves.toEqual({ + baseBranch: undefined, + baseCommitHash: undefined, + number: 0, + provider: undefined, + }) }) - it('returns 0 for a tag push', () => { + it('returns 0 for a tag push', async () => { process.env['GITHUB_REF'] = 'refs/tags/v1.2.3' - expect(detectCiPullRequestNumber()).toBe(0) + await expect(detectCiPullRequestContext()).resolves.toEqual({ + baseBranch: undefined, + baseCommitHash: undefined, + number: 0, + provider: undefined, + }) }) - it('returns 0 when GITHUB_REF is not a numbered pull ref', () => { + it('returns 0 when GITHUB_REF is not a numbered pull ref', async () => { process.env['GITHUB_REF'] = 'refs/pull/not-a-number/merge' - expect(detectCiPullRequestNumber()).toBe(0) + await expect(detectCiPullRequestContext()).resolves.toEqual({ + baseBranch: undefined, + baseCommitHash: undefined, + number: 0, + provider: undefined, + }) }) - it('returns 0 outside GitHub Actions', () => { - expect(detectCiPullRequestNumber()).toBe(0) + it('returns 0 outside GitHub Actions', async () => { + await expect(detectCiPullRequestContext()).resolves.toEqual({ + baseBranch: undefined, + baseCommitHash: undefined, + number: 0, + provider: undefined, + }) }) })