Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
45 changes: 45 additions & 0 deletions src/commands/ci/detect-ci-pull-request-context.mts
Original file line number Diff line number Diff line change
@@ -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<CiPullRequestContext> {
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',
}
}
18 changes: 3 additions & 15 deletions src/commands/ci/handle-ci.mts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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/<n>/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<void> {
debugFn('notice', 'Starting CI scan')
debugDir('inspect', { autoManifest })
Expand All @@ -42,6 +29,7 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
const cwd = process.cwd()
const branchName = (await gitBranch(cwd)) || (await detectDefaultBranch(cwd))
const repoName = await getRepoName(cwd)
const { number: pullRequest } = await detectCiPullRequestContext()

debugFn(
'notice',
Expand All @@ -62,7 +50,7 @@ export async function handleCi(autoManifest: boolean): Promise<void> {
outputKind: 'json',
// When 'pendingHead' is true, it requires 'branchName' set and 'tmp' false.
pendingHead: true,
pullRequest: detectCiPullRequestNumber(),
pullRequest,
reach: {
dynamicSbomInference: undefined,
excludePaths: [],
Expand Down
85 changes: 64 additions & 21 deletions src/commands/ci/handle-ci.test.mts
Original file line number Diff line number Diff line change
@@ -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<string, string | undefined>

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,
})
})
})
Loading