From 633ce7442ac3b5cf89421495ee6bbc4acf9a01df Mon Sep 17 00:00:00 2001 From: jdalton Date: Wed, 2 Dec 2026 12:25:46 -0500 Subject: [PATCH] feat(python-cli-parity): skip source-only PR comparisons --- .gitignore | 3 + docs/commands/ci.md | 9 + src/commands/ci/handle-ci-skip.test.mts | 100 ++++++++ src/commands/ci/handle-ci.mts | 60 +++++ src/commands/ci/skip-unchanged-manifests.mts | 131 ++++++++++ .../ci/skip-unchanged-manifests.test.mts | 228 ++++++++++++++++++ test/release-history.test.mts | 2 + 7 files changed, 533 insertions(+) create mode 100644 src/commands/ci/handle-ci-skip.test.mts create mode 100644 src/commands/ci/skip-unchanged-manifests.mts create mode 100644 src/commands/ci/skip-unchanged-manifests.test.mts diff --git a/.gitignore b/.gitignore index 282f2d317..a91c7573f 100644 --- a/.gitignore +++ b/.gitignore @@ -367,6 +367,7 @@ !/src/commands/ci/fetch-default-org-slug.test.mts !/src/commands/ci/handle-ci.mts !/src/commands/ci/handle-ci.test.mts +!/src/commands/ci/handle-ci-skip.test.mts !/src/commands/ci/detect-ci-pull-request-context.test.mts !/src/commands/ci/select-baseline-scan.mts !/src/commands/ci/select-baseline-scan.test.mts @@ -881,6 +882,8 @@ !/src/utils/github.mts !/src/commands/ci/publish-pr-comments.mts !/src/commands/ci/publish-pr-comments.test.mts +!/src/commands/ci/skip-unchanged-manifests.mts +!/src/commands/ci/skip-unchanged-manifests.test.mts !/src/utils/glob-content-dedup.test.mts !/src/utils/glob.mts !/src/utils/glob.test.mts diff --git a/docs/commands/ci.md b/docs/commands/ci.md index f059809e3..b11fa1c68 100644 --- a/docs/commands/ci.md +++ b/docs/commands/ci.md @@ -11,6 +11,15 @@ socket ci Use `--auto-manifest` to include locally generated manifests for supported projects. Run `socket ci --help` for all options. +For pull requests, `socket ci` skips the comparison when a clean checkout has +an available base commit, at least one supported manifest is discoverable, and +no supported manifest or lockfile changed in the PR range. The JSON result is +`{ "ok": true, "skipped": true, "reason": "no-manifest-changes" }` so CI can +distinguish this successful no-op from a clean scan. The command runs a normal +scan when the base commit or file patterns are unavailable, the checkout is +dirty, symlinks or submodules make the inputs uncertain, no supported manifests are discoverable, or auto-manifest generation is +enabled. + On GitHub pull request runs, pass a GitHub token with pull request write permission in `SOCKET_CLI_GITHUB_TOKEN`, `GITHUB_TOKEN`, or `GH_TOKEN`. The command posts an overview and a security findings comment, and updates them on diff --git a/src/commands/ci/handle-ci-skip.test.mts b/src/commands/ci/handle-ci-skip.test.mts new file mode 100644 index 000000000..7c11411e5 --- /dev/null +++ b/src/commands/ci/handle-ci-skip.test.mts @@ -0,0 +1,100 @@ +import { afterEach, expect, it, vi } from 'vitest' + +const mockFetchSupportedScanFileNames = vi.fn() +const mockGetPackageFilesForScan = vi.fn() +const mockSelectBaselineScan = vi.fn() +const mockHandleCreateNewScan = vi.fn() +const mockLog = vi.fn() + +vi.mock('./fetch-default-org-slug.mts', () => ({ + getDefaultOrgSlug: async () => ({ ok: true, data: 'org' }), +})) +vi.mock('./detect-ci-pull-request-context.mts', () => ({ + detectCiPullRequestContext: async () => ({ + baseBranch: 'main', + baseCommitHash: 'a'.repeat(40), + number: 12, + provider: 'github', + }), +})) +vi.mock('./select-baseline-scan.mts', () => ({ + selectBaselineScan: mockSelectBaselineScan, +})) +vi.mock('./skip-unchanged-manifests.mts', () => ({ + hasTrackedManifestInputs: async (_cwd: string, files: string[]) => + files.length > 0, + checkCiManifestChanges: async () => ({ + decision: 'skip', + changedFiles: ['src/index.ts'], + }), +})) +vi.mock('../../utils/config.mts', () => ({ + findSocketYmlSync: () => ({ ok: false }), +})) +vi.mock('../../utils/git.mts', () => ({ + detectDefaultBranch: vi.fn(), + getRepoName: vi.fn(async () => 'project'), + gitBranch: vi.fn(async () => 'feature'), +})) +vi.mock('../../utils/logger.mts', () => ({ logger: { log: mockLog } })) +vi.mock('../../utils/path-resolve.mts', () => ({ + getPackageFilesForScan: mockGetPackageFilesForScan, +})) +vi.mock('../scan/fetch-supported-scan-file-names.mts', () => ({ + fetchSupportedScanFileNames: mockFetchSupportedScanFileNames, +})) +vi.mock('../scan/handle-create-new-scan.mts', () => ({ + handleCreateNewScan: mockHandleCreateNewScan, +})) +vi.mock('./publish-pr-comments.mts', () => ({ + publishPullRequestComments: vi.fn(), +})) + +afterEach(() => { + mockFetchSupportedScanFileNames.mockReset() + mockGetPackageFilesForScan.mockReset() + mockSelectBaselineScan.mockReset() + mockHandleCreateNewScan.mockReset() + mockLog.mockReset() + vi.resetModules() + process.exitCode = undefined +}) + +it('returns a successful JSON no-op before baseline selection for source-only PRs', async () => { + mockFetchSupportedScanFileNames.mockResolvedValue({ + ok: true, + data: { npm: { manifest: { pattern: 'package.json' } } }, + }) + mockGetPackageFilesForScan.mockResolvedValue(['package.json']) + + const { handleCi } = await import('./handle-ci.mts') + await handleCi(false) + + expect(mockSelectBaselineScan).not.toHaveBeenCalled() + expect(mockHandleCreateNewScan).not.toHaveBeenCalled() + expect(mockLog).toHaveBeenCalledWith( + '{\n "ok": true,\n "skipped": true,\n "reason": "no-manifest-changes"\n}\n', + ) +}) + +it('keeps normal baseline selection when no supported manifests are discoverable', async () => { + mockFetchSupportedScanFileNames.mockResolvedValue({ + ok: true, + data: { npm: { manifest: { pattern: 'package.json' } } }, + }) + mockGetPackageFilesForScan.mockResolvedValue([]) + mockSelectBaselineScan.mockResolvedValue({ + ok: false, + message: 'baseline unavailable', + cause: 'No baseline', + }) + + const { handleCi } = await import('./handle-ci.mts') + await handleCi(false) + + expect(mockSelectBaselineScan).toHaveBeenCalledOnce() + expect(mockHandleCreateNewScan).not.toHaveBeenCalled() + expect(JSON.parse(mockLog.mock.calls[0]?.[0] ?? '{}')).toMatchObject({ + message: 'baseline unavailable', + }) +}) diff --git a/src/commands/ci/handle-ci.mts b/src/commands/ci/handle-ci.mts index f5a9434b8..e2075db70 100644 --- a/src/commands/ci/handle-ci.mts +++ b/src/commands/ci/handle-ci.mts @@ -2,8 +2,13 @@ import { detectCiPullRequestContext } from './detect-ci-pull-request-context.mts import { getDefaultOrgSlug } from './fetch-default-org-slug.mts' import { publishPullRequestComments } from './publish-pr-comments.mts' import { selectBaselineScan } from './select-baseline-scan.mts' +import { + checkCiManifestChanges, + hasTrackedManifestInputs, +} from './skip-unchanged-manifests.mts' import constants from '../../constants.mts' import { setCiExitCode } from '../../utils/ci-exit-code.mts' +import { findSocketYmlSync } from '../../utils/config.mts' import { debugDir, debugFn } from '../../utils/debug.mts' import { envAsBoolean } from '../../utils/env.mts' import { @@ -12,7 +17,9 @@ import { gitBranch, } from '../../utils/git.mts' import { logger } from '../../utils/logger.mts' +import { getPackageFilesForScan } from '../../utils/path-resolve.mts' import { serializeResultJson } from '../../utils/serialize-result-json.mts' +import { fetchSupportedScanFileNames } from '../scan/fetch-supported-scan-file-names.mts' import { handleCreateNewScan } from '../scan/handle-create-new-scan.mts' export async function handleCi(autoManifest: boolean): Promise { @@ -33,6 +40,59 @@ export async function handleCi(autoManifest: boolean): Promise { const pullRequestContext = await detectCiPullRequestContext() const { number: pullRequest } = pullRequestContext const cwd = process.cwd() + + // Only skip when a clean checkout and an authoritative supported-file list + // prove this PR has no dependency manifest changes. Auto-manifest generation + // can derive dependencies from source/build inputs, so it always scans. + if (pullRequestContext.number && !autoManifest) { + const supportedFilesCResult = await fetchSupportedScanFileNames({ + orgSlug, + silence: true, + }) + if (supportedFilesCResult.ok) { + const check = await checkCiManifestChanges({ + baseCommitHash: pullRequestContext.baseCommitHash, + cwd, + supportedFiles: supportedFilesCResult.data, + }) + if (check.decision === 'skip') { + try { + const socketYmlResult = findSocketYmlSync(cwd) + const discoveredFiles = await getPackageFilesForScan( + ['.'], + supportedFilesCResult.data, + { + cwd, + config: socketYmlResult.ok + ? socketYmlResult.data?.parsed + : undefined, + }, + ) + if (await hasTrackedManifestInputs(cwd, discoveredFiles)) { + logger.log( + `${JSON.stringify( + { + ok: true, + skipped: true, + reason: 'no-manifest-changes', + }, + null, + 2, + )}\n`, + ) + return + } + } catch (error) { + debugFn( + 'warn', + 'Manifest discovery failed during CI skip check', + error, + ) + } + } + } + } + const branchName = (await gitBranch(cwd)) || (await detectDefaultBranch(cwd)) const repoName = await getRepoName(cwd) let baselineScanId: string | undefined diff --git a/src/commands/ci/skip-unchanged-manifests.mts b/src/commands/ci/skip-unchanged-manifests.mts new file mode 100644 index 000000000..04db62a7f --- /dev/null +++ b/src/commands/ci/skip-unchanged-manifests.mts @@ -0,0 +1,131 @@ +import path from 'node:path' + +import { + filterBySupportedScanFiles, + getSupportedFilePatterns, +} from '../../utils/glob.mts' +import { spawn } from '../../utils/spawn.mts' + +import type { SocketSdkSuccessResult } from '@socketsecurity/sdk' + +export type CiManifestChangeCheck = + | { decision: 'scan'; reason: string } + | { decision: 'skip'; changedFiles: string[] } + +/** + * Returns a skip decision only when Git can prove a clean PR range contains + * no changes to files supported by Socket's org-scoped manifest patterns. + * Git or classification uncertainty always falls back to a regular scan. + */ +export async function checkCiManifestChanges({ + baseCommitHash, + cwd, + supportedFiles, +}: { + baseCommitHash: string | undefined + cwd: string + supportedFiles: SocketSdkSuccessResult<'getSupportedFiles'>['data'] +}): Promise { + if (!baseCommitHash) { + return { decision: 'scan', reason: 'missing-base-commit' } + } + if (!/^(?:[\da-f]{40}|[\da-f]{64})$/iu.test(baseCommitHash)) { + return { decision: 'scan', reason: 'invalid-base-commit' } + } + try { + const patterns = getSupportedFilePatterns(supportedFiles) + if ( + !patterns.length || + patterns.some(pattern => pattern === '**/undefined' || pattern === '**/') + ) { + return { decision: 'scan', reason: 'no-supported-file-patterns' } + } + + const status = await spawn( + 'git', + ['status', '--porcelain', '--untracked-files=all'], + { cwd }, + ) + if (status.stdout.trim()) { + return { decision: 'scan', reason: 'working-tree-not-clean' } + } + + // NUL delimiters preserve spaces and unusual characters in paths. The + // three-dot range mirrors PR comparison semantics and fails closed when + // the base commit is absent from a shallow checkout. Raw records expose + // file modes too, so links and submodules can be treated conservatively. + const diff = await spawn( + 'git', + ['diff', '--raw', '--no-renames', '-z', `${baseCommitHash}...HEAD`], + { cwd }, + ) + const rawEntries = diff.stdout.split('\0') + const changedFiles: string[] = [] + for (let i = 0; i + 1 < rawEntries.length; i += 2) { + const header = rawEntries[i] ?? '' + if (/^:(?:120000|160000) |^:\d{6} (?:120000|160000) /u.test(header)) { + return { decision: 'scan', reason: 'link-or-submodule-changed' } + } + const file = rawEntries[i + 1] + if (file) { + changedFiles.push(file.replaceAll('\\', '/').replace(/^\.\//u, '')) + } + } + + // Configuration changes can alter discovery even when they are not + // dependency manifests themselves, so they must keep the normal scan. + if ( + changedFiles.some(file => + /(^|\/)(?:socket\.json|socket\.ya?ml|\.gitignore|\.gitmodules|pyvenv\.cfg)$/iu.test( + file, + ), + ) + ) { + return { decision: 'scan', reason: 'scan-configuration-changed' } + } + if (!changedFiles.length) { + return { decision: 'scan', reason: 'empty-change-set' } + } + + const changedManifests = filterBySupportedScanFiles( + changedFiles, + supportedFiles, + ) + return changedManifests.length + ? { decision: 'scan', reason: 'supported-manifest-changed' } + : { decision: 'skip', changedFiles } + } catch { + return { decision: 'scan', reason: 'git-range-unavailable' } + } +} + +/** Git's diff can only prove that tracked, regular manifest inputs are unchanged. */ +export async function hasTrackedManifestInputs( + cwd: string, + discovered: readonly string[], +): Promise { + if (!discovered.length) { + return false + } + const { stdout } = await spawn('git', ['ls-files', '--stage', '-z'], { + cwd, + stripAnsi: false, + }) + const tracked = new Set() + for (const entry of stdout.split('\0')) { + if (!entry) { + continue + } + // A symlinked manifest or directory can change when only its target changes. + // A submodule's files similarly belong to a different index. + if (!entry.startsWith('100644 ') && !entry.startsWith('100755 ')) { + return false + } + tracked.add(entry.slice(entry.indexOf('\t') + 1)) + } + return discovered.every(file => + tracked.has( + path.relative(cwd, path.resolve(cwd, file)).split(path.sep).join('/'), + ), + ) +} diff --git a/src/commands/ci/skip-unchanged-manifests.test.mts b/src/commands/ci/skip-unchanged-manifests.test.mts new file mode 100644 index 000000000..145446caf --- /dev/null +++ b/src/commands/ci/skip-unchanged-manifests.test.mts @@ -0,0 +1,228 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('../../utils/spawn.mts', () => ({ spawn: vi.fn() })) + +import { + checkCiManifestChanges, + hasTrackedManifestInputs, +} from './skip-unchanged-manifests.mts' +import { spawn } from '../../utils/spawn.mts' + +const supportedFiles = { + npm: { + manifest: { pattern: 'package.json' }, + lock: { pattern: 'package-lock.json' }, + }, +} as never +const mockSpawn = vi.mocked(spawn) +const baseCommitHash = 'a'.repeat(40) + +beforeEach(() => { + mockSpawn.mockReset() +}) + +describe('checkCiManifestChanges', () => { + it('skips a clean PR range containing only source changes', async () => { + mockSpawn + .mockResolvedValueOnce({ stdout: '', stderr: '', code: 0 } as never) + .mockResolvedValueOnce({ + stdout: + ':100644 100644 abc def M\0src/index.ts\0:100644 100644 abc def M\0README.md\0', + stderr: '', + code: 0, + } as never) + + await expect( + checkCiManifestChanges({ + baseCommitHash, + cwd: '/repo', + supportedFiles, + }), + ).resolves.toEqual({ + decision: 'skip', + changedFiles: ['src/index.ts', 'README.md'], + }) + }) + + it.each([ + ['manifest change', 'package.json', 'supported-manifest-changed'], + ['manifest deletion', 'package-lock.json', 'supported-manifest-changed'], + ])('scans when a %s is present', async (_label, file, reason) => { + mockSpawn + .mockResolvedValueOnce({ stdout: '', stderr: '', code: 0 } as never) + .mockResolvedValueOnce({ + stdout: `:100644 100644 abc def M\0${file}\0`, + stderr: '', + code: 0, + } as never) + + await expect( + checkCiManifestChanges({ + baseCommitHash, + cwd: '/repo', + supportedFiles, + }), + ).resolves.toEqual({ decision: 'scan', reason }) + }) + + it('scans when the base SHA is missing or the checkout is dirty', async () => { + await expect( + checkCiManifestChanges({ + baseCommitHash: undefined, + cwd: '/repo', + supportedFiles, + }), + ).resolves.toEqual({ decision: 'scan', reason: 'missing-base-commit' }) + + mockSpawn.mockResolvedValueOnce({ + stdout: '?? generated.json', + stderr: '', + code: 0, + } as never) + await expect( + checkCiManifestChanges({ + baseCommitHash, + cwd: '/repo', + supportedFiles, + }), + ).resolves.toEqual({ decision: 'scan', reason: 'working-tree-not-clean' }) + }) + + it('scans on shallow history or an unavailable Git range', async () => { + mockSpawn + .mockResolvedValueOnce({ stdout: '', stderr: '', code: 0 } as never) + .mockRejectedValueOnce(new Error('bad revision')) + + await expect( + checkCiManifestChanges({ + baseCommitHash: 'b'.repeat(40), + cwd: '/repo', + supportedFiles, + }), + ).resolves.toEqual({ decision: 'scan', reason: 'git-range-unavailable' }) + }) + + it('keeps a rename away from a manifest and a symlink change on the scan path', async () => { + mockSpawn + .mockResolvedValueOnce({ stdout: '', stderr: '', code: 0 } as never) + .mockResolvedValueOnce({ + stdout: + ':100644 000000 abc 000000 D\0package.json\0:000000 100644 000000 def A\0src/package.json\0', + stderr: '', + code: 0, + } as never) + await expect( + checkCiManifestChanges({ baseCommitHash, cwd: '/repo', supportedFiles }), + ).resolves.toEqual({ + decision: 'scan', + reason: 'supported-manifest-changed', + }) + expect(mockSpawn.mock.calls[1]?.[1]).toContain('--no-renames') + + mockSpawn + .mockResolvedValueOnce({ stdout: '', stderr: '', code: 0 } as never) + .mockResolvedValueOnce({ + stdout: ':100644 120000 abc def M\0src/link\0', + stderr: '', + code: 0, + } as never) + await expect( + checkCiManifestChanges({ baseCommitHash, cwd: '/repo', supportedFiles }), + ).resolves.toEqual({ + decision: 'scan', + reason: 'link-or-submodule-changed', + }) + }) + + it('scans when a submodule is removed', async () => { + mockSpawn + .mockResolvedValueOnce({ stdout: '' } as never) + .mockResolvedValueOnce({ + stdout: ':160000 000000 abc 000 D\0vendor/lib\0', + } as never) + await expect( + checkCiManifestChanges({ baseCommitHash, cwd: '/repo', supportedFiles }), + ).resolves.toEqual({ + decision: 'scan', + reason: 'link-or-submodule-changed', + }) + }) + + it('scans when configuration changed or the range has no changed files', async () => { + mockSpawn + .mockResolvedValueOnce({ stdout: '', stderr: '', code: 0 } as never) + .mockResolvedValueOnce({ + stdout: ':100644 100644 abc def M\0socket.yml\0', + stderr: '', + code: 0, + } as never) + await expect( + checkCiManifestChanges({ + baseCommitHash, + cwd: '/repo', + supportedFiles, + }), + ).resolves.toEqual({ + decision: 'scan', + reason: 'scan-configuration-changed', + }) + + mockSpawn + .mockResolvedValueOnce({ stdout: '', stderr: '', code: 0 } as never) + .mockResolvedValueOnce({ stdout: '', stderr: '', code: 0 } as never) + await expect( + checkCiManifestChanges({ + baseCommitHash, + cwd: '/repo', + supportedFiles, + }), + ).resolves.toEqual({ decision: 'scan', reason: 'empty-change-set' }) + }) + + it('scans when supported-file classification throws', async () => { + // A command failure cannot be interpreted as proof of a source-only diff. + mockSpawn.mockRejectedValueOnce(new Error('not a Git worktree')) + await expect( + checkCiManifestChanges({ + baseCommitHash, + cwd: '/not-a-repository', + supportedFiles, + }), + ).resolves.toEqual({ decision: 'scan', reason: 'git-range-unavailable' }) + }) + + it('scans when the base SHA or supported patterns are invalid', async () => { + await expect( + checkCiManifestChanges({ + baseCommitHash: 'not-a-sha', + cwd: '/repo', + supportedFiles, + }), + ).resolves.toEqual({ decision: 'scan', reason: 'invalid-base-commit' }) + await expect( + checkCiManifestChanges({ + baseCommitHash, + cwd: '/repo', + supportedFiles: {} as never, + }), + ).resolves.toEqual({ + decision: 'scan', + reason: 'no-supported-file-patterns', + }) + }) +}) + +it('requires each discovered manifest to be tracked and regular before skipping', async () => { + const manifest = '100644 abc 0\tpackage.json\0' + mockSpawn.mockResolvedValue({ stdout: manifest } as never) + expect(await hasTrackedManifestInputs('/repo', ['package.json'])).toBe(true) + expect( + await hasTrackedManifestInputs('/repo', ['generated/pnpm-lock.yaml']), + ).toBe(false) + mockSpawn.mockResolvedValue({ + stdout: manifest + '120000 def 0\tdeps/package.json\0', + } as never) + expect(await hasTrackedManifestInputs('/repo', ['deps/package.json'])).toBe( + false, + ) +}) diff --git a/test/release-history.test.mts b/test/release-history.test.mts index b63325fd0..6bde1491c 100644 --- a/test/release-history.test.mts +++ b/test/release-history.test.mts @@ -400,6 +400,8 @@ describe('selecting a publish lane from merged release history', () => { commits[expectedCommit as keyof typeof commits], ) }, + // Each lane builds a five-commit Git history and runs the publish checkout in Bash. + 30_000, ) it('allows an independent publish from a paired preparation', () => {