diff --git a/.gitignore b/.gitignore index 3d333045c..a0cbe4048 100644 --- a/.gitignore +++ b/.gitignore @@ -597,19 +597,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 3bf8d1eae..97a0ba578 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 d1fa67000..b62fe4bfe 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 bc3a3d303..7fb0dfeb7 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 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, - ...(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 a6654b968..67a2aba75 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. + // Records each build root's saved state for `--socket-facts-sidecar`. + // The file lives 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 f395c62ae..cf50966d0 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 921d4270c..3db95fc00 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 0a04b6c4e..f7da009c0 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 fd2479621..b4970b42a 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 0b1b8c4bf..7d5e32eae 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 45d675081..606c2af69 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 42a9fdeea..654bd8e97 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 3ed9a6329..000000000 --- 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 ad436e6bc..000000000 --- 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 b1a1d35e2..000000000 --- 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 82d517c08..6417252d6 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 1c8b7c411..5c5dbcbda 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 ec261744f..000000000 --- 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 28209f538..000000000 --- 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 c72ef53b3..000000000 --- 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 f2db00278..000000000 --- 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 e4979ec54..fbf17ea1d 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' @@ -121,8 +121,7 @@ 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[] { +function withoutMavenFileOpts(opts: string[]): string[] { const kept: string[] = [] for (let i = 0, { length } = opts; i < length; i += 1) { const opt = opts[i]! @@ -138,11 +137,6 @@ function withoutMavenFileOpts(dir: string, opts: string[]): string[] { 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 } @@ -154,20 +148,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 +158,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 +169,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 +185,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, - toolOpts: config.buildOpts, + } +} + +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, + hints, + ignoreUnresolved: config.ignoreUnresolved, + includeConfigs: config.includeConfigs, + javaHome: config.javaHome, + verbose: config.verbose, } } @@ -282,7 +295,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 +330,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 +502,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 +556,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 +564,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 +583,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 +671,61 @@ 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.purpose === 'reachability' + ? 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, - } -} - -// 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 }) + result, } } -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 copies its staged facts to their target path. export async function buildUncoveredRoot({ config, + context, covered, cwd, ecosystem, @@ -789,11 +733,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 +744,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 +791,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 +817,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 +834,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(), purpose: 'upload' }), + ) if (!outcomes.some(o => o.status === 'failed')) { process.exitCode = exitCodeBefore @@ -1016,10 +904,7 @@ export function resolveEcosystemConfig( const bin = config?.bin ?? undefined return { bin: bin ?? resolveBuildToolBin('maven', dir), - buildOpts: withoutMavenFileOpts( - dir, - parseBuildToolOpts(config?.mavenOpts ?? undefined), - ), + buildOpts: parseBuildToolOpts(config?.mavenOpts ?? undefined), excludeConfigs: config?.excludeConfigs ?? '', ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', @@ -1028,3 +913,23 @@ export function resolveEcosystemConfig( 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 (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, buildOpts } +} diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index 7c78c3fdb..52c39e628 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,85 @@ 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(), + purpose: 'reachability', + } +} + +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 +176,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 +245,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 +253,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 +278,8 @@ describe('generateRecursiveManifests', () => { }) const outcomes = await generateRecursiveManifests({ + context: { workDir }, cwd: outer, - sidecarAcc, verbose: false, }) @@ -211,10 +292,17 @@ 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. + // 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) @@ -236,7 +324,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 +334,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 +355,8 @@ describe('generateRecursiveManifests', () => { }) const outcomes = await generateRecursiveManifests({ + context: { workDir }, cwd: outer, - sidecarAcc, verbose: false, }) @@ -276,19 +366,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 +395,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 +426,8 @@ describe('generateRecursiveManifests', () => { false, ) expect(existsSync(path.join(app, 'pom.xml.socket.facts.json'))).toBe(true) + expect(ownWorkDir?.purpose).toBe('upload') + expect(existsSync(ownWorkDir!.dir)).toBe(false) } finally { await fs.rm(outer, { recursive: true, force: true }) } @@ -345,42 +450,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 +511,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 +553,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 +595,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 +638,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 +657,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 +722,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 +758,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 +783,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 +803,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 +829,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 +850,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 +862,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 +890,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 +925,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 +943,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 +961,7 @@ describe('generateRecursiveManifests', () => { } : {}, ) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -885,7 +986,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 +1014,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 +1065,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 +1122,7 @@ describe('generateRecursiveManifests', () => { } return {} }) - vi.mocked(runManifestFacts).mockImplementation(async ({ cwd }) => ({ + mockFacts(async ({ cwd }) => ({ factsPath: path.join(cwd, '.socket.facts.json'), projects: [], })) @@ -1052,7 +1153,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 +1183,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 +1235,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 +1250,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 +1296,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 +1336,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 +1410,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 +1443,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 +1481,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 +1531,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 +1558,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 +1625,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 +1677,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 +1693,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 +1768,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 +1844,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 +1889,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 a45fa2673..73c71be81 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -2,17 +2,20 @@ 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, @@ -23,12 +26,14 @@ 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 +45,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 @@ -70,156 +73,126 @@ 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 + // A failure message must name an option the invoking command accepts. + 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?.purpose === 'reachability' + ? 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, - }) - abortFactsRunIfFailed('maven', outcome) + // 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) { @@ -228,11 +201,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 +280,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 f4a5e4b1b..74c9c76e3 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,130 @@ 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('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({ buildOpts: [], cwd: '/tmp/repo' }) + expect(callFor('maven')?.entryFile).toBeUndefined() + expect(callFor('gradle')).toMatchObject({ cwd: '/tmp/repo' }) + }) + + 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'] }) + }) + + // 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 } } }, + } as SocketJson) + await generateAutoManifest({ + cwd: '/tmp/repo', + detected: { ...baseDetected, maven: true, count: 1 }, + outputKind: 'text', + verbose: false, + }) + expect(callFor('maven')).toMatchObject({ + bin: './mvnw', + buildOpts: mavenOpts.split(' '), + cwd: '/tmp/repo', + excludeBase: '/tmp/repo', + }) + expect(callFor('maven')?.entryFile).toBeUndefined() + }, + ) + + 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(), + purpose: 'reachability', + } + 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 +535,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 106e3fe39..5942c879f 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 8b24b628b..32acbeedc 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -1,61 +1,224 @@ 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 { isStandaloneSea } 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 { BuildRoot } from './discover-manifest-roots.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 + excludePathsFlag?: string | undefined + // The invoking command accepts these options as flags. Users set the rest 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, +} + +// The CLI passes this build root's entry back to Coana unchanged. +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 + // 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 + orgSlug?: string | undefined + workDir?: SocketFactsWorkDir | undefined } -// 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') +// 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 + 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, of the contract +// version it states. +type SocketFactsRequest = { + contract: typeof SOCKET_FACTS_REQUEST_CONTRACT + config: { + bin?: string | undefined + buildOpts: string[] + excludeConfigs?: string | undefined + ignoreUnresolved: boolean + includeConfigs?: string | undefined + javaHome?: string | undefined + verbose: boolean + } + 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' } + | { status: 'failed' } + +type SolutionMembers = + | { members: string[] | null; status: 'members' } + | { status: 'failed' } + +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, + // Redirect Coana's logs to stderr to keep the command's 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 + // 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 + 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 +} + +// 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, cwd, @@ -65,243 +228,178 @@ 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' && isStandaloneSea(), + ) + } 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: { + contract: SOCKET_FACTS_REQUEST_CONTRACT, + config: { + bin: resolvedBin, + buildOpts, + ...(excludeConfigs ? { excludeConfigs } : {}), + ignoreUnresolved, + ...(includeConfigs ? { includeConfigs } : {}), + ...(javaHome && ecosystem !== 'dotnet' ? { javaHome } : {}), + verbose, + }, + excludeBase: path.resolve(excludeBase ?? cwd), + ...(excludePaths?.length ? { excludePaths } : {}), + hints: toRequestHints(hints), + root: { dir: path.resolve(cwd), ...(entryFile ? { entryFile } : {}) }, + 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, so a readable twin may stand in; 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, + // Different Coana releases can list the same solution differently. + 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?.status !== 'members') { + 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 + }, + ) +} + +// Lists projects without resolving dependencies. +// A failed listing reports the reason and returns undefined. +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 +} + +// 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 +}: 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, + [ + '--purpose', + workDir?.purpose ?? 'upload', + ...(workDir ? ['--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 && workDir.purpose !== 'upload' && !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 e55a8892a..ff1dff73c 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,453 @@ const baseArgs = { } let cwd = '' +let calls: Call[] = [] + +function coanaWritesResultFile(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' } + }) +} + +function coanaAnswers(result: unknown, ok = true): void { + coanaWritesResultFile( + 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({ + contract: 1, + config: { + bin: 'mvn', + buildOpts: ['-Pci'], + excludeConfigs: 'test*', + ignoreUnresolved: false, + javaHome: '$JAVA11_HOME', + verbose: false, + }, + excludeBase: cwd, + excludePaths: ['docs/**'], + hints: { + excludePathsFlag: '--exclude-paths', + flags: ['excludeConfigs', 'ignoreUnresolved', 'verbose'], + 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') + 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() + expect(vi.mocked(spawnCoana).mock.calls[0]![2]?.cwd).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() - }) - 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(), + purpose: 'reachability', + } + const result = await runManifestFacts({ + ...baseArgs, + context: { workDir }, + cwd, + }) + expect(calls[0]!.args.slice(-4)).toEqual([ + '--purpose', + 'reachability', + '--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 for socket fix', async () => { + coanaAnswers({ + factsPath: '/w/y/f', + projects: [], + sidecarEntry: { factsFile: '/r/f', stateDir: '/w/y' }, + status: 'generated', + targetPath: '/r/f', }) + const workDir: SocketFactsWorkDir = { + dir: '/w', + entries: new Map(), + purpose: 'fix', + } + await runManifestFacts({ ...baseArgs, context: { workDir }, cwd }) + expect(calls[0]!.args.slice(-4)).toEqual([ + '--purpose', + 'fix', + '--work-dir', + '/w', + ]) + }) - 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', + 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 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: SocketFactsWorkDir = { + dir: '/w', + entries: new Map(), + purpose: 'reachability', + } + expect( + await runManifestFacts({ ...baseArgs, context: { workDir }, cwd }), + ).toBeNull() + expect(process.exitCode).toBe(1) + }) + + it('is nothing to upload when the build resolves nothing', async () => { + coanaAnswers({ status: 'empty' }) + expect(await runManifestFacts({ ...baseArgs, cwd })).toBeUndefined() + expect(process.exitCode).toBeUndefined() + }) - const outcome = await runManifestFacts({ ...baseArgs, cwd }) + 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: () => coanaWritesResultFile('{"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(outcome).toBeNull() + 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() + }) +}) + +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: SocketFactsWorkDir = { + dir: '/w', + entries: new Map(), + purpose: 'reachability', + } - const outcome = await runManifestFacts({ ...baseArgs, cwd }) + 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, which takes no Java', async () => { + coanaAnswers({ members: ['/r/A/A.csproj'], status: 'members' }) + 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({ + contract: 1, + config: { + bin: 'dotnet', + buildOpts: [], + ignoreUnresolved: false, + verbose: false, + }, + excludeBase: cwd, + hints: { + excludePathsFlag: '--exclude-paths', + flags: ['excludeConfigs', 'ignoreUnresolved', 'verbose'], + setupCommand: 'socket manifest setup', + socketJson: 'socket.json', + }, + root: { dir: cwd, entryFile: 'All.sln' }, + 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)) + it('cannot tell when the SDK cannot read the solution', async () => { + coanaAnswers({ members: null, status: 'members' }) + expect( + await listDotnetSolutionMembers({ + buildOpts: [], + cwd, + entryFile: 'All.slnx', + }), + ).toBeUndefined() + }) - await runManifestFacts({ ...baseArgs, cwd, ecosystem: 'sbt' }) + 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([]) + }) - 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({ + contract: 1, + config: { + bin: 'mvn', + buildOpts: ['-Pci'], + ignoreUnresolved: false, + javaHome: '$JAVA11_HOME', + verbose: false, + }, + excludeBase: cwd, + excludePaths: ['reactor/moduleB'], + root: { dir: path.join(cwd, 'reactor'), entryFile: 'pom.xml' }, + 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 () => { + coanaWritesResultFile('') + 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 20c4a5651..7e92da93d 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 ca6cdfdf3..400ded19a 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 93550bab0..8fdcddc50 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,13 @@ 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: [], - } +function mavenProject( + 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 +186,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 +195,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 [ + mavenProject(cwd, '.', entryFile), + ...(modules[rel] ?? []).map(dir => mavenProject(cwd, dir)), + ] }) const answer = (answers: Answers) => vi.mocked(select).mockImplementation(async ({ choices, message }) => { @@ -239,7 +232,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 +325,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 [mavenProject(cwd, '.')] }) vi.mocked(setupMaven).mockImplementation(async config => { config.javaHome = '/opt/jdk-8' @@ -356,6 +349,19 @@ describe('setupRecursiveManifestConfig', () => { await setupRecursiveManifestConfig(repo, false) expect(attempts).toBe(2) + // A listing's remedies point at this wizard. + 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 481edee7b..dcee43b95 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 d9af8e8ce..31fb00622 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(), + purpose: 'reachability', + } + : 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 f7d23a602..d2ef1c4a8 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({ purpose: 'reachability' }), + }), }), ) 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 698a092c7..8e547f23b 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 e70c710b4..a03f96571 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 1c77aaf41..4a9a03558 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 4e584928e..7f2ea4980 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 fbbee8fe8..b2d9f6201 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'] + +// The consumer sets the purpose. +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,33 @@ 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, + purpose: consumer === 'reach' ? 'reachability' : 'fix', + }, + }, 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 +143,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 ecd56919e..be0248cb9 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, purpose: 'reachability' }, }, { consumer: 'fix', - sbtTmpDir: undefined, - sidecar: true, - withFiles: false, - }, - { - consumer: 'reach', - sbtTmpDir: '/tmp/sbt', - sidecar: true, - withFiles: true, + expected: { ...workDir, purpose: 'fix' }, }, + { consumer: 'upload', expected: undefined }, ] as const)( - 'generates for $consumer', - async ({ consumer, sbtTmpDir, sidecar, withFiles }) => { + 'generates every build root for $consumer, with the purpose it reads the facts for', + 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 91572be83..310310267 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/sea/README.md b/src/sea/README.md index 44babfcd9..7cda005c3 100644 --- a/src/sea/README.md +++ b/src/sea/README.md @@ -47,7 +47,7 @@ The build stages and embeds the `cdxgen` and `synp` APIs for darwin-arm64, but t Rollup creates a notice inventory from each bundled dependency graph. Some pinned packages omit their license text from npm; exact package-version entries in `.config/rollup.cdxgen-sea.config.mjs` and `src/sea/rollup-provenance.mjs` supply the missing text. A dependency bump cannot reuse a mismatched entry, so the inventory records a missing-text obligation. README files are not used as license text or shipped as notice documents. -The 2.x RC embeds Coana's CLI and analyzers for Linux and macOS. Its build needs a Socket API token with Coana artifact access; without access, the build fails. Windows, Python, and JVM capabilities remain unavailable. The runtime does not download helper tools. +The 2.x RC embeds Coana's CLI, analyzers and facts tools for Linux and macOS. Its build needs a Socket API token with Coana artifact access; without access, the build fails. Windows, Python, and JVM capabilities remain unavailable. The runtime does not download helper tools. ## Manifest diff --git a/src/sea/bootstrap.mts b/src/sea/bootstrap.mts index 960a992b2..78b42db7f 100644 --- a/src/sea/bootstrap.mts +++ b/src/sea/bootstrap.mts @@ -7,7 +7,7 @@ import os from 'node:os' import path from 'node:path' import { Worker } from 'node:worker_threads' -import { SEA_COANA_VFS_PATHS } from './paths/coana.mts' +import { COANA_COMPONENTS, SEA_COANA_VFS_PATHS } from './paths/coana.mts' import { cleanupBundledTool, getBundledTool } from './runtime.mts' import { digestVfs } from './vfs-digest.mts' @@ -72,12 +72,15 @@ async function smokeTest(): Promise { .then(stat => stat.isFile()), true, ) - assert.equal( - await fs - .stat(path.join(__dirname, SEA_COANA_VFS_PATHS.analyzers, 'repos')) - .then(stat => stat.isDirectory()), - true, - ) + for (const component of COANA_COMPONENTS) { + assert.equal( + // eslint-disable-next-line no-await-in-loop + await fs + .stat(path.join(__dirname, SEA_COANA_VFS_PATHS[component])) + .then(stat => stat.isDirectory()), + true, + ) + } const node = await getBundledTool('coana-node') try { const output = execFileSync(node, ['--version'], { diff --git a/src/sea/build-sea.mts b/src/sea/build-sea.mts index ab2fbf3e0..b8ca8a2e4 100644 --- a/src/sea/build-sea.mts +++ b/src/sea/build-sea.mts @@ -1373,14 +1373,7 @@ async function main(): Promise { file: `${coanaPayload.vfsDirectory}/`, sha256: await digestTree(coanaPayload.directory), components: { - cli: { - sha256: coanaPayload.cliSha256, - size: coanaPayload.cliSize, - }, - analyzers: { - sha256: coanaPayload.analyzersSha256, - size: coanaPayload.analyzersSize, - }, + ...coanaPayload.components, node: { version: NODE_VERSION, sha256: coanaPayload.nodeSha256, diff --git a/src/sea/build/smoke-test.mts b/src/sea/build/smoke-test.mts index 5827284a5..3679c29ee 100644 --- a/src/sea/build/smoke-test.mts +++ b/src/sea/build/smoke-test.mts @@ -66,16 +66,30 @@ export async function smokeTestSea( 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', - ), - ) + // Coana generates Socket facts, so a build without it must refuse. + const coana = capabilities.unavailable.find(tool => tool.id === 'coana') + if (coana) { + await assert.rejects( + run(['manifest', 'dotnet', 'Smoke.csproj'], 60_000), + (err: Error & { code?: number; stderr?: string }) => + err.code === 1 && Boolean(err.stderr?.includes(coana.reason)), + ) + } else { + // A fresh HOME and an unreachable API leave only the embedded facts tools. + 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( diff --git a/src/sea/paths/coana.mts b/src/sea/paths/coana.mts index b5d286bb5..a8829bc3d 100644 --- a/src/sea/paths/coana.mts +++ b/src/sea/paths/coana.mts @@ -1,9 +1,14 @@ import path from 'node:path' +export const COANA_COMPONENTS = ['analyzers', 'cli', 'facts'] as const + +export type CoanaComponent = (typeof COANA_COMPONENTS)[number] + export const SEA_COANA_VFS_PATHS = Object.freeze({ analyzers: 'tools/coana/analyzers', cli: 'tools/coana/cli', cliWrapper: 'tools/coana/cli/cli-wrapper.mjs', + facts: 'tools/coana/facts', manifest: 'tools/coana/manifest.json', node: 'tools/coana/node', nodeDigest: 'tools/coana/node.sha256', @@ -17,10 +22,10 @@ export function seaCoanaPaths(root: string) { analyzers: fromRoot(SEA_COANA_VFS_PATHS.analyzers), cli: fromRoot(SEA_COANA_VFS_PATHS.cli), cliWrapper: fromRoot(SEA_COANA_VFS_PATHS.cliWrapper), + facts: fromRoot(SEA_COANA_VFS_PATHS.facts), manifest: fromRoot(SEA_COANA_VFS_PATHS.manifest), node: fromRoot(SEA_COANA_VFS_PATHS.node), nodeDigest: fromRoot(SEA_COANA_VFS_PATHS.nodeDigest), - repos: path.join(fromRoot(SEA_COANA_VFS_PATHS.analyzers), 'repos'), root: directory, } } diff --git a/src/sea/stage/coana.mts b/src/sea/stage/coana.mts index 2822fb9a2..cafe6e4bb 100644 --- a/src/sea/stage/coana.mts +++ b/src/sea/stage/coana.mts @@ -11,9 +11,14 @@ import { getDefaultOrgSlug } from '../../commands/ci/fetch-default-org-slug.mts' import { COANA_CLI_VERSION } from '../../constants.mts' import { apiFetch, sendApiRequest } from '../../utils/api.mts' import { envAsBoolean } from '../../utils/env.mts' -import { SEA_COANA_VFS_PATHS, seaCoanaPaths } from '../paths/coana.mts' +import { + COANA_COMPONENTS, + SEA_COANA_VFS_PATHS, + seaCoanaPaths, +} from '../paths/coana.mts' + +import type { CoanaComponent } from '../paths/coana.mts' -const COMPONENTS = ['analyzers', 'cli'] as const const MAX_COMPONENT_BYTES = 512 * 1024 * 1024 const MAX_EXPANDED_BYTES = 2 * 1024 * 1024 * 1024 const SUPPORTED_TARGETS = new Set(['darwin-arm64', 'linux-arm64', 'linux-x64']) @@ -25,7 +30,7 @@ type Component = { } type CoanaArtifacts = { - components: Record + components: Record version: string } @@ -68,7 +73,7 @@ function parseArtifacts(value: unknown): CoanaArtifacts { ) } const parsed = components as Record - for (const name of COMPONENTS) { + for (const name of COANA_COMPONENTS) { if (!isComponent(parsed[name])) { throw new Error(`the API returned invalid ${name} download metadata`) } @@ -76,8 +81,8 @@ function parseArtifacts(value: unknown): CoanaArtifacts { return { version: COANA_CLI_VERSION, components: Object.fromEntries( - COMPONENTS.map(name => [name, parsed[name] as Component]), - ), + COANA_COMPONENTS.map(name => [name, parsed[name] as Component]), + ) as Record, } } @@ -85,7 +90,7 @@ async function fetchArtifacts(org: string): Promise { const result = await sendApiRequest( `orgs/${encodeURIComponent(org)}/coana-cli/artifacts`, { - body: { components: [...COMPONENTS], version: COANA_CLI_VERSION }, + body: { components: [...COANA_COMPONENTS], version: COANA_CLI_VERSION }, method: 'POST', }, ) @@ -191,10 +196,7 @@ async function normalizeTimes(directory: string): Promise { export type StagedCoana = { version: string - cliSha256: string - cliSize: number - analyzersSha256: string - analyzersSize: number + components: Record nodeSha256: string nodeSize: number directory: string @@ -228,7 +230,7 @@ export async function stageCoana( artifacts = await fetchArtifacts(org.data) } catch (error) { throw new Error( - `Coana ${COANA_CLI_VERSION} download failed for ${org.data}. Where: Socket API artifact access. Saw: ${error instanceof Error ? error.message : String(error)}; wanted: the pinned CLI and analyzer artifacts. Fix: ensure SOCKET_API_TOKEN_FOR_CLI_AND_SFW can access Coana reachability artifacts for this organization, then retry the 2.x RC build.`, + `Coana ${COANA_CLI_VERSION} download failed for ${org.data}. Where: Socket API artifact access. Saw: ${error instanceof Error ? error.message : String(error)}; wanted: the pinned Coana components. Fix: ensure SOCKET_API_TOKEN_FOR_CLI_AND_SFW can access Coana reachability artifacts for this organization, then retry the 2.x RC build.`, { cause: error }, ) } @@ -240,10 +242,10 @@ export async function stageCoana( try { await fs.mkdir(paths.root, { recursive: true }) const componentEntries = await Promise.all( - COMPONENTS.map(async name => { - const component = artifacts.components[name]! + COANA_COMPONENTS.map(async name => { + const component = artifacts.components[name] const archive = path.join(temporaryDirectory, `${name}.tar.gz`) - const destination = name === 'cli' ? paths.cli : paths.analyzers + const destination = paths[name] await downloadComponent(component, archive, `Coana ${name}`) await fs.mkdir(destination, { recursive: true }) await extractComponent(archive, destination) @@ -253,14 +255,14 @@ export async function stageCoana( ] as const }), ) - const componentDigests = Object.fromEntries(componentEntries) + const componentDigests = Object.fromEntries(componentEntries) as Record< + CoanaComponent, + { sha256: string; size: number } + > const cli = await fs.stat(paths.cliWrapper).catch(() => undefined) - const repos = await fs.stat(paths.repos).catch(() => undefined) - if (!cli?.isFile() || !repos?.isDirectory()) { - throw new Error( - 'Coana archives do not contain cli-wrapper.mjs and analyzer repos/', - ) + if (!cli?.isFile()) { + throw new Error('The Coana cli archive does not contain cli-wrapper.mjs') } await fs.copyFile(nodeExecutable, paths.node) @@ -283,10 +285,7 @@ export async function stageCoana( await normalizeTimes(paths.root) return { version: artifacts.version, - cliSha256: componentDigests['cli']!.sha256, - cliSize: componentDigests['cli']!.size, - analyzersSha256: componentDigests['analyzers']!.sha256, - analyzersSize: componentDigests['analyzers']!.size, + components: componentDigests, nodeSha256, nodeSize: nodeBytes.length, directory: paths.root, diff --git a/src/utils/coana-release.test.mts b/src/utils/coana-release.test.mts index 442a58258..ff7c7092b 100644 --- a/src/utils/coana-release.test.mts +++ b/src/utils/coana-release.test.mts @@ -5,11 +5,13 @@ * - 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 - * coana-cache.mjs, so nothing is mocked. This needs dist/coana-cache.mjs, which - * the build copies there. + * coana-cache.mjs; only the standalone build's runtime is stood in for. This + * needs dist/coana-cache.mjs, which the build copies there. * * Related Files: * - utils/coana/release.mts (implementation) @@ -31,7 +33,10 @@ import { } from 'vitest' 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 { spawnCoana } from './coana/release.mts' import { overrideCachedConfig, resetConfigForTesting } from './config.mts' import { @@ -39,6 +44,32 @@ import { getDefaultApiBaseUrl, resolveDefaultApiToken, } from './sdk.mts' +import { SEA_COANA_VFS_PATHS } from '../sea/paths/coana.mts' + +import type * as SeaRuntime from '../sea/runtime.mts' + +type CacheRun = { code: number; stderr: string; stdout: string } + +const sea = vi.hoisted(() => ({ + root: undefined as string | undefined, + runCache: undefined as + | ((args: readonly string[], env: NodeJS.ProcessEnv) => Promise) + | undefined, +})) + +vi.mock('../sea/runtime.mts', async importOriginal => ({ + ...(await importOriginal()), + assertEmbeddedToolAvailable: () => {}, + cleanupBundledTool: async () => {}, + getBundledTool: async () => process.execPath, + getEmbeddedVfsPath: (relative: string) => path.join(sea.root!, relative), + isStandaloneSea: () => sea.root !== undefined, + runEmbeddedJsTool: async ( + _id: string, + args: readonly string[], + { env = {} }: { env?: NodeJS.ProcessEnv } = {}, + ) => await sea.runCache!(args, env), +})) const VERSION = '1.2.3' @@ -58,6 +89,30 @@ type FakeRun = { env: NodeJS.ProcessEnv } +async function runCoanaCache( + args: readonly string[], + env: NodeJS.ProcessEnv = process.env, +): Promise { + try { + const result = await spawn( + process.execPath, + [path.join(constants.distPath, 'coana-cache.mjs'), ...args], + { env, stdio: 'pipe' }, + ) + return { + code: 0, + stderr: String(result.stderr), + stdout: String(result.stdout).trim(), + } + } catch (e) { + return { + code: (e as { code: number }).code, + stderr: String((e as { stderr?: unknown }).stderr ?? ''), + stdout: String((e as { stdout?: unknown }).stdout ?? '').trim(), + } + } +} + async function runFake( options?: Parameters[2], ): Promise { @@ -87,18 +142,21 @@ describe('spawnCoana', () => { path.join(extracted, 'cli-wrapper.mjs'), FAKE_CLI_WRAPPER, ) - await spawn( - 'node', - [ - path.join(constants.distPath, 'coana-cache.mjs'), - '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', + [ + path.join(constants.distPath, 'coana-cache.mjs'), + 'install', + version, + 'cli', + 'a'.repeat(64), + extracted, + ], + { stdio: 'pipe' }, + ) + } }) afterEach(() => { @@ -226,6 +284,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, @@ -236,4 +315,65 @@ describe('spawnCoana', () => { expect(result.message).toContain('Coana command failed (exit code 1)') expect(result.message).toContain('Could not resolve 1 dependency(ies)') }) + + describe('in the standalone build', () => { + beforeAll(async () => { + const root = path.join(tmpDir, 'vfs') + const write = async (relative: string, content: string) => { + const file = path.join(root, relative) + await fs.mkdir(path.dirname(file), { recursive: true }) + await fs.writeFile(file, content) + } + await write(SEA_COANA_VFS_PATHS.cliWrapper, FAKE_CLI_WRAPPER) + await write(`${SEA_COANA_VFS_PATHS.analyzers}/coana-tech/spar-jvm/x`, '') + await write( + `${SEA_COANA_VFS_PATHS.facts}/coana-tech/socket-facts-jvm/x`, + '', + ) + await write( + SEA_COANA_VFS_PATHS.manifest, + JSON.stringify({ + components: { + analyzers: { sha256: 'b'.repeat(64) }, + cli: { sha256: 'a'.repeat(64) }, + facts: { sha256: 'c'.repeat(64) }, + }, + version: COANA_CLI_VERSION, + }), + ) + sea.root = root + sea.runCache = runCoanaCache + }) + + afterAll(() => { + sea.root = undefined + }) + + it('caches every embedded component where Coana looks for it, leaving REPOS_PATH unset', async () => { + const { env } = await runFake({ coanaVersion: undefined }) + + expect(env['REPOS_PATH']).toBeUndefined() + const facts = await runCoanaCache(['lookup', COANA_CLI_VERSION, 'facts']) + expect(facts.code).toBe(0) + expect(await fs.readdir(path.join(facts.stdout, 'coana-tech'))).toEqual([ + 'socket-facts-jvm', + ]) + const analyzers = await runCoanaCache([ + 'lookup', + COANA_CLI_VERSION, + 'analyzers', + ]) + expect(analyzers.code).toBe(0) + }) + + it('leaves out a REPOS_PATH the user set', async () => { + vi.stubEnv('REPOS_PATH', path.join(tmpDir, 'elsewhere')) + try { + const { env } = await runFake({ coanaVersion: undefined }) + expect(env['REPOS_PATH']).toBeUndefined() + } finally { + vi.unstubAllEnvs() + } + }) + }) }) diff --git a/src/utils/coana/release.mts b/src/utils/coana/release.mts index 34ff4c95c..5158b5b93 100644 --- a/src/utils/coana/release.mts +++ b/src/utils/coana/release.mts @@ -21,25 +21,16 @@ import { pipeline } from 'node:stream/promises' import semver from 'semver' import { x as extractTar } from 'tar' -import { debugDir, debugFn } from '../debug.mts' -import { logger } from '../logger.mts' -import { spawn } from '../spawn.mts' import { getDefaultOrgSlug } from '../../commands/ci/fetch-default-org-slug.mts' import constants, { COANA_CLI_VERSION, ERROR_UNABLE_RESOLVE_ORG, SOCKET_CLI_API_TOKEN_VARIABLES, } from '../../constants.mts' -import { apiFetch, sendApiRequest } from '../api.mts' -import { getErrorCause } from '../errors.mts' -import { withTmpDir } from '../fs.mts' import { - getCliUserAgent, - getDefaultApiBaseUrl, - getDefaultProxyUrl, - resolveDefaultApiToken, -} from '../sdk.mts' -import { SEA_COANA_VFS_PATHS } from '../../sea/paths/coana.mts' + COANA_COMPONENTS, + SEA_COANA_VFS_PATHS, +} from '../../sea/paths/coana.mts' import { assertEmbeddedToolAvailable, cleanupBundledTool, @@ -48,6 +39,18 @@ import { isStandaloneSea, runEmbeddedJsTool, } from '../../sea/runtime.mts' +import { apiFetch, sendApiRequest } from '../api.mts' +import { debugDir, debugFn } from '../debug.mts' +import { getErrorCause } from '../errors.mts' +import { withTmpDir } from '../fs.mts' +import { logger } from '../logger.mts' +import { + getCliUserAgent, + getDefaultApiBaseUrl, + getDefaultProxyUrl, + resolveDefaultApiToken, +} from '../sdk.mts' +import { spawn } from '../spawn.mts' import type { CResult } from '../../types.mts' import type { SpawnOptions } from '../spawn.mts' @@ -76,6 +79,8 @@ type CoanaSpawnOptions = { coanaVersion?: string | undefined cwd?: string | URL | undefined env?: Record | undefined + // The resolved Coana release must meet the minimum version for this command. + minimumVersion?: string | undefined repoName?: string | undefined spinner?: Spinner | undefined stdio?: SpawnOptions['stdio'] | undefined @@ -216,9 +221,12 @@ 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. + * 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( @@ -226,7 +234,7 @@ async function getCoanaCliDir( org: CResult, env: NodeJS.ProcessEnv, spinner: Spinner | undefined, -): Promise> { +): Promise> { try { const exactVersion = semver.valid(versionSpec) if (exactVersion) { @@ -268,7 +276,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) } @@ -281,11 +292,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) } } @@ -420,9 +433,9 @@ async function runCoanaCache( } } -async function cacheEmbeddedCoana( - env: NodeJS.ProcessEnv, -): Promise<{ cliPath: string; analyzersPath: string }> { +// Coana finds its other components in the cache by version, so they are +// installed there too and REPOS_PATH stays unset. +async function cacheEmbeddedCoana(env: NodeJS.ProcessEnv): Promise { const manifest = JSON.parse( await fs.readFile(getEmbeddedVfsPath(SEA_COANA_VFS_PATHS.manifest), 'utf8'), ) as { @@ -440,7 +453,7 @@ async function cacheEmbeddedCoana( ) } const components = await Promise.all( - (['analyzers', 'cli'] as const).map(async component => { + COANA_COMPONENTS.map(async component => { const sha256 = manifestComponents[component]?.sha256 if (typeof sha256 !== 'string' || !SHA256_REGEXP.test(sha256)) { throw new Error(`Embedded Coana ${component} metadata is invalid`) @@ -455,11 +468,7 @@ async function cacheEmbeddedCoana( async source => { const extracted = path.join(source, 'component') await fs.cp( - getEmbeddedVfsPath( - component === 'cli' - ? SEA_COANA_VFS_PATHS.cli - : SEA_COANA_VFS_PATHS.analyzers, - ), + getEmbeddedVfsPath(SEA_COANA_VFS_PATHS[component]), extracted, { recursive: true }, ) @@ -484,8 +493,14 @@ async function cacheEmbeddedCoana( } }), ) - const paths = Object.fromEntries(components) - return { cliPath: paths['cli']!, analyzersPath: paths['analyzers']! } + return Object.fromEntries(components)['cli']! +} + +function withVersion( + dir: CResult, + version: string, +): CResult { + return dir.ok ? { ok: true, data: { dir: dir.data, version } } : dir } /** @@ -509,6 +524,7 @@ export async function spawnCoana( coanaVersion, cwd, env: spawnEnv, + minimumVersion, repoName, spinner, stdio = 'inherit', @@ -588,12 +604,14 @@ export async function spawnCoana( } } - let embeddedPaths: { cliPath: string; analyzersPath: string } | undefined + let embeddedCliPath: string | undefined if (standaloneSea && !localPath) { try { assertEmbeddedToolAvailable('coana') - embeddedPaths = await cacheEmbeddedCoana(userEnv) - env['REPOS_PATH'] = embeddedPaths.analyzersPath + // The embedded Coana finds its components in the cache, never through + // REPOS_PATH. + env['REPOS_PATH'] = undefined + embeddedCliPath = await cacheEmbeddedCoana(env) } catch (error) { return { ok: false, @@ -605,8 +623,8 @@ export async function spawnCoana( let scriptPath = localPath if (!scriptPath) { - if (embeddedPaths) { - scriptPath = path.join(embeddedPaths.cliPath, 'cli-wrapper.mjs') + if (embeddedCliPath) { + scriptPath = path.join(embeddedCliPath, 'cli-wrapper.mjs') } else { const coanaDirCResult = await getCoanaCliDir( coanaVersion || COANA_CLI_VERSION, @@ -617,7 +635,15 @@ export async function spawnCoana( if (!coanaDirCResult.ok) { return coanaDirCResult } - scriptPath = path.join(coanaDirCResult.data, 'cli-wrapper.mjs') + const { dir, version } = coanaDirCResult.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 = path.join(dir, 'cli-wrapper.mjs') } }