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
198 changes: 172 additions & 26 deletions src/commands/ci/select-baseline-scan.mts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { debugFn } from '../../utils/debug.mts'
import { spawn } from '../../utils/spawn.mts'
import { fetchOrgFullScanList } from '../scan/fetch-list-scans.mts'

import type { CResult } from '../../types.mts'
Expand All @@ -10,48 +12,192 @@ export type SelectBaselineScanConfig = {
repo: string
}

const ANCESTOR_WALK_MAX_DEPTH = 100
const SCAN_LOOKUP_PAGE_SIZE = 100
const SCAN_LOOKUP_MAX_PAGES = 100

function isUsableScan(
scan: FullScanItem,
): scan is FullScanItem & { commit_hash: string; id: string } {
return Boolean(
typeof scan.id === 'string' &&
scan.id &&
!(scan as FullScanItem & { tmp?: boolean }).tmp &&
typeof scan.commit_hash === 'string' &&
scan.commit_hash,
)
}

function getNextScanPage(
nextPage: number | null | undefined,
currentPage: number,
resultCount: number,
): CResult<number | undefined> {
if (
resultCount < SCAN_LOOKUP_PAGE_SIZE ||
nextPage === undefined ||
nextPage === null ||
nextPage === 0
) {
return { ok: true, data: undefined }
}
if (!Number.isSafeInteger(nextPage) || nextPage <= currentPage) {
return {
ok: false,
message: 'Cannot select PR scan baseline',
cause: `Full-scan listing did not advance to a new page (nextPage=${String(nextPage)}).`,
}
}
return { ok: true, data: nextPage }
}

export function findBaselineScan(
scans: FullScanItem[],
commitHash: string,
): FullScanItem | undefined {
return scans.find(scan => scan.commit_hash === commitHash)
return scans.find(
scan => scan.commit_hash === commitHash && isUsableScan(scan),
)
}

async function firstParentCommits(
commitHash: string,
cwd = process.cwd(),
): Promise<string[]> {
const resolved = await spawn(
'git',
['rev-parse', '--verify', '--end-of-options', `${commitHash}^{commit}`],
{ cwd },
)
const expectedCommit = resolved.stdout.trim()
if (!expectedCommit) {
throw new Error('Empty git rev-parse result')
}
Comment thread
jdalton marked this conversation as resolved.
Resolved
const result = await spawn(
'git',
[
'rev-list',
'--first-parent',
`--max-count=${ANCESTOR_WALK_MAX_DEPTH}`,
'--end-of-options',
expectedCommit,
],
{ cwd },
)
const commits = result.stdout
.split(/\r?\n/u)
.map(commit => commit.trim())
.filter(Boolean)
if (commits[0] !== expectedCommit) {
throw new Error('Unexpected git rev-list result')
}
return commits
}

export async function selectBaselineScan({
async function scanForCommit({
branch,
commitHash,
orgSlug,
repo,
}: SelectBaselineScanConfig): Promise<CResult<FullScanItem>> {
}: SelectBaselineScanConfig): Promise<CResult<FullScanItem | undefined>> {
let page = 1
for (let pageCount = 0; pageCount < SCAN_LOOKUP_MAX_PAGES; pageCount += 1) {
// eslint-disable-next-line no-await-in-loop -- Pagination must consume one page at a time.
const scansCResult = await fetchOrgFullScanList({
branch,
commitHash,
direction: 'desc',
from_time: '',
orgSlug,
page,
perPage: SCAN_LOOKUP_PAGE_SIZE,
repo,
sort: 'created_at',
})
if (!scansCResult.ok) {
return scansCResult
}
const scan = findBaselineScan(scansCResult.data.results, commitHash)
if (scan) {
return { ok: true, data: scan }
}
const results = scansCResult.data.results
const nextPageCResult = getNextScanPage(
(
scansCResult.data as typeof scansCResult.data & {
nextPage?: number | null
}
).nextPage,
page,
results.length,
)
if (!nextPageCResult.ok) {
return nextPageCResult
}
if (nextPageCResult.data === undefined) {
break
}
page = nextPageCResult.data
if (pageCount === SCAN_LOOKUP_MAX_PAGES - 1) {
return {
ok: false,
message: 'Cannot select PR scan baseline',
cause: `Full-scan listing exceeded ${SCAN_LOOKUP_MAX_PAGES} pages while searching for commit ${commitHash}.`,
}
}
}
return { ok: true, data: undefined }
}

export async function selectBaselineScan(
config: SelectBaselineScanConfig,
): Promise<CResult<FullScanItem>> {
const { branch, commitHash, repo } = config
if (!commitHash) {
return {
ok: false,
message: 'Cannot select PR scan baseline',
cause: 'The CI checkout does not provide a commit SHA.',
}
}

const scansCResult = await fetchOrgFullScanList({
branch,
commitHash,
direction: 'desc',
from_time: '',
orgSlug,
page: 1,
perPage: 1,
repo,
sort: 'created_at',
})
if (!scansCResult.ok) {
return scansCResult
const exact = await scanForCommit(config)
if (!exact.ok) {
return exact
}
if (exact.data) {
return { ok: true, data: exact.data }
}
let history: string[]
try {
history = await firstParentCommits(commitHash)
} catch (error) {
debugFn(
'debug',
`Unable to walk first-parent history from ${commitHash}`,
error,
)
return {
ok: false,
message: 'Cannot read PR base commit history',
cause: `Fetch the base commit ${commitHash} and its first-parent history into the CI checkout before retrying.`,
}
}
for (const [index, ancestor] of history.slice(1).entries()) {
// eslint-disable-next-line no-await-in-loop -- Query nearest first and stop once a baseline is found.
const result = await scanForCommit({ ...config, commitHash: ancestor })
if (!result.ok) {
return result
}
if (result.data) {
console.error(
`No scan exists for PR base commit ${commitHash}; using its scanned first-parent ancestor ${ancestor} as the baseline (${index + 1} commit(s) earlier). The diff is wider than the PR base.`,
)
return { ok: true, data: result.data }
}
}
return {
ok: false,
message: 'No matching PR scan baseline found',
cause: `No scan exists for commit ${commitHash} or a scanned first-parent ancestor within ${ANCESTOR_WALK_MAX_DEPTH} commits on ${repo}/${branch}. Run a scan for the base commit first.`,
}

const scan = findBaselineScan(scansCResult.data.results, commitHash)
return scan
? { ok: true, data: scan }
: {
ok: false,
message: 'No matching PR scan baseline found',
cause: `No scan exists for commit ${commitHash} on ${repo}/${branch}. Run a scan for the base commit first.`,
}
}
Loading
Loading