From f0f699acaaff7108448c9609116c73cc0154279a Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 15:26:39 +0100 Subject: [PATCH 01/12] Generate Socket facts with Coana socket-cli now asks `coana generate-socket-facts` for each build root instead of running its own build-tool scripts, and lists a build's projects and a .NET solution's members through the same command. - Coana writes a root's facts into its state dir under --work-dir and names where they belong. The walk always generates into a work dir, its own when no later Coana run reads one, and copies the facts of the roots it keeps to their target at the end; a dropped run never touches the file there. This replaces the save/restore of predicted facts files. - The kept roots' sidecar entries go to reachability and socket fix as --socket-facts-sidecar. - --auto-manifest builds through the same settings as the walk. Maven builds pom.xml by name, so its facts and state stay apart from a Gradle build in the same directory, and a --file in mavenOpts becomes the POM it builds instead of a build option. - A --reach-version or --fix-version older than the pinned Coana fails facts generation with a message naming that version. - The standalone build's README says every Coana use needs SOCKET_CLI_COANA_LOCAL_PATH. --- .gitignore | 7 - CHANGELOG.md | 8 + .../coana-fix-dynamic-sbom-inference.test.mts | 6 +- src/commands/fix/coana-fix.mts | 9 +- src/commands/fix/generated-socket-facts.mts | 39 +- .../fix/generated-socket-facts.test.mts | 46 +- src/commands/manifest/cmd-manifest-auto.mts | 20 +- src/commands/manifest/cmd-manifest-gradle.mts | 7 +- src/commands/manifest/cmd-manifest-kotlin.mts | 7 +- src/commands/manifest/cmd-manifest-maven.mts | 7 +- src/commands/manifest/cmd-manifest-scala.mts | 29 +- .../manifest/convert-dotnet-to-facts.mts | 17 +- .../manifest/convert-gradle-to-facts.mts | 51 -- .../manifest/convert-maven-to-facts.mts | 51 -- .../manifest/convert-sbt-to-facts.mts | 56 -- .../manifest/discover-manifest-roots.mts | 56 +- .../manifest/discover-manifest-roots.test.mts | 26 +- .../manifest/enumerate-workspaces.mts | 101 --- .../manifest/enumerate-workspaces.test.mts | 122 --- src/commands/manifest/expand-env-var-refs.mts | 33 - .../manifest/expand-env-var-refs.test.mts | 67 -- .../manifest/generate-recursive-manifests.mts | 415 ++++------ .../generate-recursive-manifests.test.mts | 765 +++++++++--------- .../manifest/generate_auto_manifest.mts | 221 +++-- .../manifest/generate_auto_manifest.test.mts | 203 ++++- src/commands/manifest/load-build.mts | 42 +- src/commands/manifest/run-manifest-facts.mts | 586 ++++++++------ .../manifest/run-manifest-facts.test.mts | 590 ++++++++------ src/commands/manifest/scripts/build-tool.mts | 7 +- .../setup-recursive-manifest-config.mts | 24 +- .../setup-recursive-manifest-config.test.mts | 61 +- src/commands/scan/cmd-scan-create.mts | 2 + src/commands/scan/handle-create-new-scan.mts | 59 +- .../scan/handle-create-new-scan.test.mts | 45 +- src/commands/scan/handle-scan-reach.mts | 33 +- src/commands/scan/handle-scan-reach.test.mts | 54 +- .../scan/perform-reachability-analysis.mts | 24 +- .../perform-reachability-analysis.test.mts | 23 +- .../scan/run-dynamic-sbom-inference.mts | 60 +- .../scan/run-dynamic-sbom-inference.test.mts | 54 +- .../scan/warn-socket-json-only-flags.mts | 2 +- src/utils/coana-release.test.mts | 40 +- src/utils/coana/release.mts | 41 +- 43 files changed, 1953 insertions(+), 2163 deletions(-) delete mode 100644 src/commands/manifest/convert-gradle-to-facts.mts delete mode 100644 src/commands/manifest/convert-maven-to-facts.mts delete mode 100644 src/commands/manifest/convert-sbt-to-facts.mts delete mode 100644 src/commands/manifest/enumerate-workspaces.mts delete mode 100644 src/commands/manifest/enumerate-workspaces.test.mts delete mode 100644 src/commands/manifest/expand-env-var-refs.mts delete mode 100644 src/commands/manifest/expand-env-var-refs.test.mts diff --git a/.gitignore b/.gitignore index ac788ddad9..d1b09261eb 100644 --- a/.gitignore +++ b/.gitignore @@ -599,19 +599,12 @@ !/src/commands/manifest/convert-conda-to-requirements.mts !/src/commands/manifest/convert-conda-to-requirements.test.mts !/src/commands/manifest/convert-dotnet-to-facts.mts -!/src/commands/manifest/convert-gradle-to-facts.mts -!/src/commands/manifest/convert-maven-to-facts.mts -!/src/commands/manifest/convert-sbt-to-facts.mts !/src/commands/manifest/convert_gradle_to_maven.mts !/src/commands/manifest/convert_sbt_to_maven.mts !/src/commands/manifest/detect-manifest-actions.mts !/src/commands/manifest/detect-manifest-actions.test.mts !/src/commands/manifest/discover-manifest-roots.mts !/src/commands/manifest/discover-manifest-roots.test.mts -!/src/commands/manifest/enumerate-workspaces.mts -!/src/commands/manifest/enumerate-workspaces.test.mts -!/src/commands/manifest/expand-env-var-refs.mts -!/src/commands/manifest/expand-env-var-refs.test.mts !/src/commands/manifest/generate-recursive-manifests.mts !/src/commands/manifest/generate-recursive-manifests.test.mts !/src/commands/manifest/generate_auto_manifest.mts diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bf8d1eae8..97a0ba5781 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Added +- Socket facts for a self-contained .NET build include its runtime packs. + ### Changed - Updated the Coana CLI to v `15.15.4`. +- Coana now generates Socket facts for Gradle, Maven, sbt and .NET builds, so generating them downloads Coana and needs network access and a Socket API token. +- `--reach-version` and `--fix-version` also select the Coana that generates Socket facts, which must be the pinned version or newer. +- With `--dynamic-sbom-inference`, reachability analyzes each JVM project on the classpath its build resolved, and `socket fix` restores a build's files when an upgrade does not take. +- `--ignore-unresolved` no longer lets through a build whose resolution did not run, or a failure that names no project. +- `--dynamic-sbom-inference` builds each POM by its own file, so it ignores a `--file` in `mavenOpts`, with a warning. ## [1.16.1](https://github.com/SocketDev/socket-cli/releases/tag/v1.16.1) - 2026-11-24 diff --git a/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts b/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts index d1fa67000e..b62fe4bfe8 100644 --- a/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts +++ b/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts @@ -156,8 +156,8 @@ describe('socket fix --dynamic-sbom-inference', () => { ) const args = coanaCalls('compute-fixes-and-upgrade-purls')[0]! expect(args).toContain('--maven-use-only-socket-facts') - expect(args).toContain('--compute-artifacts-sidecar') - expect(args[args.indexOf('--compute-artifacts-sidecar') + 1]).toBe( + expect(args).toContain('--socket-facts-sidecar') + expect(args[args.indexOf('--socket-facts-sidecar') + 1]).toBe( generated.sidecarFile, ) expect(generated.remove).toHaveBeenCalledTimes(1) @@ -178,7 +178,7 @@ describe('socket fix --dynamic-sbom-inference', () => { const args = coanaCalls('find-vulnerabilities')[0] expect(args).toContain('--maven-use-only-socket-facts') - expect(args).not.toContain('--compute-artifacts-sidecar') + expect(args).not.toContain('--socket-facts-sidecar') }) it('regenerates facts files that were already present, uploading each once', async () => { diff --git a/src/commands/fix/coana-fix.mts b/src/commands/fix/coana-fix.mts index 08528e9909..37437c21c3 100644 --- a/src/commands/fix/coana-fix.mts +++ b/src/commands/fix/coana-fix.mts @@ -396,11 +396,13 @@ async function coanaFixWithFacts( logger.info('Generating Socket facts for each build ...') } factsSlot.generated = await generateSocketFactsForFix({ + coanaVersion, cwd, excludePaths, purlTypes: factsSlot.purlTypes, findFactsPaths: async () => (await findScanFilepaths()).filter(isSocketFactsFile), + orgSlug, tmpDir: factsSlot.tmpDir, }) scanFilepaths = await withoutDiscardedFacts( @@ -414,13 +416,12 @@ async function coanaFixWithFacts( } } const sidecarFile = factsSlot?.generated?.sidecarFile - // Discovery only needs which artifacts the facts files resolve. Applying - // fixes reads each project's tree; a Coana predating facts trees can only - // tell from the sidecar's classpaths which projects resolve an artifact. + // Discovery only needs which artifacts the facts files resolve; applying + // fixes also reads what facts generation kept of each build root. const discoveryFlags = factsSlot?.generated?.artifactsFlags ?? [] const factsFlags = [ ...discoveryFlags, - ...(sidecarFile ? ['--compute-artifacts-sidecar', sidecarFile] : []), + ...(sidecarFile ? ['--socket-facts-sidecar', sidecarFile] : []), ] const uploadCResult = await handleApiCall( sockSdk.uploadManifestFiles(orgSlug, scanFilepaths, { diff --git a/src/commands/fix/generated-socket-facts.mts b/src/commands/fix/generated-socket-facts.mts index a6654b9685..b85b3b82e8 100644 --- a/src/commands/fix/generated-socket-facts.mts +++ b/src/commands/fix/generated-socket-facts.mts @@ -5,6 +5,7 @@ import { useOnlySocketFactsArtifactsFlags } from '../../utils/coana.mts' import { runDynamicSbomInference } from '../scan/run-dynamic-sbom-inference.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' +import type { KeptRootsDir } from '../scan/run-dynamic-sbom-inference.mts' export type GeneratedSocketFacts = { // Coana's flags selecting what the facts files resolve. @@ -12,7 +13,8 @@ export type GeneratedSocketFacts = { // Facts files of dropped runs, which Coana must not read. discardedPaths: string[] paths: string[] - // The facts files' per-project classpaths, written outside the repository. + // What Coana kept of each build root, for `--socket-facts-sidecar`; written + // outside the repository. sidecarFile: string remove: () => Promise restore: () => Promise @@ -40,15 +42,19 @@ async function restoreAll(backups: Backup[]): Promise { // Backed up so each fix attempt sees the pre-fix build after `git clean`, and // facts files already present are left as they were found. export async function generateSocketFactsForFix({ + coanaVersion, cwd, excludePaths, findFactsPaths, + orgSlug, purlTypes, tmpDir, }: { + coanaVersion?: string | undefined cwd: string excludePaths: string[] findFactsPaths: () => Promise + orgSlug?: string | undefined purlTypes: readonly PURL_Type[] tmpDir: string }): Promise { @@ -65,25 +71,27 @@ export async function generateSocketFactsForFix({ let discardedPaths: string[] let paths: string[] const sidecarFile = path.join(tmpDir, 'sidecar.json') + const workDir: KeptRootsDir = { + dir: path.join(tmpDir, 'work'), + entries: new Map(), + } + await mkdir(workDir.dir) try { - const { - discardedFactsPaths, - factsOnlyTypes, - factsPaths, - resolvedPathsSidecar, - } = await runDynamicSbomInference({ - consumer: 'fix', - cwd, - excludePaths, - purlTypes, - sbtTmpDir: undefined, - }) + const { discardedFactsPaths, factsOnlyTypes, factsPaths } = + await runDynamicSbomInference({ + consumer: 'fix', + context: { coanaVersion, orgSlug }, + cwd, + excludePaths, + purlTypes, + workDir, + }) artifactsFlags = useOnlySocketFactsArtifactsFlags(factsOnlyTypes) discardedPaths = discardedFactsPaths paths = factsPaths.map(p => path.resolve(cwd, p)) // Written even when empty, as for reach; applying fixes looks each facts // file up in it, so an empty one is the same as none. - await writeFile(sidecarFile, JSON.stringify(resolvedPathsSidecar ?? {})) + await writeFile(sidecarFile, JSON.stringify([...workDir.entries.values()])) } catch (e) { // A failed build root aborts inference after others wrote their facts. await reset(await findFactsPaths()) @@ -99,8 +107,7 @@ export async function generateSocketFactsForFix({ discardedPaths, paths, sidecarFile, - // A discarded file a run left as written is removed too. - remove: () => reset([...paths, ...discardedPaths]), + remove: () => reset(paths), restore: () => restoreAll(backups), } } diff --git a/src/commands/fix/generated-socket-facts.test.mts b/src/commands/fix/generated-socket-facts.test.mts index f395c62ae0..cf50966d0e 100644 --- a/src/commands/fix/generated-socket-facts.test.mts +++ b/src/commands/fix/generated-socket-facts.test.mts @@ -67,51 +67,43 @@ describe('generateSocketFactsForFix', () => { expect(existsSync(fresh)).toBe(false) }) - it('removes a discarded facts file a dropped run left behind', async () => { - const discarded = path.join(cwd, 'sub', 'pom.xml.socket.facts.json') - mockRunDynamicSbomInference.mockImplementation(async () => { - await fs.writeFile(discarded, 'dropped') - return { - discardedFactsPaths: [discarded, existing], - factsOnlyTypes: ['maven'], - factsPaths: [], - } - }) - - const generated = await generate() - await generated.remove() - - expect(existsSync(discarded)).toBe(false) - expect(await fs.readFile(existing, 'utf8')).toBe('original') - }) - - it('writes the sidecar outside the repository', async () => { - mockRunDynamicSbomInference.mockImplementation(async () => { + it('keeps what Coana kept of each build root outside the repository', async () => { + const entry = { factsFile: fresh, stateDir: path.join(tmpDir, 'work', 'x') } + let workDirExisted = false + mockRunDynamicSbomInference.mockImplementation(async ({ workDir }) => { + workDirExisted = existsSync(workDir.dir) await fs.writeFile(fresh, 'generated') + workDir.entries.set(entry.factsFile, entry) return { discardedFactsPaths: [], factsOnlyTypes: ['maven', 'nuget'], factsPaths: [fresh], - resolvedPathsSidecar: { [fresh]: { components: [], projects: [] } }, } }) const { artifactsFlags, sidecarFile } = await generate() + expect(workDirExisted).toBe(true) expect(mockRunDynamicSbomInference).toHaveBeenCalledWith( - expect.objectContaining({ consumer: 'fix', purlTypes: ['maven'] }), + expect.objectContaining({ + consumer: 'fix', + context: { coanaVersion: undefined, orgSlug: undefined }, + purlTypes: ['maven'], + workDir: { + dir: path.join(tmpDir, 'work'), + entries: new Map([[entry.factsFile, entry]]), + }, + }), ) expect(artifactsFlags).toEqual([ '--use-only-socket-facts-artifacts', 'maven,nuget', ]) expect(path.dirname(sidecarFile)).toBe(tmpDir) - expect(JSON.parse(await fs.readFile(sidecarFile, 'utf8'))).toEqual({ - [fresh]: { components: [], projects: [] }, - }) + expect(JSON.parse(await fs.readFile(sidecarFile, 'utf8'))).toEqual([entry]) }) - it('writes an empty sidecar when no build root resolved any paths', async () => { + it('writes an empty sidecar when no build root generated facts', async () => { mockRunDynamicSbomInference.mockResolvedValue({ discardedFactsPaths: [], factsOnlyTypes: ['maven'], @@ -121,7 +113,7 @@ describe('generateSocketFactsForFix', () => { const { artifactsFlags, sidecarFile } = await generate() expect(artifactsFlags).toEqual(['--maven-use-only-socket-facts']) - expect(JSON.parse(await fs.readFile(sidecarFile, 'utf8'))).toEqual({}) + expect(JSON.parse(await fs.readFile(sidecarFile, 'utf8'))).toEqual([]) }) it('restores an existing facts file that generation does not rewrite', async () => { diff --git a/src/commands/manifest/cmd-manifest-auto.mts b/src/commands/manifest/cmd-manifest-auto.mts index 921d4270cd..3db95fc001 100644 --- a/src/commands/manifest/cmd-manifest-auto.mts +++ b/src/commands/manifest/cmd-manifest-auto.mts @@ -3,11 +3,11 @@ import path from 'node:path' import { detectManifestActions } from './detect-manifest-actions.mts' import { generateAutoManifest } from './generate_auto_manifest.mts' import { excludePathsFlag } from './manifest-flags.mts' +import { EXCLUDE_PATHS_FLAG } from './run-manifest-facts.mts' import constants from '../../constants.mts' import { commonFlags } from '../../flags.mts' import { cmdFlagValueToArray } from '../../utils/cmd.mts' import { debugDir } from '../../utils/debug.mts' -import { withTmpDir } from '../../utils/fs.mts' import { getOutputKind } from '../../utils/get-output-kind.mts' import { logger } from '../../utils/logger.mts' import { meowOrExit } from '../../utils/meow-with-subcommands.mts' @@ -124,16 +124,14 @@ async function run( const excludePaths = cmdFlagValueToArray(cli.flags['excludePaths']) assertValidExcludePaths(excludePaths) - await withTmpDir('socket-manifest-auto-', tmpDir => - generateAutoManifest({ - detected, - cwd, - excludePaths, - outputKind, - tmpDir, - verbose, - }), - ) + await generateAutoManifest({ + detected, + cwd, + excludePaths, + excludePathsFlag: EXCLUDE_PATHS_FLAG, + outputKind, + verbose, + }) logger.success( `Finished. Should have attempted to generate manifest files for ${detected.count} targets.`, diff --git a/src/commands/manifest/cmd-manifest-gradle.mts b/src/commands/manifest/cmd-manifest-gradle.mts index 0a04b6c4ef..f7da009c02 100644 --- a/src/commands/manifest/cmd-manifest-gradle.mts +++ b/src/commands/manifest/cmd-manifest-gradle.mts @@ -1,9 +1,9 @@ import path from 'node:path' -import { convertGradleToFacts } from './convert-gradle-to-facts.mts' import { convertGradleToMaven } from './convert_gradle_to_maven.mts' import { excludePathsFlag } from './manifest-flags.mts' import { parseBuildToolOpts } from './parse-build-tool-opts.mts' +import { runManifestFacts } from './run-manifest-facts.mts' import { resolveBuildToolBin } from './scripts/build-tool.mts' import constants, { REQUIREMENTS_TXT, SOCKET_JSON } from '../../constants.mts' import { commonFlags } from '../../flags.mts' @@ -296,12 +296,13 @@ async function run( assertValidExcludePaths(excludePaths) if (facts) { - await convertGradleToFacts({ + await runManifestFacts({ bin: String(bin), + buildOpts: parsedGradleOpts, cwd, + ecosystem: 'gradle', excludeConfigs: String(excludeConfigs || ''), excludePaths, - gradleOpts: parsedGradleOpts, ignoreUnresolved: Boolean(ignoreUnresolved), includeConfigs: String(includeConfigs || ''), javaHome, diff --git a/src/commands/manifest/cmd-manifest-kotlin.mts b/src/commands/manifest/cmd-manifest-kotlin.mts index fd2479621a..b4970b42ad 100644 --- a/src/commands/manifest/cmd-manifest-kotlin.mts +++ b/src/commands/manifest/cmd-manifest-kotlin.mts @@ -1,9 +1,9 @@ import path from 'node:path' -import { convertGradleToFacts } from './convert-gradle-to-facts.mts' import { convertGradleToMaven } from './convert_gradle_to_maven.mts' import { excludePathsFlag } from './manifest-flags.mts' import { parseBuildToolOpts } from './parse-build-tool-opts.mts' +import { runManifestFacts } from './run-manifest-facts.mts' import { resolveBuildToolBin } from './scripts/build-tool.mts' import constants, { REQUIREMENTS_TXT, SOCKET_JSON } from '../../constants.mts' import { commonFlags } from '../../flags.mts' @@ -299,12 +299,13 @@ async function run( assertValidExcludePaths(excludePaths) if (facts) { - await convertGradleToFacts({ + await runManifestFacts({ bin: String(bin), + buildOpts: parsedGradleOpts, cwd, + ecosystem: 'gradle', excludeConfigs: String(excludeConfigs || ''), excludePaths, - gradleOpts: parsedGradleOpts, ignoreUnresolved: Boolean(ignoreUnresolved), includeConfigs: String(includeConfigs || ''), javaHome, diff --git a/src/commands/manifest/cmd-manifest-maven.mts b/src/commands/manifest/cmd-manifest-maven.mts index 0b1b8c4bf4..7d5e32eaea 100644 --- a/src/commands/manifest/cmd-manifest-maven.mts +++ b/src/commands/manifest/cmd-manifest-maven.mts @@ -1,8 +1,8 @@ import path from 'node:path' -import { convertMavenToFacts } from './convert-maven-to-facts.mts' import { excludePathsFlag } from './manifest-flags.mts' import { parseBuildToolOpts } from './parse-build-tool-opts.mts' +import { runManifestFacts } from './run-manifest-facts.mts' import { resolveBuildToolBin } from './scripts/build-tool.mts' import constants, { SOCKET_JSON } from '../../constants.mts' import { commonFlags } from '../../flags.mts' @@ -233,15 +233,16 @@ async function run( const excludePaths = cmdFlagValueToArray(cli.flags['excludePaths']) assertValidExcludePaths(excludePaths) - await convertMavenToFacts({ + await runManifestFacts({ bin: String(bin), + buildOpts: parsedMavenOpts, cwd, + ecosystem: 'maven', excludeConfigs: String(excludeConfigs || ''), excludePaths, ignoreUnresolved: Boolean(ignoreUnresolved), includeConfigs: String(includeConfigs || ''), javaHome, - mavenOpts: parsedMavenOpts, verbose: Boolean(verbose), }) } diff --git a/src/commands/manifest/cmd-manifest-scala.mts b/src/commands/manifest/cmd-manifest-scala.mts index 45d6750817..606c2af69c 100644 --- a/src/commands/manifest/cmd-manifest-scala.mts +++ b/src/commands/manifest/cmd-manifest-scala.mts @@ -1,15 +1,14 @@ import path from 'node:path' -import { convertSbtToFacts } from './convert-sbt-to-facts.mts' import { convertSbtToMaven } from './convert_sbt_to_maven.mts' import { excludePathsFlag } from './manifest-flags.mts' import { parseBuildToolOpts } from './parse-build-tool-opts.mts' +import { runManifestFacts } from './run-manifest-facts.mts' import constants, { REQUIREMENTS_TXT, SOCKET_JSON } from '../../constants.mts' import { commonFlags } from '../../flags.mts' import { checkCommandInput } from '../../utils/check-input.mts' import { cmdFlagValueToArray } from '../../utils/cmd.mts' import { debugFn } from '../../utils/debug.mts' -import { withTmpDir } from '../../utils/fs.mts' import { getOutputKind } from '../../utils/get-output-kind.mts' import { logger } from '../../utils/logger.mts' import { meowOrExit } from '../../utils/meow-with-subcommands.mts' @@ -351,20 +350,18 @@ async function run( assertValidExcludePaths(excludePaths) if (facts) { - await withTmpDir('socket-manifest-scala-', tmpDir => - convertSbtToFacts({ - bin: String(bin), - cwd, - excludeConfigs: String(excludeConfigs || ''), - excludePaths, - ignoreUnresolved: Boolean(ignoreUnresolved), - includeConfigs: String(includeConfigs || ''), - javaHome, - sbtOpts: parsedSbtOpts, - tmpDir, - verbose: Boolean(verbose), - }), - ) + await runManifestFacts({ + bin: String(bin), + buildOpts: parsedSbtOpts, + cwd, + ecosystem: 'sbt', + excludeConfigs: String(excludeConfigs || ''), + excludePaths, + ignoreUnresolved: Boolean(ignoreUnresolved), + includeConfigs: String(includeConfigs || ''), + javaHome, + verbose: Boolean(verbose), + }) return } diff --git a/src/commands/manifest/convert-dotnet-to-facts.mts b/src/commands/manifest/convert-dotnet-to-facts.mts index 42a9fdeea8..654bd8e971 100644 --- a/src/commands/manifest/convert-dotnet-to-facts.mts +++ b/src/commands/manifest/convert-dotnet-to-facts.mts @@ -7,30 +7,30 @@ import { buildUncoveredRoot } from './generate-recursive-manifests.mts' import { logger } from '../../utils/logger.mts' import type { EcosystemBuildConfig } from './generate-recursive-manifests.mts' -import type { RunManifestFactsOutcome } from './run-manifest-facts.mts' -import type { BuildOptionHints } from './scripts/resolution-report-render.mts' -import type { SidecarAccumulator } from './scripts/sidecar.mts' +import type { + BuildOptionHints, + RunManifestFactsOutcome, + SocketFactsContext, +} from './run-manifest-facts.mts' // Generates `.socket.facts.json` for the given solution or project // file, or for every solution and project at the top of `cwd`. A project a // solution there already covers is not built again. export async function convertDotnetToFacts({ config, + context, cwd, entryFile, excludePaths, hints, - sidecarAcc, - withFiles, }: { config: EcosystemBuildConfig + context?: SocketFactsContext | undefined cwd: string // Builds only this file (relative to cwd) when set. entryFile?: string | undefined excludePaths?: string[] | undefined hints?: BuildOptionHints | undefined - sidecarAcc?: SidecarAccumulator | undefined - withFiles?: boolean | undefined }): Promise { const entries = entryFile ? [entryFile] : findDotnetEntries(cwd) if (!entries.length) { @@ -47,14 +47,13 @@ export async function convertDotnetToFacts({ // eslint-disable-next-line no-await-in-loop const outcome = await buildUncoveredRoot({ config, + context, covered, cwd, ecosystem: 'dotnet', excludePaths, hints, root: { dir, entryFile: entry }, - sidecarAcc, - withFiles, }) if (outcome === 'covered') { if (config.verbose) { diff --git a/src/commands/manifest/convert-gradle-to-facts.mts b/src/commands/manifest/convert-gradle-to-facts.mts deleted file mode 100644 index 3ed9a63292..0000000000 --- a/src/commands/manifest/convert-gradle-to-facts.mts +++ /dev/null @@ -1,51 +0,0 @@ -import { runManifestFacts } from './run-manifest-facts.mts' - -import type { RunManifestFactsOutcome } from './run-manifest-facts.mts' -import type { BuildOptionHints } from './scripts/resolution-report-render.mts' -import type { SidecarAccumulator } from './scripts/sidecar.mts' - -// Generates `gradle.socket.facts.json` for a Gradle project via the bundled -// init script. -export async function convertGradleToFacts({ - bin, - cwd, - excludeConfigs, - excludePaths, - gradleOpts, - hints, - ignoreUnresolved, - includeConfigs, - javaHome, - sidecarAcc, - verbose, - withFiles, -}: { - bin: string - cwd: string - excludeConfigs: string - excludePaths?: string[] | undefined - gradleOpts: string[] - hints?: BuildOptionHints | undefined - ignoreUnresolved: boolean - includeConfigs: string - javaHome?: string | undefined - sidecarAcc?: SidecarAccumulator | undefined - verbose: boolean - withFiles?: boolean | undefined -}): Promise { - return await runManifestFacts({ - bin, - buildOpts: gradleOpts, - cwd, - ecosystem: 'gradle', - excludeConfigs, - excludePaths, - hints, - ignoreUnresolved, - includeConfigs, - javaHome, - sidecarAcc, - verbose, - withFiles, - }) -} diff --git a/src/commands/manifest/convert-maven-to-facts.mts b/src/commands/manifest/convert-maven-to-facts.mts deleted file mode 100644 index ad436e6bc4..0000000000 --- a/src/commands/manifest/convert-maven-to-facts.mts +++ /dev/null @@ -1,51 +0,0 @@ -import { runManifestFacts } from './run-manifest-facts.mts' - -import type { RunManifestFactsOutcome } from './run-manifest-facts.mts' -import type { BuildOptionHints } from './scripts/resolution-report-render.mts' -import type { SidecarAccumulator } from './scripts/sidecar.mts' - -// Generates `pom.xml.socket.facts.json` (named after the POM Maven runs on) -// for a Maven project via the bundled extension. -export async function convertMavenToFacts({ - bin, - cwd, - excludeConfigs, - excludePaths, - hints, - ignoreUnresolved, - includeConfigs, - javaHome, - mavenOpts, - sidecarAcc, - verbose, - withFiles, -}: { - bin: string - cwd: string - excludeConfigs: string - excludePaths?: string[] | undefined - hints?: BuildOptionHints | undefined - ignoreUnresolved: boolean - includeConfigs: string - javaHome?: string | undefined - mavenOpts: string[] - sidecarAcc?: SidecarAccumulator | undefined - verbose: boolean - withFiles?: boolean | undefined -}): Promise { - return await runManifestFacts({ - bin, - buildOpts: mavenOpts, - cwd, - ecosystem: 'maven', - excludeConfigs, - excludePaths, - hints, - ignoreUnresolved, - includeConfigs, - javaHome, - sidecarAcc, - verbose, - withFiles, - }) -} diff --git a/src/commands/manifest/convert-sbt-to-facts.mts b/src/commands/manifest/convert-sbt-to-facts.mts deleted file mode 100644 index b1a1d35e25..0000000000 --- a/src/commands/manifest/convert-sbt-to-facts.mts +++ /dev/null @@ -1,56 +0,0 @@ -import { runManifestFacts } from './run-manifest-facts.mts' - -import type { RunManifestFactsOutcome } from './run-manifest-facts.mts' -import type { BuildOptionHints } from './scripts/resolution-report-render.mts' -import type { SidecarAccumulator } from './scripts/sidecar.mts' - -// Generates `sbt.socket.facts.json` for an sbt project via the bundled sbt plugin. -// sbt 0.13/early 1.x can't run on modern JDKs — pass a compatible JDK via -// `--sbt-opts "--java-home "` or `JAVA_HOME`. -export async function convertSbtToFacts({ - bin, - cwd, - excludeConfigs, - excludePaths, - hints, - ignoreUnresolved, - includeConfigs, - javaHome, - sbtOpts, - sidecarAcc, - tmpDir, - verbose, - withFiles, -}: { - bin: string - cwd: string - excludeConfigs: string - excludePaths?: string[] | undefined - hints?: BuildOptionHints | undefined - ignoreUnresolved: boolean - includeConfigs: string - javaHome?: string | undefined - sbtOpts: string[] - sidecarAcc?: SidecarAccumulator | undefined - // Caller-owned; see ManifestScriptOptions.tmpDir. - tmpDir: string - verbose: boolean - withFiles?: boolean | undefined -}): Promise { - return await runManifestFacts({ - bin, - buildOpts: sbtOpts, - cwd, - ecosystem: 'sbt', - excludeConfigs, - excludePaths, - hints, - ignoreUnresolved, - includeConfigs, - javaHome, - sidecarAcc, - tmpDir, - verbose, - withFiles, - }) -} diff --git a/src/commands/manifest/discover-manifest-roots.mts b/src/commands/manifest/discover-manifest-roots.mts index 82d517c084..6417252d65 100644 --- a/src/commands/manifest/discover-manifest-roots.mts +++ b/src/commands/manifest/discover-manifest-roots.mts @@ -3,23 +3,27 @@ import path from 'node:path' import micromatch from 'micromatch' +import { listDotnetSolutionMembers } from './run-manifest-facts.mts' import { BUILD_FILES, BUILD_TOOLS, FACTS_PURL_TYPES, + buildRootPath, buildToolsFor, isDotnetSolution, } from './scripts/build-tool.mts' -import { listDotnetEntryProjects } from './scripts/run.mts' import { realpathOrResolved } from '../../utils/fs.mts' import { getOrInsert } from '../../utils/get-or-insert.mts' import { globWithGitIgnore } from '../../utils/glob.mts' import { logger } from '../../utils/logger.mts' import { excludePathToScanIgnores } from '../scan/exclude-paths.mts' +import type { + SocketFactsContext, + SocketFactsProject, + SocketFactsRequestOptions, +} from './run-manifest-facts.mts' import type { BuildTool } from './scripts/build-tool.mts' -import type { SocketFactsSbomProject } from './scripts/facts.mts' -import type { ManifestScriptOptions } from './scripts/run.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' import type { SocketJson } from '../../utils/socket-json.mts' import type { SocketYml } from '@socketsecurity/config' @@ -54,10 +58,6 @@ function containsPath(paths: ReadonlySet, value: string): boolean { // builds by file, where one directory can hold several builds. export type BuildRoot = { dir: string; entryFile?: string | undefined } -export function buildRootPath(root: BuildRoot): string { - return path.join(root.dir, root.entryFile ?? '') -} - export function isBuildFile(tool: BuildTool, basename: string): boolean { return !!BUILD_FILE_MATCHERS.get(tool)?.(basename) } @@ -102,7 +102,7 @@ export function withoutDisabledFlags(sockJson: SocketJson): SocketJson { } as SocketJson } -export { realpathOrResolved } +export { buildRootPath, realpathOrResolved } // Coverage compares files by their realpath-resolved directory. async function realFilePath(file: string): Promise { @@ -144,26 +144,19 @@ export function isPathInside(dir: string, file: string): boolean { return file === dir || file.startsWith(`${dir}${path.sep}`) } -// Paths are relative to `buildRoot`. Only what lies inside `scanRoot` (when -// given) counts, as only that can be a candidate. +// Only what lies inside `scanRoot` (when given) counts, as only that can be a +// candidate. export async function membershipOf( - buildRoot: string, - projects: readonly SocketFactsSbomProject[], + projects: readonly SocketFactsProject[], scanRoot?: string | undefined, ): Promise { const realScanRoot = scanRoot ? await realpathOrResolved(scanRoot) : undefined const inScan = (p: string) => !realScanRoot || isPathInside(realScanRoot, p) const membership = emptyMembership() const [dirs, files] = await Promise.all([ + Promise.all(projects.map(({ dir }) => realpathOrResolved(dir))), Promise.all( - projects.map(({ subprojectDir }) => - realpathOrResolved(path.resolve(buildRoot, subprojectDir)), - ), - ), - Promise.all( - projects - .flatMap(project => project.manifestFiles ?? []) - .map(({ file }) => realFilePath(path.resolve(buildRoot, file))), + projects.flatMap(({ buildFiles }) => buildFiles).map(realFilePath), ), ]) for (const dir of dirs) { @@ -211,17 +204,19 @@ export function isBuildRootCovered( ) } +export type RootBuildOptions = Pick< + SocketFactsRequestOptions, + 'bin' | 'buildOpts' | 'excludeBase' | 'excludePaths' +> & { context?: SocketFactsContext | undefined } + // A dotnet solution is covered once every project it builds is, or, when the // SDK cannot read it, by a same-named solution in the other format beside it // (`dotnet sln migrate` writes App.slnx next to App.sln) that it can read. async function isSolutionCovered( covered: Membership, root: BuildRoot, - opts: Pick< - ManifestScriptOptions, - 'bin' | 'excludeBase' | 'excludePaths' | 'toolOpts' - >, - listMembers: typeof listDotnetEntryProjects = listDotnetEntryProjects, + opts: RootBuildOptions, + listMembers: typeof listDotnetSolutionMembers = listDotnetSolutionMembers, ): Promise { const { entryFile } = root if (!entryFile || !isDotnetSolution(entryFile)) { @@ -235,7 +230,7 @@ async function isSolutionCovered( return false } const list = (file: string) => - listMembers({ ...opts, entryFile: file, projectDir: root.dir }) + listMembers({ ...opts, cwd: root.dir, entryFile: file }) const listed = await list(entryFile) if (!listed) { // Unless the twin is readable, this one is built and its failure shows. @@ -272,11 +267,8 @@ export async function isRootCovered( covered: Membership, tool: BuildTool, root: BuildRoot, - opts: Pick< - ManifestScriptOptions, - 'bin' | 'excludeBase' | 'excludePaths' | 'toolOpts' - >, - listMembers: typeof listDotnetEntryProjects = listDotnetEntryProjects, + opts: RootBuildOptions, + listMembers: typeof listDotnetSolutionMembers = listDotnetSolutionMembers, ): Promise { return ( isBuildRootCovered(covered, tool, root) || @@ -291,7 +283,7 @@ export async function isBuildCovered( covered: Membership, tool: BuildTool, root: BuildRoot, - opts: Parameters[3], + opts: RootBuildOptions, own?: Membership | undefined, ): Promise { if (!hasRootMarker(tool, root)) { diff --git a/src/commands/manifest/discover-manifest-roots.test.mts b/src/commands/manifest/discover-manifest-roots.test.mts index 1c8b7c4115..5c5dbcbdae 100644 --- a/src/commands/manifest/discover-manifest-roots.test.mts +++ b/src/commands/manifest/discover-manifest-roots.test.mts @@ -311,17 +311,6 @@ describe('isBuildRootCovered', () => { ) }) -function mavenProject(subprojectDir: string, file: string) { - return { - type: 'maven' as const, - name: subprojectDir, - id: subprojectDir, - subprojectDir, - manifestFiles: [{ file }], - children: [], - } -} - describe('membershipOf', () => { let scanRoot = '' @@ -341,14 +330,17 @@ describe('membershipOf', () => { await fs.rm(scanRoot, { recursive: true, force: true }) }) - it('takes project dirs and existing build files anywhere in the scan root, relative to the build root', async () => { + it('takes project dirs and existing build files in the scan root', async () => { + const at = (rel: string) => path.resolve(scanRoot, rel) const membership = await membershipOf( - path.join(scanRoot, 'build'), [ - mavenProject('member', 'member/pom.xml'), - mavenProject('../sibling', '../sibling/pom.xml'), - mavenProject('absent', 'absent/build.gradle'), - mavenProject('../../outside', '../../outside/pom.xml'), + { buildFiles: [at('build/member/pom.xml')], dir: at('build/member') }, + { buildFiles: [at('sibling/pom.xml')], dir: at('sibling') }, + { + buildFiles: [at('build/absent/build.gradle')], + dir: at('build/absent'), + }, + { buildFiles: [at('../outside/pom.xml')], dir: at('../outside') }, ], scanRoot, ) diff --git a/src/commands/manifest/enumerate-workspaces.mts b/src/commands/manifest/enumerate-workspaces.mts deleted file mode 100644 index ec261744f1..0000000000 --- a/src/commands/manifest/enumerate-workspaces.mts +++ /dev/null @@ -1,101 +0,0 @@ -import { - expandEnvVarRefs, - formatMissingEnvVarRefs, -} from './expand-env-var-refs.mts' -import { tailBuildOutput } from './run-manifest-facts.mts' -import { enumerateWorkspaces as enumerateWorkspacesScript } from './scripts/run.mts' -import { getErrorMessageOr } from '../../utils/errors.mts' -import { logger } from '../../utils/logger.mts' - -import type { BuildTool } from './scripts/build-tool.mts' -import type { SocketFactsSbomProject } from './scripts/facts.mts' - -export type EnumerateWorkspacesResult = { - buildRoot: string - projects: SocketFactsSbomProject[] -} - -// Cheap subproject discovery (no dependency resolution), for builds that are -// not resolved: the setup wizard's, and skipped ones. Callers decide whether -// a failure fails the command. -export async function enumerateWorkspaces({ - bin, - buildOpts, - cwd, - ecosystem, - entryFile, - excludeBase, - excludePaths, - javaHome, - verbose, -}: { - bin: string - buildOpts: string[] - cwd: string - ecosystem: BuildTool - // See ManifestScriptOptions.entryFile. - entryFile?: string | undefined - // See ManifestScriptOptions.excludeBase. - excludeBase?: string | undefined - excludePaths?: string[] | undefined - javaHome?: string | undefined - verbose: boolean -}): Promise { - let resolvedJavaHome: string | undefined - if (javaHome) { - const expanded = expandEnvVarRefs(javaHome) - if (expanded.missing) { - logger.fail( - `javaHome (\`${javaHome}\`) ${formatMissingEnvVarRefs(expanded.missing)}.`, - ) - return - } - resolvedJavaHome = expanded.value - } - - const scriptOpts = { - bin: bin || undefined, - entryFile, - excludeBase, - excludePaths: excludePaths?.length ? excludePaths : undefined, - // `env` replaces the spawned process's whole environment, not just JAVA_HOME. - env: resolvedJavaHome - ? { ...process.env, JAVA_HOME: resolvedJavaHome } - : undefined, - projectDir: cwd, - stdio: verbose ? ('inherit' as const) : ('pipe' as const), - toolOpts: buildOpts, - } - - let result - try { - result = await enumerateWorkspacesScript(ecosystem, scriptOpts) - } catch (e) { - logger.fail( - `Could not run the ${ecosystem} build tool: ${getErrorMessageOr(e, String(e))}`, - ) - return - } - - if (!result.projects.length) { - logger.fail( - `The ${ecosystem} build produced no workspace records (exit code ${result.code}); every build reports at least its own root project, so the enumeration task did not run.`, - ) - const tail = verbose ? '' : tailBuildOutput(result.stdout, result.stderr) - if (tail) { - logger.group('Build output:') - logger.error(tail) - logger.groupEnd() - } - return - } - - if (!result.buildRoot) { - logger.fail( - `The ${ecosystem} build did not report its build root, so its projects' paths cannot be located.`, - ) - return - } - - return { buildRoot: result.buildRoot, projects: result.projects } -} diff --git a/src/commands/manifest/enumerate-workspaces.test.mts b/src/commands/manifest/enumerate-workspaces.test.mts deleted file mode 100644 index 28209f538f..0000000000 --- a/src/commands/manifest/enumerate-workspaces.test.mts +++ /dev/null @@ -1,122 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('./scripts/run.mts', () => ({ - enumerateWorkspaces: vi.fn(), -})) - -import { enumerateWorkspaces } from './enumerate-workspaces.mts' -import { enumerateWorkspaces as enumerateWorkspacesScript } from './scripts/run.mts' - -import type { WorkspaceEnumerationResult } from './scripts/run.mts' - -const ENV_VAR = 'SOCKET_TEST_ENUMERATE_JAVA_HOME' - -function okResult(): WorkspaceEnumerationResult { - return { - buildRoot: '/tmp/some-project', - code: 0, - projects: [ - { - type: 'maven', - name: 'root', - subprojectDir: '.', - children: [], - }, - ], - stderr: '', - stdout: '', - } -} - -const baseArgs = { - bin: 'gradle', - buildOpts: [], - cwd: '/tmp/some-project', - ecosystem: 'gradle' as const, - verbose: false, -} - -describe('enumerateWorkspaces', () => { - beforeEach(() => { - vi.mocked(enumerateWorkspacesScript).mockReset() - delete process.env[ENV_VAR] - process.exitCode = undefined - }) - - it('returns the build root and projects from a successful run', async () => { - vi.mocked(enumerateWorkspacesScript).mockResolvedValue(okResult()) - const result = await enumerateWorkspaces(baseArgs) - expect(result?.buildRoot).toBe(okResult().buildRoot) - expect(result?.projects).toEqual(okResult().projects) - }) - - it('passes a literal javaHome straight through as JAVA_HOME', async () => { - vi.mocked(enumerateWorkspacesScript).mockResolvedValue(okResult()) - await enumerateWorkspaces({ ...baseArgs, javaHome: '/opt/jdk-17' }) - const opts = vi.mocked(enumerateWorkspacesScript).mock.calls[0]?.[1] - expect(opts?.env?.['JAVA_HOME']).toBe('/opt/jdk-17') - }) - - it('expands $VAR and ${VAR} references against the CLI process env', async () => { - process.env[ENV_VAR] = '/opt/jdk-11' - vi.mocked(enumerateWorkspacesScript).mockResolvedValue(okResult()) - await enumerateWorkspaces({ ...baseArgs, javaHome: `\${${ENV_VAR}}` }) - const opts = vi.mocked(enumerateWorkspacesScript).mock.calls[0]?.[1] - expect(opts?.env?.['JAVA_HOME']).toBe('/opt/jdk-11') - delete process.env[ENV_VAR] - }) - - it('fails closed without invoking the build tool when the referenced var is unset', async () => { - vi.mocked(enumerateWorkspacesScript).mockResolvedValue(okResult()) - const result = await enumerateWorkspaces({ - ...baseArgs, - javaHome: `$${ENV_VAR}`, - }) - expect(result).toBeUndefined() - expect(enumerateWorkspacesScript).not.toHaveBeenCalled() - expect(process.exitCode).toBeUndefined() - }) - - it('leaves the environment untouched when javaHome is unset', async () => { - vi.mocked(enumerateWorkspacesScript).mockResolvedValue(okResult()) - await enumerateWorkspaces(baseArgs) - const opts = vi.mocked(enumerateWorkspacesScript).mock.calls[0]?.[1] - expect(opts?.env).toBeUndefined() - }) - - it('fails when the build crashed before producing any workspace records', async () => { - vi.mocked(enumerateWorkspacesScript).mockResolvedValue({ - buildRoot: undefined, - code: 1, - projects: [], - stderr: '', - stdout: '', - }) - const result = await enumerateWorkspaces(baseArgs) - expect(result).toBeUndefined() - expect(process.exitCode).toBeUndefined() - }) - - it('fails even on a clean exit if no workspace records were produced - every real run reports at least its own root project', async () => { - vi.mocked(enumerateWorkspacesScript).mockResolvedValue({ - buildRoot: undefined, - code: 0, - projects: [], - stderr: '', - stdout: '', - }) - const result = await enumerateWorkspaces(baseArgs) - expect(result).toBeUndefined() - expect(process.exitCode).toBeUndefined() - }) - - it('fails when the build did not report its build root', async () => { - vi.mocked(enumerateWorkspacesScript).mockResolvedValue({ - ...okResult(), - buildRoot: undefined, - }) - const result = await enumerateWorkspaces(baseArgs) - expect(result).toBeUndefined() - expect(process.exitCode).toBeUndefined() - }) -}) diff --git a/src/commands/manifest/expand-env-var-refs.mts b/src/commands/manifest/expand-env-var-refs.mts deleted file mode 100644 index c72ef53b3d..0000000000 --- a/src/commands/manifest/expand-env-var-refs.mts +++ /dev/null @@ -1,33 +0,0 @@ -const ENV_VAR_REF = /\$\$|\$\{(\w+)\}|\$(\w+)/g - -// Expands `$VAR`/`${VAR}` references (e.g. a team-shared `javaHome: -// "$JAVA11_HOME"`) against the CLI process's own environment, so a socket.json -// value works across machines instead of hardcoding one developer's path. -// `$$` is a literal `$`, for a value that must contain a literal `$WORD`. -export function expandEnvVarRefs(value: string): { - missing?: string[] - value: string -} { - const missing: string[] = [] - const expanded = value.replace(ENV_VAR_REF, (match, braced, bare) => { - if (match === '$$') { - return '$' - } - const name = braced ?? bare - const resolved = process.env[name] - if (resolved === undefined) { - if (!missing.includes(name)) { - missing.push(name) - } - return '' - } - return resolved - }) - return missing.length ? { missing, value: expanded } : { value: expanded } -} - -export function formatMissingEnvVarRefs(missing: readonly string[]): string { - const names = missing.map(name => `\`${name}\``).join(', ') - const verb = missing.length > 1 ? 'are' : 'is' - return `references ${names}, which ${verb} not set in this environment` -} diff --git a/src/commands/manifest/expand-env-var-refs.test.mts b/src/commands/manifest/expand-env-var-refs.test.mts deleted file mode 100644 index f2db002784..0000000000 --- a/src/commands/manifest/expand-env-var-refs.test.mts +++ /dev/null @@ -1,67 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest' - -import { - expandEnvVarRefs, - formatMissingEnvVarRefs, -} from './expand-env-var-refs.mts' - -const VAR_A = 'SOCKET_TEST_EXPAND_ENV_VAR_A' -const VAR_B = 'SOCKET_TEST_EXPAND_ENV_VAR_B' - -describe('expandEnvVarRefs', () => { - beforeEach(() => { - delete process.env[VAR_A] - delete process.env[VAR_B] - }) - afterEach(() => { - delete process.env[VAR_A] - delete process.env[VAR_B] - }) - - it('expands a bare $VAR reference', () => { - process.env[VAR_A] = '/opt/jdk-17' - expect(expandEnvVarRefs(`$${VAR_A}`)).toEqual({ value: '/opt/jdk-17' }) - }) - - it('expands a braced ${VAR} reference', () => { - process.env[VAR_A] = '/opt/jdk-17' - expect(expandEnvVarRefs(`\${${VAR_A}}`)).toEqual({ value: '/opt/jdk-17' }) - }) - - it('reports every distinct missing variable, not just the first', () => { - const result = expandEnvVarRefs(`$${VAR_A}/$${VAR_B}`) - expect(result.missing).toEqual([VAR_A, VAR_B]) - expect(result.value).toBe('/') - }) - - it('reports a missing variable only once even if referenced twice', () => { - const result = expandEnvVarRefs(`$${VAR_A}:$${VAR_A}`) - expect(result.missing).toEqual([VAR_A]) - }) - - it('treats $$ as an escaped literal $, leaving the following text untouched', () => { - expect(expandEnvVarRefs('$$HOME')).toEqual({ value: '$HOME' }) - }) - - it('treats $$ as an escaped literal $ ahead of a braced-looking reference', () => { - expect(expandEnvVarRefs('$${HOME}')).toEqual({ value: '${HOME}' }) - }) - - it('does not report a missing variable for an escaped $$ reference', () => { - expect(expandEnvVarRefs(`$$${VAR_A}`).missing).toBeUndefined() - }) -}) - -describe('formatMissingEnvVarRefs', () => { - it('uses singular wording for one missing variable', () => { - expect(formatMissingEnvVarRefs(['FOO'])).toBe( - 'references `FOO`, which is not set in this environment', - ) - }) - - it('uses plural wording for multiple missing variables', () => { - expect(formatMissingEnvVarRefs(['FOO', 'BAR'])).toBe( - 'references `FOO`, `BAR`, which are not set in this environment', - ) - }) -}) diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index e4979ec547..676df8e699 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -1,5 +1,3 @@ -import { existsSync, promises as fs } from 'node:fs' -import { tmpdir } from 'node:os' import path from 'node:path' import { @@ -26,16 +24,14 @@ import { } from './discover-manifest-roots.mts' import { loadBuild, withModules } from './load-build.mts' import { parseBuildToolOpts } from './parse-build-tool-opts.mts' -import { runManifestFacts } from './run-manifest-facts.mts' -import { - BUILD_FILES, - resolveBuildToolBin, - socketFactsFileName, -} from './scripts/build-tool.mts' import { DSI_SETUP_COMMAND, + EXCLUDE_PATHS_FLAG, REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG, -} from './scripts/resolution-report-render.mts' + keepFacts, + runManifestFacts, +} from './run-manifest-facts.mts' +import { BUILD_FILES, resolveBuildToolBin } from './scripts/build-tool.mts' import { loadSocketConfig } from '../../utils/config.mts' import { withTmpDir } from '../../utils/fs.mts' import { getOrInsert } from '../../utils/get-or-insert.mts' @@ -43,18 +39,22 @@ import { logger } from '../../utils/logger.mts' import { readOrDefaultSocketJson } from '../../utils/socket-json.mts' import type { ResolvedBuildRootSettings } from './build-root-config.mts' -import type { BuildRoot, Membership } from './discover-manifest-roots.mts' +import type { + BuildRoot, + Membership, + RootBuildOptions, +} from './discover-manifest-roots.mts' import type { LoadedBuild } from './load-build.mts' import type { + BuildOption, + BuildOptionHints, RunManifestFactsOutcome, RunManifestFactsResult, + SocketFactsContext, + SocketFactsRunOptions, + SocketFactsWorkDir, } from './run-manifest-facts.mts' import type { BuildTool } from './scripts/build-tool.mts' -import type { - BuildOption, - BuildOptionHints, -} from './scripts/resolution-report-render.mts' -import type { SidecarAccumulator } from './scripts/sidecar.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' import type { SocketJson } from '../../utils/socket-json.mts' @@ -86,6 +86,8 @@ export type EcosystemBuildConfig = { ignoreUnresolved: boolean includeConfigs: string javaHome: string | undefined + // Maven's `--file` in mavenOpts, which buildOpts leaves out. + mavenFile: string | undefined // Set when this build root should be skipped entirely (never invoked). skipReason: string | undefined verbose: boolean @@ -121,29 +123,33 @@ const MAVEN_OTHER_F_OPTS = new Set([ 'fn', ]) -// Each POM is built by its own `--file`, so a user one is dropped. -function withoutMavenFileOpts(dir: string, opts: string[]): string[] { +// Maven 3.9 builds the first of several `--file`s. +function splitMavenFileOpts(opts: string[]): { + file: string | undefined + opts: string[] +} { + const files: string[] = [] const kept: string[] = [] for (let i = 0, { length } = opts; i < length; i += 1) { const opt = opts[i]! const name = opt.replace(/^--?/, '') + const { 0: key, 1: value } = name.split(/=(.*)/s) if (opt === name || MAVEN_OTHER_F_OPTS.has(name)) { kept.push(opt) } else if (MAVEN_FILE_OPTS.has(name)) { i += 1 - } else if ( - !MAVEN_FILE_OPTS.has(name.split('=')[0]!) && - !(opt.startsWith('-f') && !opt.startsWith('--')) - ) { + if (i < length) { + files.push(opts[i]!) + } + } else if (MAVEN_FILE_OPTS.has(key!) && value !== undefined) { + files.push(value) + } else if (opt.startsWith('-f') && !opt.startsWith('--')) { + files.push(opt.slice(2).replace(/^=/, '')) + } else { kept.push(opt) } } - if (kept.length !== opts.length) { - logger.warn( - `Ignoring --file in mavenOpts for ${dir}: each POM there is built by its own file.`, - ) - } - return kept + return { file: files[0], opts: kept } } type Candidate = { @@ -154,20 +160,8 @@ type Candidate = { root: BuildRoot } -type SidecarEntry = NonNullable> - -// A copy of a facts file, if there was one, and its sidecar entry. -type FactsState = { - facts: string | undefined - sidecar: SidecarEntry | undefined -} - type Run = Candidate & { - // The facts file's real path. - factsKey: string | undefined membership: Membership - // What the run wrote, written back once the walk keeps it. - output: FactsState | undefined // Undefined when the build had nothing to resolve. result: RunManifestFactsResult | undefined } @@ -176,12 +170,10 @@ type Run = Candidate & { type Load = Candidate & LoadedBuild type WalkContext = { - backupDir: () => Promise + // Every run writes into the work dir, so a dropped run leaves the facts + // file at its target as it was. + context: SocketFactsContext & { workDir: SocketFactsWorkDir } excludePaths: string[] | undefined - // What each facts file held before the walk, by real path; undefined when a - // run wrote it away from its own directory (Gradle's `-p`) before it was - // saved. - originals: Map ignoreUnresolved: boolean | undefined optionFlags: ReadonlySet realCwd: string @@ -189,10 +181,7 @@ type WalkContext = { tool: BuildTool, root: BuildRoot, ) => ResolvedBuildRootSettings - sbtTmpDir: string | undefined - sidecarAcc: SidecarAccumulator | undefined verbose: boolean - withFiles: boolean | undefined } type Loader = { path: string; skipped: boolean } @@ -208,17 +197,53 @@ function statusOf(loader: Loader | undefined): RecursiveManifestOutcomeStatus { return loader?.skipped ? 'skippedDisabled' : 'skippedCovered' } -// The options the build-tool scripts take besides the build itself. +// The options a build's listings take besides the build itself. export function buildToolScriptOptions( config: Pick, excludeBase: string | undefined, excludePaths: string[] | undefined, -) { + context?: SocketFactsContext | undefined, +): RootBuildOptions { + return { + bin: config.bin, + buildOpts: config.buildOpts, + context, + excludeBase, + excludePaths, + } +} + +export function socketFactsRunOptions( + ecosystem: BuildTool, + root: BuildRoot, + config: EcosystemBuildConfig, + { + context, + excludeBase, + excludePaths, + hints, + }: { + context?: SocketFactsContext | undefined + excludeBase: string | undefined + excludePaths: string[] | undefined + hints?: BuildOptionHints | undefined + }, +): SocketFactsRunOptions { return { bin: config.bin, + buildOpts: config.buildOpts, + context, + cwd: root.dir, + ecosystem, + entryFile: root.entryFile, excludeBase, + excludeConfigs: config.excludeConfigs, excludePaths, - toolOpts: config.buildOpts, + hints, + ignoreUnresolved: config.ignoreUnresolved, + includeConfigs: config.includeConfigs, + javaHome: config.javaHome, + verbose: config.verbose, } } @@ -282,7 +307,7 @@ async function walkTool( const { dir } = candidate.root // Builds sharing a directory and its settings resolve them once. return getOrInsert(configs, `${dir}\0${entryKey ?? ''}`, () => - resolveEcosystemConfig(ecosystem, dir, sockJson), + resolveWalkConfig(ecosystem, dir, sockJson), ) } @@ -317,7 +342,12 @@ async function walkTool( }) const scriptOpts = (candidate: Candidate) => - buildToolScriptOptions(configFor(candidate), ctx.realCwd, ctx.excludePaths) + buildToolScriptOptions( + configFor(candidate), + ctx.realCwd, + ctx.excludePaths, + ctx.context, + ) // A solution the SDK cannot read, built through its twin instead. const superseded = new Map>() @@ -484,12 +514,8 @@ async function walkTool( if (skipOf(next) === 'load') { // eslint-disable-next-line no-await-in-loop const loaded = await loadBuild({ - config: configFor(next), - ecosystem, - excludePaths: ctx.excludePaths, - root: next.root, + ...runOptions(ctx, ecosystem, next, configFor(next)), scanRoot: ctx.realCwd, - verbose: ctx.verbose, }) const why = describeDisabledBy(ecosystem, resolvedFor(next).disabledBy!) if (loaded) { @@ -542,7 +568,7 @@ async function walkTool( } const keptSet = new Set(kept) - const keptKeys = new Set(kept.map(run => run.factsKey)) + const keptTargets = new Set(kept.map(run => run.result?.targetPath)) const outcomes: RecursiveManifestOutcome[] = [] for (const candidate of candidates) { const { index, root } = candidate @@ -550,12 +576,12 @@ async function walkTool( if (run && keptSet.has(run)) { if (run.result) { // eslint-disable-next-line no-await-in-loop - await putFacts(ctx, run.result.factsPath, run.factsKey!, run.output) + await keepFacts(ctx.context.workDir, run.result) } outcomes.push({ ...root, ecosystem, - ...(run.result ? { factsPath: run.result.factsPath } : {}), + ...(run.result ? { factsPath: run.result.targetPath } : {}), status: run.result ? 'generated' : 'empty', }) continue @@ -569,8 +595,8 @@ async function walkTool( logger.info( `Dropping the Socket facts of ${buildRootPath(root)}: ${describeLoader(loader)}.`, ) - if (!keptKeys.has(run.factsKey)) { - discardedFactsPath = run.factsKey + if (!keptTargets.has(run.result.targetPath)) { + discardedFactsPath = run.result.targetPath } } status = statusOf(loader) @@ -657,131 +683,60 @@ async function warnUnappliedEntry( ) } +// Shared by listing and generation, so both run the same Coana, org and hints. +function runOptions( + ctx: WalkContext, + ecosystem: BuildTool, + { root }: Candidate, + dirConfig: EcosystemBuildConfig, +): SocketFactsRunOptions { + return { + ...socketFactsRunOptions(ecosystem, root, dirConfig, { + context: ctx.context, + // Relative to the scan root: a build can reach modules outside its own + // directory (Maven `../x` modules, relocated Gradle projects). + excludeBase: ctx.realCwd, + excludePaths: ctx.excludePaths, + hints: { + continueOnInstallErrorsFlag: ctx.context.workDir.withFiles + ? REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG + : undefined, + excludePathsFlag: EXCLUDE_PATHS_FLAG, + flags: ctx.optionFlags, + setupCommand: DSI_SETUP_COMMAND, + socketJson: socketJsonPath(root.dir), + }, + }), + ignoreUnresolved: ctx.ignoreUnresolved ?? dirConfig.ignoreUnresolved, + verbose: ctx.verbose || dirConfig.verbose, + } +} + async function runCandidate( ctx: WalkContext, ecosystem: BuildTool, candidate: Candidate, dirConfig: EcosystemBuildConfig, ): Promise { - const { root } = candidate - const expectedFactsPath = path.join( - root.dir, - socketFactsFileName(ecosystem, root.entryFile) ?? '', - ) - const expectedKey = await realpathOrResolved(expectedFactsPath) - if (!ctx.originals.has(expectedKey)) { - ctx.originals.set( - expectedKey, - await saveFacts( - ctx, - expectedFactsPath, - expectedKey, - `${ecosystem}-${candidate.index}`, - ), - ) - } - const result = await runManifestFacts({ - bin: dirConfig.bin, - buildOpts: dirConfig.buildOpts, - cwd: root.dir, - ecosystem, - entryFile: root.entryFile, - // Relative to the scan root: a build can reach modules outside its own - // directory (Maven `../x` modules, relocated Gradle projects). - excludeBase: ctx.realCwd, - excludeConfigs: dirConfig.excludeConfigs, - excludePaths: ctx.excludePaths, - hints: { - continueOnInstallErrorsFlag: ctx.withFiles - ? REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG - : undefined, - flags: ctx.optionFlags, - setupCommand: DSI_SETUP_COMMAND, - socketJson: socketJsonPath(root.dir), - }, - ignoreUnresolved: ctx.ignoreUnresolved ?? dirConfig.ignoreUnresolved, - includeConfigs: dirConfig.includeConfigs, - javaHome: dirConfig.javaHome, - sidecarAcc: ctx.sidecarAcc, - tmpDir: ecosystem === 'sbt' ? ctx.sbtTmpDir : undefined, - verbose: ctx.verbose || dirConfig.verbose, - withFiles: ctx.withFiles, - }) + const options = runOptions(ctx, ecosystem, candidate, dirConfig) + const result = await runManifestFacts(options) if (result === null) { return undefined } - let factsKey: string | undefined - let output: FactsState | undefined - if (result) { - factsKey = await realpathOrResolved(result.factsPath) - output = await saveFacts( - ctx, - result.factsPath, - factsKey, - `${ecosystem}-${candidate.index}.out`, - ) - if (!ctx.originals.has(factsKey)) { - ctx.originals.set(factsKey, undefined) - } - await putFacts(ctx, result.factsPath, factsKey, ctx.originals.get(factsKey)) - } return { ...candidate, - factsKey, - // Gradle's `-p` can root the build away from `root.dir`. membership: result - ? await membershipOf( - path.dirname(result.factsPath), - result.projects, - ctx.realCwd, - ) + ? await membershipOf(result.projects, ctx.realCwd) : emptyMembership(), - output, - result: result ?? undefined, + result, } } -// Puts `state` in place of a facts file and its sidecar entry; an unknown state -// leaves the file and drops the entry. -async function putFacts( - ctx: WalkContext, - file: string, - key: string, - state: FactsState | undefined, -): Promise { - if (state?.sidecar) { - ctx.sidecarAcc?.set(key, state.sidecar) - } else { - ctx.sidecarAcc?.delete(key) - } - if (!state) { - return - } - if (state.facts) { - await fs.copyFile(state.facts, file) - } else { - await fs.rm(file, { force: true }) - } -} - -async function saveFacts( - ctx: WalkContext, - file: string, - key: string, - name: string, -): Promise { - let facts: string | undefined - if (existsSync(file)) { - facts = path.join(await ctx.backupDir(), name) - await fs.copyFile(file, facts) - } - return { facts, sidecar: ctx.sidecarAcc?.get(key) } -} - // Builds `root` unless earlier builds cover it, then adds what it loaded to -// `covered`. +// `covered` and keeps its facts. export async function buildUncoveredRoot({ config, + context, covered, cwd, ecosystem, @@ -789,11 +744,9 @@ export async function buildUncoveredRoot({ excludePaths, hints, root, - sidecarAcc, - tmpDir, - withFiles, }: { config: EcosystemBuildConfig + context?: SocketFactsContext | undefined covered: Membership // Where the build runs, as the user named it; `root.dir` by default. cwd?: string | undefined @@ -802,60 +755,45 @@ export async function buildUncoveredRoot({ excludePaths?: string[] | undefined hints?: BuildOptionHints | undefined root: BuildRoot - sidecarAcc?: SidecarAccumulator | undefined - tmpDir?: string | undefined - withFiles?: boolean | undefined }): Promise { - const { bin, buildOpts } = config if ( await isRootCovered( covered, ecosystem, root, - buildToolScriptOptions(config, excludeBase, excludePaths), + buildToolScriptOptions(config, excludeBase, excludePaths, context), ) ) { return 'covered' } const result = await runManifestFacts({ - bin, - buildOpts, + ...socketFactsRunOptions(ecosystem, root, config, { + context, + excludeBase, + excludePaths, + hints, + }), cwd: cwd ?? root.dir, - ecosystem, - entryFile: root.entryFile, - excludeBase, - excludeConfigs: config.excludeConfigs, - excludePaths, - hints, - ignoreUnresolved: config.ignoreUnresolved, - includeConfigs: config.includeConfigs, - javaHome: config.javaHome, - sidecarAcc, - tmpDir, - verbose: config.verbose, - withFiles, }) if (result) { - addMembership( - covered, - await membershipOf(path.dirname(result.factsPath), result.projects), - ) + await keepFacts(context?.workDir, result) + addMembership(covered, await membershipOf(result.projects)) } return result } // A failure fails the walk only when no kept or skipped build loads it. export async function generateRecursiveManifests({ + context = {}, cwd, excludePaths, ignoreUnresolved, optionFlags = new Set(), purlTypes, - sbtTmpDir, - sidecarAcc, verbose, - withFiles, }: { + // Without a work dir, the walk writes into one of its own. + context?: SocketFactsContext | undefined cwd: string excludePaths?: string[] | undefined // When set, overrides every build root's own socket.json setting. @@ -864,21 +802,7 @@ export async function generateRecursiveManifests({ // build root's socket.json. optionFlags?: ReadonlySet | undefined purlTypes?: readonly PURL_Type[] | undefined - // Reachability path only: caller-supplied directory to use as sbt's shared - // global base across every sbt root in this run. sbt provisions the Scala - // toolchain under `/boot`, which withFiles' artifactPaths point into, - // so when the caller intends to consume those paths after this call - // returns (e.g. reachability analysis), it must supply a directory that - // outlives this call and delete it once it's done - mirrors - // ManifestScriptOptions.tmpDir one level up. Unset ⇒ an ephemeral shared - // dir is allocated and cleaned up before this call returns, matching - // runManifestFacts' own withFiles-less default. - sbtTmpDir?: string | undefined - // Reachability path only: run build tools with files and fold resolved - // artifact paths into sidecarAcc, keyed by each root's own factsPath. - sidecarAcc?: SidecarAccumulator | undefined verbose: boolean - withFiles?: boolean | undefined }): Promise { const rootSockJson = readOrDefaultSocketJson(cwd) // Candidate dirs come back realpath-resolved (findBuildToolCandidates); cwd @@ -904,25 +828,15 @@ export async function generateRecursiveManifests({ // A failure another build excuses leaves the exit code it set. const exitCodeBefore = process.exitCode - let backupDir: string | undefined - const runAll = async (resolvedSbtTmpDir: string | undefined) => { + const walk = async (workDir: SocketFactsWorkDir) => { const ctx: WalkContext = { - backupDir: async () => { - backupDir ??= await fs.mkdtemp( - path.join(tmpdir(), 'socket-facts-backup-'), - ) - return backupDir - }, + context: { ...context, workDir }, excludePaths, ignoreUnresolved, optionFlags, - originals: new Map(), realCwd, resolveSettings, - sbtTmpDir: resolvedSbtTmpDir, - sidecarAcc, verbose, - withFiles, } const outcomes: RecursiveManifestOutcome[] = [] for (const { 0: ecosystem, 1: roots } of candidatesByTool) { @@ -931,26 +845,11 @@ export async function generateRecursiveManifests({ } return outcomes } - - // A shared global base across every sbt root in this run lets sbt's own - // Scala-toolchain cache under /boot survive between invocations - // instead of being reprovisioned per root (the plugin file is rewritten and - // records.tsv is removed before every invocation, so reuse is safe). A - // caller-supplied sbtTmpDir is reused as-is (the caller owns its lifetime); - // otherwise one is allocated and cleaned up here, but only when there's an - // sbt root to benefit from sharing it at all. - let outcomes: RecursiveManifestOutcome[] - try { - outcomes = sbtTmpDir - ? await runAll(sbtTmpDir) - : candidatesByTool.get('sbt')?.length - ? await withTmpDir('socket-sbt-facts-shared-', runAll) - : await runAll(undefined) - } finally { - if (backupDir) { - await fs.rm(backupDir, { recursive: true, force: true }) - } - } + const outcomes = context.workDir + ? await walk(context.workDir) + : await withTmpDir('socket-facts-work-', dir => + walk({ dir, entries: new Map(), withFiles: false }), + ) if (!outcomes.some(o => o.status === 'failed')) { process.exitCode = exitCodeBefore @@ -980,6 +879,7 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: undefined, + mavenFile: undefined, skipReason: getSkipReason(ecosystem, config?.disabled), verbose: Boolean(config?.verbose), } @@ -994,6 +894,7 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, + mavenFile: undefined, skipReason: getSkipReason(ecosystem, config?.disabled, config?.facts), verbose: Boolean(config?.verbose), } @@ -1008,23 +909,41 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, + mavenFile: undefined, skipReason: getSkipReason(ecosystem, config?.disabled, config?.facts), verbose: Boolean(config?.verbose), } } const config = sockJson.defaults?.manifest?.maven const bin = config?.bin ?? undefined + const { file, opts } = splitMavenFileOpts( + parseBuildToolOpts(config?.mavenOpts ?? undefined), + ) return { bin: bin ?? resolveBuildToolBin('maven', dir), - buildOpts: withoutMavenFileOpts( - dir, - parseBuildToolOpts(config?.mavenOpts ?? undefined), - ), + buildOpts: opts, excludeConfigs: config?.excludeConfigs ?? '', ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, + mavenFile: file, skipReason: getSkipReason(ecosystem, config?.disabled), verbose: Boolean(config?.verbose), } } + +// A walk builds each POM by its own file, so a `--file` in mavenOpts is +// ignored. +export function resolveWalkConfig( + ecosystem: BuildTool, + dir: string, + sockJson: SocketJson, +): EcosystemBuildConfig { + const config = resolveEcosystemConfig(ecosystem, dir, sockJson) + if (config.mavenFile !== undefined) { + logger.warn( + `Ignoring --file in mavenOpts for ${dir}: each POM there is built by its own file.`, + ) + } + return config +} diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index 7c78c3fdb3..6e3f459cbf 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -10,22 +10,20 @@ vi.mock('../../utils/socket-json.mts', async importOriginal => ({ // Default: no nested socket.json anywhere in the fixture tree. readSocketJsonChain: vi.fn(() => []), })) -vi.mock('./run-manifest-facts.mts', () => ({ +vi.mock('./run-manifest-facts.mts', async importOriginal => ({ + ...(await importOriginal()), + listBuildProjects: vi.fn(), + listDotnetSolutionMembers: vi.fn(async () => undefined), runManifestFacts: vi.fn(), })) -vi.mock('./enumerate-workspaces.mts', () => ({ - enumerateWorkspaces: vi.fn(), -})) -vi.mock('./scripts/run.mts', async importOriginal => ({ - ...(await importOriginal()), - listDotnetEntryProjects: vi.fn(async () => undefined), -})) import { buildRootPath } from './discover-manifest-roots.mts' -import { enumerateWorkspaces } from './enumerate-workspaces.mts' import { generateRecursiveManifests } from './generate-recursive-manifests.mts' -import { runManifestFacts } from './run-manifest-facts.mts' -import { listDotnetEntryProjects } from './scripts/run.mts' +import { + listBuildProjects, + listDotnetSolutionMembers, + runManifestFacts, +} from './run-manifest-facts.mts' import { testPath } from '../../../test/utils.mts' import { logger } from '../../utils/logger.mts' import { @@ -33,6 +31,10 @@ import { readSocketJsonChain, } from '../../utils/socket-json.mts' +import type { + RunManifestFactsOutcome, + SocketFactsWorkDir, +} from './run-manifest-facts.mts' import type { SocketJson } from '../../utils/socket-json.mts' function relativePosixPath(from: string, to: string): string { @@ -43,6 +45,81 @@ function messageText(value: unknown): string { return String(value).replaceAll('\\', '/') } +type TestProject = { + manifestFiles?: Array<{ file: string }> | undefined + subprojectDir: string + [field: string]: unknown +} + +// `targetPath` is `factsPath` unless the run wrote into a work dir. +type TestFacts = { + factsPath: string + projects: TestProject[] + sidecarEntry?: { factsFile: string; stateDir: string } | undefined + targetPath?: string | undefined +} + +// What Coana reports of `projects`, as the build tool at `buildRoot` lists +// them. +function listed(buildRoot: string, projects: readonly TestProject[]) { + return projects.map(project => ({ + buildFiles: (project.manifestFiles ?? []).map(({ file }) => + path.resolve(buildRoot, file), + ), + dir: path.resolve(buildRoot, project.subprojectDir), + })) +} + +function reported({ + factsPath, + projects, + sidecarEntry, + targetPath = factsPath, +}: TestFacts) { + return { + factsPath, + projects: listed(path.dirname(targetPath), projects), + sidecarEntry, + targetPath, + } +} + +// Answers like Coana given a work dir: the facts go into a state dir of the +// run's own, keyed by its build root as Coana's are. +async function writeIntoWorkDir( + workDir: SocketFactsWorkDir, + cwd: string, + targetPath: string, + content: string, +): Promise> { + const stateDir = path.join(workDir.dir, Buffer.from(cwd).toString('hex')) + const factsPath = path.join(stateDir, path.basename(targetPath)) + await fs.mkdir(stateDir, { recursive: true }) + await fs.writeFile(factsPath, content) + return { + factsPath, + sidecarEntry: { factsFile: targetPath, stateDir }, + targetPath, + } +} + +function newWorkDir(parent = '/'): SocketFactsWorkDir { + return { dir: path.join(parent, 'work'), entries: new Map(), withFiles: true } +} + +function mockFacts( + impl: ( + options: Parameters[0], + ) => Promise, +): void { + vi.mocked(runManifestFacts).mockImplementation( + async (options): Promise => { + const facts = await impl(options) + return facts ? reported(facts) : facts + }, + ) +} + // The settings each build root's directory resolves to, as one socket.json at // the filesystem root. function mockCascade(cascade: (dir: string) => unknown): void { @@ -95,32 +172,30 @@ describe('generateRecursiveManifests', () => { }) it('invokes the reactor root once and skips its declared members, but still visits an undeclared nested submodule and a differently-tooled nested project', async () => { - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, ecosystem }) => { - if (cwd === reactor && ecosystem === 'maven') { - return { - factsPath: path.join(cwd, '.socket.facts.json'), - projects: [ - { - type: 'maven', - name: 'moduleA', - subprojectDir: 'moduleA', - manifestFiles: [{ file: 'moduleA/pom.xml' }], - children: [], - }, - { - type: 'maven', - name: 'moduleB', - subprojectDir: 'moduleB', - manifestFiles: [{ file: 'moduleB/pom.xml' }], - children: [], - }, - ], - } + mockFacts(async ({ cwd, ecosystem }) => { + if (cwd === reactor && ecosystem === 'maven') { + return { + factsPath: path.join(cwd, '.socket.facts.json'), + projects: [ + { + type: 'maven', + name: 'moduleA', + subprojectDir: 'moduleA', + manifestFiles: [{ file: 'moduleA/pom.xml' }], + children: [], + }, + { + type: 'maven', + name: 'moduleB', + subprojectDir: 'moduleB', + manifestFiles: [{ file: 'moduleB/pom.xml' }], + children: [], + }, + ], } - return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } - }, - ) + } + return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } + }) const outcomes = await generateRecursiveManifests({ cwd: monorepo, @@ -166,7 +241,7 @@ describe('generateRecursiveManifests', () => { const reactorA = path.join(outer, 'reactor-a') const sharedLib = path.join(outer, sharedLibName) const sharedFacts = path.join(sharedLib, 'pom.xml.socket.facts.json') - const sidecarAcc = new Map() + const workDir = newWorkDir(outer) try { await fs.mkdir(reactorA, { recursive: true }) await fs.mkdir(sharedLib, { recursive: true }) @@ -174,12 +249,14 @@ describe('generateRecursiveManifests', () => { await fs.writeFile(path.join(sharedLib, 'pom.xml'), '') await fs.writeFile(sharedFacts, 'committed') - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => { - const factsPath = path.join(cwd, 'pom.xml.socket.facts.json') - await fs.writeFile(factsPath, 'generated') - sidecarAcc.set(factsPath, { components: [], projects: [] }) + mockFacts(async ({ context, cwd }) => { return { - factsPath, + ...(await writeIntoWorkDir( + context!.workDir!, + cwd, + path.join(cwd, 'pom.xml.socket.facts.json'), + 'generated', + )), projects: cwd === reactorA ? [ @@ -197,8 +274,8 @@ describe('generateRecursiveManifests', () => { }) const outcomes = await generateRecursiveManifests({ + context: { workDir }, cwd: outer, - sidecarAcc, verbose: false, }) @@ -211,10 +288,16 @@ describe('generateRecursiveManifests', () => { .mock.calls.some(([opts]) => opts.cwd === sharedLib), ).toBe(builtAlone) expect(await fs.readFile(sharedFacts, 'utf8')).toBe('committed') - expect([...sidecarAcc.keys()]).toEqual([ + expect( + await fs.readFile( + path.join(reactorA, 'pom.xml.socket.facts.json'), + 'utf8', + ), + ).toBe('generated') + expect([...workDir.entries.keys()]).toEqual([ path.join(reactorA, 'pom.xml.socket.facts.json'), ]) - // The restored file is not this scan's, so it is not to be collected. + // The file there is not this scan's, so it is not to be collected. expect( outcomes.find(o => o.dir === sharedLib)?.discardedFactsPath, ).toBe(builtAlone ? sharedFacts : undefined) @@ -236,7 +319,7 @@ describe('generateRecursiveManifests', () => { ) const main = path.join(outer, mainName!) const alias = path.join(outer, aliasName!) - const sidecarAcc = new Map() + const workDir = newWorkDir(outer) try { for (const dir of [main, alias]) { for (const file of ['settings.gradle', 'build.gradle']) { @@ -246,12 +329,14 @@ describe('generateRecursiveManifests', () => { await fs.writeFile(path.join(dir, file), '') } } - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => { - const factsPath = path.join(main, 'gradle.socket.facts.json') - await fs.writeFile(factsPath, cwd) - sidecarAcc.set(factsPath, { components: [], projects: [], cwd }) + mockFacts(async ({ context, cwd }) => { return { - factsPath, + ...(await writeIntoWorkDir( + context!.workDir!, + cwd, + path.join(main, 'gradle.socket.facts.json'), + cwd, + )), projects: [ { type: 'maven' as const, @@ -265,8 +350,8 @@ describe('generateRecursiveManifests', () => { }) const outcomes = await generateRecursiveManifests({ + context: { workDir }, cwd: outer, - sidecarAcc, verbose: false, }) @@ -276,19 +361,28 @@ describe('generateRecursiveManifests', () => { expect(generated[0]!.discardedFactsPath).toBeUndefined() // The kept build's own facts and sidecar entry, whichever ran last. expect(await fs.readFile(factsPath!, 'utf8')).toBe(generated[0]!.dir) - expect(sidecarAcc.get(factsPath!)?.cwd).toBe(generated[0]!.dir) + expect([...workDir.entries.values()]).toEqual([ + { + factsFile: factsPath, + stateDir: path.join( + workDir.dir, + Buffer.from(generated[0]!.dir).toString('hex'), + ), + }, + ]) } finally { await fs.rm(outer, { recursive: true, force: true }) } }, ) - it('removes the facts file of a dropped run when none existed before it', async () => { + it("places only the kept runs' facts, from a work dir of its own that it removes", async () => { const outer = await fs.realpath( await fs.mkdtemp(path.join(tmpdir(), 'dropped-run-')), ) const lib = path.join(outer, 'aaa-lib') const app = path.join(outer, 'app') + let ownWorkDir: SocketFactsWorkDir | undefined try { for (const dir of [lib, app]) { // eslint-disable-next-line no-await-in-loop @@ -296,11 +390,15 @@ describe('generateRecursiveManifests', () => { // eslint-disable-next-line no-await-in-loop await fs.writeFile(path.join(dir, 'pom.xml'), '') } - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => { - const factsPath = path.join(cwd, 'pom.xml.socket.facts.json') - await fs.writeFile(factsPath, 'generated') + mockFacts(async ({ context, cwd }) => { + ownWorkDir = context!.workDir return { - factsPath, + ...(await writeIntoWorkDir( + context!.workDir!, + cwd, + path.join(cwd, 'pom.xml.socket.facts.json'), + 'generated', + )), projects: cwd === app ? [ @@ -323,6 +421,8 @@ describe('generateRecursiveManifests', () => { false, ) expect(existsSync(path.join(app, 'pom.xml.socket.facts.json'))).toBe(true) + expect(ownWorkDir?.withFiles).toBe(false) + expect(existsSync(ownWorkDir!.dir)).toBe(false) } finally { await fs.rm(outer, { recursive: true, force: true }) } @@ -345,42 +445,40 @@ describe('generateRecursiveManifests', () => { await fs.writeFile(path.join(gradleMember, 'build.gradle'), '') await fs.writeFile(path.join(gradleMember, 'pom.xml'), '') - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, ecosystem }) => { - if (cwd === outer && ecosystem === 'maven') { - return { - factsPath: path.join(cwd, 'pom.xml.socket.facts.json'), - projects: [ - { - type: 'maven', - name: 'shared', - subprojectDir: 'shared', - manifestFiles: [{ file: 'shared/alt.xml' }], - children: [], - }, - ], - } - } - if (cwd === outer && ecosystem === 'gradle') { - return { - factsPath: path.join(cwd, 'gradle.socket.facts.json'), - projects: [ - { - type: 'maven', - name: 'gradle-member', - subprojectDir: 'gradle-member', - manifestFiles: [{ file: 'gradle-member/build.gradle' }], - children: [], - }, - ], - } + mockFacts(async ({ cwd, ecosystem }) => { + if (cwd === outer && ecosystem === 'maven') { + return { + factsPath: path.join(cwd, 'pom.xml.socket.facts.json'), + projects: [ + { + type: 'maven', + name: 'shared', + subprojectDir: 'shared', + manifestFiles: [{ file: 'shared/alt.xml' }], + children: [], + }, + ], } + } + if (cwd === outer && ecosystem === 'gradle') { return { - factsPath: path.join(cwd, `${ecosystem}.socket.facts.json`), - projects: [], + factsPath: path.join(cwd, 'gradle.socket.facts.json'), + projects: [ + { + type: 'maven', + name: 'gradle-member', + subprojectDir: 'gradle-member', + manifestFiles: [{ file: 'gradle-member/build.gradle' }], + children: [], + }, + ], } - }, - ) + } + return { + factsPath: path.join(cwd, `${ecosystem}.socket.facts.json`), + projects: [], + } + }) const outcomes = await generateRecursiveManifests({ cwd: outer, @@ -408,7 +506,7 @@ describe('generateRecursiveManifests', () => { await fs.writeFile(path.join(outer, 'build.sbt'), '') await fs.writeFile(path.join(member, 'build.sbt'), '') - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, 'sbt.socket.facts.json'), projects: cwd === outer @@ -450,7 +548,7 @@ describe('generateRecursiveManifests', () => { await fs.writeFile(path.join(outer, 'settings.gradle'), "include 'tools'") await fs.writeFile(path.join(tools, 'settings.gradle'), '') - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, 'gradle.socket.facts.json'), projects: cwd === outer @@ -492,7 +590,7 @@ describe('generateRecursiveManifests', () => { // eslint-disable-next-line no-await-in-loop await fs.writeFile(path.join(dir, 'pom.xml'), '') } - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => { + mockFacts(async ({ cwd }) => { if (cwd === outer) { return { factsPath: path.join(buildRoot, 'x.xml.socket.facts.json'), @@ -535,7 +633,7 @@ describe('generateRecursiveManifests', () => { }) it("runs both ecosystems unconditionally at a dual-marker directory (matches auto's existing behavior)", async () => { - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -554,15 +652,13 @@ describe('generateRecursiveManifests', () => { }) it('aborts only the build roots in and under a failed one, which may be its members, while siblings and other ecosystems proceed', async () => { - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, ecosystem }) => { - if (ecosystem === 'maven' && cwd === reactor) { - process.exitCode = 1 - return null - } - return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } - }, - ) + mockFacts(async ({ cwd, ecosystem }) => { + if (ecosystem === 'maven' && cwd === reactor) { + process.exitCode = 1 + return null + } + return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } + }) const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger) try { @@ -621,7 +717,7 @@ describe('generateRecursiveManifests', () => { // eslint-disable-next-line no-await-in-loop await fs.writeFile(path.join(dir, 'pom.xml'), '') } - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => { + mockFacts(async ({ cwd }) => { if (cwd === core) { process.exitCode = 1 return null @@ -657,15 +753,13 @@ describe('generateRecursiveManifests', () => { it('still classifies a failure as failed (not empty) when process.exitCode was already non-zero beforehand', async () => { process.exitCode = 1 - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, ecosystem }) => { - if (ecosystem === 'maven' && cwd === dualMarkerDir) { - process.exitCode = 1 - return null - } - return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } - }, - ) + mockFacts(async ({ cwd, ecosystem }) => { + if (ecosystem === 'maven' && cwd === dualMarkerDir) { + process.exitCode = 1 + return null + } + return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } + }) const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger) try { @@ -684,15 +778,13 @@ describe('generateRecursiveManifests', () => { }) it('reports a non-fatal empty result distinctly from a failure', async () => { - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, ecosystem }) => { - if (ecosystem === 'maven' && cwd === dualMarkerDir) { - // No resolvable dependencies; runManifestFacts warns but does not fail. - return undefined - } - return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } - }, - ) + mockFacts(async ({ cwd, ecosystem }) => { + if (ecosystem === 'maven' && cwd === dualMarkerDir) { + // No resolvable dependencies; runManifestFacts warns but does not fail. + return undefined + } + return { factsPath: path.join(cwd, '.socket.facts.json'), projects: [] } + }) const outcomes = await generateRecursiveManifests({ cwd: monorepo, @@ -706,7 +798,7 @@ describe('generateRecursiveManifests', () => { }) it('passes every build root the scan-root-relative --exclude-paths and the scan root', async () => { - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -732,21 +824,19 @@ describe('generateRecursiveManifests', () => { try { await fs.writeFile(path.join(dir, 'pom.xml'), '') await fs.writeFile(path.join(dir, 'App.sln'), '') - vi.mocked(listDotnetEntryProjects).mockClear() - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, entryFile }) => ({ - factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), - projects: [ - { - type: 'maven', - name: 'app', - subprojectDir: '', - manifestFiles: [{ file: 'pom.xml' }], - children: [], - }, - ], - }), - ) + vi.mocked(listDotnetSolutionMembers).mockClear() + mockFacts(async ({ cwd, entryFile }) => ({ + factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), + projects: [ + { + type: 'maven', + name: 'app', + subprojectDir: '', + manifestFiles: [{ file: 'pom.xml' }], + children: [], + }, + ], + })) const outcomes = await generateRecursiveManifests({ cwd: dir, verbose: false, @@ -755,7 +845,7 @@ describe('generateRecursiveManifests', () => { expect( outcomes.map(o => `${o.ecosystem}:${o.entryFile}:${o.status}`).sort(), ).toEqual(['dotnet:App.sln:generated', 'maven:pom.xml:generated']) - expect(listDotnetEntryProjects).not.toHaveBeenCalled() + expect(listDotnetSolutionMembers).not.toHaveBeenCalled() } finally { await fs.rm(dir, { recursive: true, force: true }) } @@ -767,7 +857,7 @@ describe('generateRecursiveManifests', () => { ? { defaults: { manifest: { maven: { javaHome: '/opt/jdk-11' } } } } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -795,12 +885,17 @@ describe('generateRecursiveManifests', () => { dir === dualMarkerDir ? { defaults: { - manifest: { maven: { excludeConfigs: null, javaHome: null } }, + manifest: { + maven: { + excludeConfigs: null, + javaHome: null, + }, + }, }, } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -825,7 +920,7 @@ describe('generateRecursiveManifests', () => { ? { defaults: { manifest: { maven: { verbose: true } } } } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -843,6 +938,7 @@ describe('generateRecursiveManifests', () => { `${opts.ecosystem}:${relOf(opts.cwd)}` === 'maven:dual-marker-dir', )?.hints expect(hints?.flags.size).toBe(0) + expect(hints?.excludePathsFlag).toBe('--exclude-paths') expect(path.resolve(hints?.socketJson ?? '')).toBe( path.join(dualMarkerDir, 'socket.json'), ) @@ -860,7 +956,7 @@ describe('generateRecursiveManifests', () => { } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -885,7 +981,7 @@ describe('generateRecursiveManifests', () => { ? { defaults: { manifest: { maven: { ignoreUnresolved: true } } } } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -913,7 +1009,7 @@ describe('generateRecursiveManifests', () => { ? { defaults: { manifest: { gradle: { facts: false } } } } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -964,7 +1060,7 @@ describe('generateRecursiveManifests', () => { ? { defaults: { manifest: { maven: { disabled: true } } } } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -1021,7 +1117,7 @@ describe('generateRecursiveManifests', () => { } return {} }) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -1052,7 +1148,7 @@ describe('generateRecursiveManifests', () => { mockCascade(dir => ({ defaults: { manifest: { maven: { disabled: dir !== reactor } } }, })) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -1082,7 +1178,7 @@ describe('generateRecursiveManifests', () => { ? { defaults: { manifest: { maven: { disabled: true } } } } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -1134,7 +1230,7 @@ describe('generateRecursiveManifests', () => { }), ) await fs.symlink(realCwd, cwdLink) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -1149,137 +1245,29 @@ describe('generateRecursiveManifests', () => { } }) - it('shares one sbt tmpDir across every discovered sbt root, but passes tmpDir: undefined for gradle/maven', async () => { - const outer = await fs.mkdtemp(path.join(tmpdir(), 'sbt-shared-tmpdir-')) - const sbtA = path.join(outer, 'sbt-a') - const sbtB = path.join(outer, 'sbt-b') - const mavenRoot = path.join(outer, 'maven-root') - try { - await fs.mkdir(sbtA, { recursive: true }) - await fs.mkdir(sbtB, { recursive: true }) - await fs.mkdir(mavenRoot, { recursive: true }) - await fs.writeFile(path.join(sbtA, 'build.sbt'), '') - await fs.writeFile(path.join(sbtB, 'build.sbt'), '') - await fs.writeFile(path.join(mavenRoot, 'pom.xml'), '') - - const tmpDirsSeen: Record> = {} - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, ecosystem, tmpDir }) => { - ;(tmpDirsSeen[ecosystem] ??= []).push(tmpDir) - return { - factsPath: path.join(cwd, '.socket.facts.json'), - projects: [], - } - }, - ) - - await generateRecursiveManifests({ - cwd: outer, - verbose: false, - }) - - expect(tmpDirsSeen['sbt']).toHaveLength(2) - expect(tmpDirsSeen['sbt']![0]).toBeDefined() - expect(tmpDirsSeen['sbt']![0]).toBe(tmpDirsSeen['sbt']![1]) - expect(tmpDirsSeen['maven']).toEqual([undefined]) - } finally { - await fs.rm(outer, { recursive: true, force: true }) - } - }) - - it('does not allocate a shared tmpDir at all when no sbt root is discovered', async () => { - const outer = await fs.mkdtemp(path.join(tmpdir(), 'no-sbt-tmpdir-')) - try { - await fs.writeFile(path.join(outer, 'pom.xml'), '') - - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ - factsPath: path.join(cwd, '.socket.facts.json'), - projects: [], - })) - - await generateRecursiveManifests({ - cwd: outer, - verbose: false, - }) - - expect( - vi.mocked(runManifestFacts).mock.calls[0]?.[0].tmpDir, - ).toBeUndefined() - } finally { - await fs.rm(outer, { recursive: true, force: true }) - } - }) - - it('reuses a caller-supplied sbtTmpDir as-is for every sbt root, and does not delete it', async () => { - const outer = await fs.mkdtemp(path.join(tmpdir(), 'sbt-caller-tmpdir-')) - const sbtA = path.join(outer, 'sbt-a') - const sbtB = path.join(outer, 'sbt-b') - const callerOwnedDir = await fs.mkdtemp( - path.join(tmpdir(), 'caller-owned-sbt-base-'), - ) - try { - await fs.mkdir(sbtA, { recursive: true }) - await fs.mkdir(sbtB, { recursive: true }) - await fs.writeFile(path.join(sbtA, 'build.sbt'), '') - await fs.writeFile(path.join(sbtB, 'build.sbt'), '') - - const tmpDirsSeen: Array = [] - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, tmpDir }) => { - tmpDirsSeen.push(tmpDir) - return { - factsPath: path.join(cwd, '.socket.facts.json'), - projects: [], - } - }, - ) - - await generateRecursiveManifests({ - cwd: outer, - sbtTmpDir: callerOwnedDir, - verbose: false, - }) - - expect(tmpDirsSeen).toEqual([callerOwnedDir, callerOwnedDir]) - // generateRecursiveManifests must not clean up a directory it didn't - // allocate - the caller (e.g. handleCreateNewScan keeping it alive - // until reachability analysis consumes the sidecar's resolved paths) - // owns that lifetime. - await expect(fs.access(callerOwnedDir)).resolves.toBeUndefined() - } finally { - await fs.rm(outer, { recursive: true, force: true }) - await fs.rm(callerOwnedDir, { recursive: true, force: true }) - } - }) - - it('threads sidecarAcc/withFiles through to every build root, not just the first', async () => { - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + it('threads the work dir through to every build root, not just the first', async () => { + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) - const sidecarAcc = new Map() - await generateRecursiveManifests({ - cwd: monorepo, - sidecarAcc, - verbose: false, - withFiles: true, - }) + const context = { orgSlug: 'acme', workDir: newWorkDir() } + await generateRecursiveManifests({ context, cwd: monorepo, verbose: false }) expect(vi.mocked(runManifestFacts).mock.calls.length).toBeGreaterThan(1) for (const [opts] of vi.mocked(runManifestFacts).mock.calls) { - expect(opts.sidecarAcc).toBe(sidecarAcc) - expect(opts.withFiles).toBe(true) + expect(opts.context).toEqual(context) + expect(opts.hints?.continueOnInstallErrorsFlag).toBe( + '--reach-continue-on-install-errors', + ) } }) it('runs every POM in a directory as its own build', async () => { - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, entryFile }) => ({ - factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), - projects: [], - }), - ) + mockFacts(async ({ cwd, entryFile }) => ({ + factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), + projects: [], + })) const outcomes = await generateRecursiveManifests({ cwd: pomNames, @@ -1303,23 +1291,21 @@ describe('generateRecursiveManifests', () => { }) it('covers a POM by file, so a sibling POM in the same directory still runs', async () => { - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, entryFile }) => ({ - factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), - projects: - cwd === pomNames && entryFile === 'pom.xml' - ? [ - { - type: 'maven', - name: 'bare', - subprojectDir: 'bare', - manifestFiles: [{ file: 'bare/pom' }], - children: [], - }, - ] - : [], - }), - ) + mockFacts(async ({ cwd, entryFile }) => ({ + factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), + projects: + cwd === pomNames && entryFile === 'pom.xml' + ? [ + { + type: 'maven', + name: 'bare', + subprojectDir: 'bare', + manifestFiles: [{ file: 'bare/pom' }], + children: [], + }, + ] + : [], + })) const outcomes = await generateRecursiveManifests({ cwd: pomNames, @@ -1345,12 +1331,10 @@ describe('generateRecursiveManifests', () => { }, })) vi.mocked(readSocketJsonChain).mockClear() - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, entryFile }) => ({ - factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), - projects: [], - }), - ) + mockFacts(async ({ cwd, entryFile }) => ({ + factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), + projects: [], + })) const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger) try { @@ -1421,7 +1405,7 @@ describe('generateRecursiveManifests', () => { 'runs the nested build and keeps it only when it loads more (%j)', async ({ 0: subProjects, 1: subStatus }) => { const sub = path.join(outer, 'sub') - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => + mockFacts(async ({ cwd }) => cwd === outer ? gradleFacts(cwd, [ '.', @@ -1454,7 +1438,7 @@ describe('generateRecursiveManifests', () => { ) it('ignores the failure of a nested build of its own when the build that includes its directory succeeds', async () => { - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => { + mockFacts(async ({ cwd }) => { if (cwd === path.join(outer, 'sub')) { process.exitCode = 1 return null @@ -1492,13 +1476,10 @@ describe('generateRecursiveManifests', () => { }, }, }) - vi.mocked(enumerateWorkspaces).mockResolvedValue({ - buildRoot: sub, - projects: gradleFacts(sub, [...subProjects]).projects, - }) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => - gradleFacts(cwd, ['.']), + vi.mocked(listBuildProjects).mockResolvedValue( + listed(sub, gradleFacts(sub, [...subProjects]).projects), ) + mockFacts(async ({ cwd }) => gradleFacts(cwd, ['.'])) const warnSpy = vi .spyOn(logger, 'warn') .mockImplementation(() => logger) @@ -1545,12 +1526,10 @@ describe('generateRecursiveManifests', () => { }, }, }) - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, entryFile }) => ({ - factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), - projects: [], - }), - ) + mockFacts(async ({ cwd, entryFile }) => ({ + factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), + projects: [], + })) await generateRecursiveManifests({ cwd: pomNames, verbose: false }) @@ -1574,24 +1553,22 @@ describe('generateRecursiveManifests', () => { }, }, }) - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, ecosystem }) => ({ - factsPath: path.join(cwd, '.socket.facts.json'), - projects: - cwd === reactor && ecosystem === 'maven' - ? [ - { - type: 'maven', - name: 'moduleA', - id: 'moduleA', - subprojectDir: 'moduleA', - manifestFiles: [{ file: 'moduleA/pom.xml' }], - children: [], - }, - ] - : [], - }), - ) + mockFacts(async ({ cwd, ecosystem }) => ({ + factsPath: path.join(cwd, '.socket.facts.json'), + projects: + cwd === reactor && ecosystem === 'maven' + ? [ + { + type: 'maven', + name: 'moduleA', + id: 'moduleA', + subprojectDir: 'moduleA', + manifestFiles: [{ file: 'moduleA/pom.xml' }], + children: [], + }, + ] + : [], + })) const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger) try { @@ -1643,35 +1620,33 @@ describe('generateRecursiveManifests', () => { }, }, }) - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, entryFile }) => { - const factsPath = path.join(cwd, `${entryFile}.socket.facts.json`) - await fs.writeFile(factsPath, 'generated') - return { - factsPath, - projects: [ - { - ...mavenProject('.'), - manifestFiles: [{ file: entryFile ?? 'pom.xml' }], - }, - ], - } - }, - ) + mockFacts(async ({ context, cwd, entryFile }) => ({ + ...(await writeIntoWorkDir( + context!.workDir!, + `${cwd}/${entryFile}`, + path.join(cwd, `${entryFile}.socket.facts.json`), + 'generated', + )), + projects: [ + { + ...mavenProject('.'), + manifestFiles: [{ file: entryFile ?? 'pom.xml' }], + }, + ], + })) }) afterEach(async () => { await fs.rm(outer, { recursive: true, force: true }) }) it('loads it without resolving, and skips what it loads with it, wherever that is', async () => { - vi.mocked(enumerateWorkspaces).mockResolvedValue({ - buildRoot: path.join(outer, 'legacy'), - projects: [ + vi.mocked(listBuildProjects).mockResolvedValue( + listed(path.join(outer, 'legacy'), [ mavenProject('.'), mavenProject('old'), mavenProject('../aaa-module'), - ], - }) + ]), + ) const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger) try { @@ -1697,7 +1672,7 @@ describe('generateRecursiveManifests', () => { expect( existsSync(path.join(outer, 'aaa-module/pom.xml.socket.facts.json')), ).toBe(false) - expect(enumerateWorkspaces).toHaveBeenCalledWith( + expect(listBuildProjects).toHaveBeenCalledWith( expect.objectContaining({ cwd: path.join(outer, 'legacy'), entryFile: 'pom.xml', @@ -1713,27 +1688,54 @@ describe('generateRecursiveManifests', () => { } }) + it('loads it with the Coana, org and hints its build would run with', async () => { + vi.mocked(listBuildProjects).mockResolvedValue( + listed(path.join(outer, 'legacy'), [mavenProject('.')]), + ) + const context = { coanaVersion: '1.2.3', orgSlug: 'acme' } + vi.spyOn(logger, 'warn').mockImplementation(() => logger) + + await generateRecursiveManifests({ + context, + cwd: outer, + optionFlags: new Set(['verbose']), + verbose: false, + }) + + expect(listBuildProjects).toHaveBeenCalledWith( + expect.objectContaining({ + context: expect.objectContaining(context), + cwd: path.join(outer, 'legacy'), + entryFile: 'pom.xml', + hints: { + continueOnInstallErrorsFlag: undefined, + excludePathsFlag: '--exclude-paths', + flags: new Set(['verbose']), + setupCommand: 'socket manifest setup --dynamic-sbom-inference', + socketJson: expect.stringMatching(/legacy[\\/]socket\.json$/), + }, + }), + ) + }) + it('reports a skipped build that another build includes as part of that build, warning that the skip does not apply', async () => { await fs.mkdir(path.join(outer, 'zzz-reactor'), { recursive: true }) await fs.writeFile(pom('zzz-reactor'), '') - vi.mocked(enumerateWorkspaces).mockResolvedValue({ - buildRoot: path.join(outer, 'legacy'), - projects: [mavenProject('.')], - }) - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, entryFile }) => ({ - factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), - projects: - cwd === path.join(outer, 'zzz-reactor') - ? [mavenProject('.'), mavenProject('../legacy')] - : [ - { - ...mavenProject('.'), - manifestFiles: [{ file: entryFile ?? 'pom.xml' }], - }, - ], - }), + vi.mocked(listBuildProjects).mockResolvedValue( + listed(path.join(outer, 'legacy'), [mavenProject('.')]), ) + mockFacts(async ({ cwd, entryFile }) => ({ + factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), + projects: + cwd === path.join(outer, 'zzz-reactor') + ? [mavenProject('.'), mavenProject('../legacy')] + : [ + { + ...mavenProject('.'), + manifestFiles: [{ file: entryFile ?? 'pom.xml' }], + }, + ], + })) const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger) try { @@ -1761,7 +1763,7 @@ describe('generateRecursiveManifests', () => { }) it('fails, without building what lies beneath it, when it cannot be loaded', async () => { - vi.mocked(enumerateWorkspaces).mockImplementation(async () => { + vi.mocked(listBuildProjects).mockImplementation(async () => { process.exitCode = 1 return undefined }) @@ -1837,25 +1839,22 @@ describe('generateRecursiveManifests', () => { defaults: { manifest: { builds: { 'Y.sln': { disabled: true } } } }, }, }) - vi.mocked(listDotnetEntryProjects).mockImplementation( + vi.mocked(listDotnetSolutionMembers).mockImplementation( async ({ entryFile }) => members[entryFile ?? ''], ) - vi.mocked(enumerateWorkspaces).mockResolvedValue({ - buildRoot: at('skip'), - projects: [projectRecord('../p/a/A.csproj')], - }) - vi.mocked(runManifestFacts).mockImplementation( - async ({ cwd, entryFile }) => ({ - factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), - projects: - entryFile === 'R.sln' - ? [ - projectRecord('../p/a/A.csproj'), - projectRecord('../p/c/C.csproj'), - ] - : [projectRecord(entryFile ?? '')], - }), + vi.mocked(listBuildProjects).mockResolvedValue( + listed(at('skip'), [projectRecord('../p/a/A.csproj')]), ) + mockFacts(async ({ cwd, entryFile }) => ({ + factsPath: path.join(cwd, `${entryFile}.socket.facts.json`), + projects: + entryFile === 'R.sln' + ? [ + projectRecord('../p/a/A.csproj'), + projectRecord('../p/c/C.csproj'), + ] + : [projectRecord(entryFile ?? '')], + })) const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger) const outcomes = await generateRecursiveManifests({ @@ -1885,7 +1884,7 @@ describe('generateRecursiveManifests', () => { ), ) } finally { - vi.mocked(listDotnetEntryProjects).mockImplementation( + vi.mocked(listDotnetSolutionMembers).mockImplementation( async () => undefined, ) await fs.rm(outer, { recursive: true, force: true }) diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index a45fa26736..578701fabe 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -2,33 +2,39 @@ import path from 'node:path' import { extractBazelToMaven } from './bazel/extract_bazel_to_maven.mts' import { convertDotnetToFacts } from './convert-dotnet-to-facts.mts' -import { convertGradleToFacts } from './convert-gradle-to-facts.mts' -import { convertMavenToFacts } from './convert-maven-to-facts.mts' -import { convertSbtToFacts } from './convert-sbt-to-facts.mts' import { convertGradleToMaven } from './convert_gradle_to_maven.mts' import { convertSbtToMaven } from './convert_sbt_to_maven.mts' -import { resolveEcosystemConfig } from './generate-recursive-manifests.mts' +import { + resolveEcosystemConfig, + socketFactsRunOptions, +} from './generate-recursive-manifests.mts' import { handleManifestConda } from './handle-manifest-conda.mts' import { parseBuildToolOpts } from './parse-build-tool-opts.mts' +import { + REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG, + keepFacts, + runManifestFacts, +} from './run-manifest-facts.mts' import { resolveBuildToolBin } from './scripts/build-tool.mts' -import { REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG } from './scripts/resolution-report-render.mts' -import { hasSidecarEntries, serializeSidecar } from './scripts/sidecar.mts' import { ENVIRONMENT_YML, REQUIREMENTS_TXT, SOCKET_JSON, } from '../../constants.mts' import { InputError } from '../../utils/errors.mts' +import { isDirSync } from '../../utils/fs.mts' import { logger } from '../../utils/logger.mts' import { readOrDefaultSocketJson } from '../../utils/socket-json.mts' import type { GeneratableManifests } from './detect-manifest-actions.mts' -import type { RunManifestFactsOutcome } from './run-manifest-facts.mts' -import type { BuildOptionHints } from './scripts/resolution-report-render.mts' +import type { BuildRoot } from './discover-manifest-roots.mts' +import type { EcosystemBuildConfig } from './generate-recursive-manifests.mts' import type { - ResolvedPathsSidecar, - SidecarAccumulator, -} from './scripts/sidecar.mts' + BuildOptionHints, + RunManifestFactsOutcome, + SocketFactsContext, +} from './run-manifest-facts.mts' +import type { BuildTool } from './scripts/build-tool.mts' import type { OutputKind } from '../../types.mts' // Auto-manifest reads every build option from the root socket.json. @@ -40,8 +46,6 @@ const AUTO_MANIFEST_HINTS: BuildOptionHints = { export type GenerateAutoManifestResult = { generatedFiles: string[] - // Reachability path only: resolved on-disk paths from the build-tool run. - resolvedPathsSidecar?: ResolvedPathsSidecar | undefined } // A failed generator aborts --auto-manifest: a partial SBOM silently @@ -58,6 +62,24 @@ function abortFactsRunIfFailed( } } +// Maven's `-f, --file`: "Force the use of an alternate POM file (or directory +// with pom.xml)" (`mvn --help`), relative to where Maven runs. +function mavenRoot(cwd: string, file: string | undefined): BuildRoot { + if (file === undefined) { + return { dir: cwd, entryFile: 'pom.xml' } + } + const named = path.resolve(cwd, file) + return isDirSync(named) + ? { dir: named, entryFile: 'pom.xml' } + : { dir: path.dirname(named), entryFile: path.basename(named) } +} + +// A command naming a path runs that file, relative to `dir`; a bare name is +// looked up on PATH. +function binIn(dir: string, bin: string): string { + return /[/\\]/.test(bin) ? path.resolve(dir, bin) : bin +} + function abortManifestRunIfFailed( ecosystem: string, beforeExitCode: string | number | undefined, @@ -70,156 +92,124 @@ function abortManifestRunIfFailed( } export async function generateAutoManifest({ - computeArtifactsSidecar, + context, cwd, detected, excludePaths, + excludePathsFlag, outputKind, - tmpDir, verbose, }: { - // Reachability path: run build tools with files to emit the sidecar. - computeArtifactsSidecar?: boolean | undefined + context?: SocketFactsContext | undefined detected: GeneratableManifests cwd: string - // Scan-root-relative `--exclude-paths`: skip excluded subprojects and drop - // excluded source roots from the resolved-paths sidecar. + // Scan-root-relative `--exclude-paths`: skip excluded subprojects. excludePaths?: string[] | undefined + // The invoking command's flag for `excludePaths`, when it takes one. + excludePathsFlag?: string | undefined outputKind: OutputKind - // Caller-owned; see ManifestScriptOptions.tmpDir. Only sbt reads it, but - // required here so every caller allocates one via withTmpDir uniformly. - tmpDir: string verbose: boolean }): Promise { const sockJson = readOrDefaultSocketJson(cwd) const generatedFiles: string[] = [] - const hints: BuildOptionHints = computeArtifactsSidecar - ? { - ...AUTO_MANIFEST_HINTS, - continueOnInstallErrorsFlag: REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG, - } - : AUTO_MANIFEST_HINTS - - // Resolved paths across all JVM roots, serialized to one sidecar at the end. - const sidecarAcc: SidecarAccumulator | undefined = computeArtifactsSidecar - ? new Map() - : undefined + const hints: BuildOptionHints = { + ...AUTO_MANIFEST_HINTS, + continueOnInstallErrorsFlag: context?.workDir?.withFiles + ? REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG + : undefined, + excludePathsFlag, + } if (verbose) { logger.info(`Using this ${SOCKET_JSON} for defaults:`, sockJson) } - if (!sockJson?.defaults?.manifest?.sbt?.disabled && detected.sbt) { - // Args shared by both paths. The facts-only knobs (`includeConfigs`, - // `excludeConfigs`, `ignoreUnresolved`) and the pom-only `out` are added - // per branch so neither handler is spread properties it doesn't accept. - const sbtArgs = { - // Note: `sbt` is more likely to be resolved against PATH env. - bin: sockJson.defaults?.manifest?.sbt?.bin ?? 'sbt', - cwd, - sbtOpts: parseBuildToolOpts( - sockJson.defaults?.manifest?.sbt?.sbtOpts ?? undefined, - ), - verbose: Boolean(sockJson.defaults?.manifest?.sbt?.verbose), + const generateFacts = async ( + tool: BuildTool, + root: BuildRoot, + config: EcosystemBuildConfig, + ) => { + const outcome = await runManifestFacts( + socketFactsRunOptions(tool, root, config, { + context, + excludeBase: cwd, + excludePaths, + hints, + }), + ) + if (outcome) { + await keepFacts(context?.workDir, outcome) } + abortFactsRunIfFailed(tool, outcome) + } + + if (!sockJson?.defaults?.manifest?.sbt?.disabled && detected.sbt) { // Socket facts is the default; opt into pom generation with // `defaults.manifest.sbt.facts: false` in socket.json. if (sockJson.defaults?.manifest?.sbt?.facts !== false) { logger.log('Detected a Scala sbt build, generating Socket facts...') - const outcome = await convertSbtToFacts({ - ...sbtArgs, - excludeConfigs: sockJson.defaults?.manifest?.sbt?.excludeConfigs ?? '', - excludePaths, - ignoreUnresolved: Boolean( - sockJson.defaults?.manifest?.sbt?.ignoreUnresolved, - ), - includeConfigs: sockJson.defaults?.manifest?.sbt?.includeConfigs ?? '', - javaHome: sockJson.defaults?.manifest?.sbt?.javaHome ?? undefined, - hints, - sidecarAcc, - tmpDir, - withFiles: computeArtifactsSidecar, - }) - abortFactsRunIfFailed('sbt', outcome) + await generateFacts( + 'sbt', + { dir: cwd }, + resolveEcosystemConfig('sbt', cwd, sockJson), + ) } else { logger.log('Detected a Scala sbt build, generating pom files with sbt...') const beforeExitCode = process.exitCode await convertSbtToMaven({ - ...sbtArgs, + // Note: `sbt` is more likely to be resolved against PATH env. + bin: sockJson.defaults?.manifest?.sbt?.bin ?? 'sbt', + cwd, out: sockJson.defaults?.manifest?.sbt?.outfile ?? './pom.xml', + sbtOpts: parseBuildToolOpts( + sockJson.defaults?.manifest?.sbt?.sbtOpts ?? undefined, + ), + verbose: Boolean(sockJson.defaults?.manifest?.sbt?.verbose), }) abortManifestRunIfFailed('sbt', beforeExitCode) } } if (!sockJson?.defaults?.manifest?.gradle?.disabled && detected.gradle) { - const gradleArgs = { - // Configured bin wins; else prefer ./gradlew, else gradle on PATH. - bin: sockJson.defaults?.manifest?.gradle?.bin - ? path.resolve(cwd, sockJson.defaults.manifest.gradle.bin) - : resolveBuildToolBin('gradle', cwd), - cwd, - verbose: Boolean(sockJson.defaults?.manifest?.gradle?.verbose), - gradleOpts: parseBuildToolOpts( - sockJson.defaults?.manifest?.gradle?.gradleOpts ?? undefined, - ), - } // Socket facts is the default; opt into pom generation with // `defaults.manifest.gradle.facts: false` in socket.json. if (sockJson.defaults?.manifest?.gradle?.facts !== false) { logger.log( 'Detected a gradle build (Gradle, Kotlin, Scala), generating Socket facts...', ) - const outcome = await convertGradleToFacts({ - ...gradleArgs, - excludeConfigs: - sockJson.defaults?.manifest?.gradle?.excludeConfigs ?? '', - excludePaths, - ignoreUnresolved: Boolean( - sockJson.defaults?.manifest?.gradle?.ignoreUnresolved, - ), - includeConfigs: - sockJson.defaults?.manifest?.gradle?.includeConfigs ?? '', - javaHome: sockJson.defaults?.manifest?.gradle?.javaHome ?? undefined, - hints, - sidecarAcc, - withFiles: computeArtifactsSidecar, - }) - abortFactsRunIfFailed('gradle', outcome) + await generateFacts( + 'gradle', + { dir: cwd }, + resolveEcosystemConfig('gradle', cwd, sockJson), + ) } else { logger.log( 'Detected a gradle build (Gradle, Kotlin, Scala), running default gradle generator...', ) const beforeExitCode = process.exitCode - await convertGradleToMaven(gradleArgs) + await convertGradleToMaven({ + // Configured bin wins; else prefer ./gradlew, else gradle on PATH. + bin: sockJson.defaults?.manifest?.gradle?.bin + ? path.resolve(cwd, sockJson.defaults.manifest.gradle.bin) + : resolveBuildToolBin('gradle', cwd), + cwd, + verbose: Boolean(sockJson.defaults?.manifest?.gradle?.verbose), + gradleOpts: parseBuildToolOpts( + sockJson.defaults?.manifest?.gradle?.gradleOpts ?? undefined, + ), + }) abortManifestRunIfFailed('gradle', beforeExitCode) } } if (!sockJson?.defaults?.manifest?.maven?.disabled && detected.maven) { logger.log('Detected a Maven pom.xml build, generating Socket facts...') - const outcome = await convertMavenToFacts({ - // Configured bin wins; else prefer ./mvnw, else mvn on PATH. - bin: - sockJson.defaults?.manifest?.maven?.bin ?? - resolveBuildToolBin('maven', cwd), - cwd, - excludeConfigs: sockJson.defaults?.manifest?.maven?.excludeConfigs ?? '', - excludePaths, - ignoreUnresolved: Boolean( - sockJson.defaults?.manifest?.maven?.ignoreUnresolved, - ), - includeConfigs: sockJson.defaults?.manifest?.maven?.includeConfigs ?? '', - javaHome: sockJson.defaults?.manifest?.maven?.javaHome ?? undefined, - mavenOpts: parseBuildToolOpts( - sockJson.defaults?.manifest?.maven?.mavenOpts ?? undefined, - ), - hints, - sidecarAcc, - verbose: Boolean(sockJson.defaults?.manifest?.maven?.verbose), - withFiles: computeArtifactsSidecar, + const config = resolveEcosystemConfig('maven', cwd, sockJson) + await generateFacts('maven', mavenRoot(cwd, config.mavenFile), { + ...config, + // Maven runs in the POM's directory, which `--file` can move. + bin: binIn(cwd, config.bin), }) - abortFactsRunIfFailed('maven', outcome) } if (!sockJson?.defaults?.manifest?.dotnet?.disabled && detected.dotnet) { @@ -228,11 +218,10 @@ export async function generateAutoManifest({ ) const outcome = await convertDotnetToFacts({ config: resolveEcosystemConfig('dotnet', cwd, sockJson), + context, cwd, excludePaths, hints, - sidecarAcc, - withFiles: computeArtifactsSidecar, }) abortFactsRunIfFailed('dotnet', outcome) } @@ -308,11 +297,5 @@ export async function generateAutoManifest({ } } - return { - generatedFiles, - resolvedPathsSidecar: - sidecarAcc && hasSidecarEntries(sidecarAcc) - ? serializeSidecar(sidecarAcc) - : undefined, - } + return { generatedFiles } } diff --git a/src/commands/manifest/generate_auto_manifest.test.mts b/src/commands/manifest/generate_auto_manifest.test.mts index f4a5e4b1b5..e0cefe6390 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -1,3 +1,7 @@ +import { existsSync, promises as fs } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' + import { beforeEach, describe, expect, it, vi } from 'vitest' // Mock the helpers BEFORE importing generateAutoManifest. @@ -19,11 +23,9 @@ vi.mock('./convert_sbt_to_maven.mts', () => ({ vi.mock('./convert-dotnet-to-facts.mts', () => ({ convertDotnetToFacts: vi.fn(async () => undefined), })) -vi.mock('./convert-gradle-to-facts.mts', () => ({ - convertGradleToFacts: vi.fn(async () => undefined), -})) -vi.mock('./convert-sbt-to-facts.mts', () => ({ - convertSbtToFacts: vi.fn(async () => undefined), +vi.mock('./run-manifest-facts.mts', async importOriginal => ({ + ...(await importOriginal()), + runManifestFacts: vi.fn(async () => undefined), })) vi.mock('./handle-manifest-conda.mts', () => ({ handleManifestConda: vi.fn(async () => undefined), @@ -34,10 +36,10 @@ vi.mock('../../utils/socket-json.mts', () => ({ import { extractBazelToMaven } from './bazel/extract_bazel_to_maven.mts' import { convertDotnetToFacts } from './convert-dotnet-to-facts.mts' -import { convertGradleToFacts } from './convert-gradle-to-facts.mts' import { convertGradleToMaven } from './convert_gradle_to_maven.mts' import { generateAutoManifest } from './generate_auto_manifest.mts' import { handleManifestConda } from './handle-manifest-conda.mts' +import { runManifestFacts } from './run-manifest-facts.mts' import { logger } from '../../utils/logger.mts' import { readOrDefaultSocketJson } from '../../utils/socket-json.mts' @@ -58,7 +60,7 @@ const baseDetected = { describe('generateAutoManifest — bazel branch', () => { beforeEach(() => { vi.mocked(extractBazelToMaven).mockClear() - vi.mocked(convertGradleToFacts).mockClear() + vi.mocked(runManifestFacts).mockClear() vi.mocked(convertGradleToMaven).mockClear() vi.mocked(readOrDefaultSocketJson).mockReturnValue({} as SocketJson) vi.mocked(extractBazelToMaven).mockResolvedValue({ @@ -271,10 +273,26 @@ describe('generateAutoManifest — bazel branch', () => { }) expect(extractBazelToMaven).toHaveBeenCalledTimes(1) // Socket facts is the default for the gradle branch. - expect(convertGradleToFacts).toHaveBeenCalledTimes(1) + expect(runManifestFacts).toHaveBeenCalledTimes(1) expect(convertGradleToMaven).not.toHaveBeenCalled() }) + it.for([['--exclude-paths'], [undefined]] as const)( + 'names the exclude-paths flag %s in remedies only when the command takes one', + async ({ 0: excludePathsFlag }) => { + await generateAutoManifest({ + cwd: '/tmp/repo', + detected: { ...baseDetected, maven: true, count: 1 }, + excludePathsFlag, + outputKind: 'text', + verbose: false, + }) + expect(vi.mocked(runManifestFacts).mock.calls[0]?.[0].hints).toEqual( + expect.objectContaining({ excludePathsFlag }), + ) + }, + ) + it('uses the gradle pom generator when defaults.manifest.gradle.facts is false', async () => { vi.mocked(readOrDefaultSocketJson).mockReturnValue({ defaults: { manifest: { gradle: { facts: false } } }, @@ -286,7 +304,7 @@ describe('generateAutoManifest — bazel branch', () => { verbose: false, }) expect(convertGradleToMaven).toHaveBeenCalledTimes(1) - expect(convertGradleToFacts).not.toHaveBeenCalled() + expect(runManifestFacts).not.toHaveBeenCalled() }) it('honors socket.json out override (user-supplied .socket-auto-manifest dir)', async () => { @@ -310,6 +328,171 @@ describe('generateAutoManifest — bazel branch', () => { }) }) +function callFor(ecosystem: string) { + return vi + .mocked(runManifestFacts) + .mock.calls.find(([opts]) => opts.ecosystem === ecosystem)?.[0] +} + +describe('generateAutoManifest — JVM facts', () => { + beforeEach(() => { + vi.mocked(runManifestFacts).mockReset() + vi.mocked(readOrDefaultSocketJson).mockReturnValue({} as SocketJson) + }) + + it("builds a Maven root's pom.xml by name, apart from a Gradle build beside it", async () => { + await generateAutoManifest({ + cwd: '/tmp/repo', + detected: { ...baseDetected, gradle: true, maven: true, count: 2 }, + outputKind: 'text', + verbose: false, + }) + expect(callFor('maven')).toMatchObject({ + cwd: '/tmp/repo', + entryFile: 'pom.xml', + }) + expect(callFor('gradle')).toMatchObject({ cwd: '/tmp/repo' }) + expect(callFor('gradle')?.entryFile).toBeUndefined() + }) + + it('takes each JVM build tool its socket.json section as the walk does', async () => { + vi.mocked(readOrDefaultSocketJson).mockReturnValue({ + defaults: { + manifest: { + gradle: { + excludeConfigs: 'test*', + gradleOpts: '--offline', + ignoreUnresolved: true, + javaHome: '$GRADLE_JDK', + }, + maven: { bin: 'mvn', includeConfigs: 'compile', verbose: true }, + sbt: { sbtOpts: '-Dx=1' }, + }, + }, + } as SocketJson) + await generateAutoManifest({ + cwd: '/tmp/repo', + detected: { ...baseDetected, gradle: true, maven: true, sbt: true }, + excludePaths: ['docs/**'], + outputKind: 'text', + verbose: false, + }) + expect(callFor('gradle')).toMatchObject({ + buildOpts: ['--offline'], + excludeBase: '/tmp/repo', + excludeConfigs: 'test*', + excludePaths: ['docs/**'], + ignoreUnresolved: true, + javaHome: '$GRADLE_JDK', + }) + expect(callFor('maven')).toMatchObject({ + bin: 'mvn', + includeConfigs: 'compile', + verbose: true, + }) + expect(callFor('sbt')).toMatchObject({ bin: 'sbt', buildOpts: ['-Dx=1'] }) + }) + + it.for([ + ['--file sub/app.xml', 'sub', 'app.xml'], + ['-fsub/app.xml', 'sub', 'app.xml'], + ['--file=sub', 'sub', 'pom.xml'], + ['-f sub -f other.xml', 'sub', 'pom.xml'], + ] as const)( + 'builds the POM `%s` in mavenOpts names, keeping it out of the build options', + async ({ 0: fileOpts, 1: dir, 2: entryFile }) => { + const cwd = await fs.realpath( + await fs.mkdtemp(path.join(tmpdir(), 'auto-manifest-file-')), + ) + try { + await fs.mkdir(path.join(cwd, 'sub')) + vi.mocked(readOrDefaultSocketJson).mockReturnValue({ + defaults: { + manifest: { maven: { bin: 'mvn', mavenOpts: `-Pci ${fileOpts}` } }, + }, + } as SocketJson) + await generateAutoManifest({ + cwd, + detected: { ...baseDetected, maven: true, count: 1 }, + outputKind: 'text', + verbose: false, + }) + expect(callFor('maven')).toMatchObject({ + buildOpts: ['-Pci'], + cwd: path.join(cwd, dir), + entryFile, + excludeBase: cwd, + }) + } finally { + await fs.rm(cwd, { recursive: true, force: true }) + } + }, + ) + + it('runs a relative bin from the scan root when --file moves Maven into another directory', async () => { + const cwd = await fs.realpath( + await fs.mkdtemp(path.join(tmpdir(), 'auto-manifest-bin-')), + ) + try { + await fs.mkdir(path.join(cwd, 'sub')) + vi.mocked(readOrDefaultSocketJson).mockReturnValue({ + defaults: { + manifest: { maven: { bin: './mvnw', mavenOpts: '-f sub' } }, + }, + } as SocketJson) + await generateAutoManifest({ + cwd, + detected: { ...baseDetected, maven: true, count: 1 }, + outputKind: 'text', + verbose: false, + }) + expect(callFor('maven')).toMatchObject({ + bin: path.join(cwd, 'mvnw'), + cwd: path.join(cwd, 'sub'), + }) + } finally { + await fs.rm(cwd, { recursive: true, force: true }) + } + }) + + it('places the facts of each build it generates, with its sidecar entry', async () => { + const cwd = await fs.realpath( + await fs.mkdtemp(path.join(tmpdir(), 'auto-manifest-keep-')), + ) + try { + const stateDir = path.join(cwd, 'work', 'state') + const factsPath = path.join(stateDir, 'pom.xml.socket.facts.json') + const targetPath = path.join(cwd, 'pom.xml.socket.facts.json') + await fs.mkdir(stateDir, { recursive: true }) + await fs.writeFile(factsPath, 'generated') + const sidecarEntry = { factsFile: targetPath, stateDir } + vi.mocked(runManifestFacts).mockResolvedValue({ + factsPath, + projects: [], + sidecarEntry, + targetPath, + }) + const workDir = { + dir: path.join(cwd, 'work'), + entries: new Map(), + withFiles: true, + } + await generateAutoManifest({ + context: { workDir }, + cwd, + detected: { ...baseDetected, maven: true, count: 1 }, + outputKind: 'text', + verbose: false, + }) + expect(existsSync(targetPath)).toBe(true) + expect(await fs.readFile(targetPath, 'utf8')).toBe('generated') + expect([...workDir.entries]).toEqual([[targetPath, sidecarEntry]]) + } finally { + await fs.rm(cwd, { recursive: true, force: true }) + } + }) +}) + describe('generateAutoManifest — conda branch', () => { beforeEach(() => { vi.mocked(handleManifestConda).mockClear() @@ -393,7 +576,7 @@ describe('generateAutoManifest — conda branch', () => { it('aborts on a failed facts generator even when the exit code was already set', async () => { process.exitCode = 1 - vi.mocked(convertGradleToFacts).mockResolvedValueOnce(null) + vi.mocked(runManifestFacts).mockResolvedValueOnce(null) await expect( generateAutoManifest({ cwd: '/tmp/repo', diff --git a/src/commands/manifest/load-build.mts b/src/commands/manifest/load-build.mts index 106e3fe390..5942c879f8 100644 --- a/src/commands/manifest/load-build.mts +++ b/src/commands/manifest/load-build.mts @@ -1,10 +1,9 @@ import { membershipOf } from './discover-manifest-roots.mts' -import { enumerateWorkspaces } from './enumerate-workspaces.mts' +import { listBuildProjects } from './run-manifest-facts.mts' import { pluralize } from '../../utils/words.mts' -import type { BuildRoot, Membership } from './discover-manifest-roots.mts' -import type { EcosystemBuildConfig } from './generate-recursive-manifests.mts' -import type { BuildTool } from './scripts/build-tool.mts' +import type { Membership } from './discover-manifest-roots.mts' +import type { SocketFactsRunOptions } from './run-manifest-facts.mts' export type LoadedBuild = { membership: Membership @@ -14,37 +13,18 @@ export type LoadedBuild = { // Lets the build tool load a build, resolving nothing, for what it includes. export async function loadBuild({ - config, - ecosystem, - excludePaths, - root, scanRoot, - verbose, -}: { - config: EcosystemBuildConfig - ecosystem: BuildTool - excludePaths: string[] | undefined - root: BuildRoot - scanRoot: string - verbose: boolean -}): Promise { - const result = await enumerateWorkspaces({ - bin: config.bin, - buildOpts: config.buildOpts, - cwd: root.dir, - ecosystem, - entryFile: root.entryFile, - excludeBase: scanRoot, - excludePaths, - javaHome: config.javaHome, - verbose: verbose || config.verbose, - }) - if (!result) { + ...options +}: SocketFactsRunOptions & { scanRoot: string }): Promise< + LoadedBuild | undefined +> { + const projects = await listBuildProjects(options) + if (!projects) { return undefined } return { - membership: await membershipOf(result.buildRoot, result.projects, scanRoot), - modules: Math.max(0, result.projects.length - 1), + membership: await membershipOf(projects, scanRoot), + modules: Math.max(0, projects.length - 1), } } diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 8b24b628be..2f7b539fda 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -1,61 +1,215 @@ import { existsSync, promises as fs } from 'node:fs' import path from 'node:path' -import { buildRootPath } from './discover-manifest-roots.mts' import { - expandEnvVarRefs, - formatMissingEnvVarRefs, -} from './expand-env-var-refs.mts' -import { looksLikeSbtBuild } from './scripts/build-tool.mts' -import { - FLAG_HINTS, - renderResolutionErrorReport, - verboseHint, -} from './scripts/resolution-report-render.mts' -import { runManifestScript } from './scripts/run.mts' -import { accumulateSidecar } from './scripts/sidecar.mts' -import constants from '../../constants.mts' + buildRootPath, + looksLikeSbtBuild, + resolveBuildToolBin, +} from './scripts/build-tool.mts' +import { COANA_CLI_VERSION, SOCKET_JSON } from '../../constants.mts' +import { isSea } from '../../sea/runtime.mts' +import { spawnCoana } from '../../utils/coana/release.mts' import { getErrorMessageOr } from '../../utils/errors.mts' -import { realpathOrResolved } from '../../utils/fs.mts' +import { withTmpDir } from '../../utils/fs.mts' +import { getOrInsert } from '../../utils/get-or-insert.mts' import { logger } from '../../utils/logger.mts' import type { BuildTool } from './scripts/build-tool.mts' -import type { SocketFactsSbomProject } from './scripts/facts.mts' -import type { BuildOptionHints } from './scripts/resolution-report-render.mts' -import type { ManifestRunResult } from './scripts/run.mts' -import type { SidecarAccumulator } from './scripts/sidecar.mts' +import type { CResult } from '../../types.mts' -const MAX_FAILURE_OUTPUT_LINES = 40 +export type BuildOption = 'excludeConfigs' | 'ignoreUnresolved' | 'verbose' -export type RunManifestFactsResult = { - factsPath: string - projects: SocketFactsSbomProject[] +// Where the invoking command lets the user set each build option, so a remedy +// in Coana's failure report names something they can actually set. +export type BuildOptionHints = { + // Reachability scans only: reachability cannot install a dependency that + // `ignoreUnresolved` lets through, so it must be told to continue too. + continueOnInstallErrorsFlag?: string | undefined + // The invoking command's option that leaves paths out of the scan. + excludePathsFlag?: string | undefined + // Taken as flags; every other option is set in `socketJson`. + flags: ReadonlySet + // Wizard that writes `socketJson`. + setupCommand: string + socketJson: string +} + +export const DSI_SETUP_COMMAND = + 'socket manifest setup --dynamic-sbom-inference' + +export const EXCLUDE_PATHS_FLAG = '--exclude-paths' + +export const REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG = + '--reach-continue-on-install-errors' + +// The single-build manifest commands take every option as a flag. +const FLAG_HINTS: BuildOptionHints = { + excludePathsFlag: EXCLUDE_PATHS_FLAG, + flags: new Set([ + 'excludeConfigs', + 'ignoreUnresolved', + 'verbose', + ]), + setupCommand: 'socket manifest setup', + socketJson: SOCKET_JSON, } -// Last N non-empty lines of the captured build output, for diagnosing a crash -// without forcing a --verbose rebuild. -export function tailBuildOutput(stdout: string, stderr: string): string { - const combined = [stdout, stderr] - .map(s => s.trimEnd()) - .filter(Boolean) - .join('\n') - return combined.split('\n').slice(-MAX_FAILURE_OUTPUT_LINES).join('\n') +// What a later Coana run needs of one generated build root; passed back to it +// unread. +export type SocketFactsSidecarEntry = { + factsFile: string + stateDir: string +} + +// A directory socket-cli owns until the Coana run that reads it is done, and +// the entries of the build roots whose facts were kept. +export type SocketFactsWorkDir = { + dir: string + // By the facts file Coana places a root's facts at. + entries: Map + // Reachability only: also install the dependencies the analysis reads. + withFiles: boolean +} + +export type SocketFactsContext = { + // The Coana that reads `workDir` must be the one that wrote it. + coanaVersion?: string | undefined + orgSlug?: string | undefined + workDir?: SocketFactsWorkDir | undefined +} + +// A project the build loaded, with absolute paths. Gradle reports a project's +// build file even when absent. +export type SocketFactsProject = { buildFiles: string[]; dir: string } + +export type RunManifestFactsResult = { + // Where Coana wrote the facts: in the work dir with one, else `targetPath`. + factsPath: string + projects: SocketFactsProject[] + sidecarEntry?: SocketFactsSidecarEntry | undefined + // Where the facts belong. + targetPath: string } // `null` = a real failure (crash, missing config, blocking unresolved // dependency); `undefined` = genuinely nothing to resolve, not a failure. -// Distinguishing the two here means callers never have to infer it from -// `process.exitCode`, which can already be non-zero for an unrelated reason. export type RunManifestFactsOutcome = RunManifestFactsResult | null | undefined -// Runs the bundled build-tool resolution script for a JVM project and writes -// its `.socket.facts.json` (see socketFactsFileName). `withFiles` -// (reachability only) additionally folds resolved artifact paths into -// `sidecarAcc`. A blocking resolution failure sets -// a non-zero exit code and returns (matching the `--pom` generator) unless -// `ignoreUnresolved`; a crashed build — a process failure, not an unresolved -// dependency — always fails. -export async function runManifestFacts({ +// The request `coana generate-socket-facts --request` reads. +type SocketFactsRequest = { + buildRoot: string + config: { + bin?: string | undefined + buildOpts: string[] + excludeConfigs?: string | undefined + ignoreUnresolved: boolean + includeConfigs?: string | undefined + javaHome?: string | undefined + verbose: boolean + } + entryFile?: string | undefined + excludeBase: string + excludePaths?: string[] | undefined + hints: Omit & { flags: BuildOption[] } + tool: BuildTool +} + +type SocketFactsResult = + | (RunManifestFactsResult & { status: 'generated' }) + | { status: 'empty' } + | { status: 'failed' } + +type SolutionMembers = { members: string[] | null } + +type ProjectList = + | { projects: SocketFactsProject[]; status: 'listed' } + | { status: 'failed' } + +async function readResult( + resultFile: string, +): Promise<{ error?: string | undefined; result: T | undefined }> { + if (!existsSync(resultFile)) { + return { result: undefined } + } + try { + return { result: JSON.parse(await fs.readFile(resultFile, 'utf8')) as T } + } catch (e) { + return { + error: `Coana's result is unreadable (${getErrorMessageOr(e, String(e))})`, + result: undefined, + } + } +} + +function toRequestHints(hints: BuildOptionHints): SocketFactsRequest['hints'] { + return { ...hints, flags: [...hints.flags].sort() } +} + +async function runGenerateSocketFacts( + request: SocketFactsRequest, + flags: string[], + context: SocketFactsContext, +): Promise<{ message?: string | undefined; result: T | undefined }> { + return await withTmpDir('socket-facts-request-', async tmpDir => { + const requestFile = path.join(tmpDir, 'request.json') + const resultFile = path.join(tmpDir, 'result.json') + await fs.writeFile(requestFile, JSON.stringify(request), 'utf8') + const spawned = await spawnCoana( + [ + 'generate-socket-facts', + '--request', + requestFile, + '--output-file', + resultFile, + ...flags, + ], + context.orgSlug, + { + coanaVersion: context.coanaVersion, + minimumVersion: COANA_CLI_VERSION, + // Coana logs to stdout; keep the command's own stdout machine-readable. + stdio: ['inherit', 2, 'inherit'], + }, + ) + const { error, result } = await readResult(resultFile) + const failure = spawned.ok + ? undefined + : [spawned.message, spawned.cause].filter(Boolean).join(': ') + return { + message: [failure, error].filter(Boolean).join('; ') || undefined, + result, + } + }) +} + +export type SocketFactsRequestOptions = { + bin?: string | undefined + buildOpts: string[] + cwd: string + ecosystem: BuildTool + // The file in `cwd` to build: Maven's POM (unset leaves Maven's default), + // dotnet's solution or project (required). + entryFile?: string | undefined + // What `excludePaths` are relative to, as a build can reach modules outside + // its own directory; `cwd` when unset. + excludeBase?: string | undefined + excludeConfigs?: string | undefined + excludePaths?: string[] | undefined + hints?: BuildOptionHints | undefined + ignoreUnresolved?: boolean | undefined + includeConfigs?: string | undefined + // As written: Coana expands `$VAR` references itself. + javaHome?: string | undefined + verbose?: boolean | undefined +} + +export type SocketFactsRunOptions = SocketFactsRequestOptions & { + context?: SocketFactsContext | undefined +} + +// SOCKET_CLI_*_PATH, else `bin`, the project wrapper, then PATH; standalone, +// JVM tools take only SOCKET_CLI_*_PATH, as no JVM tooling is bundled. +function toSocketFactsRequest({ bin, buildOpts, cwd, @@ -65,243 +219,179 @@ export async function runManifestFacts({ excludeConfigs, excludePaths, hints = FLAG_HINTS, - ignoreUnresolved, + ignoreUnresolved = false, includeConfigs, javaHome, - sidecarAcc, - tmpDir, - verbose, - withFiles, -}: { - bin: string - buildOpts: string[] - cwd: string - ecosystem: BuildTool - // See ManifestScriptOptions.entryFile. - entryFile?: string | undefined - // See ManifestScriptOptions.excludeBase. - excludeBase?: string | undefined - excludeConfigs: string - excludePaths?: string[] | undefined - // Where the user sets build options, for remedy hints. - hints?: BuildOptionHints | undefined - ignoreUnresolved: boolean - includeConfigs: string - javaHome?: string | undefined - sidecarAcc?: SidecarAccumulator | undefined - // sbt only; see ManifestScriptOptions.tmpDir. - tmpDir?: string | undefined - verbose: boolean - withFiles?: boolean | undefined -}): Promise { - let resolvedJavaHome: string | undefined - if (javaHome) { - const expanded = expandEnvVarRefs(javaHome) - if (expanded.missing) { - process.exitCode = 1 - logger.fail( - `javaHome (\`${javaHome}\`) ${formatMissingEnvVarRefs(expanded.missing)}.`, - ) - return null + verbose = false, +}: SocketFactsRequestOptions): CResult { + let resolvedBin: string + try { + resolvedBin = resolveBuildToolBin( + ecosystem, + cwd, + bin || undefined, + ecosystem !== 'dotnet' && isSea(), + ) + } catch (e) { + return { + ok: false, + message: `Could not run the ${ecosystem} build tool`, + cause: getErrorMessageOr(e, String(e)), } - resolvedJavaHome = expanded.value } + return { + ok: true, + data: { + buildRoot: path.resolve(cwd), + config: { + bin: resolvedBin, + buildOpts, + ...(excludeConfigs ? { excludeConfigs } : {}), + ignoreUnresolved, + ...(includeConfigs ? { includeConfigs } : {}), + ...(javaHome ? { javaHome } : {}), + verbose, + }, + ...(entryFile ? { entryFile } : {}), + excludeBase: path.resolve(excludeBase ?? cwd), + ...(excludePaths?.length ? { excludePaths } : {}), + hints: toRequestHints(hints), + tool: ecosystem, + }, + } +} - if (ecosystem === 'sbt' && !looksLikeSbtBuild(cwd)) { - process.exitCode = 1 - logger.fail( - `No sbt build found at \`${cwd}\` (expected a build.sbt file or a project directory).`, - ) - return null +// Puts a kept build root's facts where they belong, and keeps its sidecar +// entry for the Coana run that reads `workDir`. +export async function keepFacts( + workDir: SocketFactsWorkDir | undefined, + { factsPath, sidecarEntry, targetPath }: RunManifestFactsResult, +): Promise { + if (factsPath !== targetPath) { + await fs.copyFile(factsPath, targetPath) + } + if (workDir && sidecarEntry) { + workDir.entries.set(targetPath, sidecarEntry) } +} - const location = buildRootPath({ dir: cwd, entryFile }) - logger.info( - `Generating Socket facts for the ${ecosystem} project at \`${location}\` ...`, - ) +const membersByRequest = new Map>() - const scriptOpts = { - bin: bin || undefined, - entryFile, - excludeBase, - excludeConfigs: excludeConfigs || undefined, - excludePaths: excludePaths?.length ? excludePaths : undefined, - // `env` replaces the spawned process's whole environment, not just JAVA_HOME. - env: resolvedJavaHome - ? { ...process.env, JAVA_HOME: resolvedJavaHome } - : undefined, - includeConfigs: includeConfigs || undefined, - projectDir: cwd, - // Stream the build tool's output only when asked; otherwise capture it and - // show a spinner, surfacing the output only if the build crashes. - stdio: verbose ? ('inherit' as const) : ('pipe' as const), - tmpDir, - toolOpts: buildOpts, - withFiles, +// The projects a dotnet solution builds; undefined when the SDK cannot read +// it, empty when the listing fails, which the build itself then reports. +export async function listDotnetSolutionMembers({ + context = {}, + ...options +}: Omit & { + context?: SocketFactsContext | undefined +}): Promise { + const request = toSocketFactsRequest({ ...options, ecosystem: 'dotnet' }) + if (!request.ok) { + // Left for the build itself to report. + return [] } - const { spinner } = constants - let result: ManifestRunResult - try { - if (verbose) { - logger.info( - `(Running ${ecosystem} with output streaming; this can take a while.)`, - ) - result = await runManifestScript(ecosystem, scriptOpts) - } else { - logger.info( - `(No live output; to stream the ${ecosystem} build output, ${verboseHint(hints, ecosystem)}.)`, + return await getOrInsert( + membersByRequest, + // The Coana that answers is part of the question. + JSON.stringify([context.coanaVersion, request.data]), + async () => { + const { result } = await runGenerateSocketFacts( + request.data, + ['--list-members'], + context, ) - spinner.start(`Resolving ${ecosystem} dependencies ...`) - result = await runManifestScript(ecosystem, scriptOpts) - if (result.code === 0) { - spinner.successAndStop(`Resolved ${ecosystem} dependencies.`) - } else { - spinner.failAndStop( - `${ecosystem} build exited with code ${result.code}.`, - ) + if (!result) { + return [] } - } - } catch (e) { - // Only a spawn-level failure (e.g. the build tool missing from PATH) reaches - // here; runNeverThrow returns non-zero build exits rather than throwing. - if (!verbose) { - spinner.failAndStop(`Failed to run ${ecosystem}.`) - } - process.exitCode = 1 + return result.members ?? undefined + }, + ) +} + +// Resolves nothing; undefined, after reporting why, when the build cannot list +// its projects. +export async function listBuildProjects({ + context = {}, + ...options +}: SocketFactsRunOptions): Promise { + const { cwd, ecosystem, entryFile } = options + const request = toSocketFactsRequest(options) + if (!request.ok) { + logger.fail(`${request.message}: ${request.cause}`) + return undefined + } + const { message, result } = await runGenerateSocketFacts( + request.data, + ['--list-projects'], + context, + ) + if (!result) { logger.fail( - `Could not run the ${ecosystem} build tool: ${getErrorMessageOr(e, String(e))}`, + `Could not list the projects of the ${ecosystem} build at \`${buildRootPath({ dir: cwd, entryFile })}\`${message ? `: ${message}` : '.'}`, ) - return null + return undefined } - const { - artifactPaths, - buildRoot, - code, - facts, - factsFileName, - report, - stderr, - stdout, - } = result - - // A non-zero build exit with no usable output (no graph, no first-party - // modules, no failure records) means the build died before the socketFacts - // task emitted anything — a script/plugin compile error, OOM, or an unchecked - // exception in the extension. The build tool's own exit is the only signal, so - // fail closed rather than silently dropping the ecosystem with an empty SBOM - // (the empty-facts branch below would otherwise just log "nothing to upload"). - // The dotnet tool exits non-zero only when it crashed, so whatever it - // recorded before is incomplete however much there is. - if ( - code !== 0 && - (ecosystem === 'dotnet' || - (!facts.components.length && - !facts.projects?.length && - !report.failures.length && - !report.unscannable.length)) - ) { - if (!verbose) { - const tail = tailBuildOutput(stdout, stderr) - if (tail) { - logger.group('Build output:') - logger.error(tail) - logger.groupEnd() - } - } - // A crashed build is a process failure (missing JDK/build tool, unparseable - // project, OOM, plugin error), not an unresolved dependency, so it fails - // regardless of `ignoreUnresolved` — that flag only tolerates dependencies a - // successful run couldn't resolve. + return result.status === 'listed' ? result.projects : undefined +} + +// A failure sets a non-zero exit code; only a failed build is Coana's to +// report. With a work dir, the facts stay there until keepFacts places them. +export async function runManifestFacts({ + context = {}, + ...options +}: SocketFactsRunOptions): Promise { + const { cwd, ecosystem, entryFile } = options + if (ecosystem === 'sbt' && !looksLikeSbtBuild(cwd)) { process.exitCode = 1 logger.fail( - `The ${ecosystem} build at \`${location}\` failed (exit code ${code}) without completing its Socket facts.`, + `No sbt build found at \`${cwd}\` (expected a build.sbt file or a project directory).`, ) return null } - const rendered = renderResolutionErrorReport( - report.failures, - report.scannedConfigs, - ecosystem, - { - hints, - ignoreUnresolved, - resolvedModules: report.resolvedModules, - unscannable: report.unscannable, - }, + const request = toSocketFactsRequest(options) + if (!request.ok) { + process.exitCode = 1 + logger.fail(`${request.message}: ${request.cause}`) + return null + } + + const { workDir } = context + const { message, result } = await runGenerateSocketFacts( + request.data, + workDir + ? [ + ...(workDir.withFiles ? ['--with-files'] : []), + '--work-dir', + workDir.dir, + ] + : [], + context, ) - if (rendered.hasBlockingFailures) { - if (ignoreUnresolved) { - logger.warn(rendered.summary) - } else { - process.exitCode = 1 - logger.fail(rendered.summary) - if (verbose && rendered.details) { - logger.info(rendered.details) - } - return null + if (!result || result.status === 'failed') { + process.exitCode = 1 + if (!result) { + logger.fail( + `Could not generate Socket facts for the ${ecosystem} project at \`${buildRootPath({ dir: cwd, entryFile })}\`${message ? `: ${message}` : '.'}`, + ) } + return null } - if (rendered.nonBlockingNotice) { - logger.info(rendered.nonBlockingNotice) - } - if (verbose && rendered.details) { - logger.info(rendered.details) + if (result.status === 'empty') { + return undefined } - - // Nothing resolved at all — no dependencies and no first-party modules. A - // project with only first-party modules (empty components, non-empty projects) - // still has source roots reachability needs, so it must be written. - if (!facts.components.length && !facts.projects?.length) { - logger.warn( - `No resolvable ${ecosystem} dependencies found; nothing to upload.`, - ) - return - } - - if (!buildRoot || !factsFileName) { + if (workDir && !result.sidecarEntry) { process.exitCode = 1 logger.fail( - `The ${ecosystem} build did not report its ${buildRoot ? 'entry build file' : 'root directory'}, so its Socket facts file cannot be placed.`, + `Coana returned no sidecar entry for \`${result.targetPath}\`, which reachability analysis and socket fix need. This is a Coana bug; please report it to Socket.`, ) return null } - // Every path in the facts is relative to the build root, which `-f`/`-p` - // can move away from cwd. - const factsPath = path.join(buildRoot, factsFileName) - // Not a name producers write, so a copy here is stale and would be uploaded - // alongside the new file. - const legacyFactsPath = path.join( - buildRoot, - constants.DOT_SOCKET_DOT_FACTS_JSON, - ) - if (existsSync(legacyFactsPath)) { - logger.warn( - `Found \`${legacyFactsPath}\`, which is uploaded alongside \`${factsFileName}\`. Delete it if an earlier \`socket manifest\` run left it behind.`, - ) - } - - const socketCliVersion = constants.ENV.INLINED_SOCKET_CLI_VERSION - if (facts.metadata && socketCliVersion) { - facts.metadata.socketCliVersion = socketCliVersion + return { + factsPath: result.factsPath, + projects: result.projects, + sidecarEntry: result.sidecarEntry, + targetPath: result.targetPath, } - await fs.writeFile(factsPath, JSON.stringify(facts), 'utf8') - - if (sidecarAcc) { - // Key by the symlink-resolved path so the sidecar's keys are comparable - // regardless of which caller's cwd it was joined against (the recursive - // discovery path already resolves symlinks before this point; the plain - // single-root path does not). - accumulateSidecar( - sidecarAcc, - facts, - artifactPaths, - await realpathOrResolved(factsPath), - !!withFiles, - ) - } - - logger.success('Generated Socket facts') - return { factsPath, projects: facts.projects ?? [] } } diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index e55a8892a1..2b8bcb3eb5 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -4,47 +4,27 @@ import path from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -vi.mock('./scripts/run.mts', () => ({ - runManifestScript: vi.fn(), +vi.mock('../../utils/coana/release.mts', () => ({ + spawnCoana: vi.fn(), })) -import { runManifestFacts } from './run-manifest-facts.mts' -import { runManifestScript } from './scripts/run.mts' -import constants from '../../constants.mts' +import { + keepFacts, + listBuildProjects, + listDotnetSolutionMembers, + runManifestFacts, +} from './run-manifest-facts.mts' +import { COANA_CLI_VERSION } from '../../constants.mts' +import { spawnCoana } from '../../utils/coana/release.mts' +import { logger } from '../../utils/logger.mts' -import type { ManifestRunResult } from './scripts/run.mts' -import type { SidecarAccumulator } from './scripts/sidecar.mts' +import type { SocketFactsWorkDir } from './run-manifest-facts.mts' -const ENV_VAR = 'SOCKET_TEST_JAVA_HOME' - -function okResult(buildRoot: string): ManifestRunResult { - return { - buildRoot, - code: 0, - facts: { - components: [{ id: 'a', type: 'maven', name: 'a' }], - projects: [], - }, - factsFileName: 'pom.xml.socket.facts.json', - report: { - failures: [], - resolvedModules: new Set(), - scannedConfigs: [], - unscannable: [], - }, - artifactPaths: { - pathsById: new Map(), - classpathByProject: new Map(), - directDependenciesByProject: new Map(), - }, - stderr: '', - stdout: '', - } -} +type Call = { args: string[]; request: any } const baseArgs = { bin: 'mvn', - buildOpts: [], + buildOpts: ['-Pci'], ecosystem: 'maven' as const, excludeConfigs: '', ignoreUnresolved: false, @@ -53,276 +33,402 @@ const baseArgs = { } let cwd = '' +let calls: Call[] = [] + +// Answers each Coana run by writing `text` as its result file, or nothing when +// `text` is undefined. +function coanaWrites(text: string | undefined, ok = true): void { + vi.mocked(spawnCoana).mockImplementation(async args => { + const list = [...args] + const request = JSON.parse( + await fs.readFile(list[list.indexOf('--request') + 1]!, 'utf8'), + ) + calls.push({ args: list, request }) + if (text !== undefined) { + await fs.writeFile(list[list.indexOf('--output-file') + 1]!, text) + } + return ok + ? { ok: true, data: '' } + : { ok: false, message: 'Coana command failed', cause: 'exit code 3' } + }) +} + +// Answers each Coana run with `result`, as `coana generate-socket-facts` writes +// it, or writes nothing when `result` is undefined. +function coanaAnswers(result: unknown, ok = true): void { + coanaWrites(result === undefined ? undefined : JSON.stringify(result), ok) +} beforeEach(async () => { - cwd = await fs.mkdtemp(path.join(tmpdir(), 'run-manifest-facts-')) - vi.mocked(runManifestScript).mockReset() + cwd = await fs.realpath( + await fs.mkdtemp(path.join(tmpdir(), 'run-manifest-facts-')), + ) + calls = [] + vi.mocked(spawnCoana).mockReset() process.exitCode = undefined }) afterEach(async () => { + vi.restoreAllMocks() await fs.rm(cwd, { recursive: true, force: true }) + delete process.env['SOCKET_CLI_MAVEN_PATH'] process.exitCode = undefined }) -describe('runManifestFacts - javaHome', () => { - beforeEach(() => { - delete process.env[ENV_VAR] - }) - afterEach(() => { - delete process.env[ENV_VAR] - }) - - it('passes a literal javaHome straight through as JAVA_HOME', async () => { - vi.mocked(runManifestScript).mockResolvedValue(okResult(cwd)) - await runManifestFacts({ ...baseArgs, cwd, javaHome: '/opt/jdk-17' }) - const opts = vi.mocked(runManifestScript).mock.calls[0]?.[1] - expect(opts?.env?.['JAVA_HOME']).toBe('/opt/jdk-17') - }) - - it('expands $VAR and ${VAR} references against the CLI process env', async () => { - process.env[ENV_VAR] = '/opt/jdk-11' - vi.mocked(runManifestScript).mockResolvedValue(okResult(cwd)) - await runManifestFacts({ - ...baseArgs, - cwd, - javaHome: `\${${ENV_VAR}}`, +describe('runManifestFacts', () => { + it('asks Coana for one build root with its options as written', async () => { + const projects = [{ buildFiles: [path.join(cwd, 'pom.xml')], dir: cwd }] + coanaAnswers({ + factsPath: path.join(cwd, 'pom.xml.socket.facts.json'), + projects, + status: 'generated', + targetPath: path.join(cwd, 'pom.xml.socket.facts.json'), }) - const opts = vi.mocked(runManifestScript).mock.calls[0]?.[1] - expect(opts?.env?.['JAVA_HOME']).toBe('/opt/jdk-11') - }) - - it('fails closed without invoking the build tool when the referenced var is unset', async () => { - vi.mocked(runManifestScript).mockResolvedValue(okResult(cwd)) const result = await runManifestFacts({ ...baseArgs, + context: { coanaVersion: '1.2.3', orgSlug: 'acme' }, cwd, - javaHome: `$${ENV_VAR}`, + entryFile: 'pom.xml', + excludeConfigs: 'test*', + excludePaths: ['docs/**'], + javaHome: '$JAVA11_HOME', + }) + expect(result).toEqual({ + factsPath: path.join(cwd, 'pom.xml.socket.facts.json'), + projects, + sidecarEntry: undefined, + targetPath: path.join(cwd, 'pom.xml.socket.facts.json'), + }) + expect(calls[0]!.args.slice(0, 1)).toEqual(['generate-socket-facts']) + expect(calls[0]!.args).not.toContain('--work-dir') + expect(calls[0]!.request).toEqual({ + buildRoot: cwd, + config: { + bin: 'mvn', + buildOpts: ['-Pci'], + excludeConfigs: 'test*', + ignoreUnresolved: false, + javaHome: '$JAVA11_HOME', + verbose: false, + }, + entryFile: 'pom.xml', + excludeBase: cwd, + excludePaths: ['docs/**'], + hints: { + excludePathsFlag: '--exclude-paths', + flags: ['excludeConfigs', 'ignoreUnresolved', 'verbose'], + setupCommand: 'socket manifest setup', + socketJson: 'socket.json', + }, + tool: 'maven', + }) + expect(vi.mocked(spawnCoana).mock.calls[0]![1]).toBe('acme') + expect(vi.mocked(spawnCoana).mock.calls[0]![2]).toMatchObject({ + coanaVersion: '1.2.3', + minimumVersion: COANA_CLI_VERSION, }) - expect(result).toBeNull() - expect(runManifestScript).not.toHaveBeenCalled() - expect(process.exitCode).toBe(1) }) - it('leaves the environment untouched when javaHome is unset', async () => { - vi.mocked(runManifestScript).mockResolvedValue(okResult(cwd)) + it("runs Coana in socket-cli's own cwd, so its logs show paths from there", async () => { + coanaAnswers({ status: 'empty' }) await runManifestFacts({ ...baseArgs, cwd }) - const opts = vi.mocked(runManifestScript).mock.calls[0]?.[1] - expect(opts?.env).toBeUndefined() - }) -}) - -describe('runManifestFacts - sidecar', () => { - it('keys the sidecar by the symlink-resolved factsPath, not the raw cwd-joined one', async () => { - const result = okResult(cwd) - result.facts.projects = [ - { - type: 'maven', - namespace: 'com.example', - name: 'app', - version: '1.0', - subprojectDir: '.', - children: [], - }, - ] - vi.mocked(runManifestScript).mockResolvedValue(result) - - const sidecarAcc: SidecarAccumulator = new Map() - await runManifestFacts({ ...baseArgs, cwd, sidecarAcc, withFiles: true }) - - const expectedFactsFile = await fs.realpath( - path.join(cwd, 'pom.xml.socket.facts.json'), - ) - expect([...sidecarAcc.keys()]).toEqual([expectedFactsFile]) - const bucket = sidecarAcc.get(expectedFactsFile) - expect(bucket?.projects.find(m => m.name === 'app')).toBeDefined() + expect(vi.mocked(spawnCoana).mock.calls[0]![2]?.cwd).toBeUndefined() }) - it('stamps the inlined socket-cli version into the written facts metadata', async () => { - const result = okResult(cwd) - result.facts.metadata = { - format: 'socket-facts-sbom', - tool: 'maven', - toolVersion: '3.9.9', - } - vi.mocked(runManifestScript).mockResolvedValue(result) + it('sends the SOCKET_CLI_*_PATH override as the bin', async () => { + const mvn = path.join(cwd, 'mvn') + await fs.writeFile(mvn, '', { mode: 0o755 }) + process.env['SOCKET_CLI_MAVEN_PATH'] = mvn + coanaAnswers({ status: 'empty' }) await runManifestFacts({ ...baseArgs, cwd }) + expect(calls[0]!.request.config.bin).toBe(mvn) + }) - const written = JSON.parse( - await fs.readFile(path.join(cwd, 'pom.xml.socket.facts.json'), 'utf8'), - ) - // Unit tests run unbuilt, where the version isn't inlined; the field is - // then omitted rather than written empty. - expect(written.metadata.socketCliVersion).toBe( - constants.ENV.INLINED_SOCKET_CLI_VERSION || undefined, + it('fails the root without running Coana when the bin cannot be resolved', async () => { + const fail = vi.spyOn(logger, 'fail') + process.env['SOCKET_CLI_MAVEN_PATH'] = path.join(cwd, 'missing-mvn') + expect(await runManifestFacts({ ...baseArgs, cwd })).toBeNull() + expect(process.exitCode).toBe(1) + expect(spawnCoana).not.toHaveBeenCalled() + expect(fail).toHaveBeenCalledWith( + expect.stringContaining('Could not run the maven build tool: '), ) }) -}) -describe('runManifestFacts - facts file naming', () => { - it('gives builds sharing a directory distinct facts files', async () => { - const sidecarAcc: SidecarAccumulator = new Map() - const outcomes = [] - for (const factsFileName of [ - 'pom.xml.socket.facts.json', - 'other-pom.xml.socket.facts.json', - ]) { - vi.mocked(runManifestScript).mockResolvedValueOnce({ - ...okResult(cwd), - factsFileName, - }) - // eslint-disable-next-line no-await-in-loop - outcomes.push(await runManifestFacts({ ...baseArgs, cwd, sidecarAcc })) + it('generates into the work dir with files for reachability, leaving the facts there', async () => { + const stateDir = path.join(cwd, 'state') + const entry = { + factsFile: path.join(cwd, 'pom.xml.socket.facts.json'), + stateDir, } - vi.mocked(runManifestScript).mockResolvedValueOnce({ - ...okResult(cwd), - factsFileName: 'gradle.socket.facts.json', + coanaAnswers({ + factsPath: path.join(stateDir, 'pom.xml.socket.facts.json'), + projects: [], + sidecarEntry: entry, + status: 'generated', + targetPath: entry.factsFile, }) - outcomes.push( - await runManifestFacts({ - ...baseArgs, - cwd, - ecosystem: 'gradle', - sidecarAcc, - }), - ) - - expect(outcomes.map(o => o && path.basename(o.factsPath))).toEqual([ - 'pom.xml.socket.facts.json', - 'other-pom.xml.socket.facts.json', - 'gradle.socket.facts.json', - ]) - expect((await fs.readdir(cwd)).sort()).toEqual([ - 'gradle.socket.facts.json', - 'other-pom.xml.socket.facts.json', - 'pom.xml.socket.facts.json', + const workDir: SocketFactsWorkDir = { + dir: '/w', + entries: new Map(), + withFiles: true, + } + const result = await runManifestFacts({ + ...baseArgs, + context: { workDir }, + cwd, + }) + expect(calls[0]!.args.slice(-3)).toEqual([ + '--with-files', + '--work-dir', + '/w', ]) - expect(sidecarAcc.size).toBe(3) + expect(result).toMatchObject({ sidecarEntry: entry }) + expect(workDir.entries.size).toBe(0) }) - it('writes the facts file into the build root the tool reports', async () => { - const buildRoot = path.join(cwd, 'sub') - await fs.mkdir(buildRoot) - vi.mocked(runManifestScript).mockResolvedValue({ - ...okResult(buildRoot), - factsFileName: 'other-pom.xml.socket.facts.json', + it('keeps state without installing files for socket fix', async () => { + coanaAnswers({ + factsPath: '/w/y/f', + projects: [], + sidecarEntry: { factsFile: '/r/f', stateDir: '/w/y' }, + status: 'generated', + targetPath: '/r/f', }) - - const outcome = await runManifestFacts({ ...baseArgs, cwd }) - - expect(outcome?.factsPath).toBe( - path.join(buildRoot, 'other-pom.xml.socket.facts.json'), - ) - expect(await fs.readdir(buildRoot)).toEqual([ - 'other-pom.xml.socket.facts.json', - ]) + const workDir = { dir: '/w', entries: new Map(), withFiles: false } + await runManifestFacts({ ...baseArgs, context: { workDir }, cwd }) + expect(calls[0]!.args.slice(-2)).toEqual(['--work-dir', '/w']) + expect(calls[0]!.args).not.toContain('--with-files') }) - it('fails without writing when the build did not report its root', async () => { - vi.mocked(runManifestScript).mockResolvedValue({ - ...okResult(cwd), - buildRoot: undefined, + it('fails when Coana keeps no sidecar entry in the work dir', async () => { + coanaAnswers({ + factsPath: '/w/y/f', + projects: [], + status: 'generated', + targetPath: '/r/f', }) + const workDir = { dir: '/w', entries: new Map(), withFiles: true } + expect( + await runManifestFacts({ ...baseArgs, context: { workDir }, cwd }), + ).toBeNull() + expect(process.exitCode).toBe(1) + }) - const outcome = await runManifestFacts({ ...baseArgs, cwd }) + it('is nothing to upload when the build resolves nothing', async () => { + coanaAnswers({ status: 'empty' }) + expect(await runManifestFacts({ ...baseArgs, cwd })).toBeUndefined() + expect(process.exitCode).toBeUndefined() + }) - expect(outcome).toBeNull() + it.for([ + { + name: 'reports a failed build, which Coana reports itself', + answer: () => coanaAnswers({ status: 'failed' }, false), + reported: undefined, + }, + { + name: 'writes no result, naming the build and the cause', + answer: () => coanaAnswers(undefined, false), + reported: (dir: string) => + `Could not generate Socket facts for the maven project at \`${path.join(dir, 'alt.pom.xml')}\`: Coana command failed`, + }, + { + name: 'writes an unreadable result', + answer: () => coanaWrites('{"status":"gener'), + reported: () => "Coana's result is unreadable", + }, + ])('fails the root when Coana $name', async ({ answer, reported }) => { + const fail = vi.spyOn(logger, 'fail') + answer() + + expect( + await runManifestFacts({ ...baseArgs, cwd, entryFile: 'alt.pom.xml' }), + ).toBeNull() expect(process.exitCode).toBe(1) - expect(await fs.readdir(cwd)).toEqual([]) + if (reported) { + expect(fail).toHaveBeenCalledWith(expect.stringContaining(reported(cwd))) + } else { + expect(fail).not.toHaveBeenCalled() + } }) - it('fails without writing when the build did not report its entry file', async () => { - vi.mocked(runManifestScript).mockResolvedValue({ - ...okResult(cwd), - factsFileName: undefined, - }) + it('does not run Coana outside an sbt build', async () => { + coanaAnswers({ status: 'empty' }) + expect( + await runManifestFacts({ + ...baseArgs, + bin: 'sbt', + cwd, + ecosystem: 'sbt', + }), + ).toBeNull() + expect(spawnCoana).not.toHaveBeenCalled() + }) +}) - const outcome = await runManifestFacts({ ...baseArgs, cwd }) +describe('keepFacts', () => { + it('copies the facts to their target and keeps the sidecar entry', async () => { + const factsPath = path.join(cwd, 'state', 'pom.xml.socket.facts.json') + const targetPath = path.join(cwd, 'pom.xml.socket.facts.json') + await fs.mkdir(path.dirname(factsPath)) + await fs.writeFile(factsPath, 'generated') + await fs.writeFile(targetPath, 'committed') + const sidecarEntry = { factsFile: targetPath, stateDir: '/w/x' } + const workDir = { dir: '/w', entries: new Map(), withFiles: true } + + await keepFacts(workDir, { + factsPath, + projects: [], + sidecarEntry, + targetPath, + }) - expect(outcome).toBeNull() - expect(process.exitCode).toBe(1) - expect(await fs.readdir(cwd)).toEqual([]) + expect(await fs.readFile(targetPath, 'utf8')).toBe('generated') + expect([...workDir.entries]).toEqual([[targetPath, sidecarEntry]]) }) - it('leaves a legacy .socket.facts.json in place', async () => { - const legacy = path.join(cwd, '.socket.facts.json') - await fs.writeFile(legacy, '{}') - vi.mocked(runManifestScript).mockResolvedValue(okResult(cwd)) + it('leaves facts Coana wrote in place where they are', async () => { + const targetPath = path.join(cwd, 'pom.xml.socket.facts.json') + await fs.writeFile(targetPath, 'generated') - await runManifestFacts({ ...baseArgs, cwd }) + await keepFacts(undefined, { + factsPath: targetPath, + projects: [], + targetPath, + }) - expect(await fs.readFile(legacy, 'utf8')).toBe('{}') - expect((await fs.readdir(cwd)).sort()).toEqual([ - '.socket.facts.json', - 'pom.xml.socket.facts.json', - ]) + expect(await fs.readFile(targetPath, 'utf8')).toBe('generated') }) }) -describe('runManifestFacts - sbt build detection', () => { - it('fails without running sbt when the directory has no sbt build', async () => { - const outcome = await runManifestFacts({ - ...baseArgs, +describe('listDotnetSolutionMembers', () => { + it('lists the members once for the same request', async () => { + coanaAnswers({ members: ['/r/A/A.csproj'] }) + const request = { + buildOpts: [], cwd, - ecosystem: 'sbt', + entryFile: 'All.sln', + javaHome: '$JAVA11_HOME', + } + expect(await listDotnetSolutionMembers(request)).toEqual(['/r/A/A.csproj']) + expect(await listDotnetSolutionMembers(request)).toEqual(['/r/A/A.csproj']) + expect(spawnCoana).toHaveBeenCalledOnce() + expect(calls[0]!.args).toContain('--list-members') + expect(calls[0]!.request).toEqual({ + buildRoot: cwd, + config: { + bin: 'dotnet', + buildOpts: [], + ignoreUnresolved: false, + javaHome: '$JAVA11_HOME', + verbose: false, + }, + entryFile: 'All.sln', + excludeBase: cwd, + hints: { + excludePathsFlag: '--exclude-paths', + flags: ['excludeConfigs', 'ignoreUnresolved', 'verbose'], + setupCommand: 'socket manifest setup', + socketJson: 'socket.json', + }, + tool: 'dotnet', }) - - expect(outcome).toBeNull() - expect(process.exitCode).toBe(1) - expect(runManifestScript).not.toHaveBeenCalled() - await expect( - fs.access(path.join(cwd, 'pom.xml.socket.facts.json')), - ).rejects.toThrow() }) - it.each(['build.sbt', 'project'])( - 'runs sbt when the directory has %s', - async marker => { - if (marker === 'project') { - await fs.mkdir(path.join(cwd, marker)) - } else { - await fs.writeFile(path.join(cwd, marker), '') - } - vi.mocked(runManifestScript).mockResolvedValue(okResult(cwd)) - - await runManifestFacts({ ...baseArgs, cwd, ecosystem: 'sbt' }) + it('cannot tell when the SDK cannot read the solution', async () => { + coanaAnswers({ members: null }) + expect( + await listDotnetSolutionMembers({ + buildOpts: [], + cwd, + entryFile: 'All.slnx', + }), + ).toBeUndefined() + }) - expect(runManifestScript).toHaveBeenCalledOnce() - }, - ) + it('lists nothing when Coana fails', async () => { + coanaAnswers(undefined, false) + expect( + await listDotnetSolutionMembers({ + buildOpts: [], + cwd, + entryFile: 'Broken.sln', + }), + ).toEqual([]) + }) }) -describe('runManifestFacts - crashed build', () => { - it('fails closed on a dotnet tool exit, whatever it recorded before', async () => { - vi.mocked(runManifestScript).mockResolvedValue({ - ...okResult(cwd), - code: 1, - factsFileName: 'App.sln.socket.facts.json', - stderr: 'socket-facts-dotnet: System.InvalidOperationException', +describe('listBuildProjects', () => { + const listArgs = { + bin: 'mvn', + buildOpts: ['-Pci'], + ecosystem: 'maven' as const, + verbose: false, + } + + it('asks Coana to list the build root, unresolved, with its options as written', async () => { + const projects = [{ buildFiles: [path.join(cwd, 'pom.xml')], dir: cwd }] + coanaAnswers({ buildRoot: cwd, projects, status: 'listed' }) + expect( + await listBuildProjects({ + ...listArgs, + cwd: path.join(cwd, 'reactor'), + entryFile: 'pom.xml', + excludeBase: cwd, + excludePaths: ['reactor/moduleB'], + javaHome: '$JAVA11_HOME', + }), + ).toEqual(projects) + expect(calls[0]!.args).toContain('--list-projects') + expect(calls[0]!.args).not.toContain('--work-dir') + expect(calls[0]!.request).toMatchObject({ + buildRoot: path.join(cwd, 'reactor'), + config: { + bin: 'mvn', + buildOpts: ['-Pci'], + ignoreUnresolved: false, + javaHome: '$JAVA11_HOME', + verbose: false, + }, + entryFile: 'pom.xml', + excludeBase: cwd, + excludePaths: ['reactor/moduleB'], + tool: 'maven', }) + }) - const outcome = await runManifestFacts({ - ...baseArgs, - bin: 'dotnet', + it('lists with the Coana version and org of its context', async () => { + coanaAnswers({ projects: [], status: 'listed' }) + await listBuildProjects({ + ...listArgs, + context: { coanaVersion: '1.2.3', orgSlug: 'acme' }, cwd, - ecosystem: 'dotnet', - entryFile: 'App.sln', - ignoreUnresolved: true, }) + expect(spawnCoana).toHaveBeenCalledWith( + expect.arrayContaining(['--list-projects']), + 'acme', + expect.objectContaining({ coanaVersion: '1.2.3' }), + ) + }) - expect(outcome).toBeNull() - expect(process.exitCode).toBe(1) - expect(await fs.readdir(cwd)).toEqual([]) + it('lists nothing without running Coana when the bin cannot be resolved', async () => { + process.env['SOCKET_CLI_MAVEN_PATH'] = path.join(cwd, 'missing-mvn') + expect(await listBuildProjects({ ...listArgs, cwd })).toBeUndefined() + expect(spawnCoana).not.toHaveBeenCalled() }) - it('keeps what a JVM build resolved before a non-zero exit', async () => { - vi.mocked(runManifestScript).mockResolvedValue({ - ...okResult(cwd), - code: 1, - }) + it('lists nothing when the build cannot list its projects', async () => { + coanaAnswers({ status: 'failed' }, false) + expect(await listBuildProjects({ ...listArgs, cwd })).toBeUndefined() + }) - const outcome = await runManifestFacts({ ...baseArgs, cwd }) + it('lists nothing when Coana writes no result', async () => { + coanaAnswers(undefined, false) + expect(await listBuildProjects({ ...listArgs, cwd })).toBeUndefined() + }) - expect(outcome?.factsPath).toBe(path.join(cwd, 'pom.xml.socket.facts.json')) - expect(process.exitCode).toBeUndefined() + it('lists nothing when Coana writes an unreadable result', async () => { + coanaWrites('') + expect(await listBuildProjects({ ...listArgs, cwd })).toBeUndefined() }) }) diff --git a/src/commands/manifest/scripts/build-tool.mts b/src/commands/manifest/scripts/build-tool.mts index 20c4a5651b..7e92da93d9 100644 --- a/src/commands/manifest/scripts/build-tool.mts +++ b/src/commands/manifest/scripts/build-tool.mts @@ -4,12 +4,13 @@ import { constants as fsConstants, statSync, } from 'node:fs' -import { basename, resolve } from 'node:path' +import { basename, join, resolve } from 'node:path' import constants from '../../../constants.mts' import type { FactsOnlyTypes } from '../../../utils/coana.mts' import type { PURL_Type } from '../../../utils/ecosystem.mts' +import type { BuildRoot } from '../discover-manifest-roots.mts' export type BuildTool = 'dotnet' | 'gradle' | 'maven' | 'sbt' @@ -37,6 +38,10 @@ export const FACTS_PURL_TYPES = [ ...new Set(Object.values(PURL_TYPE_BY_TOOL)), ].sort() as unknown as FactsOnlyTypes +export function buildRootPath(root: BuildRoot): string { + return join(root.dir, root.entryFile ?? '') +} + export function buildToolsFor(purlTypes: readonly PURL_Type[]): BuildTool[] { return BUILD_TOOLS.filter(tool => purlTypes.includes(PURL_TYPE_BY_TOOL[tool])) } diff --git a/src/commands/manifest/setup-recursive-manifest-config.mts b/src/commands/manifest/setup-recursive-manifest-config.mts index ca6cdfdf38..400ded19a3 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.mts @@ -21,11 +21,12 @@ import { } from './discover-manifest-roots.mts' import { buildToolScriptOptions, - resolveEcosystemConfig, + resolveWalkConfig, + socketFactsRunOptions, } from './generate-recursive-manifests.mts' import { loadBuild, withModules } from './load-build.mts' +import { DSI_SETUP_COMMAND, EXCLUDE_PATHS_FLAG } from './run-manifest-facts.mts' import { BUILD_FILES, ECOSYSTEM_LABELS } from './scripts/build-tool.mts' -import { DSI_SETUP_COMMAND } from './scripts/resolution-report-render.mts' import { setupDotnet, setupGradle, @@ -397,7 +398,7 @@ function membershipFor( } function buildConfig(walk: Walk, { ecosystem, root }: WalkBuild) { - return resolveEcosystemConfig( + return resolveWalkConfig( ecosystem, root.dir, resolveDraftSettings(walk.draft, ecosystem, root).sockJson, @@ -626,14 +627,21 @@ async function loadOrAsk( allowDirectory = true, ): Promise> { for (;;) { + const config = buildConfig(walk, build) // eslint-disable-next-line no-await-in-loop const loaded = await loadBuild({ - config: buildConfig(walk, build), - ecosystem: build.ecosystem, - excludePaths: walk.excludePaths, - root: build.root, + ...socketFactsRunOptions(build.ecosystem, build.root, config, { + excludeBase: walk.cwd, + excludePaths: walk.excludePaths, + // A failure's remedy is this wizard's answers, for the scan to read. + hints: { + excludePathsFlag: EXCLUDE_PATHS_FLAG, + flags: new Set(), + setupCommand: DSI_SETUP_COMMAND, + socketJson: socketJsonPath(build.root.dir), + }, + }), scanRoot: walk.cwd, - verbose: false, }) if (loaded) { return { ok: true, data: { canceled: false, loaded } } diff --git a/src/commands/manifest/setup-recursive-manifest-config.test.mts b/src/commands/manifest/setup-recursive-manifest-config.test.mts index 93550bab0f..ba46539ee3 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.test.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.test.mts @@ -12,8 +12,9 @@ vi.mock('./discover-manifest-roots.mts', async importOriginal => { findBuildToolCandidates: vi.fn(actual.findBuildToolCandidates), } }) -vi.mock('./enumerate-workspaces.mts', () => ({ - enumerateWorkspaces: vi.fn(), +vi.mock('./run-manifest-facts.mts', async importOriginal => ({ + ...(await importOriginal()), + listBuildProjects: vi.fn(), })) vi.mock('../../utils/prompts.mts', () => ({ select: vi.fn(), @@ -26,7 +27,7 @@ vi.mock('./setup-manifest-config.mts', () => ({ })) import { findBuildToolCandidates } from './discover-manifest-roots.mts' -import { enumerateWorkspaces } from './enumerate-workspaces.mts' +import { listBuildProjects } from './run-manifest-facts.mts' import { setupMaven } from './setup-manifest-config.mts' import { discoverBuildRoots, @@ -37,7 +38,7 @@ import { logger } from '../../utils/logger.mts' import { select } from '../../utils/prompts.mts' import type { BuildRoot } from './discover-manifest-roots.mts' -import type { SocketFactsSbomProject } from './scripts/facts.mts' +import type { SocketFactsProject } from './run-manifest-facts.mts' import type { SocketJson } from '../../utils/socket-json.mts' function dirRoots(...dirs: string[]): BuildRoot[] { @@ -48,15 +49,14 @@ function mavenRoots(...dirs: string[]): BuildRoot[] { return dirs.map(dir => ({ dir, entryFile: 'pom.xml' })) } -function project(subprojectDir: string): SocketFactsSbomProject { - return { - type: 'maven', - name: subprojectDir, - id: subprojectDir, - subprojectDir, - manifestFiles: [{ file: `${subprojectDir}/pom.xml` }], - children: [], - } +// A Maven project of the build at `buildRoot`, loaded from `pomFile`. +function project( + buildRoot: string, + subprojectDir: string, + pomFile = 'pom.xml', +): SocketFactsProject { + const dir = path.resolve(buildRoot, subprojectDir) + return { buildFiles: [path.join(dir, pomFile)], dir } } describe('scanBuildRoots', () => { @@ -187,7 +187,7 @@ describe('setupRecursiveManifestConfig', () => { // listed as undefined can't be loaded. const loads = (modules: Record) => vi - .mocked(enumerateWorkspaces) + .mocked(listBuildProjects) .mockImplementation(async ({ cwd, entryFile }) => { const rel = path .relative(repo, path.join(cwd, entryFile ?? '')) @@ -196,16 +196,10 @@ describe('setupRecursiveManifestConfig', () => { if (rel in modules && !modules[rel]) { return undefined } - return { - buildRoot: cwd, - projects: [ - { - ...project('.'), - manifestFiles: [{ file: entryFile ?? 'pom.xml' }], - }, - ...(modules[rel] ?? []).map(project), - ], - } + return [ + project(cwd, '.', entryFile), + ...(modules[rel] ?? []).map(dir => project(cwd, dir)), + ] }) const answer = (answers: Answers) => vi.mocked(select).mockImplementation(async ({ choices, message }) => { @@ -239,7 +233,7 @@ describe('setupRecursiveManifestConfig', () => { // eslint-disable-next-line no-await-in-loop await fs.writeFile(file(rel), '') } - vi.mocked(enumerateWorkspaces).mockReset() + vi.mocked(listBuildProjects).mockReset() vi.mocked(setupMaven).mockReset() vi.spyOn(logger, 'log').mockImplementation(() => logger) vi.spyOn(logger, 'info').mockImplementation(() => logger) @@ -332,11 +326,11 @@ describe('setupRecursiveManifestConfig', () => { it('loads a build again after configuring it, and skips it once it loads', async () => { let attempts = 0 - vi.mocked(enumerateWorkspaces).mockImplementation(async ({ cwd }) => { + vi.mocked(listBuildProjects).mockImplementation(async ({ cwd }) => { if (cwd === file('legacy') && (attempts += 1) === 1) { return undefined } - return { buildRoot: cwd, projects: [project('.')] } + return [project(cwd, '.')] }) vi.mocked(setupMaven).mockImplementation(async config => { config.javaHome = '/opt/jdk-8' @@ -356,6 +350,19 @@ describe('setupRecursiveManifestConfig', () => { await setupRecursiveManifestConfig(repo, false) expect(attempts).toBe(2) + // A listing's remedies point at this wizard, not at flags. + expect( + vi + .mocked(listBuildProjects) + .mock.calls.map(([{ hints }]) => [hints?.setupCommand, hints?.flags]), + ).toEqual( + vi + .mocked(listBuildProjects) + .mock.calls.map(() => [ + 'socket manifest setup --dynamic-sbom-inference', + new Set(), + ]), + ) expect(await readSettings('legacy')).toMatchObject({ defaults: { manifest: { diff --git a/src/commands/scan/cmd-scan-create.mts b/src/commands/scan/cmd-scan-create.mts index 481edee7b5..dcee43b954 100644 --- a/src/commands/scan/cmd-scan-create.mts +++ b/src/commands/scan/cmd-scan-create.mts @@ -47,6 +47,7 @@ import { hasDefaultApiToken } from '../../utils/sdk.mts' import { readOrDefaultSocketJsonUp } from '../../utils/socket-json.mts' import { socketDashboardLink } from '../../utils/terminal-link.mts' import { detectManifestActions } from '../manifest/detect-manifest-actions.mts' +import { EXCLUDE_PATHS_FLAG } from '../manifest/run-manifest-facts.mts' import type { REPORT_LEVEL } from './types.mts' import type { MeowFlags } from '../../flags.mts' @@ -681,6 +682,7 @@ async function run( committers: (committers && String(committers)) || '', cwd, defaultBranch: Boolean(defaultBranch), + excludePathsFlag: EXCLUDE_PATHS_FLAG, generateScanFiles: uvMemberDirs ? () => generateUvMemberSboms(uvMemberDirs) : undefined, diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index d9af8e8cea..f95e2e2962 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -1,4 +1,4 @@ -import { unlink } from 'node:fs/promises' +import { mkdir, unlink } from 'node:fs/promises' import path from 'node:path' import micromatch from 'micromatch' @@ -32,7 +32,6 @@ import { pluralize } from '../../utils/words.mts' import { detectManifestActions } from '../manifest/detect-manifest-actions.mts' import { generateAutoManifest } from '../manifest/generate_auto_manifest.mts' import { buildToolsFor } from '../manifest/scripts/build-tool.mts' -import { mergeResolvedPathsSidecars } from '../manifest/scripts/sidecar.mts' import type { ReachabilityFallback } from './output-create-new-scan.mts' import type { ReachabilityOptions } from './perform-reachability-analysis.mts' @@ -40,7 +39,7 @@ import type { REPORT_LEVEL } from './types.mts' import type { OutputKind } from '../../types.mts' import type { FactsOnlyTypes } from '../../utils/coana.mts' import type { Remap } from '../../utils/objects.mts' -import type { ResolvedPathsSidecar } from '../manifest/scripts/sidecar.mts' +import type { SocketFactsContext } from '../manifest/run-manifest-facts.mts' import type { SocketSdkSuccessResult } from '@socketsecurity/sdk' // Supported-files response keys whose files count as pre-generated SBOMs: @@ -91,6 +90,8 @@ export type HandleCreateNewScanConfig = { committers: string cwd: string defaultBranch: boolean + // The invoking command's flag for `reach.excludePaths`, when it takes one. + excludePathsFlag?: string | undefined // Supplies the complete scan input and replaces manifest discovery. generateScanFiles?: (() => Promise) | undefined interactive: boolean @@ -122,6 +123,7 @@ async function createNewScan( committers, cwd, defaultBranch, + excludePathsFlag, interactive, orgSlug, outputKind, @@ -160,17 +162,26 @@ async function createNewScan( workspace, }) - // Sidecar forwarded to reachability; populated only when reach runs. - let resolvedPathsSidecar: ResolvedPathsSidecar | undefined let factsOnlyTypes: FactsOnlyTypes | undefined let discardedFactsPaths: string[] | undefined - // sbt provisions its Scala toolchain under the directory passed as its - // isolated global base; reach's artifactPaths point into it, so it must - // stay on disk until the reachability analysis below has consumed those - // paths. Always allocated (even when unused) to keep this uniform rather - // than conditional on autoManifest/reach. + // Coana's reachability run reads what facts generation keeps in the work + // dir, so it lives until the analysis below is done. await withTmpDir('socket-auto-manifest-', async manifestTmpDir => { + const factsContext: SocketFactsContext = { + coanaVersion: reach.reachVersion, + orgSlug, + workDir: reach.runReachabilityAnalysis + ? { + dir: path.join(manifestTmpDir, 'socket-facts-work'), + entries: new Map(), + withFiles: true, + } + : undefined, + } + if (factsContext.workDir) { + await mkdir(factsContext.workDir.dir) + } if (autoManifest || reach.dynamicSbomInference) { logger.info('Auto-generating manifest files ...') debugFn('notice', 'Manifest auto-generation enabled') @@ -181,21 +192,17 @@ async function createNewScan( // one at cwd. This runs on its own, so nothing outside those // ecosystems is generated unless --auto-manifest also asked for it. const dynamicResult = await runDynamicSbomInference({ - consumer: reach.runReachabilityAnalysis ? 'reach' : 'upload', + ...(factsContext.workDir + ? { consumer: 'reach', workDir: factsContext.workDir } + : { consumer: 'upload' }), + context: factsContext, cwd, excludePaths: reach.excludePaths, purlTypes: reach.dynamicSbomInference, - // sbt's Scala toolchain lives under its shared global base; - // reach's artifactPaths point into it, so when reachability - // will consume them afterward, reuse manifestTmpDir (kept alive - // until reach finishes below) instead of letting the call clean - // its own ephemeral base up before reach ever reads those paths. - sbtTmpDir: manifestTmpDir, }) scanTargets = Array.from( new Set([...scanTargets, ...dynamicResult.factsPaths]), ) - resolvedPathsSidecar = dynamicResult.resolvedPathsSidecar factsOnlyTypes = dynamicResult.factsOnlyTypes discardedFactsPaths = dynamicResult.discardedFactsPaths } @@ -214,22 +221,14 @@ async function createNewScan( } const autoManifestResult = await generateAutoManifest({ - computeArtifactsSidecar: reach.runReachabilityAnalysis, + context: factsContext, cwd, detected, excludePaths: reach.excludePaths, + excludePathsFlag, outputKind, - tmpDir: manifestTmpDir, verbose: false, }) - if (autoManifestResult.resolvedPathsSidecar) { - resolvedPathsSidecar = resolvedPathsSidecar - ? mergeResolvedPathsSidecars( - resolvedPathsSidecar, - autoManifestResult.resolvedPathsSidecar, - ) - : autoManifestResult.resolvedPathsSidecar - } if (autoManifestResult.generatedFiles.length) { scanTargets = Array.from( new Set([...scanTargets, ...autoManifestResult.generatedFiles]), @@ -343,7 +342,9 @@ async function createNewScan( packagePaths, reachabilityOptions: mergedReachabilityOptions, repoName, - resolvedPathsSidecar, + socketFactsSidecar: factsContext.workDir && [ + ...factsContext.workDir.entries.values(), + ], spinner, target: targets[0]!, }) diff --git a/src/commands/scan/handle-create-new-scan.test.mts b/src/commands/scan/handle-create-new-scan.test.mts index f7d23a6025..038fcd5161 100644 --- a/src/commands/scan/handle-create-new-scan.test.mts +++ b/src/commands/scan/handle-create-new-scan.test.mts @@ -389,9 +389,8 @@ describe('handleCreateNewScan excludePaths', () => { expect(mockGenerateRecursiveManifests).toHaveBeenCalledWith( expect.objectContaining({ + context: expect.objectContaining({ workDir: undefined }), cwd: '/repo', - sbtTmpDir: undefined, - withFiles: false, }), ) expect(mockGenerateAutoManifest).toHaveBeenCalledWith( @@ -489,24 +488,16 @@ describe('handleCreateNewScan excludePaths', () => { expect(mockGetPackageFilesForScan).toHaveBeenCalled() }) - it('accumulates a sidecar across recursively discovered build roots and forwards it to reachability analysis', async () => { + it('collects what Coana kept of each build root and forwards it to reachability analysis', async () => { + const entry = { + factsFile: '/repo/service-a/.socket.facts.json', + stateDir: '/work/a', + } + let workDirExisted = false mockGenerateRecursiveManifests.mockImplementationOnce( - async ({ sidecarAcc }) => { - sidecarAcc?.set('/repo/service-a/.socket.facts.json', { - projects: [ - { - type: 'maven', - namespace: 'com.example', - name: 'app', - version: '1.0', - subprojectDir: '.', - dependencies: [], - targets: ['/repo/service-a/build/classes'], - sources: ['/repo/service-a/src/main/java'], - }, - ], - components: [], - }) + async ({ context }) => { + workDirExisted = existsSync(context.workDir.dir) + context.workDir.entries.set(entry.factsFile, entry) return [ { dir: '/repo/service-a', @@ -524,21 +515,17 @@ describe('handleCreateNewScan excludePaths', () => { await handleCreateNewScan(config) + expect(workDirExisted).toBe(true) expect(mockGenerateRecursiveManifests).toHaveBeenCalledWith( expect.objectContaining({ - sbtTmpDir: expect.any(String), - withFiles: true, + context: expect.objectContaining({ + orgSlug: config.orgSlug, + workDir: expect.objectContaining({ withFiles: true }), + }), }), ) expect(mockPerformReachabilityAnalysis).toHaveBeenCalledWith( - expect.objectContaining({ - resolvedPathsSidecar: { - '/repo/service-a/.socket.facts.json': { - projects: [expect.objectContaining({ name: 'app' })], - components: [], - }, - }, - }), + expect.objectContaining({ socketFactsSidecar: [entry] }), ) }) diff --git a/src/commands/scan/handle-scan-reach.mts b/src/commands/scan/handle-scan-reach.mts index 698a092c72..8e547f23b4 100644 --- a/src/commands/scan/handle-scan-reach.mts +++ b/src/commands/scan/handle-scan-reach.mts @@ -16,8 +16,12 @@ import { getPackageFilesForScan } from '../../utils/path-resolve.mts' import { pluralize } from '../../utils/words.mts' import type { ReachabilityOptions } from './perform-reachability-analysis.mts' -import type { DynamicSbomInferenceResult } from './run-dynamic-sbom-inference.mts' +import type { + DynamicSbomInferenceResult, + KeptRootsDir, +} from './run-dynamic-sbom-inference.mts' import type { OutputKind } from '../../types.mts' +import type { FactsOnlyTypes } from '../../utils/coana.mts' export type HandleScanReachConfig = { cwd: string @@ -39,7 +43,9 @@ async function runScanReach( reachabilityOptions, targets, }: HandleScanReachConfig, - sbtTmpDir: string | undefined, + // The ecosystems --dynamic-sbom-inference generates facts for, with the + // work dir Coana's run reads. + dsi: { purlTypes: FactsOnlyTypes; workDir: KeptRootsDir } | undefined, ) { const { spinner } = constants @@ -48,14 +54,15 @@ async function runScanReach( let scanTargets = targets let dynamicResult: DynamicSbomInferenceResult | undefined - if (reachabilityOptions.dynamicSbomInference) { + if (dsi) { logger.info('Generating Socket facts for each build root ...') dynamicResult = await runDynamicSbomInference({ consumer: 'reach', + context: { coanaVersion: reachabilityOptions.reachVersion, orgSlug }, cwd, excludePaths: reachabilityOptions.excludePaths, - purlTypes: reachabilityOptions.dynamicSbomInference, - sbtTmpDir, + purlTypes: dsi.purlTypes, + workDir: dsi.workDir, }) scanTargets = Array.from( new Set([...scanTargets, ...dynamicResult.factsPaths]), @@ -133,7 +140,7 @@ async function runScanReach( outputPath, packagePaths, reachabilityOptions: mergedReachabilityOptions, - resolvedPathsSidecar: dynamicResult?.resolvedPathsSidecar, + socketFactsSidecar: dsi && [...dsi.workDir.entries.values()], spinner, target: targets[0]!, }) @@ -162,12 +169,14 @@ async function runScanReach( export async function handleScanReach( config: HandleScanReachConfig, ): Promise { - // sbt provisions its Scala toolchain under the directory passed as its - // isolated global base; the sidecar's artifactPaths point into it, so it - // must stay on disk until the reachability analysis has consumed them. - return config.reachabilityOptions.dynamicSbomInference - ? await withTmpDir('socket-dynamic-sbom-inference-', tmpDir => - runScanReach(config, tmpDir), + const purlTypes = config.reachabilityOptions.dynamicSbomInference + // Coana's run reads what facts generation keeps in the work dir. + return purlTypes + ? await withTmpDir('socket-dynamic-sbom-inference-', dir => + runScanReach(config, { + purlTypes, + workDir: { dir, entries: new Map() }, + }), ) : await runScanReach(config, undefined) } diff --git a/src/commands/scan/handle-scan-reach.test.mts b/src/commands/scan/handle-scan-reach.test.mts index e70c710b4c..a03f965710 100644 --- a/src/commands/scan/handle-scan-reach.test.mts +++ b/src/commands/scan/handle-scan-reach.test.mts @@ -112,10 +112,7 @@ describe('handleScanReach', () => { tier1ReachabilityScanId: undefined, }, }) - mockRunDynamicSbomInference.mockResolvedValue({ - factsPaths: [], - resolvedPathsSidecar: undefined, - }) + mockRunDynamicSbomInference.mockResolvedValue({ factsPaths: [] }) }) it('applies excludePaths to manifest discovery and reachability analysis', async () => { @@ -353,20 +350,23 @@ describe('handleScanReach', () => { excludePaths: ['vendor/**'], } - it('generates per-build-root facts, merges them into manifest discovery, and forwards the sidecar', async () => { - mockRunDynamicSbomInference.mockResolvedValueOnce({ - factsOnlyTypes: ['maven'], - factsPaths: [ - '/repo/service-a/.socket.facts.json', - '/repo/service-b/.socket.facts.json', - ], - resolvedPathsSidecar: { - '/repo/service-a/.socket.facts.json': { - projects: [], - components: [], - }, + it('generates per-build-root facts, merges them into manifest discovery, and forwards what Coana kept of them', async () => { + const entry = { + factsFile: '/repo/service-a/.socket.facts.json', + stateDir: '/work/a', + } + mockRunDynamicSbomInference.mockImplementationOnce( + async ({ workDir }) => { + workDir.entries.set(entry.factsFile, entry) + return { + factsOnlyTypes: ['maven'], + factsPaths: [ + '/repo/service-a/.socket.facts.json', + '/repo/service-b/.socket.facts.json', + ], + } }, - }) + ) await handleScanReach({ cwd: '/repo', @@ -380,11 +380,18 @@ describe('handleScanReach', () => { expect(mockRunDynamicSbomInference).toHaveBeenCalledWith({ consumer: 'reach', + context: { + coanaVersion: baseReachabilityOptions.reachVersion, + orgSlug: 'fakeOrg', + }, cwd: '/repo', excludePaths: ['vendor/**'], purlTypes: ['maven', 'nuget'], - // A caller-owned dir that outlives the analysis consuming its paths. - sbtTmpDir: expect.any(String), + // A caller-owned dir that outlives the analysis reading it. + workDir: { + dir: expect.any(String), + entries: new Map([[entry.factsFile, entry]]), + }, }) expect(mockGetPackageFilesForScan).toHaveBeenCalledWith( [ @@ -398,12 +405,7 @@ describe('handleScanReach', () => { expect(mockPerformReachabilityAnalysis).toHaveBeenCalledWith( expect.objectContaining({ factsOnlyTypes: ['maven'], - resolvedPathsSidecar: { - '/repo/service-a/.socket.facts.json': { - projects: [], - components: [], - }, - }, + socketFactsSidecar: [entry], // The reachability target stays the user's own, never a facts file. target: '/repo', }), @@ -475,7 +477,7 @@ describe('handleScanReach', () => { expect(mockRunDynamicSbomInference).not.toHaveBeenCalled() expect(mockPerformReachabilityAnalysis).toHaveBeenCalledWith( - expect.objectContaining({ resolvedPathsSidecar: undefined }), + expect.objectContaining({ socketFactsSidecar: undefined }), ) }) }) diff --git a/src/commands/scan/perform-reachability-analysis.mts b/src/commands/scan/perform-reachability-analysis.mts index 1c77aaf411..4a9a03558e 100644 --- a/src/commands/scan/perform-reachability-analysis.mts +++ b/src/commands/scan/perform-reachability-analysis.mts @@ -16,14 +16,13 @@ import { logger } from '../../utils/logger.mts' import { hasEnterpriseOrgPlan } from '../../utils/organization.mts' import { setupSdk } from '../../utils/sdk.mts' import { socketDevLink } from '../../utils/terminal-link.mts' -import { hasResolvedPathsSidecarEntries } from '../manifest/scripts/sidecar.mts' import { fetchOrganization } from '../organization/fetch-organization-list.mts' import type { CResult, OutputKind } from '../../types.mts' import type { FactsOnlyTypes } from '../../utils/coana.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' import type { Spinner } from '../../utils/spinner.mts' -import type { ResolvedPathsSidecar } from '../manifest/scripts/sidecar.mts' +import type { SocketFactsSidecarEntry } from '../manifest/run-manifest-facts.mts' import type { StdioOptions } from 'node:child_process' export type ReachabilityOptions = { @@ -63,10 +62,9 @@ export type ReachabilityAnalysisOptions = { outputPath?: string | undefined packagePaths: string[] reachabilityOptions: ReachabilityOptions - // Resolved-paths sidecar from the auto-manifest run; passed to coana so it - // reuses these paths instead of re-resolving the build. - resolvedPathsSidecar?: ResolvedPathsSidecar | undefined repoName?: string | undefined + // What facts generation kept of each build root, for Coana to read back. + socketFactsSidecar?: SocketFactsSidecarEntry[] | undefined spinner?: Spinner | undefined target: string } @@ -88,7 +86,7 @@ export async function performReachabilityAnalysis( packagePaths, reachabilityOptions, repoName, - resolvedPathsSidecar, + socketFactsSidecar, spinner, target, } = { __proto__: null, ...options } as ReachabilityAnalysisOptions @@ -189,20 +187,16 @@ export async function performReachabilityAnalysis( spinner?.start() spinner?.infoAndStop('Running reachability analysis with Coana...') - // Temp file for --compute-artifacts-sidecar, removed in the finally below. + // Temp file for --socket-facts-sidecar, removed in the finally below. // Written even when empty with factsOnlyTypes: `coana run` rejects the // facts-only flag without one. let sidecarPath: string | undefined - if ( - factsOnlyTypes || - (resolvedPathsSidecar && - hasResolvedPathsSidecarEntries(resolvedPathsSidecar)) - ) { + if (factsOnlyTypes || socketFactsSidecar?.length) { sidecarPath = path.join( tmpdir(), - `socket-compute-artifacts-sidecar-${randomUUID()}.json`, + `socket-facts-sidecar-${randomUUID()}.json`, ) - await fs.writeFile(sidecarPath, JSON.stringify(resolvedPathsSidecar ?? {})) + await fs.writeFile(sidecarPath, JSON.stringify(socketFactsSidecar ?? [])) } // Build Coana arguments. @@ -268,7 +262,7 @@ export async function performReachabilityAnalysis( ...(reachabilityOptions.reachUseOnlyPregeneratedSboms ? ['--use-only-pregenerated-sboms'] : []), - ...(sidecarPath ? ['--compute-artifacts-sidecar', sidecarPath] : []), + ...(sidecarPath ? ['--socket-facts-sidecar', sidecarPath] : []), ] // In machine-readable modes (--json/--markdown) the final payload is written diff --git a/src/commands/scan/perform-reachability-analysis.test.mts b/src/commands/scan/perform-reachability-analysis.test.mts index 4e584928ef..7f2ea49801 100644 --- a/src/commands/scan/perform-reachability-analysis.test.mts +++ b/src/commands/scan/perform-reachability-analysis.test.mts @@ -357,29 +357,29 @@ describe('performReachabilityAnalysis --use-only-socket-facts-artifacts gating', rmSync(scanCwd, { force: true, recursive: true }) }) - const sidecar = { - '/repo/reactor/.socket.facts.json': { components: [], projects: [] }, - } + const sidecar = [ + { factsFile: '/repo/reactor/.socket.facts.json', stateDir: '/work/r' }, + ] it.for([ { name: 'names every facts-only type next to the sidecar', factsOnlyTypes: ['maven', 'nuget'], - resolvedPathsSidecar: sidecar, + socketFactsSidecar: sidecar, expected: ['--use-only-socket-facts-artifacts', 'maven,nuget'], expectedSidecar: sidecar, }, { name: 'keeps the Maven-only flag older Coana releases know, with an empty sidecar', factsOnlyTypes: ['maven'], - resolvedPathsSidecar: undefined, + socketFactsSidecar: undefined, expected: ['--maven-use-only-socket-facts'], - expectedSidecar: {}, + expectedSidecar: [], }, { name: 'passes no facts-only flag without facts-only types, even with a sidecar', factsOnlyTypes: undefined, - resolvedPathsSidecar: sidecar, + socketFactsSidecar: sidecar, expected: [], expectedSidecar: sidecar, }, @@ -389,12 +389,11 @@ describe('performReachabilityAnalysis --use-only-socket-facts-artifacts gating', expected, expectedSidecar, factsOnlyTypes, - resolvedPathsSidecar, + socketFactsSidecar, }) => { let sidecarAtSpawn: unknown mockSpawnCoana.mockImplementationOnce(async (args: string[]) => { - const sidecarPath = - args[args.indexOf('--compute-artifacts-sidecar') + 1]! + const sidecarPath = args[args.indexOf('--socket-facts-sidecar') + 1]! sidecarAtSpawn = JSON.parse(readFileSync(sidecarPath, 'utf8')) return { ok: true, data: '' } }) @@ -402,7 +401,7 @@ describe('performReachabilityAnalysis --use-only-socket-facts-artifacts gating', const args = await coanaArgsFor( scanCwd, {}, - { factsOnlyTypes, resolvedPathsSidecar }, + { factsOnlyTypes, socketFactsSidecar }, ) expect(factsOnlyArgs(args)).toEqual(expected) @@ -414,7 +413,7 @@ describe('performReachabilityAnalysis --use-only-socket-facts-artifacts gating', const args = await coanaArgsFor(scanCwd, { dynamicSbomInference: ['maven', 'nuget'], }) - expect(args).not.toContain('--compute-artifacts-sidecar') + expect(args).not.toContain('--socket-facts-sidecar') }) }) diff --git a/src/commands/scan/run-dynamic-sbom-inference.mts b/src/commands/scan/run-dynamic-sbom-inference.mts index fbbee8fe84..857e363c99 100644 --- a/src/commands/scan/run-dynamic-sbom-inference.mts +++ b/src/commands/scan/run-dynamic-sbom-inference.mts @@ -6,30 +6,33 @@ import { InputError } from '../../utils/errors.mts' import { realpathOrResolved } from '../../utils/fs.mts' import { logger } from '../../utils/logger.mts' import { generateRecursiveManifests } from '../manifest/generate-recursive-manifests.mts' +import { DSI_SETUP_COMMAND } from '../manifest/run-manifest-facts.mts' import { PURL_TYPE_BY_TOOL, buildToolLabelsFor, } from '../manifest/scripts/build-tool.mts' -import { DSI_SETUP_COMMAND } from '../manifest/scripts/resolution-report-render.mts' -import { - hasSidecarEntries, - serializeSidecar, -} from '../manifest/scripts/sidecar.mts' import type { FactsOnlyTypes } from '../../utils/coana.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' import type { RecursiveManifestOutcome } from '../manifest/generate-recursive-manifests.mts' import type { - ResolvedPathsSidecar, - SidecarAccumulator, -} from '../manifest/scripts/sidecar.mts' + SocketFactsContext, + SocketFactsWorkDir, +} from '../manifest/run-manifest-facts.mts' const DSI_SETTINGS_DOCS_URL = 'https://github.com/SocketDev/socket-cli/blob/v1.x/docs/dynamic-sbom-inference-settings.md' -// Who consumes the facts: Coana for `fix` and `reach` (which also resolves -// artifact paths), or only the scan upload. -export type FactsConsumer = 'fix' | 'reach' | 'upload' +// Who consumes the facts: Coana for `fix` and `reach`, with the work dir that +// collects what its run reads, or only the scan upload. +export type FactsTarget = + | { consumer: 'upload'; workDir?: undefined } + | { consumer: 'fix' | 'reach'; workDir: KeptRootsDir } + +export type FactsConsumer = FactsTarget['consumer'] + +// Only reachability installs the dependencies its analysis reads. +export type KeptRootsDir = Omit export type DynamicSbomInferenceResult = { // Facts files of dropped runs, which the scan must not collect. @@ -38,7 +41,6 @@ export type DynamicSbomInferenceResult = { // these types' artifacts only from facts files. factsOnlyTypes: FactsOnlyTypes factsPaths: string[] - resolvedPathsSidecar: ResolvedPathsSidecar | undefined } // Coana takes the discovered ecosystems' artifacts only from facts files, so a @@ -73,38 +75,30 @@ function checkFactsForCoana( } // Recursively discovers and generates Socket facts for every independent -// build root of the selected ecosystems under `cwd`, returning the generated -// facts paths plus the resolved-paths sidecar that reachability forwards to -// Coana. +// build root of the selected ecosystems under `cwd`. export async function runDynamicSbomInference({ consumer, + context, cwd, excludePaths, purlTypes, - sbtTmpDir, -}: { - consumer: FactsConsumer + workDir, +}: FactsTarget & { + context: Omit cwd: string excludePaths: string[] purlTypes: readonly PURL_Type[] - // sbt provisions its Scala toolchain under this directory and reach's - // artifactPaths point into it, so it must outlive whoever consumes them. - // Only meaningful for `reach`. - sbtTmpDir: string | undefined }): Promise { - const withFiles = consumer === 'reach' - const coanaReadsFacts = consumer === 'fix' || consumer === 'reach' - const sidecarAcc: SidecarAccumulator | undefined = coanaReadsFacts - ? new Map() - : undefined + const coanaReadsFacts = consumer !== 'upload' const outcomes = await generateRecursiveManifests({ + context: { + ...context, + workDir: workDir && { ...workDir, withFiles: consumer === 'reach' }, + }, cwd, excludePaths, purlTypes, - sbtTmpDir: withFiles ? sbtTmpDir : undefined, - sidecarAcc, verbose: false, - withFiles, }) const factsOnlyTypes = [ ...new Set(outcomes.map(o => PURL_TYPE_BY_TOOL[o.ecosystem])), @@ -146,15 +140,11 @@ export async function runDynamicSbomInference({ ), factsOnlyTypes, factsPaths, - resolvedPathsSidecar: - sidecarAcc && hasSidecarEntries(sidecarAcc) - ? serializeSidecar(sidecarAcc) - : undefined, } } // `paths` without the facts files discovery discarded: each holds what was -// there before the scan, or a dropped run's facts, not a kept build's. +// there before the scan, not a kept build's. export async function withoutDiscardedFacts( paths: string[], discarded: readonly string[] | undefined, diff --git a/src/commands/scan/run-dynamic-sbom-inference.test.mts b/src/commands/scan/run-dynamic-sbom-inference.test.mts index ecd56919e6..612f51c536 100644 --- a/src/commands/scan/run-dynamic-sbom-inference.test.mts +++ b/src/commands/scan/run-dynamic-sbom-inference.test.mts @@ -32,16 +32,19 @@ const generated = { status: 'generated', } +const context = { coanaVersion: '1.2.3' } +const workDir = { dir: '/work', entries: new Map() } + function run( consumer: FactsConsumer, purlTypes: readonly PURL_Type[] = ['maven', 'nuget'], ) { return runDynamicSbomInference({ - consumer, + ...(consumer === 'upload' ? { consumer } : { consumer, workDir }), + context, cwd: '/repo', excludePaths: ['vendor/**'], purlTypes, - sbtTmpDir: '/tmp/sbt', }) } @@ -51,41 +54,28 @@ describe('runDynamicSbomInference', () => { }) it.for([ - // sbtTmpDir only matters for reach; withheld otherwise so the callee - // allocates and cleans up its own ephemeral base. { - consumer: 'upload', - sbtTmpDir: undefined, - sidecar: false, - withFiles: false, + consumer: 'reach', + expected: { ...workDir, withFiles: true }, }, { consumer: 'fix', - sbtTmpDir: undefined, - sidecar: true, - withFiles: false, - }, - { - consumer: 'reach', - sbtTmpDir: '/tmp/sbt', - sidecar: true, - withFiles: true, + expected: { ...workDir, withFiles: false }, }, + { consumer: 'upload', expected: undefined }, ] as const)( - 'generates for $consumer', - async ({ consumer, sbtTmpDir, sidecar, withFiles }) => { + 'generates every build root for $consumer, installing files only for reach', + async ({ consumer, expected }) => { mockGenerateRecursiveManifests.mockResolvedValueOnce([generated]) await run(consumer) expect(mockGenerateRecursiveManifests).toHaveBeenCalledWith({ + context: { ...context, workDir: expected }, cwd: '/repo', excludePaths: ['vendor/**'], purlTypes: ['maven', 'nuget'], - sbtTmpDir, - sidecarAcc: sidecar ? expect.any(Map) : undefined, verbose: false, - withFiles, }) }, ) @@ -102,26 +92,6 @@ describe('runDynamicSbomInference', () => { discardedFactsPaths: [], factsOnlyTypes: ['maven'], factsPaths: ['/repo/a/.socket.facts.json'], - resolvedPathsSidecar: undefined, - }) - }) - - it('serializes the accumulated sidecar', async () => { - mockGenerateRecursiveManifests.mockImplementationOnce( - async ({ sidecarAcc }) => { - sidecarAcc.set('/repo/a/.socket.facts.json', { - projects: [{ name: 'app' }], - components: [], - }) - return [generated] - }, - ) - - expect((await run('reach')).resolvedPathsSidecar).toEqual({ - '/repo/a/.socket.facts.json': { - projects: [{ name: 'app' }], - components: [], - }, }) }) diff --git a/src/commands/scan/warn-socket-json-only-flags.mts b/src/commands/scan/warn-socket-json-only-flags.mts index 91572be83e..3103102674 100644 --- a/src/commands/scan/warn-socket-json-only-flags.mts +++ b/src/commands/scan/warn-socket-json-only-flags.mts @@ -1,6 +1,6 @@ import { logger } from '../../utils/logger.mts' import { camelToKebab } from '../../utils/strings.mts' -import { DSI_SETUP_COMMAND } from '../manifest/scripts/resolution-report-render.mts' +import { DSI_SETUP_COMMAND } from '../manifest/run-manifest-facts.mts' // Build options that `socket manifest ` takes as flags but the scan // commands read from each build's socket.json, so passing them does nothing. diff --git a/src/utils/coana-release.test.mts b/src/utils/coana-release.test.mts index 67cfc2794e..80a526235c 100644 --- a/src/utils/coana-release.test.mts +++ b/src/utils/coana-release.test.mts @@ -5,6 +5,7 @@ * - spawnCoana: runs cli-wrapper.mjs from the cache with the caller's args, * cwd and environment, sets the variables Coana reads, leaves the user's * API token variables out, and surfaces a failing run's output. + * - spawnCoana with a minimum version: refuses an older Coana. * * Testing Approach: * A fake cli-wrapper.mjs is installed into a temporary cache with the real @@ -41,7 +42,10 @@ import { resolveDefaultApiToken, } from './sdk.mts' import { spawn } from './spawn.mts' -import constants, { SOCKET_CLI_API_TOKEN_VARIABLES } from '../constants.mts' +import constants, { + COANA_CLI_VERSION, + SOCKET_CLI_API_TOKEN_VARIABLES, +} from '../constants.mts' import { COANA_CLI_WRAPPER_FILENAME, coanaCacheDistPath, @@ -94,11 +98,14 @@ describe('spawnCoana', () => { const extracted = path.join(tmpDir, 'extracted') await fs.mkdir(extracted) await fs.writeFile(coanaCliWrapperPath(extracted), FAKE_CLI_WRAPPER) - await spawn( - 'node', - [CACHE_SCRIPT, 'install', VERSION, 'cli', 'a'.repeat(64), extracted], - { stdio: 'pipe' }, - ) + for (const version of [VERSION, COANA_CLI_VERSION]) { + // eslint-disable-next-line no-await-in-loop + await spawn( + 'node', + [CACHE_SCRIPT, 'install', version, 'cli', 'a'.repeat(64), extracted], + { stdio: 'pipe' }, + ) + } }) afterEach(() => { @@ -286,6 +293,27 @@ describe('spawnCoana', () => { }, ) + it('refuses a Coana older than the minimum, naming the minimum', async () => { + const result = await spawnCoana(['run', '.'], 'acme', { + coanaVersion: VERSION, + minimumVersion: COANA_CLI_VERSION, + stdio: 'pipe', + }) + + expect(result.ok).toBe(false) + expect(result.message).toBe(`Coana ${VERSION} is too old for this command`) + expect(result.cause).toContain(`Coana ${COANA_CLI_VERSION} or newer`) + }) + + it('runs a Coana at the minimum', async () => { + const run = await runFake({ + coanaVersion: COANA_CLI_VERSION, + minimumVersion: COANA_CLI_VERSION, + }) + + expect(run.args).toEqual(['run', '.']) + }) + it('surfaces captured stdout when stderr is empty (Coana logs some failures to stdout)', async () => { const result = await spawnCoana(['fail'], 'acme', { coanaVersion: VERSION, diff --git a/src/utils/coana/release.mts b/src/utils/coana/release.mts index 50017b7ad8..bef3e2dd2c 100644 --- a/src/utils/coana/release.mts +++ b/src/utils/coana/release.mts @@ -76,6 +76,9 @@ type CoanaSpawnOptions = { coanaVersion?: string | undefined cwd?: string | URL | undefined env?: Record | undefined + // The oldest Coana the command exists in; checked against the version a + // pinned spec resolves to. + minimumVersion?: string | undefined repoName?: string | undefined spinner?: Spinner | undefined stdio?: SpawnOptions['stdio'] | undefined @@ -215,17 +218,20 @@ async function downloadComponent( return { ok: true } } +type CoanaCliDir = { dir: string; version: string } + /** * The directory of the Coana CLI's `cli` component for `versionSpec`, an exact - * version or a range, downloading it into the cache when the cache lacks it. - * `env` reaches the cache script, which reads `XDG_CACHE_HOME` from it. + * version or a range, and the version it holds, downloading it into the cache + * when the cache lacks it. `env` reaches the cache script, which reads + * `XDG_CACHE_HOME` from it. */ async function getCoanaCliDir( versionSpec: string, org: CResult, env: NodeJS.ProcessEnv, spinner: Spinner | undefined, -): Promise> { +): Promise> { try { const exactVersion = semver.valid(versionSpec) if (exactVersion) { @@ -267,7 +273,10 @@ async function getCoanaCliDir( logger.info(downloading) } try { - return await installComponent(artifacts.data, orgSlug, env) + return withVersion( + await installComponent(artifacts.data, orgSlug, env), + artifacts.data.version, + ) } finally { spinning?.setText(previousText) } @@ -280,11 +289,13 @@ async function getCoanaCliDir( } /** The cached directory or a failure; `undefined` when the cache lacks it. */ - async function lookup(version: string): Promise | undefined> { + async function lookup( + version: string, + ): Promise | undefined> { const result = await runCoanaCache(['lookup', version, COMPONENT], env) return result.exitCode === NOT_CACHED_EXIT_CODE ? undefined - : cacheResultToCResult(result) + : withVersion(cacheResultToCResult(result), version) } } @@ -419,6 +430,13 @@ async function runCoanaCache( } } +function withVersion( + dir: CResult, + version: string, +): CResult { + return dir.ok ? { ok: true, data: { dir: dir.data, version } } : dir +} + /** * Run the Coana CLI, downloading it into the cache that Coana and the Socket * CLIs share when the cache lacks the version. Returns a CResult with Coana's @@ -440,6 +458,7 @@ export async function spawnCoana( coanaVersion, cwd, env: spawnEnv, + minimumVersion, repoName, spinner, stdio = 'inherit', @@ -505,7 +524,15 @@ export async function spawnCoana( if (!coanaDir.ok) { return coanaDir } - scriptPath = coanaCliWrapperPath(coanaDir.data) + const { dir, version } = coanaDir.data + if (minimumVersion && semver.lt(version, minimumVersion)) { + return { + ok: false, + message: `Coana ${version} is too old for this command`, + cause: `It needs Coana ${minimumVersion} or newer. Pin that or a newer version with --reach-version or --fix-version, or leave the version unpinned.`, + } + } + scriptPath = coanaCliWrapperPath(dir) } // A local path may name a native binary. From 479beb980650d783b83f9e85283ae8bfa6e61153 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Fri, 20 Nov 2026 17:34:44 +0100 Subject: [PATCH 02/12] Write the generate-socket-facts request of its contract version --- src/commands/manifest/run-manifest-facts.mts | 17 +++++++++++------ .../manifest/run-manifest-facts.test.mts | 15 +++++++-------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 2f7b539fda..006d846a0e 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -14,6 +14,7 @@ import { withTmpDir } from '../../utils/fs.mts' import { getOrInsert } from '../../utils/get-or-insert.mts' import { logger } from '../../utils/logger.mts' +import type { BuildRoot } from './discover-manifest-roots.mts' import type { BuildTool } from './scripts/build-tool.mts' import type { CResult } from '../../types.mts' @@ -95,9 +96,10 @@ export type RunManifestFactsResult = { // dependency); `undefined` = genuinely nothing to resolve, not a failure. export type RunManifestFactsOutcome = RunManifestFactsResult | null | undefined -// The request `coana generate-socket-facts --request` reads. +// The request `coana generate-socket-facts --request` reads, of the contract +// version it states. type SocketFactsRequest = { - buildRoot: string + contract: typeof SOCKET_FACTS_REQUEST_CONTRACT config: { bin?: string | undefined buildOpts: string[] @@ -107,13 +109,15 @@ type SocketFactsRequest = { javaHome?: string | undefined verbose: boolean } - entryFile?: string | undefined excludeBase: string excludePaths?: string[] | undefined hints: Omit & { flags: BuildOption[] } + root: BuildRoot tool: BuildTool } +const SOCKET_FACTS_REQUEST_CONTRACT = 1 + type SocketFactsResult = | (RunManifestFactsResult & { status: 'generated' }) | { status: 'empty' } @@ -242,20 +246,21 @@ function toSocketFactsRequest({ return { ok: true, data: { - buildRoot: path.resolve(cwd), + contract: SOCKET_FACTS_REQUEST_CONTRACT, config: { bin: resolvedBin, buildOpts, ...(excludeConfigs ? { excludeConfigs } : {}), ignoreUnresolved, ...(includeConfigs ? { includeConfigs } : {}), - ...(javaHome ? { javaHome } : {}), + // .NET builds take no Java. + ...(javaHome && ecosystem !== 'dotnet' ? { javaHome } : {}), verbose, }, - ...(entryFile ? { entryFile } : {}), excludeBase: path.resolve(excludeBase ?? cwd), ...(excludePaths?.length ? { excludePaths } : {}), hints: toRequestHints(hints), + root: { dir: path.resolve(cwd), ...(entryFile ? { entryFile } : {}) }, tool: ecosystem, }, } diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index 2b8bcb3eb5..a1bee625f1 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -101,7 +101,7 @@ describe('runManifestFacts', () => { expect(calls[0]!.args.slice(0, 1)).toEqual(['generate-socket-facts']) expect(calls[0]!.args).not.toContain('--work-dir') expect(calls[0]!.request).toEqual({ - buildRoot: cwd, + contract: 1, config: { bin: 'mvn', buildOpts: ['-Pci'], @@ -110,7 +110,6 @@ describe('runManifestFacts', () => { javaHome: '$JAVA11_HOME', verbose: false, }, - entryFile: 'pom.xml', excludeBase: cwd, excludePaths: ['docs/**'], hints: { @@ -119,6 +118,7 @@ describe('runManifestFacts', () => { setupCommand: 'socket manifest setup', socketJson: 'socket.json', }, + root: { dir: cwd, entryFile: 'pom.xml' }, tool: 'maven', }) expect(vi.mocked(spawnCoana).mock.calls[0]![1]).toBe('acme') @@ -302,7 +302,7 @@ describe('keepFacts', () => { }) describe('listDotnetSolutionMembers', () => { - it('lists the members once for the same request', async () => { + it('lists the members once for the same request, which takes no Java', async () => { coanaAnswers({ members: ['/r/A/A.csproj'] }) const request = { buildOpts: [], @@ -315,15 +315,13 @@ describe('listDotnetSolutionMembers', () => { expect(spawnCoana).toHaveBeenCalledOnce() expect(calls[0]!.args).toContain('--list-members') expect(calls[0]!.request).toEqual({ - buildRoot: cwd, + contract: 1, config: { bin: 'dotnet', buildOpts: [], ignoreUnresolved: false, - javaHome: '$JAVA11_HOME', verbose: false, }, - entryFile: 'All.sln', excludeBase: cwd, hints: { excludePathsFlag: '--exclude-paths', @@ -331,6 +329,7 @@ describe('listDotnetSolutionMembers', () => { setupCommand: 'socket manifest setup', socketJson: 'socket.json', }, + root: { dir: cwd, entryFile: 'All.sln' }, tool: 'dotnet', }) }) @@ -382,7 +381,7 @@ describe('listBuildProjects', () => { expect(calls[0]!.args).toContain('--list-projects') expect(calls[0]!.args).not.toContain('--work-dir') expect(calls[0]!.request).toMatchObject({ - buildRoot: path.join(cwd, 'reactor'), + contract: 1, config: { bin: 'mvn', buildOpts: ['-Pci'], @@ -390,9 +389,9 @@ describe('listBuildProjects', () => { javaHome: '$JAVA11_HOME', verbose: false, }, - entryFile: 'pom.xml', excludeBase: cwd, excludePaths: ['reactor/moduleB'], + root: { dir: path.join(cwd, 'reactor'), entryFile: 'pom.xml' }, tool: 'maven', }) }) From 7f066b1671805d19a83ae6cc1df7576ae7041f66 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 24 Nov 2026 14:24:19 +0100 Subject: [PATCH 03/12] Name the purpose Coana generates each root's facts for --- .../manifest/generate-recursive-manifests.mts | 9 +-- .../generate-recursive-manifests.test.mts | 8 ++- .../manifest/generate_auto_manifest.mts | 7 ++- .../manifest/generate_auto_manifest.test.mts | 2 +- src/commands/manifest/run-manifest-facts.mts | 21 +++---- .../manifest/run-manifest-facts.test.mts | 60 ++++++++++++++++--- src/commands/scan/handle-create-new-scan.mts | 2 +- .../scan/handle-create-new-scan.test.mts | 2 +- .../scan/run-dynamic-sbom-inference.mts | 9 ++- .../scan/run-dynamic-sbom-inference.test.mts | 6 +- 10 files changed, 89 insertions(+), 37 deletions(-) diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index 676df8e699..7de441b769 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -698,9 +698,10 @@ function runOptions( excludeBase: ctx.realCwd, excludePaths: ctx.excludePaths, hints: { - continueOnInstallErrorsFlag: ctx.context.workDir.withFiles - ? REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG - : undefined, + continueOnInstallErrorsFlag: + ctx.context.workDir.purpose === 'reachability' + ? REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG + : undefined, excludePathsFlag: EXCLUDE_PATHS_FLAG, flags: ctx.optionFlags, setupCommand: DSI_SETUP_COMMAND, @@ -848,7 +849,7 @@ export async function generateRecursiveManifests({ const outcomes = context.workDir ? await walk(context.workDir) : await withTmpDir('socket-facts-work-', dir => - walk({ dir, entries: new Map(), withFiles: false }), + walk({ dir, entries: new Map(), purpose: 'upload' }), ) if (!outcomes.some(o => o.status === 'failed')) { diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index 6e3f459cbf..4f7765034f 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -104,7 +104,11 @@ async function writeIntoWorkDir( } function newWorkDir(parent = '/'): SocketFactsWorkDir { - return { dir: path.join(parent, 'work'), entries: new Map(), withFiles: true } + return { + dir: path.join(parent, 'work'), + entries: new Map(), + purpose: 'reachability', + } } function mockFacts( @@ -421,7 +425,7 @@ describe('generateRecursiveManifests', () => { false, ) expect(existsSync(path.join(app, 'pom.xml.socket.facts.json'))).toBe(true) - expect(ownWorkDir?.withFiles).toBe(false) + expect(ownWorkDir?.purpose).toBe('upload') expect(existsSync(ownWorkDir!.dir)).toBe(false) } finally { await fs.rm(outer, { recursive: true, force: true }) diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index 578701fabe..e9c241ef8e 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -114,9 +114,10 @@ export async function generateAutoManifest({ const generatedFiles: string[] = [] const hints: BuildOptionHints = { ...AUTO_MANIFEST_HINTS, - continueOnInstallErrorsFlag: context?.workDir?.withFiles - ? REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG - : undefined, + continueOnInstallErrorsFlag: + context?.workDir?.purpose === 'reachability' + ? REACH_CONTINUE_ON_INSTALL_ERRORS_FLAG + : undefined, excludePathsFlag, } diff --git a/src/commands/manifest/generate_auto_manifest.test.mts b/src/commands/manifest/generate_auto_manifest.test.mts index e0cefe6390..e89b508ed5 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -475,7 +475,7 @@ describe('generateAutoManifest — JVM facts', () => { const workDir = { dir: path.join(cwd, 'work'), entries: new Map(), - withFiles: true, + purpose: 'reachability', } await generateAutoManifest({ context: { workDir }, diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 006d846a0e..6a159f6925 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -68,10 +68,13 @@ export type SocketFactsWorkDir = { dir: string // By the facts file Coana places a root's facts at. entries: Map - // Reachability only: also install the dependencies the analysis reads. - withFiles: boolean + // What the facts are for, as Coana's `--purpose` takes it: a fix or reachability resolution keeps the state its + // Coana run reads. + purpose: SocketFactsPurpose } +export type SocketFactsPurpose = 'upload' | 'fix' | 'reachability' + export type SocketFactsContext = { // The Coana that reads `workDir` must be the one that wrote it. coanaVersion?: string | undefined @@ -364,13 +367,11 @@ export async function runManifestFacts({ const { workDir } = context const { message, result } = await runGenerateSocketFacts( request.data, - workDir - ? [ - ...(workDir.withFiles ? ['--with-files'] : []), - '--work-dir', - workDir.dir, - ] - : [], + [ + '--purpose', + workDir?.purpose ?? 'upload', + ...(workDir ? ['--work-dir', workDir.dir] : []), + ], context, ) @@ -386,7 +387,7 @@ export async function runManifestFacts({ if (result.status === 'empty') { return undefined } - if (workDir && !result.sidecarEntry) { + if (workDir && workDir.purpose !== 'upload' && !result.sidecarEntry) { process.exitCode = 1 logger.fail( `Coana returned no sidecar entry for \`${result.targetPath}\`, which reachability analysis and socket fix need. This is a Coana bug; please report it to Socket.`, diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index a1bee625f1..05fcfeb247 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -170,15 +170,16 @@ describe('runManifestFacts', () => { const workDir: SocketFactsWorkDir = { dir: '/w', entries: new Map(), - withFiles: true, + purpose: 'reachability', } const result = await runManifestFacts({ ...baseArgs, context: { workDir }, cwd, }) - expect(calls[0]!.args.slice(-3)).toEqual([ - '--with-files', + expect(calls[0]!.args.slice(-4)).toEqual([ + '--purpose', + 'reachability', '--work-dir', '/w', ]) @@ -186,7 +187,7 @@ describe('runManifestFacts', () => { expect(workDir.entries.size).toBe(0) }) - it('keeps state without installing files for socket fix', async () => { + it('keeps state for socket fix', async () => { coanaAnswers({ factsPath: '/w/y/f', projects: [], @@ -194,10 +195,43 @@ describe('runManifestFacts', () => { status: 'generated', targetPath: '/r/f', }) - const workDir = { dir: '/w', entries: new Map(), withFiles: false } + const workDir: SocketFactsWorkDir = { + dir: '/w', + entries: new Map(), + purpose: 'fix', + } await runManifestFacts({ ...baseArgs, context: { workDir }, cwd }) - expect(calls[0]!.args.slice(-2)).toEqual(['--work-dir', '/w']) - expect(calls[0]!.args).not.toContain('--with-files') + expect(calls[0]!.args.slice(-4)).toEqual([ + '--purpose', + 'fix', + '--work-dir', + '/w', + ]) + }) + + it('generates facts for upload without a work dir, or staged in one without its state', async () => { + coanaAnswers({ + factsPath: '/w/y/f', + projects: [], + status: 'generated', + targetPath: '/r/f', + }) + const workDir: SocketFactsWorkDir = { + dir: '/w', + entries: new Map(), + purpose: 'upload', + } + expect( + await runManifestFacts({ ...baseArgs, context: { workDir }, cwd }), + ).toMatchObject({ factsPath: '/w/y/f', targetPath: '/r/f' }) + expect(calls[0]!.args.slice(-4)).toEqual([ + '--purpose', + 'upload', + '--work-dir', + '/w', + ]) + await runManifestFacts({ ...baseArgs, cwd }) + expect(calls[1]!.args.slice(-2)).toEqual(['--purpose', 'upload']) }) it('fails when Coana keeps no sidecar entry in the work dir', async () => { @@ -207,7 +241,11 @@ describe('runManifestFacts', () => { status: 'generated', targetPath: '/r/f', }) - const workDir = { dir: '/w', entries: new Map(), withFiles: true } + const workDir: SocketFactsWorkDir = { + dir: '/w', + entries: new Map(), + purpose: 'reachability', + } expect( await runManifestFacts({ ...baseArgs, context: { workDir }, cwd }), ).toBeNull() @@ -274,7 +312,11 @@ describe('keepFacts', () => { await fs.writeFile(factsPath, 'generated') await fs.writeFile(targetPath, 'committed') const sidecarEntry = { factsFile: targetPath, stateDir: '/w/x' } - const workDir = { dir: '/w', entries: new Map(), withFiles: true } + const workDir: SocketFactsWorkDir = { + dir: '/w', + entries: new Map(), + purpose: 'reachability', + } await keepFacts(workDir, { factsPath, diff --git a/src/commands/scan/handle-create-new-scan.mts b/src/commands/scan/handle-create-new-scan.mts index f95e2e2962..31fb006228 100644 --- a/src/commands/scan/handle-create-new-scan.mts +++ b/src/commands/scan/handle-create-new-scan.mts @@ -175,7 +175,7 @@ async function createNewScan( ? { dir: path.join(manifestTmpDir, 'socket-facts-work'), entries: new Map(), - withFiles: true, + purpose: 'reachability', } : undefined, } diff --git a/src/commands/scan/handle-create-new-scan.test.mts b/src/commands/scan/handle-create-new-scan.test.mts index 038fcd5161..d2ef1c4a86 100644 --- a/src/commands/scan/handle-create-new-scan.test.mts +++ b/src/commands/scan/handle-create-new-scan.test.mts @@ -520,7 +520,7 @@ describe('handleCreateNewScan excludePaths', () => { expect.objectContaining({ context: expect.objectContaining({ orgSlug: config.orgSlug, - workDir: expect.objectContaining({ withFiles: true }), + workDir: expect.objectContaining({ purpose: 'reachability' }), }), }), ) diff --git a/src/commands/scan/run-dynamic-sbom-inference.mts b/src/commands/scan/run-dynamic-sbom-inference.mts index 857e363c99..b2d9f62016 100644 --- a/src/commands/scan/run-dynamic-sbom-inference.mts +++ b/src/commands/scan/run-dynamic-sbom-inference.mts @@ -31,8 +31,8 @@ export type FactsTarget = export type FactsConsumer = FactsTarget['consumer'] -// Only reachability installs the dependencies its analysis reads. -export type KeptRootsDir = Omit +// The consumer sets the purpose. +export type KeptRootsDir = Omit export type DynamicSbomInferenceResult = { // Facts files of dropped runs, which the scan must not collect. @@ -93,7 +93,10 @@ export async function runDynamicSbomInference({ const outcomes = await generateRecursiveManifests({ context: { ...context, - workDir: workDir && { ...workDir, withFiles: consumer === 'reach' }, + workDir: workDir && { + ...workDir, + purpose: consumer === 'reach' ? 'reachability' : 'fix', + }, }, cwd, excludePaths, diff --git a/src/commands/scan/run-dynamic-sbom-inference.test.mts b/src/commands/scan/run-dynamic-sbom-inference.test.mts index 612f51c536..be0248cb9a 100644 --- a/src/commands/scan/run-dynamic-sbom-inference.test.mts +++ b/src/commands/scan/run-dynamic-sbom-inference.test.mts @@ -56,15 +56,15 @@ describe('runDynamicSbomInference', () => { it.for([ { consumer: 'reach', - expected: { ...workDir, withFiles: true }, + expected: { ...workDir, purpose: 'reachability' }, }, { consumer: 'fix', - expected: { ...workDir, withFiles: false }, + expected: { ...workDir, purpose: 'fix' }, }, { consumer: 'upload', expected: undefined }, ] as const)( - 'generates every build root for $consumer, installing files only for reach', + 'generates every build root for $consumer, with the purpose it reads the facts for', async ({ consumer, expected }) => { mockGenerateRecursiveManifests.mockResolvedValueOnce([generated]) From 12e585beabf81b3f222bce415b13ea93f3162966 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 13:42:51 +0100 Subject: [PATCH 04/12] Run auto-manifest's Maven where the scan starts Maven resolves relative arguments such as `--settings` and `--file` from the directory it starts in, and reports a `--file` without its argument. Auto-manifest moved Maven into the directory of the POM a `--file` in mavenOpts named and dropped the option, which broke both. It now runs Maven in the scan root with mavenOpts as written, as `socket manifest maven` does. The recursive walk still builds each POM by its own file and ignores a `--file`. --- .../manifest/generate-recursive-manifests.mts | 41 ++++------ .../manifest/generate_auto_manifest.mts | 32 ++------ .../manifest/generate_auto_manifest.test.mts | 75 +++++-------------- 3 files changed, 37 insertions(+), 111 deletions(-) diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index 7de441b769..fbe3748d2b 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -86,8 +86,6 @@ export type EcosystemBuildConfig = { ignoreUnresolved: boolean includeConfigs: string javaHome: string | undefined - // Maven's `--file` in mavenOpts, which buildOpts leaves out. - mavenFile: string | undefined // Set when this build root should be skipped entirely (never invoked). skipReason: string | undefined verbose: boolean @@ -123,33 +121,23 @@ const MAVEN_OTHER_F_OPTS = new Set([ 'fn', ]) -// Maven 3.9 builds the first of several `--file`s. -function splitMavenFileOpts(opts: string[]): { - file: string | undefined - opts: string[] -} { - const files: string[] = [] +function withoutMavenFileOpts(opts: string[]): string[] { const kept: string[] = [] for (let i = 0, { length } = opts; i < length; i += 1) { const opt = opts[i]! const name = opt.replace(/^--?/, '') - const { 0: key, 1: value } = name.split(/=(.*)/s) if (opt === name || MAVEN_OTHER_F_OPTS.has(name)) { kept.push(opt) } else if (MAVEN_FILE_OPTS.has(name)) { i += 1 - if (i < length) { - files.push(opts[i]!) - } - } else if (MAVEN_FILE_OPTS.has(key!) && value !== undefined) { - files.push(value) - } else if (opt.startsWith('-f') && !opt.startsWith('--')) { - files.push(opt.slice(2).replace(/^=/, '')) - } else { + } else if ( + !MAVEN_FILE_OPTS.has(name.split('=')[0]!) && + !(opt.startsWith('-f') && !opt.startsWith('--')) + ) { kept.push(opt) } } - return { file: files[0], opts: kept } + return kept } type Candidate = { @@ -880,7 +868,6 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: undefined, - mavenFile: undefined, skipReason: getSkipReason(ecosystem, config?.disabled), verbose: Boolean(config?.verbose), } @@ -895,7 +882,6 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, - mavenFile: undefined, skipReason: getSkipReason(ecosystem, config?.disabled, config?.facts), verbose: Boolean(config?.verbose), } @@ -910,24 +896,19 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, - mavenFile: undefined, skipReason: getSkipReason(ecosystem, config?.disabled, config?.facts), verbose: Boolean(config?.verbose), } } const config = sockJson.defaults?.manifest?.maven const bin = config?.bin ?? undefined - const { file, opts } = splitMavenFileOpts( - parseBuildToolOpts(config?.mavenOpts ?? undefined), - ) return { bin: bin ?? resolveBuildToolBin('maven', dir), - buildOpts: opts, + buildOpts: parseBuildToolOpts(config?.mavenOpts ?? undefined), excludeConfigs: config?.excludeConfigs ?? '', ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, - mavenFile: file, skipReason: getSkipReason(ecosystem, config?.disabled), verbose: Boolean(config?.verbose), } @@ -941,10 +922,14 @@ export function resolveWalkConfig( sockJson: SocketJson, ): EcosystemBuildConfig { const config = resolveEcosystemConfig(ecosystem, dir, sockJson) - if (config.mavenFile !== undefined) { + if (ecosystem !== 'maven') { + return config + } + const buildOpts = withoutMavenFileOpts(config.buildOpts) + if (buildOpts.length !== config.buildOpts.length) { logger.warn( `Ignoring --file in mavenOpts for ${dir}: each POM there is built by its own file.`, ) } - return config + return { ...config, buildOpts } } diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index e9c241ef8e..1797e1c315 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -22,7 +22,6 @@ import { SOCKET_JSON, } from '../../constants.mts' import { InputError } from '../../utils/errors.mts' -import { isDirSync } from '../../utils/fs.mts' import { logger } from '../../utils/logger.mts' import { readOrDefaultSocketJson } from '../../utils/socket-json.mts' @@ -62,24 +61,6 @@ function abortFactsRunIfFailed( } } -// Maven's `-f, --file`: "Force the use of an alternate POM file (or directory -// with pom.xml)" (`mvn --help`), relative to where Maven runs. -function mavenRoot(cwd: string, file: string | undefined): BuildRoot { - if (file === undefined) { - return { dir: cwd, entryFile: 'pom.xml' } - } - const named = path.resolve(cwd, file) - return isDirSync(named) - ? { dir: named, entryFile: 'pom.xml' } - : { dir: path.dirname(named), entryFile: path.basename(named) } -} - -// A command naming a path runs that file, relative to `dir`; a bare name is -// looked up on PATH. -function binIn(dir: string, bin: string): string { - return /[/\\]/.test(bin) ? path.resolve(dir, bin) : bin -} - function abortManifestRunIfFailed( ecosystem: string, beforeExitCode: string | number | undefined, @@ -205,12 +186,13 @@ export async function generateAutoManifest({ if (!sockJson?.defaults?.manifest?.maven?.disabled && detected.maven) { logger.log('Detected a Maven pom.xml build, generating Socket facts...') - const config = resolveEcosystemConfig('maven', cwd, sockJson) - await generateFacts('maven', mavenRoot(cwd, config.mavenFile), { - ...config, - // Maven runs in the POM's directory, which `--file` can move. - bin: binIn(cwd, config.bin), - }) + // Maven resolves relative arguments such as `--file` and `--settings` + // from where it starts, so it starts here with mavenOpts as written. + await generateFacts( + 'maven', + { dir: cwd }, + resolveEcosystemConfig('maven', cwd, sockJson), + ) } if (!sockJson?.defaults?.manifest?.dotnet?.disabled && detected.dotnet) { diff --git a/src/commands/manifest/generate_auto_manifest.test.mts b/src/commands/manifest/generate_auto_manifest.test.mts index e89b508ed5..74c9c76e35 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -340,19 +340,16 @@ describe('generateAutoManifest — JVM facts', () => { vi.mocked(readOrDefaultSocketJson).mockReturnValue({} as SocketJson) }) - it("builds a Maven root's pom.xml by name, apart from a Gradle build beside it", async () => { + it('runs Maven where the scan starts, leaving it to find its POM', async () => { await generateAutoManifest({ cwd: '/tmp/repo', detected: { ...baseDetected, gradle: true, maven: true, count: 2 }, outputKind: 'text', verbose: false, }) - expect(callFor('maven')).toMatchObject({ - cwd: '/tmp/repo', - entryFile: 'pom.xml', - }) + expect(callFor('maven')).toMatchObject({ buildOpts: [], cwd: '/tmp/repo' }) + expect(callFor('maven')?.entryFile).toBeUndefined() expect(callFor('gradle')).toMatchObject({ cwd: '/tmp/repo' }) - expect(callFor('gradle')?.entryFile).toBeUndefined() }) it('takes each JVM build tool its socket.json section as the walk does', async () => { @@ -393,67 +390,29 @@ describe('generateAutoManifest — JVM facts', () => { expect(callFor('sbt')).toMatchObject({ bin: 'sbt', buildOpts: ['-Dx=1'] }) }) - it.for([ - ['--file sub/app.xml', 'sub', 'app.xml'], - ['-fsub/app.xml', 'sub', 'app.xml'], - ['--file=sub', 'sub', 'pom.xml'], - ['-f sub -f other.xml', 'sub', 'pom.xml'], - ] as const)( - 'builds the POM `%s` in mavenOpts names, keeping it out of the build options', - async ({ 0: fileOpts, 1: dir, 2: entryFile }) => { - const cwd = await fs.realpath( - await fs.mkdtemp(path.join(tmpdir(), 'auto-manifest-file-')), - ) - try { - await fs.mkdir(path.join(cwd, 'sub')) - vi.mocked(readOrDefaultSocketJson).mockReturnValue({ - defaults: { - manifest: { maven: { bin: 'mvn', mavenOpts: `-Pci ${fileOpts}` } }, - }, - } as SocketJson) - await generateAutoManifest({ - cwd, - detected: { ...baseDetected, maven: true, count: 1 }, - outputKind: 'text', - verbose: false, - }) - expect(callFor('maven')).toMatchObject({ - buildOpts: ['-Pci'], - cwd: path.join(cwd, dir), - entryFile, - excludeBase: cwd, - }) - } finally { - await fs.rm(cwd, { recursive: true, force: true }) - } - }, - ) - - it('runs a relative bin from the scan root when --file moves Maven into another directory', async () => { - const cwd = await fs.realpath( - await fs.mkdtemp(path.join(tmpdir(), 'auto-manifest-bin-')), - ) - try { - await fs.mkdir(path.join(cwd, 'sub')) + // Maven resolves `--settings` from where it starts, and reports a `--file` + // without its argument. + it.for(['-f sub/pom.xml -s settings.xml', '-Pci --file'])( + 'passes mavenOpts `%s` to Maven as written, from the scan root', + async mavenOpts => { vi.mocked(readOrDefaultSocketJson).mockReturnValue({ - defaults: { - manifest: { maven: { bin: './mvnw', mavenOpts: '-f sub' } }, - }, + defaults: { manifest: { maven: { bin: './mvnw', mavenOpts } } }, } as SocketJson) await generateAutoManifest({ - cwd, + cwd: '/tmp/repo', detected: { ...baseDetected, maven: true, count: 1 }, outputKind: 'text', verbose: false, }) expect(callFor('maven')).toMatchObject({ - bin: path.join(cwd, 'mvnw'), - cwd: path.join(cwd, 'sub'), + bin: './mvnw', + buildOpts: mavenOpts.split(' '), + cwd: '/tmp/repo', + excludeBase: '/tmp/repo', }) - } finally { - await fs.rm(cwd, { recursive: true, force: true }) - } - }) + expect(callFor('maven')?.entryFile).toBeUndefined() + }, + ) it('places the facts of each build it generates, with its sidecar entry', async () => { const cwd = await fs.realpath( From 53c2b04ce1651db51d88555c2f7a2ecd2cb00396 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 13:43:39 +0100 Subject: [PATCH 05/12] Tell a failed solution listing from an unreadable solution A crashed `--list-members` run answers `status: failed` with no members, which read as the SDK being unable to read the solution, so a readable twin beside it could skip it. Only `members: null` means that now; a failed listing lists nothing and the solution is built. --- src/commands/manifest/run-manifest-facts.mts | 11 +++++++---- src/commands/manifest/run-manifest-facts.test.mts | 15 +++++++++++++-- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 6a159f6925..5629b471ec 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -126,7 +126,9 @@ type SocketFactsResult = | { status: 'empty' } | { status: 'failed' } -type SolutionMembers = { members: string[] | null } +type SolutionMembers = + | { members: string[] | null; status: 'members' } + | { status: 'failed' } type ProjectList = | { projects: SocketFactsProject[]; status: 'listed' } @@ -285,8 +287,9 @@ export async function keepFacts( const membersByRequest = new Map>() -// The projects a dotnet solution builds; undefined when the SDK cannot read -// it, empty when the listing fails, which the build itself then reports. +// The projects a dotnet solution builds. Undefined when the SDK cannot read +// it, so a readable twin may stand in; empty when the listing fails, which the +// build itself then reports. export async function listDotnetSolutionMembers({ context = {}, ...options @@ -308,7 +311,7 @@ export async function listDotnetSolutionMembers({ ['--list-members'], context, ) - if (!result) { + if (result?.status !== 'members') { return [] } return result.members ?? undefined diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index 05fcfeb247..daafc21519 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -345,7 +345,7 @@ describe('keepFacts', () => { describe('listDotnetSolutionMembers', () => { it('lists the members once for the same request, which takes no Java', async () => { - coanaAnswers({ members: ['/r/A/A.csproj'] }) + coanaAnswers({ members: ['/r/A/A.csproj'], status: 'members' }) const request = { buildOpts: [], cwd, @@ -377,7 +377,7 @@ describe('listDotnetSolutionMembers', () => { }) it('cannot tell when the SDK cannot read the solution', async () => { - coanaAnswers({ members: null }) + coanaAnswers({ members: null, status: 'members' }) expect( await listDotnetSolutionMembers({ buildOpts: [], @@ -387,6 +387,17 @@ describe('listDotnetSolutionMembers', () => { ).toBeUndefined() }) + it('lists nothing when Coana reports a failed listing', async () => { + coanaAnswers({ blame: 'coana', reason: 'crashed', status: 'failed' }, false) + expect( + await listDotnetSolutionMembers({ + buildOpts: [], + cwd, + entryFile: 'Crashed.sln', + }), + ).toEqual([]) + }) + it('lists nothing when Coana fails', async () => { coanaAnswers(undefined, false) expect( From dae0d20f3c1dea697c298e3cad142ecbf133dee0 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 13:43:55 +0100 Subject: [PATCH 06/12] Say when the scan excludes a module's old facts file --- src/commands/manifest/generate-recursive-manifests.test.mts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index 4f7765034f..52c39e628e 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -301,7 +301,8 @@ describe('generateRecursiveManifests', () => { expect([...workDir.entries.keys()]).toEqual([ path.join(reactorA, 'pom.xml.socket.facts.json'), ]) - // The file there is not this scan's, so it is not to be collected. + // A discarded independent build of the module excludes its old file + // from the scan. expect( outcomes.find(o => o.dir === sharedLib)?.discardedFactsPath, ).toBe(builtAlone ? sharedFacts : undefined) From 3cb966e15fa1b2681a4cec7e6a20e6603ffff288 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 13:45:18 +0100 Subject: [PATCH 07/12] Tighten comments on facts generation and the Coana launcher --- src/commands/fix/coana-fix.mts | 4 +-- src/commands/fix/generated-socket-facts.mts | 4 +-- .../manifest/generate-recursive-manifests.mts | 2 +- .../manifest/generate_auto_manifest.mts | 2 +- src/commands/manifest/run-manifest-facts.mts | 31 +++++++++---------- src/utils/coana-release.test.mts | 1 - src/utils/coana/release.mts | 8 ++--- 7 files changed, 24 insertions(+), 28 deletions(-) diff --git a/src/commands/fix/coana-fix.mts b/src/commands/fix/coana-fix.mts index 37437c21c3..7101a76f60 100644 --- a/src/commands/fix/coana-fix.mts +++ b/src/commands/fix/coana-fix.mts @@ -416,8 +416,8 @@ async function coanaFixWithFacts( } } const sidecarFile = factsSlot?.generated?.sidecarFile - // Discovery only needs which artifacts the facts files resolve; applying - // fixes also reads what facts generation kept of each build root. + // Discovery reads the artifacts resolved by the facts files. + // Applying a fix also reads the saved state for each build root. const discoveryFlags = factsSlot?.generated?.artifactsFlags ?? [] const factsFlags = [ ...discoveryFlags, diff --git a/src/commands/fix/generated-socket-facts.mts b/src/commands/fix/generated-socket-facts.mts index b85b3b82e8..67a2aba759 100644 --- a/src/commands/fix/generated-socket-facts.mts +++ b/src/commands/fix/generated-socket-facts.mts @@ -13,8 +13,8 @@ export type GeneratedSocketFacts = { // Facts files of dropped runs, which Coana must not read. discardedPaths: string[] paths: string[] - // What Coana kept of each build root, for `--socket-facts-sidecar`; written - // outside the repository. + // Records each build root's saved state for `--socket-facts-sidecar`. + // The file lives outside the repository. sidecarFile: string remove: () => Promise restore: () => Promise diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index fbe3748d2b..fbf17ea1d7 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -722,7 +722,7 @@ async function runCandidate( } // Builds `root` unless earlier builds cover it, then adds what it loaded to -// `covered` and keeps its facts. +// `covered` and copies its staged facts to their target path. export async function buildUncoveredRoot({ config, context, diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index 1797e1c315..73c71be813 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -86,7 +86,7 @@ export async function generateAutoManifest({ cwd: string // Scan-root-relative `--exclude-paths`: skip excluded subprojects. excludePaths?: string[] | undefined - // The invoking command's flag for `excludePaths`, when it takes one. + // A failure message must name an option the invoking command accepts. excludePathsFlag?: string | undefined outputKind: OutputKind verbose: boolean diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 5629b471ec..9456ba4308 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -26,9 +26,9 @@ export type BuildOptionHints = { // Reachability scans only: reachability cannot install a dependency that // `ignoreUnresolved` lets through, so it must be told to continue too. continueOnInstallErrorsFlag?: string | undefined - // The invoking command's option that leaves paths out of the scan. excludePathsFlag?: string | undefined - // Taken as flags; every other option is set in `socketJson`. + // The invoking command accepts these options as flags. Users set the rest in + // `socketJson`. flags: ReadonlySet // Wizard that writes `socketJson`. setupCommand: string @@ -55,8 +55,7 @@ const FLAG_HINTS: BuildOptionHints = { socketJson: SOCKET_JSON, } -// What a later Coana run needs of one generated build root; passed back to it -// unread. +// The CLI passes this build root's entry back to Coana unchanged. export type SocketFactsSidecarEntry = { factsFile: string stateDir: string @@ -91,7 +90,6 @@ export type RunManifestFactsResult = { factsPath: string projects: SocketFactsProject[] sidecarEntry?: SocketFactsSidecarEntry | undefined - // Where the facts belong. targetPath: string } @@ -176,7 +174,8 @@ async function runGenerateSocketFacts( { coanaVersion: context.coanaVersion, minimumVersion: COANA_CLI_VERSION, - // Coana logs to stdout; keep the command's own stdout machine-readable. + // Redirect Coana's logs to stderr to keep the command's stdout + // machine-readable. stdio: ['inherit', 2, 'inherit'], }, ) @@ -199,8 +198,8 @@ export type SocketFactsRequestOptions = { // The file in `cwd` to build: Maven's POM (unset leaves Maven's default), // dotnet's solution or project (required). entryFile?: string | undefined - // What `excludePaths` are relative to, as a build can reach modules outside - // its own directory; `cwd` when unset. + // A build can include modules outside its directory, so exclusions are + // relative to this base. Defaults to `cwd`. excludeBase?: string | undefined excludeConfigs?: string | undefined excludePaths?: string[] | undefined @@ -216,8 +215,9 @@ export type SocketFactsRunOptions = SocketFactsRequestOptions & { context?: SocketFactsContext | undefined } -// SOCKET_CLI_*_PATH, else `bin`, the project wrapper, then PATH; standalone, -// JVM tools take only SOCKET_CLI_*_PATH, as no JVM tooling is bundled. +// Check SOCKET_CLI_*_PATH, then `bin`, the project wrapper and PATH. +// Standalone JVM builds require SOCKET_CLI_*_PATH because the CLI ships without +// JVM tooling. function toSocketFactsRequest({ bin, buildOpts, @@ -258,7 +258,6 @@ function toSocketFactsRequest({ ...(excludeConfigs ? { excludeConfigs } : {}), ignoreUnresolved, ...(includeConfigs ? { includeConfigs } : {}), - // .NET builds take no Java. ...(javaHome && ecosystem !== 'dotnet' ? { javaHome } : {}), verbose, }, @@ -303,7 +302,7 @@ export async function listDotnetSolutionMembers({ } return await getOrInsert( membersByRequest, - // The Coana that answers is part of the question. + // Different Coana releases can list the same solution differently. JSON.stringify([context.coanaVersion, request.data]), async () => { const { result } = await runGenerateSocketFacts( @@ -319,8 +318,8 @@ export async function listDotnetSolutionMembers({ ) } -// Resolves nothing; undefined, after reporting why, when the build cannot list -// its projects. +// Lists projects without resolving dependencies. +// A failed listing reports the reason and returns undefined. export async function listBuildProjects({ context = {}, ...options @@ -345,8 +344,8 @@ export async function listBuildProjects({ return result.status === 'listed' ? result.projects : undefined } -// A failure sets a non-zero exit code; only a failed build is Coana's to -// report. With a work dir, the facts stay there until keepFacts places them. +// Failures set a nonzero exit code. Coana reports build failures. +// With a work directory, facts stay there until keepFacts places them. export async function runManifestFacts({ context = {}, ...options diff --git a/src/utils/coana-release.test.mts b/src/utils/coana-release.test.mts index 80a526235c..94360d2440 100644 --- a/src/utils/coana-release.test.mts +++ b/src/utils/coana-release.test.mts @@ -5,7 +5,6 @@ * - spawnCoana: runs cli-wrapper.mjs from the cache with the caller's args, * cwd and environment, sets the variables Coana reads, leaves the user's * API token variables out, and surfaces a failing run's output. - * - spawnCoana with a minimum version: refuses an older Coana. * * Testing Approach: * A fake cli-wrapper.mjs is installed into a temporary cache with the real diff --git a/src/utils/coana/release.mts b/src/utils/coana/release.mts index bef3e2dd2c..0e321ce2af 100644 --- a/src/utils/coana/release.mts +++ b/src/utils/coana/release.mts @@ -76,8 +76,7 @@ type CoanaSpawnOptions = { coanaVersion?: string | undefined cwd?: string | URL | undefined env?: Record | undefined - // The oldest Coana the command exists in; checked against the version a - // pinned spec resolves to. + // The resolved Coana release must meet the minimum version for this command. minimumVersion?: string | undefined repoName?: string | undefined spinner?: Spinner | undefined @@ -222,9 +221,8 @@ type CoanaCliDir = { dir: string; version: string } /** * The directory of the Coana CLI's `cli` component for `versionSpec`, an exact - * version or a range, and the version it holds, downloading it into the cache - * when the cache lacks it. `env` reaches the cache script, which reads - * `XDG_CACHE_HOME` from it. + * version or a range, downloading it into the cache when the cache lacks it. + * `env` reaches the cache script, which reads `XDG_CACHE_HOME` from it. */ async function getCoanaCliDir( versionSpec: string, From a0bdf83079247886a89b1cf486dcb4886857ee7f Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 13:45:25 +0100 Subject: [PATCH 08/12] Name test helpers for what they do instead of commenting them --- src/commands/manifest/run-manifest-facts.test.mts | 15 +++++++-------- .../setup-recursive-manifest-config.test.mts | 11 +++++------ 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index daafc21519..ff1dff73c1 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -35,9 +35,7 @@ const baseArgs = { let cwd = '' let calls: Call[] = [] -// Answers each Coana run by writing `text` as its result file, or nothing when -// `text` is undefined. -function coanaWrites(text: string | undefined, ok = true): void { +function coanaWritesResultFile(text: string | undefined, ok = true): void { vi.mocked(spawnCoana).mockImplementation(async args => { const list = [...args] const request = JSON.parse( @@ -53,10 +51,11 @@ function coanaWrites(text: string | undefined, ok = true): void { }) } -// Answers each Coana run with `result`, as `coana generate-socket-facts` writes -// it, or writes nothing when `result` is undefined. function coanaAnswers(result: unknown, ok = true): void { - coanaWrites(result === undefined ? undefined : JSON.stringify(result), ok) + coanaWritesResultFile( + result === undefined ? undefined : JSON.stringify(result), + ok, + ) } beforeEach(async () => { @@ -272,7 +271,7 @@ describe('runManifestFacts', () => { }, { name: 'writes an unreadable result', - answer: () => coanaWrites('{"status":"gener'), + answer: () => coanaWritesResultFile('{"status":"gener'), reported: () => "Coana's result is unreadable", }, ])('fails the root when Coana $name', async ({ answer, reported }) => { @@ -480,7 +479,7 @@ describe('listBuildProjects', () => { }) it('lists nothing when Coana writes an unreadable result', async () => { - coanaWrites('') + coanaWritesResultFile('') expect(await listBuildProjects({ ...listArgs, cwd })).toBeUndefined() }) }) diff --git a/src/commands/manifest/setup-recursive-manifest-config.test.mts b/src/commands/manifest/setup-recursive-manifest-config.test.mts index ba46539ee3..8fdcddc50a 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.test.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.test.mts @@ -49,8 +49,7 @@ function mavenRoots(...dirs: string[]): BuildRoot[] { return dirs.map(dir => ({ dir, entryFile: 'pom.xml' })) } -// A Maven project of the build at `buildRoot`, loaded from `pomFile`. -function project( +function mavenProject( buildRoot: string, subprojectDir: string, pomFile = 'pom.xml', @@ -197,8 +196,8 @@ describe('setupRecursiveManifestConfig', () => { return undefined } return [ - project(cwd, '.', entryFile), - ...(modules[rel] ?? []).map(dir => project(cwd, dir)), + mavenProject(cwd, '.', entryFile), + ...(modules[rel] ?? []).map(dir => mavenProject(cwd, dir)), ] }) const answer = (answers: Answers) => @@ -330,7 +329,7 @@ describe('setupRecursiveManifestConfig', () => { if (cwd === file('legacy') && (attempts += 1) === 1) { return undefined } - return [project(cwd, '.')] + return [mavenProject(cwd, '.')] }) vi.mocked(setupMaven).mockImplementation(async config => { config.javaHome = '/opt/jdk-8' @@ -350,7 +349,7 @@ describe('setupRecursiveManifestConfig', () => { await setupRecursiveManifestConfig(repo, false) expect(attempts).toBe(2) - // A listing's remedies point at this wizard, not at flags. + // A listing's remedies point at this wizard. expect( vi .mocked(listBuildProjects) From 7efaeb88d171e2897979c986ecce455c1f7f9764 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 14:29:08 +0100 Subject: [PATCH 09/12] Restore what the Coana launcher comments said about versions getCoanaCliDir's doc again says it returns the version it resolved, and the test header again lists the minimum-version tests, plus the standalone build's. --- src/utils/coana-release.test.mts | 2 ++ src/utils/coana/release.mts | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/utils/coana-release.test.mts b/src/utils/coana-release.test.mts index 94360d2440..29519fe663 100644 --- a/src/utils/coana-release.test.mts +++ b/src/utils/coana-release.test.mts @@ -5,6 +5,8 @@ * - spawnCoana: runs cli-wrapper.mjs from the cache with the caller's args, * cwd and environment, sets the variables Coana reads, leaves the user's * API token variables out, and surfaces a failing run's output. + * - spawnCoana with a minimum version: refuses an older Coana. + * - spawnCoana in the standalone build: caches every embedded component. * * Testing Approach: * A fake cli-wrapper.mjs is installed into a temporary cache with the real diff --git a/src/utils/coana/release.mts b/src/utils/coana/release.mts index 0e321ce2af..038c066432 100644 --- a/src/utils/coana/release.mts +++ b/src/utils/coana/release.mts @@ -221,7 +221,8 @@ type CoanaCliDir = { dir: string; version: string } /** * The directory of the Coana CLI's `cli` component for `versionSpec`, an exact - * version or a range, downloading it into the cache when the cache lacks it. + * version or a range, and the version it holds, downloading it into the cache + * when the cache lacks it. * `env` reaches the cache script, which reads `XDG_CACHE_HOME` from it. */ async function getCoanaCliDir( From 17c261f7b1cf3be5d48432ee5c79b123cbd05abb Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 17:45:37 +0100 Subject: [PATCH 10/12] Drop the Coana launcher comments that repeat the test name and the return type The minimum-version bullet repeats its test's name, and getCoanaCliDir's doc repeats CoanaCliDir's version field. --- src/utils/coana-release.test.mts | 1 - src/utils/coana/release.mts | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/utils/coana-release.test.mts b/src/utils/coana-release.test.mts index 29519fe663..35e8ba758e 100644 --- a/src/utils/coana-release.test.mts +++ b/src/utils/coana-release.test.mts @@ -5,7 +5,6 @@ * - spawnCoana: runs cli-wrapper.mjs from the cache with the caller's args, * cwd and environment, sets the variables Coana reads, leaves the user's * API token variables out, and surfaces a failing run's output. - * - spawnCoana with a minimum version: refuses an older Coana. * - spawnCoana in the standalone build: caches every embedded component. * * Testing Approach: diff --git a/src/utils/coana/release.mts b/src/utils/coana/release.mts index 038c066432..0e321ce2af 100644 --- a/src/utils/coana/release.mts +++ b/src/utils/coana/release.mts @@ -221,8 +221,7 @@ type CoanaCliDir = { dir: string; version: string } /** * The directory of the Coana CLI's `cli` component for `versionSpec`, an exact - * version or a range, and the version it holds, downloading it into the cache - * when the cache lacks it. + * version or a range, downloading it into the cache when the cache lacks it. * `env` reaches the cache script, which reads `XDG_CACHE_HOME` from it. */ async function getCoanaCliDir( From f2d6627c2921e16a4f4277ab2c88472203855cea Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 21:08:16 +0100 Subject: [PATCH 11/12] Drop the test header's bullet for the standalone build's embedded Coana The standalone build downloads Coana like the npm CLI, so no test covers caching embedded components. --- src/utils/coana-release.test.mts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/utils/coana-release.test.mts b/src/utils/coana-release.test.mts index 35e8ba758e..94360d2440 100644 --- a/src/utils/coana-release.test.mts +++ b/src/utils/coana-release.test.mts @@ -5,7 +5,6 @@ * - spawnCoana: runs cli-wrapper.mjs from the cache with the caller's args, * cwd and environment, sets the variables Coana reads, leaves the user's * API token variables out, and surfaces a failing run's output. - * - spawnCoana in the standalone build: caches every embedded component. * * Testing Approach: * A fake cli-wrapper.mjs is installed into a temporary cache with the real From 63f04c928852bf69feece0839a7f744395fe1156 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 21:14:51 +0100 Subject: [PATCH 12/12] Drop the standalone build's .NET facts smoke step Coana generates .NET facts, as it does JVM facts, and the standalone build downloads Coana at runtime with the user's credentials, which its offline smoke test does not have. The step only exercised the .NET facts helper the build used to embed. --- src/sea/README.md | 2 +- src/sea/build/smoke-test.mts | 34 +--------------------------------- 2 files changed, 2 insertions(+), 34 deletions(-) diff --git a/src/sea/README.md b/src/sea/README.md index 98986a2c19..62e0359c2b 100644 --- a/src/sea/README.md +++ b/src/sea/README.md @@ -75,7 +75,7 @@ Terminal images trim unused rows while preserving internal spacing. Each animati ### Build, test, and publish the RC -Run `pnpm build:sea` on the target OS and CPU. The builder checks help and version output and runs `patch --version` where available. It generates .NET facts with package sources disabled and generates SBOMs for npm and Yarn Classic fixtures. +Run `pnpm build:sea` on the target OS and CPU. The builder checks help and version output and runs `patch --version` where available. It generates SBOMs for npm and Yarn Classic fixtures. `socket sea smoke-test` verifies VFS integrity and checks that an empty Coana cache reports a miss. It checks the bundled Node and uv versions and removes the extracted executables. Run `pnpm test:sea` for the native suite. diff --git a/src/sea/build/smoke-test.mts b/src/sea/build/smoke-test.mts index f096b1c2e0..777f571fcc 100644 --- a/src/sea/build/smoke-test.mts +++ b/src/sea/build/smoke-test.mts @@ -26,15 +26,6 @@ export async function smokeTestSea( const env = { PATH: process.env['PATH'], SystemRoot: process.env['SystemRoot'], - // NuGet and MSBuild locate machine-wide configuration and SDKs here. - ProgramData: process.env['ProgramData'], - ProgramFiles: process.env['ProgramFiles'], - 'ProgramFiles(x86)': process.env['ProgramFiles(x86)'], - ProgramW6432: process.env['ProgramW6432'], - DOTNET_ROOT: process.env['DOTNET_ROOT'], - DOTNET_CLI_HOME: cwd, - DOTNET_CLI_TELEMETRY_OPTOUT: '1', - MSBUILDDISABLENODEREUSE: '1', HOME: cwd, USERPROFILE: cwd, APPDATA: cwd, @@ -63,31 +54,8 @@ export async function smokeTestSea( } const { stdout } = await run(['sea', 'smoke-test']) assert.match(stdout, /^VFS smoke test passed$/mu) - await fs.writeFile( - path.join(cwd, 'NuGet.Config'), - '', - ) - await fs.writeFile( - path.join(cwd, 'Smoke.csproj'), - 'net8.0true', - ) - await run(['manifest', 'dotnet', 'Smoke.csproj'], 60_000) - const facts = JSON.parse( - await fs.readFile(path.join(cwd, 'Smoke.csproj.socket.facts.json'), 'utf8'), - ) - assert.equal(facts.metadata.tool, 'dotnet') - assert.ok( - facts.projects.some( - (project: { id: string }) => project.id === 'Smoke.csproj', - ), - ) - assert.deepEqual( - (await fs.readdir(tmp)).filter( - name => - name.startsWith('socket-cli-sea-') || - name.startsWith('socket-dotnet-facts-'), - ), + (await fs.readdir(tmp)).filter(name => name.startsWith('socket-cli-sea-')), [], )