From 3a7c8e337dd8f9ec645e8d5da429fbd761a3922b Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 15:40:51 +0100 Subject: [PATCH 01/12] Add socket.json reachability settings for the build tools A build tool's socket.json section takes a `reachability` object, which reachability scans send to Coana with each build root's request: - `build`: "compile" builds the project before the analysis, "none" or unset analyses it unbuilt; - `javaHome`, Maven, Gradle and sbt: the JDK the analysis takes the program to run on, as written; - `runtimeVersion`, .NET: the runtime a framework-dependent build's analysis starts on, as major.minor or major.minor.patch[-prerelease]. Each field cascades on its own, a build's own `builds` entry last, and null clears an inherited one. Only a reachability scan reads them, for the build tools it runs, so an invalid value never stops another command. It checks them before any build runs and fails naming the socket.json and setting, including a field the build tool does not take. --- CHANGELOG.md | 1 + docs/dynamic-sbom-inference-settings.md | 7 + src/commands/manifest/build-root-config.mts | 148 ++++++++++++- .../manifest/build-root-config.test.mts | 197 ++++++++++++++++++ .../manifest/convert-dotnet-to-facts.mts | 4 + .../manifest/generate-recursive-manifests.mts | 48 +++-- .../generate-recursive-manifests.test.mts | 151 ++++++++++++++ .../manifest/generate_auto_manifest.mts | 18 ++ .../manifest/generate_auto_manifest.test.mts | 110 +++++++++- src/commands/manifest/run-manifest-facts.mts | 13 ++ .../manifest/run-manifest-facts.test.mts | 18 ++ src/utils/socket-json.mts | 64 +++++- src/utils/socket-json.test.mts | 56 ++++- 13 files changed, 807 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d6253860b..3bb944df0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added - Socket facts for a self-contained .NET build include its runtime packs. +- Tune reachability per build tool in `socket.json`: `reachability.build` compiles the project before the analysis, `reachability.javaHome` (Maven, Gradle, sbt) sets the JDK the analysis assumes, and `reachability.runtimeVersion` (.NET) sets the runtime it starts on. ### Changed - Updated the Coana CLI to v `15.15.4`. diff --git a/docs/dynamic-sbom-inference-settings.md b/docs/dynamic-sbom-inference-settings.md index 4d28e1441..dabf04cb4 100644 --- a/docs/dynamic-sbom-inference-settings.md +++ b/docs/dynamic-sbom-inference-settings.md @@ -77,6 +77,13 @@ Under `defaults.manifest.maven`, `.gradle`, `.sbt` or `.dotnet`, or inside a | `disabled` | `true` skips builds; see below. | | `facts` | Gradle and sbt: `false` skips the build. | | `verbose` | `true` streams the build tool's output. | +| `reachability.build` | `"compile"` builds the project before the analysis, and a failed build fails the scan; `"none"` or unset analyses it unbuilt. | +| `reachability.javaHome` | Maven, Gradle and sbt: the JDK the analysis takes the program to run on, passed to Coana as written. | +| `reachability.runtimeVersion` | .NET: the runtime a framework-dependent build's analysis starts on. `major.minor` takes its latest installed patch; `major.minor.patch[-prerelease]` takes exactly that runtime. | + +Only reachability scans read the `reachability` fields, each cascading on its +own, and only for the build tools they run. An invalid value or a field the +build tool does not take fails the scan. ## Skipping builds diff --git a/src/commands/manifest/build-root-config.mts b/src/commands/manifest/build-root-config.mts index 795275d89..3b0364542 100644 --- a/src/commands/manifest/build-root-config.mts +++ b/src/commands/manifest/build-root-config.mts @@ -8,16 +8,20 @@ import { buildRootPath, } from './scripts/build-tool.mts' import { SOCKET_JSON } from '../../constants.mts' +import { joinAnd, joinOr } from '../../utils/arrays.mts' import { InputError } from '../../utils/errors.mts' import { getOrInsert } from '../../utils/get-or-insert.mts' import { logger } from '../../utils/logger.mts' import { isRecord } from '../../utils/objects.mts' import { + REACHABILITY_BUILDS, + mergeBuildToolDefaults, mergeSocketJsonChain, readSocketJsonChain, } from '../../utils/socket-json.mts' import type { BuildRoot } from './discover-manifest-roots.mts' +import type { ReachabilitySettings } from './run-manifest-facts.mts' import type { BuildTool } from './scripts/build-tool.mts' import type { SocketJson, @@ -37,10 +41,77 @@ export type ResolvedBuildRootSettings = { disabledBy: DisabledBy | undefined // The key of the build's own `defaults.manifest.builds` entry. entryKey: string | undefined + // The cascaded `reachability` settings, checked in every socket.json that + // sets them; throws an InputError naming an invalid one. + reachability: () => ReachabilitySettings | undefined // The cascaded settings, the build's own entries applied last. sockJson: SocketJson } +// major.minor, or major.minor.patch[-prerelease] as `RuntimeFrameworkVersion` +// takes a .NET runtime, written as SemVer 2.0.0 items 2 and 9 say. +const NUMBER = '(?:0|[1-9][0-9]*)' +const PRERELEASE_IDENTIFIER = `(?:${NUMBER}|[0-9]*[A-Za-z-][0-9A-Za-z-]*)` +const DOTNET_RUNTIME_VERSION = new RegExp( + `^${NUMBER}\\.${NUMBER}(?:\\.${NUMBER}(?:-${PRERELEASE_IDENTIFIER}(?:\\.${PRERELEASE_IDENTIFIER})*)?)?$`, +) + +type ReachabilityField = { + // What a valid value is, as "set it to …" names it. + expected: string + takes: (value: unknown) => boolean + tools: readonly BuildTool[] +} + +const REACHABILITY_FIELDS: Record< + keyof ReachabilitySettings, + ReachabilityField +> = { + __proto__: null, + build: { + expected: joinOr(REACHABILITY_BUILDS.map(b => `"${b}"`)), + takes: (value: unknown) => + (REACHABILITY_BUILDS as readonly unknown[]).includes(value), + tools: BUILD_TOOLS, + }, + javaHome: { + expected: 'a JDK path', + takes: (value: unknown) => typeof value === 'string' && !!value, + tools: ['gradle', 'maven', 'sbt'], + }, + runtimeVersion: { + expected: + 'a .NET runtime version: major.minor, such as "8.0", for its latest installed patch, or major.minor.patch[-prerelease], such as "8.0.11", for exactly that runtime', + takes: (value: unknown) => + typeof value === 'string' && DOTNET_RUNTIME_VERSION.test(value), + tools: ['dotnet'], + }, +} as unknown as Record + +function checkReachability( + tool: BuildTool, + value: unknown, + setting: string, + socketJson: string, +): void { + if (value === undefined) { + return + } + if (!isRecord(value)) { + throw new InputError( + `\`${setting}\` in ${socketJson} is ${JSON.stringify(value)}; set it to an object, or remove it.`, + ) + } + for (const { 0: field, 1: fieldValue } of Object.entries(value)) { + const problem = reachabilityProblem(tool, field, fieldValue) + if (problem) { + throw new InputError( + `\`${setting}.${field}\` in ${socketJson} ${problem}`, + ) + } + } +} + // Gradle and sbt name a build by any build file of its directory. function namesBuildFile(key: string): boolean { return BUILD_TOOLS.some(tool => { @@ -66,6 +137,27 @@ function ownEntryKeys( ) } +function reachabilityKey(tool: BuildTool): string { + return `defaults.manifest.${tool}.reachability` +} + +// Without the fields a socket.json cleared with null. +function reachabilitySettings( + value: unknown, +): ReachabilitySettings | undefined { + if (!isRecord(value)) { + return undefined + } + const settings = Object.fromEntries( + Object.entries(value).filter( + ({ 1: setting }) => setting !== null && setting !== undefined, + ), + ) + return Object.keys(settings).length + ? (settings as ReachabilitySettings) + : undefined +} + function validateBuilds({ dir, sockJson }: SocketJsonInDir): void { const builds: unknown = sockJson.defaults?.manifest?.builds if (builds === undefined) { @@ -180,9 +272,11 @@ export function createBuildRootSettingsResolver( ? ownEntryKeys(tool, root.dir, builds, root.entryFile)[0] : undefined let entryDisabledBy: DisabledBy | undefined - if (entryKey) { - const entry = builds![entryKey] as SocketJsonBuildEntry - Object.assign(section, entry) + const entry = entryKey + ? (builds![entryKey] as SocketJsonBuildEntry) + : undefined + if (entryKey && entry) { + Object.assign(section, mergeBuildToolDefaults(section, entry)) if (entry.disabled !== undefined) { entryDisabledBy = { dir: root.dir, key: entryKey } } @@ -198,6 +292,20 @@ export function createBuildRootSettingsResolver( return { disabledBy, entryKey, + reachability: () => { + for (const file of chain) { + socketJsonReachability(tool, file) + } + if (entryKey && entry) { + checkReachability( + tool, + entry['reachability'], + `${buildsSetting(entryKey)}.reachability`, + socketJsonPath(root.dir), + ) + } + return reachabilitySettings(section['reachability']) + }, sockJson: { ...merged, defaults: { @@ -230,6 +338,40 @@ export function displayPath(file: string): string { return rel.startsWith('..') || path.isAbsolute(rel) ? file : rel || '.' } +// Why `tool`'s reachability `field` cannot be `value`, as the rest of a +// sentence about it; undefined when it can. +export function reachabilityProblem( + tool: BuildTool, + field: string, + value: unknown, +): string | undefined { + const spec = REACHABILITY_FIELDS[field as keyof ReachabilitySettings] as + | ReachabilityField + | undefined + if (!spec?.tools.includes(tool)) { + const fields = Object.keys(REACHABILITY_FIELDS).filter(name => + REACHABILITY_FIELDS[name as keyof ReachabilitySettings].tools.includes( + tool, + ), + ) + return `is not a reachability setting of ${tool} builds, which take ${joinAnd(fields)}; remove it.` + } + if (value === null || spec.takes(value)) { + return undefined + } + return `is ${JSON.stringify(value)}; set it to ${spec.expected}, to null to clear an inherited value, or remove it.` +} + export function socketJsonPath(dir: string): string { return displayPath(path.join(dir, SOCKET_JSON)) } + +// The `reachability` settings of `tool` in one socket.json, checked. +export function socketJsonReachability( + tool: BuildTool, + { dir, sockJson }: SocketJsonInDir, +): ReachabilitySettings | undefined { + const value = sockJson.defaults?.manifest?.[tool]?.reachability + checkReachability(tool, value, reachabilityKey(tool), socketJsonPath(dir)) + return reachabilitySettings(value) +} diff --git a/src/commands/manifest/build-root-config.test.mts b/src/commands/manifest/build-root-config.test.mts index 998026f51..ae07a1a67 100644 --- a/src/commands/manifest/build-root-config.test.mts +++ b/src/commands/manifest/build-root-config.test.mts @@ -8,8 +8,10 @@ import { createBuildRootSettingsResolver, describeDisabledBy, displayPath, + socketJsonReachability, } from './build-root-config.mts' import { InputError } from '../../utils/errors.mts' +import { escapeRegExp } from '../../utils/escape-regexp.mts' import { logger } from '../../utils/logger.mts' describe('createBuildRootSettingsResolver', () => { @@ -35,6 +37,10 @@ describe('createBuildRootSettingsResolver', () => { dir: path.join(scanRoot, dir), entryFile, }) + const dotnet = (dir: string) => ({ + dir: path.join(scanRoot, dir), + entryFile: 'App.sln', + }) beforeEach(async () => { scanRoot = await fs.realpath( @@ -240,4 +246,195 @@ describe('createBuildRootSettingsResolver', () => { createBuildRootSettingsResolver()('maven', maven('legacy')).disabledBy, ).toEqual({ dir: path.join(scanRoot, 'legacy') }) }) + + describe('reachability', () => { + it('cascades each field on its own, the build entry last, and drops cleared ones', async () => { + await write('.', { + maven: { reachability: { build: 'compile', javaHome: '$JDK17' } }, + }) + await write( + 'svc', + { + maven: { reachability: { javaHome: null } }, + builds: { 'pom.xml': { reachability: { javaHome: '$JDK21' } } }, + }, + ['pom.xml', 'svc-alt.pom.xml'], + ) + const resolve = createBuildRootSettingsResolver() + + expect(resolve('maven', maven('svc')).reachability()).toEqual({ + build: 'compile', + javaHome: '$JDK21', + }) + expect( + resolve('maven', maven('svc', 'svc-alt.pom.xml')).reachability(), + ).toEqual({ build: 'compile' }) + }) + + it.for([ + { + name: 'no socket.json sets any', + settings: {}, + files: undefined, + }, + { + name: 'a socket.json clears every field with null', + settings: { maven: { reachability: { build: null } } }, + files: undefined, + }, + { + name: "the build's own entry clears what its directory sets", + settings: { + maven: { reachability: { build: 'compile' } }, + builds: { 'pom.xml': { reachability: { build: null } } }, + }, + files: ['pom.xml'], + }, + ])('is undefined when $name', async ({ files, settings }) => { + await write('.', settings, files) + + expect( + createBuildRootSettingsResolver()('maven', maven('.')).reachability(), + ).toBeUndefined() + }) + + it.for([ + { runtimeVersion: '8.0', valid: true }, + { runtimeVersion: '10.0.1', valid: true }, + { runtimeVersion: '9.0.0-rc.2.24473.5', valid: true }, + { runtimeVersion: '8', valid: false }, + { runtimeVersion: 'net8.0', valid: false }, + { runtimeVersion: '08.0', valid: false }, + { runtimeVersion: '8.0.1.2', valid: false }, + { runtimeVersion: '8.0-rc.1', valid: false }, + { runtimeVersion: '8.0.1+build', valid: false }, + ])( + 'takes the .NET runtime version $runtimeVersion: $valid', + async ({ runtimeVersion, valid }) => { + await write('.', { dotnet: { reachability: { runtimeVersion } } }) + const resolved = createBuildRootSettingsResolver()( + 'dotnet', + dotnet('.'), + ) + + if (valid) { + expect(resolved.reachability()).toEqual({ runtimeVersion }) + } else { + expect(() => resolved.reachability()).toThrow( + /reachability\.runtimeVersion` in .*socket\.json is .*; set it to a \.NET runtime version/, + ) + } + }, + ) + + it.for([ + { + name: 'a field of another tool', + tool: 'maven', + reachability: { runtimeVersion: '8.0' }, + reason: 'is not a reachability setting of maven builds', + }, + { + name: 'a JVM field on dotnet', + tool: 'dotnet', + reachability: { javaHome: '/jdk' }, + reason: 'is not a reachability setting of dotnet builds', + }, + { + name: 'a misspelt field', + tool: 'gradle', + reachability: { java_home: '/jdk' }, + reason: 'is not a reachability setting of gradle builds', + }, + { + name: 'an unknown build', + tool: 'sbt', + reachability: { build: 'test' }, + reason: 'set it to "compile" or "none"', + }, + { + name: 'a JDK that is no string', + tool: 'gradle', + reachability: { javaHome: 17 }, + reason: 'set it to a JDK path', + }, + { + name: 'an empty JDK', + tool: 'maven', + reachability: { javaHome: '' }, + reason: 'set it to a JDK path', + }, + { + name: 'a section that is no object', + tool: 'maven', + reachability: 'compile', + reason: 'set it to an object', + }, + ] as const)( + 'rejects $name, naming the socket.json that sets it', + async ({ reachability, reason, tool }) => { + await write('.', { [tool]: { reachability: {} } }) + await write('nested', { [tool]: { reachability } }) + const root = { dir: path.join(scanRoot, 'nested') } + + expect(() => + createBuildRootSettingsResolver()(tool, root).reachability(), + ).toThrow( + expect.objectContaining({ + constructor: InputError, + message: expect.stringMatching( + new RegExp( + `^\`defaults\\.manifest\\.${tool}\\.reachability.*\\bnested.socket\\.json.*${escapeRegExp(reason)}`, + ), + ), + }), + ) + }, + ) + + it("rejects an invalid setting in a build's own entry, naming the entry", async () => { + await write( + '.', + { builds: { 'pom.xml': { reachability: { runtimeVersion: '8.0' } } } }, + ['pom.xml'], + ) + + expect(() => + createBuildRootSettingsResolver()('maven', maven('.')).reachability(), + ).toThrow( + /^`defaults\.manifest\.builds\["pom\.xml"\]\.reachability\.runtimeVersion` in /, + ) + }) + + it("resolves a build's other settings whatever its reachability holds", async () => { + await write('.', { + maven: { mavenOpts: '-B', reachability: { build: 'always' } }, + }) + + expect( + createBuildRootSettingsResolver()('maven', maven('.')).sockJson.defaults + ?.manifest?.maven?.mavenOpts, + ).toBe('-B') + }) + }) +}) + +describe('socketJsonReachability', () => { + it("checks one socket.json's section for the tool alone", () => { + const sockJson = { + defaults: { + manifest: { + dotnet: { reachability: { runtimeVersion: 'latest' } }, + gradle: { reachability: { build: 'compile' } }, + }, + }, + } as any + + expect(socketJsonReachability('gradle', { dir: '/r', sockJson })).toEqual({ + build: 'compile', + }) + expect(() => + socketJsonReachability('dotnet', { dir: '/r', sockJson }), + ).toThrow(InputError) + }) }) diff --git a/src/commands/manifest/convert-dotnet-to-facts.mts b/src/commands/manifest/convert-dotnet-to-facts.mts index 57cc73374..ae18eb6d4 100644 --- a/src/commands/manifest/convert-dotnet-to-facts.mts +++ b/src/commands/manifest/convert-dotnet-to-facts.mts @@ -7,6 +7,7 @@ import { logger } from '../../utils/logger.mts' import type { EcosystemBuildConfig } from './generate-recursive-manifests.mts' import type { BuildOptionHints, + ReachabilitySettings, RunManifestFactsOutcome, SocketFactsContext, } from './run-manifest-facts.mts' @@ -21,6 +22,7 @@ export async function convertDotnetToFacts({ entryFile, excludePaths, hints, + reachability, }: { config: EcosystemBuildConfig context?: SocketFactsContext | undefined @@ -29,6 +31,7 @@ export async function convertDotnetToFacts({ entryFile?: string | undefined excludePaths?: string[] | undefined hints?: BuildOptionHints | undefined + reachability?: ReachabilitySettings | undefined }): Promise { const entries = entryFile ? [entryFile] : findDotnetEntries(cwd) if (!entries.length) { @@ -51,6 +54,7 @@ export async function convertDotnetToFacts({ ecosystem: 'dotnet', excludePaths, hints, + reachability, root: { dir, entryFile: entry }, }) if (outcome === 'covered') { diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index a7f5b5e2d..8f364a5ea 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -45,6 +45,7 @@ import type { LoadedBuild } from './load-build.mts' import type { BuildOptionHints, CommandHints, + ReachabilitySettings, RunManifestFactsOutcome, RunManifestFactsResult, SocketFactsContext, @@ -92,15 +93,20 @@ export type EcosystemBuildConfig = { // root here, on top of its existing root-only ecosystem-wide meaning for // auto/gradle/etc. facts:false has no pom-mode equivalent here (facts-only), // so it skips too. -function getSkipReason( +// Only Gradle and sbt take `facts: false`, which generates pom files instead. +export function getSkipReason( ecosystem: BuildTool, - disabled: boolean | undefined, - facts?: boolean | undefined, + section: + | { disabled?: boolean | undefined; facts?: boolean | undefined } + | undefined, ): string | undefined { - if (disabled) { + if (section?.disabled) { return `defaults.manifest.${ecosystem}.disabled is true` } - if (facts === false) { + if ( + (ecosystem === 'gradle' || ecosystem === 'sbt') && + section?.facts === false + ) { return `defaults.manifest.${ecosystem}.facts is false (pom mode)` } return undefined @@ -170,11 +176,13 @@ export function socketFactsRunOptions( excludeBase, excludePaths, hints, + reachability, }: { context?: SocketFactsContext | undefined excludeBase: string | undefined excludePaths: string[] | undefined hints?: BuildOptionHints | undefined + reachability?: ReachabilitySettings | undefined }, ): SocketFactsRunOptions { return { @@ -191,6 +199,7 @@ export function socketFactsRunOptions( ignoreUnresolved: config.ignoreUnresolved, includeConfigs: config.includeConfigs, javaHome: config.javaHome, + reachability, verbose: config.verbose, } } @@ -652,9 +661,16 @@ async function runCandidate( candidate: Candidate, options: SocketFactsRunOptions, ): Promise { + const reachability = ctx.context.workDir.withFiles + ? ctx.resolveSettings(options.ecosystem, candidate.root).reachability() + : undefined // A run a later build turns out to cover is dropped before its facts are // placed. - const result = await runManifestFacts({ ...options, staged: true }) + const result = await runManifestFacts({ + ...options, + reachability, + staged: true, + }) if (result === null) { return undefined } @@ -678,6 +694,7 @@ export async function buildUncoveredRoot({ excludeBase, excludePaths, hints, + reachability, root, }: { config: EcosystemBuildConfig @@ -689,6 +706,7 @@ export async function buildUncoveredRoot({ excludeBase?: string | undefined excludePaths?: string[] | undefined hints?: BuildOptionHints | undefined + reachability?: ReachabilitySettings | undefined root: BuildRoot }): Promise { const options: SocketFactsRunOptions = { @@ -703,7 +721,7 @@ export async function buildUncoveredRoot({ if (await isRootCovered(covered, ecosystem, root, options)) { return 'covered' } - const result = await runManifestFacts(options) + const result = await runManifestFacts({ ...options, reachability }) if (result) { addMembership(covered, await membershipOf(result.projects)) } @@ -750,7 +768,13 @@ export async function generateRecursiveManifests({ // Invalid settings fail the scan before any build runs. for (const { 0: tool, 1: roots } of candidatesByTool) { for (const root of roots) { - resolveSettings(tool, root) + const settings = resolveSettings(tool, root) + if ( + context.workDir?.withFiles && + !getSkipReason(tool, settings.sockJson.defaults?.manifest?.[tool]) + ) { + settings.reachability() + } } } // A failure another build excuses leaves the exit code it set. @@ -808,7 +832,7 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: undefined, - skipReason: getSkipReason(ecosystem, config?.disabled), + skipReason: getSkipReason(ecosystem, config), verbose: Boolean(config?.verbose), } } @@ -822,7 +846,7 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, - skipReason: getSkipReason(ecosystem, config?.disabled, config?.facts), + skipReason: getSkipReason(ecosystem, config), verbose: Boolean(config?.verbose), } } @@ -836,7 +860,7 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, - skipReason: getSkipReason(ecosystem, config?.disabled, config?.facts), + skipReason: getSkipReason(ecosystem, config), verbose: Boolean(config?.verbose), } } @@ -849,7 +873,7 @@ export function resolveEcosystemConfig( ignoreUnresolved: Boolean(config?.ignoreUnresolved), includeConfigs: config?.includeConfigs ?? '', javaHome: config?.javaHome ?? undefined, - skipReason: getSkipReason(ecosystem, config?.disabled), + skipReason: getSkipReason(ecosystem, config), verbose: Boolean(config?.verbose), } } diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index 50deeda51..2b7b94e6f 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -138,6 +138,14 @@ function relOf(dir: string): string { return path.relative(monorepo, dir).replaceAll('\\', '/') } +function sentReachability() { + return Object.fromEntries( + vi + .mocked(runManifestFacts) + .mock.calls.map(([opts]) => [opts.ecosystem, opts.reachability]), + ) +} + describe('generateRecursiveManifests', () => { beforeEach(() => { vi.mocked(runManifestFacts).mockReset() @@ -758,6 +766,149 @@ describe('generateRecursiveManifests', () => { expect(javaHomeByCall.get('maven:reactor')).toBeUndefined() }) + describe('reachability settings', () => { + let outer = '' + beforeEach(async () => { + outer = await fs.realpath( + await fs.mkdtemp(path.join(tmpdir(), 'dsi-reachability-')), + ) + for (const file of [ + 'dotnet/App.sln', + 'gradle/build.gradle', + 'maven/pom.xml', + 'sbt/build.sbt', + ]) { + // eslint-disable-next-line no-await-in-loop + await fs.mkdir(path.join(outer, path.dirname(file))) + // eslint-disable-next-line no-await-in-loop + await fs.writeFile(path.join(outer, file), '') + } + mockFacts(async ({ cwd }) => ({ + factsPath: path.join(cwd, '.socket.facts.json'), + projects: [], + })) + }) + afterEach(async () => { + await fs.rm(outer, { recursive: true, force: true }) + }) + + it("sends each root's cascaded settings on a reachability scan", async () => { + mockCascade(() => ({ + defaults: { + manifest: { + dotnet: { + reachability: { build: 'compile', runtimeVersion: '8.0' }, + }, + gradle: { + reachability: { build: 'compile', javaHome: '$GRADLE_JDK' }, + }, + maven: { reachability: { build: 'none' } }, + }, + }, + })) + + await generateRecursiveManifests({ + context: { workDir: newWorkDir() }, + cwd: outer, + verbose: false, + }) + + expect(sentReachability()).toStrictEqual({ + dotnet: { build: 'compile', runtimeVersion: '8.0' }, + gradle: { build: 'compile', javaHome: '$GRADLE_JDK' }, + maven: { build: 'none' }, + sbt: undefined, + }) + }) + + it('neither sends nor checks them without a reachability scan', async () => { + mockCascade(() => ({ + defaults: { + manifest: { maven: { reachability: { build: 'always' } } }, + }, + })) + + const outcomes = await generateRecursiveManifests({ + cwd: outer, + verbose: false, + }) + + expect(outcomes.every(o => o.status === 'generated')).toBe(true) + expect(Object.values(sentReachability())).toEqual([ + undefined, + undefined, + undefined, + undefined, + ]) + }) + + it('fails a reachability scan on an invalid setting of a tool it runs, before any build, not of one it does not', async () => { + mockCascade(() => ({ + defaults: { + manifest: { dotnet: { reachability: { runtimeVersion: 'net8.0' } } }, + }, + })) + await expect( + generateRecursiveManifests({ + context: { workDir: newWorkDir() }, + cwd: outer, + purlTypes: ['maven'], + verbose: false, + }), + ).resolves.toBeDefined() + + await expect( + generateRecursiveManifests({ + context: { workDir: newWorkDir() }, + cwd: outer, + purlTypes: ['nuget'], + verbose: false, + }), + ).rejects.toThrow(/reachability\.runtimeVersion` in .* is "net8\.0"/) + + // sbt builds after Gradle and Maven. + mockCascade(() => ({ + defaults: { manifest: { sbt: { reachability: { build: 'always' } } } }, + })) + vi.mocked(runManifestFacts).mockClear() + await expect( + generateRecursiveManifests({ + context: { workDir: newWorkDir() }, + cwd: outer, + purlTypes: ['maven'], + verbose: false, + }), + ).rejects.toThrow(/sbt\.reachability\.build` in .* is "always"/) + expect(runManifestFacts).not.toHaveBeenCalled() + }) + + it.for([ + { + name: 'socket.json disables', + manifest: { + sbt: { disabled: true, reachability: { build: 'always' } }, + }, + }, + { + name: 'generates pom files', + manifest: { + gradle: { facts: false, reachability: { build: 'always' } }, + }, + }, + ])('does not check the settings of a build $name', async ({ manifest }) => { + mockCascade(() => ({ defaults: { manifest } }) as SocketJson) + + await expect( + generateRecursiveManifests({ + context: { workDir: newWorkDir() }, + cwd: outer, + purlTypes: ['maven'], + verbose: false, + }), + ).resolves.toBeDefined() + }) + }) + it('resolves an explicit null override back to the no-restriction default, not a literal null', async () => { mockCascade(dir => dir === dualMarkerDir diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index 5367b04c3..8f0dbbaec 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -1,13 +1,16 @@ import { extractBazelToMaven } from './bazel/extract_bazel_to_maven.mts' +import { socketJsonReachability } from './build-root-config.mts' import { convertDotnetToFacts } from './convert-dotnet-to-facts.mts' import { convertGradleToMaven } from './convert_gradle_to_maven.mts' import { convertSbtToMaven } from './convert_sbt_to_maven.mts' import { + getSkipReason, resolveEcosystemConfig, socketFactsRunOptions, } from './generate-recursive-manifests.mts' import { handleManifestConda } from './handle-manifest-conda.mts' import { runManifestFacts } from './run-manifest-facts.mts' +import { BUILD_TOOLS } from './scripts/build-tool.mts' import { ENVIRONMENT_YML, REQUIREMENTS_TXT, @@ -93,6 +96,19 @@ export async function generateAutoManifest({ const configOf = (tool: BuildTool) => resolveEcosystemConfig(tool, cwd, sockJson) + // Read only by a reachability scan for the tools that generate facts, so + // checked only for those, and before any build runs. + const generatesFacts = (tool: BuildTool) => + detected[tool] && !getSkipReason(tool, sockJson.defaults?.manifest?.[tool]) + const reachabilityByTool = new Map( + context?.workDir?.withFiles + ? BUILD_TOOLS.filter(generatesFacts).map(tool => [ + tool, + socketJsonReachability(tool, { dir: cwd, sockJson }), + ]) + : [], + ) + const generateFacts = async ( tool: BuildTool, config: EcosystemBuildConfig, @@ -103,6 +119,7 @@ export async function generateAutoManifest({ excludeBase: cwd, excludePaths, hints, + reachability: reachabilityByTool.get(tool), }), ) abortFactsRunIfFailed(tool, outcome) @@ -170,6 +187,7 @@ export async function generateAutoManifest({ cwd, excludePaths, hints, + reachability: reachabilityByTool.get('dotnet'), }) abortFactsRunIfFailed('dotnet', outcome) } diff --git a/src/commands/manifest/generate_auto_manifest.test.mts b/src/commands/manifest/generate_auto_manifest.test.mts index 9e3f24952..ee36c1d3f 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -26,7 +26,8 @@ vi.mock('./run-manifest-facts.mts', async importOriginal => ({ vi.mock('./handle-manifest-conda.mts', () => ({ handleManifestConda: vi.fn(async () => undefined), })) -vi.mock('../../utils/socket-json.mts', () => ({ +vi.mock('../../utils/socket-json.mts', async importOriginal => ({ + ...(await importOriginal()), readOrDefaultSocketJson: vi.fn(() => ({})), })) @@ -409,6 +410,113 @@ describe('generateAutoManifest — JVM facts', () => { expect(callFor('maven')?.entryFile).toBeUndefined() }, ) + + it("sends each tool's reachability settings on a reachability scan only", async () => { + vi.mocked(readOrDefaultSocketJson).mockReturnValue({ + defaults: { + manifest: { + dotnet: { reachability: { runtimeVersion: '8.0' } }, + gradle: { reachability: { build: 'compile' } }, + maven: { bin: 'mvn', reachability: { javaHome: '$MAVEN_JDK' } }, + sbt: { reachability: { build: 'none', javaHome: null } }, + }, + }, + } as SocketJson) + const detected = { + ...baseDetected, + dotnet: true, + gradle: true, + maven: true, + sbt: true, + } + const workDir = { dir: '/w', entries: new Map(), withFiles: true } + await generateAutoManifest({ + context: { workDir }, + cwd: '/tmp/repo', + detected, + outputKind: 'text', + verbose: false, + }) + expect( + Object.fromEntries( + vi + .mocked(runManifestFacts) + .mock.calls.map(([opts]) => [opts.ecosystem, opts.reachability]), + ), + ).toEqual({ + gradle: { build: 'compile' }, + maven: { javaHome: '$MAVEN_JDK' }, + sbt: { build: 'none' }, + }) + expect(vi.mocked(convertDotnetToFacts).mock.calls[0]?.[0]).toMatchObject({ + reachability: { runtimeVersion: '8.0' }, + }) + + vi.mocked(runManifestFacts).mockClear() + await generateAutoManifest({ + cwd: '/tmp/repo', + detected, + outputKind: 'text', + verbose: false, + }) + expect( + vi.mocked(runManifestFacts).mock.calls.map(([opts]) => opts.reachability), + ).toEqual([undefined, undefined, undefined]) + }) + + it("fails a reachability scan on an invalid setting of a detected tool, before any build, not of another's", async () => { + vi.mocked(readOrDefaultSocketJson).mockReturnValue({ + defaults: { + manifest: { dotnet: { reachability: { javaHome: '/jdk' } } }, + }, + } as SocketJson) + const context = { + workDir: { dir: '/w', entries: new Map(), withFiles: true }, + } + await generateAutoManifest({ + context, + cwd: '/tmp/repo', + detected: { ...baseDetected, gradle: true, count: 1 }, + outputKind: 'text', + verbose: false, + }) + vi.mocked(runManifestFacts).mockClear() + await expect( + generateAutoManifest({ + context, + cwd: '/tmp/repo', + detected: { ...baseDetected, dotnet: true, gradle: true, count: 2 }, + outputKind: 'text', + verbose: false, + }), + ).rejects.toThrow( + /dotnet\.reachability\.javaHome` in .* is not a reachability setting of dotnet builds/, + ) + expect(runManifestFacts).not.toHaveBeenCalled() + }) + + it('does not check the settings of a tool that generates pom files', async () => { + vi.mocked(readOrDefaultSocketJson).mockReturnValue({ + defaults: { + manifest: { + gradle: { facts: false, reachability: { runtimeVersion: '8.0' } }, + }, + }, + } as SocketJson) + + await expect( + generateAutoManifest({ + context: { + workDir: { dir: '/w', entries: new Map(), withFiles: true }, + }, + cwd: '/tmp/repo', + detected: { ...baseDetected, gradle: true, count: 1 }, + outputKind: 'text', + verbose: false, + }), + ).resolves.toBeDefined() + }) + }) describe('generateAutoManifest — conda branch', () => { diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 17471f256..86eba48be 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -17,6 +17,7 @@ import { logger } from '../../utils/logger.mts' import type { BuildRoot } from './discover-manifest-roots.mts' import type { BuildTool } from './scripts/build-tool.mts' import type { CResult } from '../../types.mts' +import type { ReachabilityBuild } from '../../utils/socket-json.mts' export type BuildOption = 'excludeConfigs' | 'ignoreUnresolved' | 'verbose' @@ -91,6 +92,14 @@ export type SocketFactsContext = { workDir?: SocketFactsWorkDir | undefined } +// What a reachability scan's analysis reads of a build's settings; only set +// fields are sent. +export type ReachabilitySettings = { + build?: ReachabilityBuild | undefined + javaHome?: string | undefined + runtimeVersion?: string | undefined +} + // A project the build loaded, with absolute paths. Gradle reports a project's // build file even when absent. export type SocketFactsProject = { buildFiles: string[]; dir: string } @@ -118,6 +127,7 @@ type SocketFactsRequest = { ignoreUnresolved: boolean includeConfigs?: string | undefined javaHome?: string | undefined + reachability?: ReachabilitySettings | undefined verbose: boolean } excludeBase: string @@ -227,6 +237,7 @@ export type SocketFactsRequestOptions = { includeConfigs?: string | undefined // As written: Coana expands `$VAR` references itself. javaHome?: string | undefined + reachability?: ReachabilitySettings | undefined verbose?: boolean | undefined } @@ -251,6 +262,7 @@ function toSocketFactsRequest( ignoreUnresolved = false, includeConfigs, javaHome, + reachability, verbose = false, }: SocketFactsRequestOptions, context: SocketFactsContext, @@ -281,6 +293,7 @@ function toSocketFactsRequest( ignoreUnresolved, ...(includeConfigs ? { includeConfigs } : {}), ...(javaHome && ecosystem !== 'dotnet' ? { javaHome } : {}), + ...(reachability ? { reachability } : {}), verbose, }, excludeBase: path.resolve(excludeBase ?? cwd), diff --git a/src/commands/manifest/run-manifest-facts.test.mts b/src/commands/manifest/run-manifest-facts.test.mts index 7c8d605b8..e712434ab 100644 --- a/src/commands/manifest/run-manifest-facts.test.mts +++ b/src/commands/manifest/run-manifest-facts.test.mts @@ -127,6 +127,24 @@ describe('runManifestFacts', () => { }) }) + it.for([ + { build: 'compile', javaHome: '${JAVA17_HOME}' }, + { build: 'none', runtimeVersion: '8.0.11' }, + ] as const)( + 'sends the reachability settings %j as given', + async reachability => { + coanaAnswers({ status: 'empty' }) + await runManifestFacts({ ...baseArgs, cwd, reachability }) + expect(calls[0]!.request.config.reachability).toEqual(reachability) + }, + ) + + it('sends no reachability settings when none are set', async () => { + coanaAnswers({ status: 'empty' }) + await runManifestFacts({ ...baseArgs, cwd }) + expect(calls[0]!.request.config).not.toHaveProperty('reachability') + }) + it("runs Coana in socket-cli's own cwd, so its logs show paths from there", async () => { coanaAnswers({ status: 'empty' }) await runManifestFacts({ ...baseArgs, cwd }) diff --git a/src/utils/socket-json.mts b/src/utils/socket-json.mts index 2e640f17e..c90baf74d 100644 --- a/src/utils/socket-json.mts +++ b/src/utils/socket-json.mts @@ -25,10 +25,30 @@ import { debugDir, debugFn } from './debug.mts' import { formatErrorWithDetail } from './errors.mts' import { findUp } from './fs.mts' import { logger } from './logger.mts' +import { isRecord } from './objects.mts' import { SOCKET_JSON, SOCKET_WEBSITE_URL } from '../constants.mts' import type { CResult } from '../types.mts' +export const REACHABILITY_BUILDS = ['compile', 'none'] as const + +// Whether a reachability analysis builds the project first; unset is "none". +export type ReachabilityBuild = (typeof REACHABILITY_BUILDS)[number] + +// Read only by reachability scans; a null field clears an inherited value. +export type JvmReachabilityDefaults = { + build?: ReachabilityBuild | undefined | null + // JDK the analysis takes the program to run on, as written. + javaHome?: string | undefined | null +} + +export type DotnetReachabilityDefaults = { + build?: ReachabilityBuild | undefined | null + // The .NET runtime a framework-dependent build's analysis starts on: + // major.minor, or a full version as `RuntimeFrameworkVersion` takes one. + runtimeVersion?: string | undefined | null +} + export interface SocketJson { ' _____ _ _ ': string '| __|___ ___| |_ ___| |_ ': string @@ -75,6 +95,7 @@ export interface SocketJson { excludeConfigs?: string | undefined | null includeConfigs?: string | undefined | null ignoreUnresolved?: boolean | undefined + reachability?: DotnetReachabilityDefaults | undefined verbose?: boolean | undefined } gradle?: { @@ -93,6 +114,7 @@ export interface SocketJson { // JDK path; sets JAVA_HOME for this ecosystem's build tool. Supports // $VAR/${VAR} expansion against the CLI's own environment. javaHome?: string | undefined | null + reachability?: JvmReachabilityDefaults | undefined verbose?: boolean | undefined } maven?: { @@ -108,6 +130,7 @@ export interface SocketJson { // $VAR/${VAR} expansion against the CLI's own environment. javaHome?: string | undefined | null mavenOpts?: string | undefined | null + reachability?: JvmReachabilityDefaults | undefined verbose?: boolean | undefined } sbt?: { @@ -126,6 +149,7 @@ export interface SocketJson { // $VAR/${VAR} expansion against the CLI's own environment. javaHome?: string | undefined | null outfile?: string | undefined | null + reachability?: JvmReachabilityDefaults | undefined sbtOpts?: string | undefined | null stdout?: boolean | undefined verbose?: boolean | undefined @@ -186,7 +210,19 @@ export async function readOrDefaultSocketJsonUp( return getDefaultSocketJson() } -// Shallow-merges `defaults.manifest.` per ecosystem: fields set in +// A build tool's `reachability` merges field by field, as its section does. +export function mergeBuildToolDefaults( + base: T | undefined, + override: T, +): T { + const merged = { ...base, ...override } + if (isRecord(base?.reachability) && isRecord(override.reachability)) { + merged.reachability = { ...base.reachability, ...override.reachability } + } + return merged +} + +// Merges `defaults.manifest.` per ecosystem: fields set in // `override` win, others fall through to `base`. Only this section cascades; // everything else in `defaults` comes from `base` only. function mergeManifestDefaults( @@ -208,22 +244,28 @@ function mergeManifestDefaults( mergedManifest.conda = { ...baseManifest?.conda, ...overrideManifest.conda } } if (overrideManifest.dotnet) { - mergedManifest.dotnet = { - ...baseManifest?.dotnet, - ...overrideManifest.dotnet, - } + mergedManifest.dotnet = mergeBuildToolDefaults( + baseManifest?.dotnet, + overrideManifest.dotnet, + ) } if (overrideManifest.gradle) { - mergedManifest.gradle = { - ...baseManifest?.gradle, - ...overrideManifest.gradle, - } + mergedManifest.gradle = mergeBuildToolDefaults( + baseManifest?.gradle, + overrideManifest.gradle, + ) } if (overrideManifest.maven) { - mergedManifest.maven = { ...baseManifest?.maven, ...overrideManifest.maven } + mergedManifest.maven = mergeBuildToolDefaults( + baseManifest?.maven, + overrideManifest.maven, + ) } if (overrideManifest.sbt) { - mergedManifest.sbt = { ...baseManifest?.sbt, ...overrideManifest.sbt } + mergedManifest.sbt = mergeBuildToolDefaults( + baseManifest?.sbt, + overrideManifest.sbt, + ) } return { ...base, diff --git a/src/utils/socket-json.test.mts b/src/utils/socket-json.test.mts index d0ed1c46b..75466061d 100644 --- a/src/utils/socket-json.test.mts +++ b/src/utils/socket-json.test.mts @@ -4,7 +4,11 @@ import path from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { mergeSocketJsonChain, readSocketJsonChain } from './socket-json.mts' +import { + mergeSocketJsonChain, + readOrDefaultSocketJson, + readSocketJsonChain, +} from './socket-json.mts' import type { SocketJson } from './socket-json.mts' @@ -134,4 +138,54 @@ describe('readSocketJsonChain and mergeSocketJsonChain', () => { excludeConfigs: null, }) }) + + it("cascades a build tool's reachability field by field", async () => { + await writeSocketJson(root, { + version: 1, + defaults: { + manifest: { + dotnet: { reachability: { build: 'compile', runtimeVersion: '8.0' } }, + maven: { reachability: { build: 'compile', javaHome: '/jdk-17' } }, + }, + }, + }) + const buildRoot = path.join(root, 'project') + await fs.mkdir(buildRoot, { recursive: true }) + await writeSocketJson(buildRoot, { + version: 1, + defaults: { + manifest: { + dotnet: { reachability: { runtimeVersion: null } }, + maven: { reachability: { build: 'none' } }, + }, + }, + }) + + const manifest = readSocketJsonCascade(buildRoot).defaults?.manifest + expect(manifest?.maven?.reachability).toEqual({ + build: 'none', + javaHome: '/jdk-17', + }) + expect(manifest?.dotnet?.reachability).toEqual({ + build: 'compile', + runtimeVersion: null, + }) + }) + + it('reads a socket.json whatever its reachability settings hold', async () => { + await writeSocketJson(root, { + version: 1, + defaults: { + manifest: { + dotnet: { reachability: { runtimeVersion: 'net8.0' } }, + maven: { bin: 'mvn', reachability: 'compile' }, + }, + }, + }) + + expect(mavenConfig(readOrDefaultSocketJson(root))?.bin).toBe('mvn') + expect(mavenConfig(readSocketJsonCascade(root))?.reachability).toBe( + 'compile', + ) + }) }) From 9e4775103f54f1dce6ec50b3ad442ba8ee446a8b Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 24 Nov 2026 14:27:53 +0100 Subject: [PATCH 02/12] Read the reachability settings for a reachability resolution --- .../manifest/generate-recursive-manifests.mts | 9 +++++---- .../manifest/generate_auto_manifest.mts | 2 +- .../manifest/generate_auto_manifest.test.mts | 18 +++++++++++++++--- 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index 8f364a5ea..f20bc1cd9 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -661,9 +661,10 @@ async function runCandidate( candidate: Candidate, options: SocketFactsRunOptions, ): Promise { - const reachability = ctx.context.workDir.withFiles - ? ctx.resolveSettings(options.ecosystem, candidate.root).reachability() - : undefined + const reachability = + ctx.context.workDir.purpose === 'reachability' + ? ctx.resolveSettings(options.ecosystem, candidate.root).reachability() + : undefined // A run a later build turns out to cover is dropped before its facts are // placed. const result = await runManifestFacts({ @@ -770,7 +771,7 @@ export async function generateRecursiveManifests({ for (const root of roots) { const settings = resolveSettings(tool, root) if ( - context.workDir?.withFiles && + context.workDir?.purpose === 'reachability' && !getSkipReason(tool, settings.sockJson.defaults?.manifest?.[tool]) ) { settings.reachability() diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index 8f0dbbaec..10a5f83eb 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -101,7 +101,7 @@ export async function generateAutoManifest({ const generatesFacts = (tool: BuildTool) => detected[tool] && !getSkipReason(tool, sockJson.defaults?.manifest?.[tool]) const reachabilityByTool = new Map( - context?.workDir?.withFiles + context?.workDir?.purpose === 'reachability' ? BUILD_TOOLS.filter(generatesFacts).map(tool => [ tool, socketJsonReachability(tool, { dir: cwd, sockJson }), diff --git a/src/commands/manifest/generate_auto_manifest.test.mts b/src/commands/manifest/generate_auto_manifest.test.mts index ee36c1d3f..ba50bd46a 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -429,7 +429,11 @@ describe('generateAutoManifest — JVM facts', () => { maven: true, sbt: true, } - const workDir = { dir: '/w', entries: new Map(), withFiles: true } + const workDir = { + dir: '/w', + entries: new Map(), + purpose: 'reachability' as const, + } await generateAutoManifest({ context: { workDir }, cwd: '/tmp/repo', @@ -471,7 +475,11 @@ describe('generateAutoManifest — JVM facts', () => { }, } as SocketJson) const context = { - workDir: { dir: '/w', entries: new Map(), withFiles: true }, + workDir: { + dir: '/w', + entries: new Map(), + purpose: 'reachability' as const, + }, } await generateAutoManifest({ context, @@ -507,7 +515,11 @@ describe('generateAutoManifest — JVM facts', () => { await expect( generateAutoManifest({ context: { - workDir: { dir: '/w', entries: new Map(), withFiles: true }, + workDir: { + dir: '/w', + entries: new Map(), + purpose: 'reachability' as const, + }, }, cwd: '/tmp/repo', detected: { ...baseDetected, gradle: true, count: 1 }, From 680874ab631a21464ac02bbbabee5b313ad17595 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 13:41:38 +0100 Subject: [PATCH 03/12] Drop the comment repeating which tools take facts: false --- src/commands/manifest/generate-recursive-manifests.mts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index f20bc1cd9..4416a72cd 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -93,7 +93,6 @@ export type EcosystemBuildConfig = { // root here, on top of its existing root-only ecosystem-wide meaning for // auto/gradle/etc. facts:false has no pom-mode equivalent here (facts-only), // so it skips too. -// Only Gradle and sbt take `facts: false`, which generates pom files instead. export function getSkipReason( ecosystem: BuildTool, section: From 42ce541dae04f07d478a2f80178069251e420060 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 13:41:51 +0100 Subject: [PATCH 04/12] Reword the reachability settings comments --- src/commands/manifest/build-root-config.mts | 8 ++++---- src/commands/manifest/run-manifest-facts.mts | 3 +-- src/utils/socket-json.mts | 6 ++++-- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/commands/manifest/build-root-config.mts b/src/commands/manifest/build-root-config.mts index 3b0364542..f8035943a 100644 --- a/src/commands/manifest/build-root-config.mts +++ b/src/commands/manifest/build-root-config.mts @@ -41,8 +41,8 @@ export type ResolvedBuildRootSettings = { disabledBy: DisabledBy | undefined // The key of the build's own `defaults.manifest.builds` entry. entryKey: string | undefined - // The cascaded `reachability` settings, checked in every socket.json that - // sets them; throws an InputError naming an invalid one. + // Checks reachability settings in every socket.json that supplies them. + // An invalid setting raises an InputError naming the file and field. reachability: () => ReachabilitySettings | undefined // The cascaded settings, the build's own entries applied last. sockJson: SocketJson @@ -338,8 +338,8 @@ export function displayPath(file: string): string { return rel.startsWith('..') || path.isAbsolute(rel) ? file : rel || '.' } -// Why `tool`'s reachability `field` cannot be `value`, as the rest of a -// sentence about it; undefined when it can. +// Returns a phrase explaining why the tool rejects this field value. +// Returns undefined for a valid value. export function reachabilityProblem( tool: BuildTool, field: string, diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 86eba48be..2c1defbb7 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -92,8 +92,7 @@ export type SocketFactsContext = { workDir?: SocketFactsWorkDir | undefined } -// What a reachability scan's analysis reads of a build's settings; only set -// fields are sent. +// A reachability scan sends Coana only the settings configured for this build. export type ReachabilitySettings = { build?: ReachabilityBuild | undefined javaHome?: string | undefined diff --git a/src/utils/socket-json.mts b/src/utils/socket-json.mts index c90baf74d..f74c2314f 100644 --- a/src/utils/socket-json.mts +++ b/src/utils/socket-json.mts @@ -32,10 +32,12 @@ import type { CResult } from '../types.mts' export const REACHABILITY_BUILDS = ['compile', 'none'] as const -// Whether a reachability analysis builds the project first; unset is "none". +// Controls whether reachability analysis builds the project first. +// Defaults to "none". export type ReachabilityBuild = (typeof REACHABILITY_BUILDS)[number] -// Read only by reachability scans; a null field clears an inherited value. +// Only reachability scans read these settings. +// A null field clears its inherited value. export type JvmReachabilityDefaults = { build?: ReachabilityBuild | undefined | null // JDK the analysis takes the program to run on, as written. From b680cd9576965a5d990c89762641cbec0df66d7b Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 13:42:01 +0100 Subject: [PATCH 05/12] Say what checking a socket.json's reachability settings raises --- src/commands/manifest/build-root-config.mts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/commands/manifest/build-root-config.mts b/src/commands/manifest/build-root-config.mts index f8035943a..dad39f0d1 100644 --- a/src/commands/manifest/build-root-config.mts +++ b/src/commands/manifest/build-root-config.mts @@ -366,7 +366,7 @@ export function socketJsonPath(dir: string): string { return displayPath(path.join(dir, SOCKET_JSON)) } -// The `reachability` settings of `tool` in one socket.json, checked. +// An invalid setting raises an InputError naming the file. export function socketJsonReachability( tool: BuildTool, { dir, sockJson }: SocketJsonInDir, From 64f6cbd75724ebefd6dfa3a535550bc7c8c30f5b Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 14:07:21 +0100 Subject: [PATCH 06/12] Read inherited reachability settings in auto-manifest `socket scan create --reach --auto-manifest` read the reachability settings only from the socket.json in the directory it scans, so a JDK or .NET runtime set by a parent socket.json was dropped. It now cascades them from every socket.json down to that directory, as `socket manifest` does, and a null in a nearer file still clears an inherited value. An invalid setting in any of those files fails the scan before a build runs. --- src/commands/manifest/build-root-config.mts | 33 ++++--- .../manifest/generate_auto_manifest.mts | 15 +++- .../manifest/generate_auto_manifest.test.mts | 87 +++++++++++++++++-- 3 files changed, 116 insertions(+), 19 deletions(-) diff --git a/src/commands/manifest/build-root-config.mts b/src/commands/manifest/build-root-config.mts index dad39f0d1..d4ffdd6a2 100644 --- a/src/commands/manifest/build-root-config.mts +++ b/src/commands/manifest/build-root-config.mts @@ -293,17 +293,16 @@ export function createBuildRootSettingsResolver( disabledBy, entryKey, reachability: () => { - for (const file of chain) { - socketJsonReachability(tool, file) - } - if (entryKey && entry) { - checkReachability( - tool, - entry['reachability'], - `${buildsSetting(entryKey)}.reachability`, - socketJsonPath(root.dir), - ) + const cascaded = cascadedReachability(tool, chain) + if (!entryKey || !entry) { + return cascaded } + checkReachability( + tool, + entry['reachability'], + `${buildsSetting(entryKey)}.reachability`, + socketJsonPath(root.dir), + ) return reachabilitySettings(section['reachability']) }, sockJson: { @@ -366,6 +365,20 @@ export function socketJsonPath(dir: string): string { return displayPath(path.join(dir, SOCKET_JSON)) } +// The `reachability` settings of `tool` that `chain` cascades to, checked in +// every socket.json that sets them. +export function cascadedReachability( + tool: BuildTool, + chain: readonly SocketJsonInDir[], +): ReachabilitySettings | undefined { + for (const file of chain) { + socketJsonReachability(tool, file) + } + return reachabilitySettings( + mergeSocketJsonChain(chain).defaults?.manifest?.[tool]?.reachability, + ) +} + // An invalid setting raises an InputError naming the file. export function socketJsonReachability( tool: BuildTool, diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index 10a5f83eb..b4887a3e0 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -1,5 +1,5 @@ import { extractBazelToMaven } from './bazel/extract_bazel_to_maven.mts' -import { socketJsonReachability } from './build-root-config.mts' +import { cascadedReachability } from './build-root-config.mts' import { convertDotnetToFacts } from './convert-dotnet-to-facts.mts' import { convertGradleToMaven } from './convert_gradle_to_maven.mts' import { convertSbtToMaven } from './convert_sbt_to_maven.mts' @@ -18,7 +18,10 @@ import { } from '../../constants.mts' import { InputError } from '../../utils/errors.mts' import { logger } from '../../utils/logger.mts' -import { readOrDefaultSocketJson } from '../../utils/socket-json.mts' +import { + readOrDefaultSocketJson, + readSocketJsonChain, +} from '../../utils/socket-json.mts' import type { GeneratableManifests } from './detect-manifest-actions.mts' import type { EcosystemBuildConfig } from './generate-recursive-manifests.mts' @@ -100,11 +103,15 @@ export async function generateAutoManifest({ // checked only for those, and before any build runs. const generatesFacts = (tool: BuildTool) => detected[tool] && !getSkipReason(tool, sockJson.defaults?.manifest?.[tool]) - const reachabilityByTool = new Map( + const reachabilityChain = context?.workDir?.purpose === 'reachability' + ? readSocketJsonChain(cwd) + : undefined + const reachabilityByTool = new Map( + reachabilityChain ? BUILD_TOOLS.filter(generatesFacts).map(tool => [ tool, - socketJsonReachability(tool, { dir: cwd, sockJson }), + cascadedReachability(tool, reachabilityChain), ]) : [], ) diff --git a/src/commands/manifest/generate_auto_manifest.test.mts b/src/commands/manifest/generate_auto_manifest.test.mts index ba50bd46a..c3887c54f 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -29,6 +29,7 @@ vi.mock('./handle-manifest-conda.mts', () => ({ vi.mock('../../utils/socket-json.mts', async importOriginal => ({ ...(await importOriginal()), readOrDefaultSocketJson: vi.fn(() => ({})), + readSocketJsonChain: vi.fn(() => []), })) import { extractBazelToMaven } from './bazel/extract_bazel_to_maven.mts' @@ -38,10 +39,26 @@ 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' +import { + readOrDefaultSocketJson, + readSocketJsonChain, +} from '../../utils/socket-json.mts' import type { SocketJson } from '../../utils/socket-json.mts' +// What both of auto-manifest's socket.json reads see: cwd's own file, and +// the chain of `parents` down to it. +function useSettings( + sockJson: SocketJson, + parents: Array<{ dir: string; sockJson: SocketJson }> = [], +): void { + vi.mocked(readOrDefaultSocketJson).mockReturnValue(sockJson) + vi.mocked(readSocketJsonChain).mockReturnValue([ + ...parents, + { dir: '/tmp/repo', sockJson }, + ]) +} + const baseDetected = { bazel: false, cdxgen: false, @@ -54,6 +71,22 @@ const baseDetected = { sbt: false, } +// The reachability settings a reachability scan of a Maven build at +// /tmp/repo sends. +async function mavenReachabilitySent(): Promise { + vi.mocked(runManifestFacts).mockClear() + await generateAutoManifest({ + context: { + workDir: { dir: '/w', entries: new Map(), purpose: 'reachability' }, + }, + cwd: '/tmp/repo', + detected: { ...baseDetected, maven: true, count: 1 }, + outputKind: 'text', + verbose: false, + }) + return vi.mocked(runManifestFacts).mock.calls[0]?.[0].reachability +} + describe('generateAutoManifest — bazel branch', () => { beforeEach(() => { vi.mocked(extractBazelToMaven).mockClear() @@ -334,7 +367,7 @@ function callFor(ecosystem: string) { describe('generateAutoManifest — JVM facts', () => { beforeEach(() => { vi.mocked(runManifestFacts).mockReset() - vi.mocked(readOrDefaultSocketJson).mockReturnValue({} as SocketJson) + useSettings({} as SocketJson) }) it('runs Maven where the scan starts, leaving it to find its POM', async () => { @@ -412,7 +445,7 @@ describe('generateAutoManifest — JVM facts', () => { ) it("sends each tool's reachability settings on a reachability scan only", async () => { - vi.mocked(readOrDefaultSocketJson).mockReturnValue({ + useSettings({ defaults: { manifest: { dotnet: { reachability: { runtimeVersion: '8.0' } }, @@ -469,7 +502,7 @@ describe('generateAutoManifest — JVM facts', () => { }) it("fails a reachability scan on an invalid setting of a detected tool, before any build, not of another's", async () => { - vi.mocked(readOrDefaultSocketJson).mockReturnValue({ + useSettings({ defaults: { manifest: { dotnet: { reachability: { javaHome: '/jdk' } } }, }, @@ -504,7 +537,7 @@ describe('generateAutoManifest — JVM facts', () => { }) it('does not check the settings of a tool that generates pom files', async () => { - vi.mocked(readOrDefaultSocketJson).mockReturnValue({ + useSettings({ defaults: { manifest: { gradle: { facts: false, reachability: { runtimeVersion: '8.0' } }, @@ -529,6 +562,50 @@ describe('generateAutoManifest — JVM facts', () => { ).resolves.toBeDefined() }) + it('sends the reachability settings a parent socket.json cascades to, unless cwd clears them', async () => { + const parent = { + dir: '/tmp', + sockJson: { + defaults: { + manifest: { + maven: { reachability: { build: 'compile', javaHome: '/jdk-17' } }, + }, + }, + } as SocketJson, + } + + useSettings({} as SocketJson, [parent]) + expect(await mavenReachabilitySent()).toEqual({ + build: 'compile', + javaHome: '/jdk-17', + }) + + useSettings( + { + defaults: { manifest: { maven: { reachability: { javaHome: null } } } }, + } as SocketJson, + [parent], + ) + expect(await mavenReachabilitySent()).toEqual({ build: 'compile' }) + }) + + it('fails a reachability scan on an invalid setting a parent socket.json cascades to', async () => { + useSettings({} as SocketJson, [ + { + dir: '/tmp', + sockJson: { + defaults: { + manifest: { maven: { reachability: { build: 'always' } } }, + }, + } as SocketJson, + }, + ]) + + await expect(mavenReachabilitySent()).rejects.toThrow( + /maven\.reachability\.build` in .*tmp.socket\.json is "always"/, + ) + expect(runManifestFacts).not.toHaveBeenCalled() + }) }) describe('generateAutoManifest — conda branch', () => { From 1eba228168c597b54a96b3ce1a8b7e30af162fe0 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Thu, 26 Nov 2026 12:29:26 +0100 Subject: [PATCH 07/12] Ask one predicate whether a run reads the reachability settings --- .../manifest/generate-recursive-manifests.mts | 10 +++++----- src/commands/manifest/generate_auto_manifest.mts | 12 +++++++----- src/commands/manifest/run-manifest-facts.mts | 7 +++++++ 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index 4416a72cd..c4b7a6ae3 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -26,6 +26,7 @@ import { DSI_SETUP_COMMAND, createSocketFactsWorkDir, keepFacts, + readsReachabilitySettings, runManifestFacts, } from './run-manifest-facts.mts' import { @@ -660,10 +661,9 @@ async function runCandidate( candidate: Candidate, options: SocketFactsRunOptions, ): Promise { - const reachability = - ctx.context.workDir.purpose === 'reachability' - ? ctx.resolveSettings(options.ecosystem, candidate.root).reachability() - : undefined + const reachability = readsReachabilitySettings(ctx.context) + ? ctx.resolveSettings(options.ecosystem, candidate.root).reachability() + : undefined // A run a later build turns out to cover is dropped before its facts are // placed. const result = await runManifestFacts({ @@ -770,7 +770,7 @@ export async function generateRecursiveManifests({ for (const root of roots) { const settings = resolveSettings(tool, root) if ( - context.workDir?.purpose === 'reachability' && + readsReachabilitySettings(context) && !getSkipReason(tool, settings.sockJson.defaults?.manifest?.[tool]) ) { settings.reachability() diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index b4887a3e0..2b4785163 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -9,7 +9,10 @@ import { socketFactsRunOptions, } from './generate-recursive-manifests.mts' import { handleManifestConda } from './handle-manifest-conda.mts' -import { runManifestFacts } from './run-manifest-facts.mts' +import { + readsReachabilitySettings, + runManifestFacts, +} from './run-manifest-facts.mts' import { BUILD_TOOLS } from './scripts/build-tool.mts' import { ENVIRONMENT_YML, @@ -103,10 +106,9 @@ export async function generateAutoManifest({ // checked only for those, and before any build runs. const generatesFacts = (tool: BuildTool) => detected[tool] && !getSkipReason(tool, sockJson.defaults?.manifest?.[tool]) - const reachabilityChain = - context?.workDir?.purpose === 'reachability' - ? readSocketJsonChain(cwd) - : undefined + const reachabilityChain = readsReachabilitySettings(context) + ? readSocketJsonChain(cwd) + : undefined const reachabilityByTool = new Map( reachabilityChain ? BUILD_TOOLS.filter(generatesFacts).map(tool => [ diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 2c1defbb7..4b0e21903 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -164,6 +164,13 @@ export function coanaReadsFacts(context: SocketFactsContext): boolean { return purposeOf(context) !== 'upload' } +// Only a reachability scan reads the builds' socket.json reachability settings. +export function readsReachabilitySettings( + context: SocketFactsContext | undefined, +): boolean { + return context !== undefined && purposeOf(context) === 'reachability' +} + async function readResult( resultFile: string, ): Promise<{ error?: string | undefined; result: T | undefined }> { From a61a2e6ea76645b5a6dca6a5d1e7882b8ba4c3e0 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Fri, 27 Nov 2026 10:25:24 +0100 Subject: [PATCH 08/12] Parse each socket.json's reachability settings once One table says which reachability fields each build tool takes, and the socket.json types and the settings sent to Coana derive from it. One parse checks a value and builds the typed settings as it goes, so the resolver checks each socket.json once and keeps the result per build. Skips read the resolved config's skip reason, and a build tool section merges each of its object-valued fields field by field. --- src/commands/manifest/build-root-config.mts | 227 ++++++++++-------- .../manifest/build-root-config.test.mts | 10 +- .../manifest/convert-dotnet-to-facts.mts | 2 +- .../manifest/generate-recursive-manifests.mts | 10 +- .../manifest/generate_auto_manifest.mts | 3 +- src/commands/manifest/run-manifest-facts.mts | 9 +- src/utils/socket-json.mts | 96 ++++---- 7 files changed, 195 insertions(+), 162 deletions(-) diff --git a/src/commands/manifest/build-root-config.mts b/src/commands/manifest/build-root-config.mts index d4ffdd6a2..4c8cf578c 100644 --- a/src/commands/manifest/build-root-config.mts +++ b/src/commands/manifest/build-root-config.mts @@ -15,17 +15,20 @@ import { logger } from '../../utils/logger.mts' import { isRecord } from '../../utils/objects.mts' import { REACHABILITY_BUILDS, + REACHABILITY_FIELDS_BY_TOOL, mergeBuildToolDefaults, mergeSocketJsonChain, readSocketJsonChain, } from '../../utils/socket-json.mts' +import { isNonEmptyString } from '../../utils/strings.mts' import type { BuildRoot } from './discover-manifest-roots.mts' -import type { ReachabilitySettings } from './run-manifest-facts.mts' import type { BuildTool } from './scripts/build-tool.mts' import type { + ReachabilityDefaults, + ReachabilityField, + ReachabilitySettings, SocketJson, - SocketJsonBuildEntry, SocketJsonInDir, } from '../../utils/socket-json.mts' @@ -56,37 +59,40 @@ const DOTNET_RUNTIME_VERSION = new RegExp( `^${NUMBER}\\.${NUMBER}(?:\\.${NUMBER}(?:-${PRERELEASE_IDENTIFIER}(?:\\.${PRERELEASE_IDENTIFIER})*)?)?$`, ) -type ReachabilityField = { - // What a valid value is, as "set it to …" names it. - expected: string - takes: (value: unknown) => boolean - tools: readonly BuildTool[] -} +const DOTNET_RUNTIME_VERSION_FORMAT = + 'major.minor, such as "8.0", for its latest installed patch, or major.minor.patch[-prerelease], such as "8.0.11", for exactly that runtime' -const REACHABILITY_FIELDS: Record< - keyof ReachabilitySettings, - ReachabilityField -> = { +const REACHABILITY_FIELDS = { __proto__: null, build: { expected: joinOr(REACHABILITY_BUILDS.map(b => `"${b}"`)), takes: (value: unknown) => (REACHABILITY_BUILDS as readonly unknown[]).includes(value), - tools: BUILD_TOOLS, }, javaHome: { expected: 'a JDK path', - takes: (value: unknown) => typeof value === 'string' && !!value, - tools: ['gradle', 'maven', 'sbt'], + takes: isNonEmptyString, }, runtimeVersion: { - expected: - 'a .NET runtime version: major.minor, such as "8.0", for its latest installed patch, or major.minor.patch[-prerelease], such as "8.0.11", for exactly that runtime', + expected: `a .NET runtime version: ${DOTNET_RUNTIME_VERSION_FORMAT}`, takes: (value: unknown) => typeof value === 'string' && DOTNET_RUNTIME_VERSION.test(value), - tools: ['dotnet'], }, -} as unknown as Record +} satisfies { __proto__: null } & Record< + ReachabilityField, + { + // What a valid value is, as "set it to …" names it. + expected: string + takes: (value: unknown) => boolean + } +> + +type ReachabilityProblem = { + // Undefined when the value is not an object. + field: string | undefined + // Why the tool rejects it, and the remedy. + problem: string +} function checkReachability( tool: BuildTool, @@ -94,24 +100,29 @@ function checkReachability( setting: string, socketJson: string, ): void { - if (value === undefined) { - return - } - if (!isRecord(value)) { - throw new InputError( - `\`${setting}\` in ${socketJson} is ${JSON.stringify(value)}; set it to an object, or remove it.`, - ) - } - for (const { 0: field, 1: fieldValue } of Object.entries(value)) { - const problem = reachabilityProblem(tool, field, fieldValue) - if (problem) { - throw new InputError( - `\`${setting}.${field}\` in ${socketJson} ${problem}`, - ) - } + const { + problems: { 0: first }, + } = parseReachability(tool, value) + if (first) { + const key = + first.field === undefined ? setting : `${setting}.${first.field}` + throw new InputError(`\`${key}\` in ${socketJson} ${first.problem}`) } } +// An invalid setting raises an InputError naming the file. +function checkSocketJsonReachability( + tool: BuildTool, + { dir, sockJson }: SocketJsonInDir, +): void { + checkReachability( + tool, + sockJson.defaults?.manifest?.[tool]?.reachability, + `defaults.manifest.${tool}.reachability`, + socketJsonPath(dir), + ) +} + // Gradle and sbt name a build by any build file of its directory. function namesBuildFile(key: string): boolean { return BUILD_TOOLS.some(tool => { @@ -137,24 +148,59 @@ function ownEntryKeys( ) } -function reachabilityKey(tool: BuildTool): string { - return `defaults.manifest.${tool}.reachability` +// The valid fields of `value`, nulls kept, and the problem with each other one. +function parseReachability( + tool: BuildTool, + value: unknown, +): { problems: ReachabilityProblem[]; settings: ReachabilityDefaults } { + const settings: ReachabilityDefaults = {} + if (value === undefined) { + return { problems: [], settings } + } + if (!isRecord(value)) { + return { + problems: [ + { + field: undefined, + problem: `is ${JSON.stringify(value)}; set it to an object, or remove it.`, + }, + ], + settings, + } + } + const fields = REACHABILITY_FIELDS_BY_TOOL[tool] + const problems: ReachabilityProblem[] = [] + for (const { 0: name, 1: fieldValue } of Object.entries(value)) { + const field = fields.find(f => f === name) + if (!field) { + problems.push({ + field: name, + problem: `is not a reachability setting of ${tool} builds, which take ${joinAnd(fields)}; remove it.`, + }) + } else if ( + fieldValue === null || + REACHABILITY_FIELDS[field].takes(fieldValue) + ) { + Object.assign(settings, { [field]: fieldValue }) + } else { + problems.push({ + field, + problem: `is ${JSON.stringify(fieldValue)}; set it to ${REACHABILITY_FIELDS[field].expected}, to null to clear an inherited value, or remove it.`, + }) + } + } + return { problems, settings } } // Without the fields a socket.json cleared with null. -function reachabilitySettings( - value: unknown, +function settingsInEffect( + settings: ReachabilityDefaults, ): ReachabilitySettings | undefined { - if (!isRecord(value)) { - return undefined - } - const settings = Object.fromEntries( - Object.entries(value).filter( - ({ 1: setting }) => setting !== null && setting !== undefined, - ), + const entries = Object.entries(settings).filter( + ({ 1: setting }) => setting !== null && setting !== undefined, ) - return Object.keys(settings).length - ? (settings as ReachabilitySettings) + return entries.length + ? (Object.fromEntries(entries) as ReachabilitySettings) : undefined } @@ -228,6 +274,7 @@ export function createBuildRootSettingsResolver( const chains = new Map() const resolved = new Map() const validated = new Set() + const reachabilityChecked = new Set() const chainFor = (dir: string): SocketJsonInDir[] => { let chain = chains.get(dir) @@ -251,7 +298,7 @@ export function createBuildRootSettingsResolver( ): ResolvedBuildRootSettings => { const chain = chainFor(root.dir) const merged = mergeSocketJsonChain(chain) - const section: Record = { + let section: Record = { ...merged.defaults?.manifest?.[tool], } let sectionDisabledBy: DisabledBy | undefined @@ -272,11 +319,9 @@ export function createBuildRootSettingsResolver( ? ownEntryKeys(tool, root.dir, builds, root.entryFile)[0] : undefined let entryDisabledBy: DisabledBy | undefined - const entry = entryKey - ? (builds![entryKey] as SocketJsonBuildEntry) - : undefined - if (entryKey && entry) { - Object.assign(section, mergeBuildToolDefaults(section, entry)) + const entry = entryKey ? builds?.[entryKey] : undefined + if (entry) { + section = mergeBuildToolDefaults(section, entry) if (entry.disabled !== undefined) { entryDisabledBy = { dir: root.dir, key: entryKey } } @@ -289,21 +334,34 @@ export function createBuildRootSettingsResolver( disabledBy = directorySkip ? sectionDisabledBy : entryDisabledBy } + let reachability: { settings: ReachabilitySettings | undefined } | undefined return { disabledBy, entryKey, reachability: () => { - const cascaded = cascadedReachability(tool, chain) - if (!entryKey || !entry) { - return cascaded + if (!reachability) { + for (const file of chain) { + const key = `${tool}\0${file.dir}` + if (!reachabilityChecked.has(key)) { + checkSocketJsonReachability(tool, file) + reachabilityChecked.add(key) + } + } + if (entryKey && entry) { + checkReachability( + tool, + entry['reachability'], + `${buildsSetting(entryKey)}.reachability`, + socketJsonPath(root.dir), + ) + } + reachability = { + settings: settingsInEffect( + parseReachability(tool, section['reachability']).settings, + ), + } } - checkReachability( - tool, - entry['reachability'], - `${buildsSetting(entryKey)}.reachability`, - socketJsonPath(root.dir), - ) - return reachabilitySettings(section['reachability']) + return reachability.settings }, sockJson: { ...merged, @@ -337,30 +395,6 @@ export function displayPath(file: string): string { return rel.startsWith('..') || path.isAbsolute(rel) ? file : rel || '.' } -// Returns a phrase explaining why the tool rejects this field value. -// Returns undefined for a valid value. -export function reachabilityProblem( - tool: BuildTool, - field: string, - value: unknown, -): string | undefined { - const spec = REACHABILITY_FIELDS[field as keyof ReachabilitySettings] as - | ReachabilityField - | undefined - if (!spec?.tools.includes(tool)) { - const fields = Object.keys(REACHABILITY_FIELDS).filter(name => - REACHABILITY_FIELDS[name as keyof ReachabilitySettings].tools.includes( - tool, - ), - ) - return `is not a reachability setting of ${tool} builds, which take ${joinAnd(fields)}; remove it.` - } - if (value === null || spec.takes(value)) { - return undefined - } - return `is ${JSON.stringify(value)}; set it to ${spec.expected}, to null to clear an inherited value, or remove it.` -} - export function socketJsonPath(dir: string): string { return displayPath(path.join(dir, SOCKET_JSON)) } @@ -372,19 +406,12 @@ export function cascadedReachability( chain: readonly SocketJsonInDir[], ): ReachabilitySettings | undefined { for (const file of chain) { - socketJsonReachability(tool, file) + checkSocketJsonReachability(tool, file) } - return reachabilitySettings( - mergeSocketJsonChain(chain).defaults?.manifest?.[tool]?.reachability, + return settingsInEffect( + parseReachability( + tool, + mergeSocketJsonChain(chain).defaults?.manifest?.[tool]?.reachability, + ).settings, ) } - -// An invalid setting raises an InputError naming the file. -export function socketJsonReachability( - tool: BuildTool, - { dir, sockJson }: SocketJsonInDir, -): ReachabilitySettings | undefined { - const value = sockJson.defaults?.manifest?.[tool]?.reachability - checkReachability(tool, value, reachabilityKey(tool), socketJsonPath(dir)) - return reachabilitySettings(value) -} diff --git a/src/commands/manifest/build-root-config.test.mts b/src/commands/manifest/build-root-config.test.mts index ae07a1a67..d70c783b4 100644 --- a/src/commands/manifest/build-root-config.test.mts +++ b/src/commands/manifest/build-root-config.test.mts @@ -5,10 +5,10 @@ import path from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { + cascadedReachability, createBuildRootSettingsResolver, describeDisabledBy, displayPath, - socketJsonReachability, } from './build-root-config.mts' import { InputError } from '../../utils/errors.mts' import { escapeRegExp } from '../../utils/escape-regexp.mts' @@ -419,8 +419,8 @@ describe('createBuildRootSettingsResolver', () => { }) }) -describe('socketJsonReachability', () => { - it("checks one socket.json's section for the tool alone", () => { +describe('cascadedReachability', () => { + it("checks each socket.json's section for the tool alone", () => { const sockJson = { defaults: { manifest: { @@ -430,11 +430,11 @@ describe('socketJsonReachability', () => { }, } as any - expect(socketJsonReachability('gradle', { dir: '/r', sockJson })).toEqual({ + expect(cascadedReachability('gradle', [{ dir: '/r', sockJson }])).toEqual({ build: 'compile', }) expect(() => - socketJsonReachability('dotnet', { dir: '/r', sockJson }), + cascadedReachability('dotnet', [{ dir: '/r', sockJson }]), ).toThrow(InputError) }) }) diff --git a/src/commands/manifest/convert-dotnet-to-facts.mts b/src/commands/manifest/convert-dotnet-to-facts.mts index ae18eb6d4..7b1fae10c 100644 --- a/src/commands/manifest/convert-dotnet-to-facts.mts +++ b/src/commands/manifest/convert-dotnet-to-facts.mts @@ -7,10 +7,10 @@ import { logger } from '../../utils/logger.mts' import type { EcosystemBuildConfig } from './generate-recursive-manifests.mts' import type { BuildOptionHints, - ReachabilitySettings, RunManifestFactsOutcome, SocketFactsContext, } from './run-manifest-facts.mts' +import type { ReachabilitySettings } from '../../utils/socket-json.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 diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index c4b7a6ae3..5853d9641 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -46,7 +46,6 @@ import type { LoadedBuild } from './load-build.mts' import type { BuildOptionHints, CommandHints, - ReachabilitySettings, RunManifestFactsOutcome, RunManifestFactsResult, SocketFactsContext, @@ -55,7 +54,10 @@ import type { } from './run-manifest-facts.mts' import type { BuildTool } from './scripts/build-tool.mts' import type { PURL_Type } from '../../utils/ecosystem.mts' -import type { SocketJson } from '../../utils/socket-json.mts' +import type { + ReachabilitySettings, + SocketJson, +} from '../../utils/socket-json.mts' function normalizePathKey(value: string): string { return value.replaceAll('\\', '/') @@ -94,7 +96,7 @@ export type EcosystemBuildConfig = { // root here, on top of its existing root-only ecosystem-wide meaning for // auto/gradle/etc. facts:false has no pom-mode equivalent here (facts-only), // so it skips too. -export function getSkipReason( +function getSkipReason( ecosystem: BuildTool, section: | { disabled?: boolean | undefined; facts?: boolean | undefined } @@ -771,7 +773,7 @@ export async function generateRecursiveManifests({ const settings = resolveSettings(tool, root) if ( readsReachabilitySettings(context) && - !getSkipReason(tool, settings.sockJson.defaults?.manifest?.[tool]) + !resolveEcosystemConfig(tool, root.dir, settings.sockJson).skipReason ) { settings.reachability() } diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index 2b4785163..30595039a 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -4,7 +4,6 @@ import { convertDotnetToFacts } from './convert-dotnet-to-facts.mts' import { convertGradleToMaven } from './convert_gradle_to_maven.mts' import { convertSbtToMaven } from './convert_sbt_to_maven.mts' import { - getSkipReason, resolveEcosystemConfig, socketFactsRunOptions, } from './generate-recursive-manifests.mts' @@ -105,7 +104,7 @@ export async function generateAutoManifest({ // Read only by a reachability scan for the tools that generate facts, so // checked only for those, and before any build runs. const generatesFacts = (tool: BuildTool) => - detected[tool] && !getSkipReason(tool, sockJson.defaults?.manifest?.[tool]) + detected[tool] && !configOf(tool).skipReason const reachabilityChain = readsReachabilitySettings(context) ? readSocketJsonChain(cwd) : undefined diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 4b0e21903..ebe935661 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -17,7 +17,7 @@ import { logger } from '../../utils/logger.mts' import type { BuildRoot } from './discover-manifest-roots.mts' import type { BuildTool } from './scripts/build-tool.mts' import type { CResult } from '../../types.mts' -import type { ReachabilityBuild } from '../../utils/socket-json.mts' +import type { ReachabilitySettings } from '../../utils/socket-json.mts' export type BuildOption = 'excludeConfigs' | 'ignoreUnresolved' | 'verbose' @@ -92,13 +92,6 @@ export type SocketFactsContext = { workDir?: SocketFactsWorkDir | undefined } -// A reachability scan sends Coana only the settings configured for this build. -export type ReachabilitySettings = { - build?: ReachabilityBuild | undefined - javaHome?: string | undefined - runtimeVersion?: string | undefined -} - // A project the build loaded, with absolute paths. Gradle reports a project's // build file even when absent. export type SocketFactsProject = { buildFiles: string[]; dir: string } diff --git a/src/utils/socket-json.mts b/src/utils/socket-json.mts index f74c2314f..decf9cb16 100644 --- a/src/utils/socket-json.mts +++ b/src/utils/socket-json.mts @@ -28,6 +28,7 @@ import { logger } from './logger.mts' import { isRecord } from './objects.mts' import { SOCKET_JSON, SOCKET_WEBSITE_URL } from '../constants.mts' +import type { BuildTool } from '../commands/manifest/scripts/build-tool.mts' import type { CResult } from '../types.mts' export const REACHABILITY_BUILDS = ['compile', 'none'] as const @@ -37,18 +38,39 @@ export const REACHABILITY_BUILDS = ['compile', 'none'] as const export type ReachabilityBuild = (typeof REACHABILITY_BUILDS)[number] // Only reachability scans read these settings. -// A null field clears its inherited value. -export type JvmReachabilityDefaults = { - build?: ReachabilityBuild | undefined | null +type ReachabilityValues = { + build: ReachabilityBuild // JDK the analysis takes the program to run on, as written. - javaHome?: string | undefined | null -} - -export type DotnetReachabilityDefaults = { - build?: ReachabilityBuild | undefined | null + javaHome: string // The .NET runtime a framework-dependent build's analysis starts on: // major.minor, or a full version as `RuntimeFrameworkVersion` takes one. - runtimeVersion?: string | undefined | null + runtimeVersion: string +} + +export type ReachabilityField = keyof ReachabilityValues + +export const REACHABILITY_FIELDS_BY_TOOL = { + __proto__: null, + dotnet: ['build', 'runtimeVersion'], + gradle: ['build', 'javaHome'], + maven: ['build', 'javaHome'], + sbt: ['build', 'javaHome'], +} as const satisfies { __proto__: null } & Record< + BuildTool, + readonly ReachabilityField[] +> + +// A null field clears its inherited value. +export type ReachabilityDefaults = { + [F in (typeof REACHABILITY_FIELDS_BY_TOOL)[Tool][number]]?: + | ReachabilityValues[F] + | undefined + | null +} + +// The settings in effect for a build, which a reachability scan sends Coana. +export type ReachabilitySettings = { + [F in ReachabilityField]?: ReachabilityValues[F] | undefined } export interface SocketJson { @@ -97,7 +119,7 @@ export interface SocketJson { excludeConfigs?: string | undefined | null includeConfigs?: string | undefined | null ignoreUnresolved?: boolean | undefined - reachability?: DotnetReachabilityDefaults | undefined + reachability?: ReachabilityDefaults<'dotnet'> | undefined verbose?: boolean | undefined } gradle?: { @@ -116,7 +138,7 @@ export interface SocketJson { // JDK path; sets JAVA_HOME for this ecosystem's build tool. Supports // $VAR/${VAR} expansion against the CLI's own environment. javaHome?: string | undefined | null - reachability?: JvmReachabilityDefaults | undefined + reachability?: ReachabilityDefaults<'gradle'> | undefined verbose?: boolean | undefined } maven?: { @@ -132,7 +154,7 @@ export interface SocketJson { // $VAR/${VAR} expansion against the CLI's own environment. javaHome?: string | undefined | null mavenOpts?: string | undefined | null - reachability?: JvmReachabilityDefaults | undefined + reachability?: ReachabilityDefaults<'maven'> | undefined verbose?: boolean | undefined } sbt?: { @@ -151,7 +173,7 @@ export interface SocketJson { // $VAR/${VAR} expansion against the CLI's own environment. javaHome?: string | undefined | null outfile?: string | undefined | null - reachability?: JvmReachabilityDefaults | undefined + reachability?: ReachabilityDefaults<'sbt'> | undefined sbtOpts?: string | undefined | null stdout?: boolean | undefined verbose?: boolean | undefined @@ -212,16 +234,20 @@ export async function readOrDefaultSocketJsonUp( return getDefaultSocketJson() } -// A build tool's `reachability` merges field by field, as its section does. -export function mergeBuildToolDefaults( +// A build tool's section merges field by field, and so does each of its +// object-valued fields (`reachability`). +export function mergeBuildToolDefaults>( base: T | undefined, override: T, ): T { - const merged = { ...base, ...override } - if (isRecord(base?.reachability) && isRecord(override.reachability)) { - merged.reachability = { ...base.reachability, ...override.reachability } + const merged: Record = { ...base, ...override } + for (const { 0: key, 1: value } of Object.entries(override)) { + const inherited = base?.[key] + if (isRecord(inherited) && isRecord(value)) { + merged[key] = { ...inherited, ...value } + } } - return merged + return merged as T } // Merges `defaults.manifest.` per ecosystem: fields set in @@ -245,29 +271,15 @@ function mergeManifestDefaults( if (overrideManifest.conda) { mergedManifest.conda = { ...baseManifest?.conda, ...overrideManifest.conda } } - if (overrideManifest.dotnet) { - mergedManifest.dotnet = mergeBuildToolDefaults( - baseManifest?.dotnet, - overrideManifest.dotnet, - ) - } - if (overrideManifest.gradle) { - mergedManifest.gradle = mergeBuildToolDefaults( - baseManifest?.gradle, - overrideManifest.gradle, - ) - } - if (overrideManifest.maven) { - mergedManifest.maven = mergeBuildToolDefaults( - baseManifest?.maven, - overrideManifest.maven, - ) - } - if (overrideManifest.sbt) { - mergedManifest.sbt = mergeBuildToolDefaults( - baseManifest?.sbt, - overrideManifest.sbt, - ) + for (const tool of ['dotnet', 'gradle', 'maven', 'sbt'] as const) { + if (overrideManifest[tool]) { + Object.assign(mergedManifest, { + [tool]: mergeBuildToolDefaults( + baseManifest?.[tool], + overrideManifest[tool], + ), + }) + } } return { ...base, From 03a907d27d9b885553f3d658f1073796bd9fe651 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Fri, 27 Nov 2026 10:25:32 +0100 Subject: [PATCH 09/12] Share the reachability scan context and per-tool settings in tests --- .../generate-recursive-manifests.test.mts | 7 +-- .../manifest/generate_auto_manifest.test.mts | 44 +++++-------------- test/socket-facts-projects.mts | 16 ++++++- 3 files changed, 29 insertions(+), 38 deletions(-) diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index 2b7b94e6f..3383f64bc 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -27,6 +27,7 @@ import { import { buildRootPath } from './scripts/build-tool.mts' import { mavenProject, + reachabilityByTool, socketFactsProject, } from '../../../test/socket-facts-projects.mts' import { testPath } from '../../../test/utils.mts' @@ -139,11 +140,7 @@ function relOf(dir: string): string { } function sentReachability() { - return Object.fromEntries( - vi - .mocked(runManifestFacts) - .mock.calls.map(([opts]) => [opts.ecosystem, opts.reachability]), - ) + return reachabilityByTool(vi.mocked(runManifestFacts).mock.calls) } describe('generateRecursiveManifests', () => { diff --git a/src/commands/manifest/generate_auto_manifest.test.mts b/src/commands/manifest/generate_auto_manifest.test.mts index c3887c54f..7cb4bf463 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -38,12 +38,14 @@ 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 { reachabilityByTool } from '../../../test/socket-facts-projects.mts' import { logger } from '../../utils/logger.mts' import { readOrDefaultSocketJson, readSocketJsonChain, } from '../../utils/socket-json.mts' +import type { SocketFactsContext } from './run-manifest-facts.mts' import type { SocketJson } from '../../utils/socket-json.mts' // What both of auto-manifest's socket.json reads see: cwd's own file, and @@ -71,14 +73,16 @@ const baseDetected = { sbt: false, } +const REACHABILITY_SCAN: SocketFactsContext = { + workDir: { dir: '/w', entries: new Map(), purpose: 'reachability' }, +} + // The reachability settings a reachability scan of a Maven build at // /tmp/repo sends. async function mavenReachabilitySent(): Promise { vi.mocked(runManifestFacts).mockClear() await generateAutoManifest({ - context: { - workDir: { dir: '/w', entries: new Map(), purpose: 'reachability' }, - }, + context: REACHABILITY_SCAN, cwd: '/tmp/repo', detected: { ...baseDetected, maven: true, count: 1 }, outputKind: 'text', @@ -462,25 +466,14 @@ describe('generateAutoManifest — JVM facts', () => { maven: true, sbt: true, } - const workDir = { - dir: '/w', - entries: new Map(), - purpose: 'reachability' as const, - } await generateAutoManifest({ - context: { workDir }, + context: REACHABILITY_SCAN, cwd: '/tmp/repo', detected, outputKind: 'text', verbose: false, }) - expect( - Object.fromEntries( - vi - .mocked(runManifestFacts) - .mock.calls.map(([opts]) => [opts.ecosystem, opts.reachability]), - ), - ).toEqual({ + expect(reachabilityByTool(vi.mocked(runManifestFacts).mock.calls)).toEqual({ gradle: { build: 'compile' }, maven: { javaHome: '$MAVEN_JDK' }, sbt: { build: 'none' }, @@ -507,15 +500,8 @@ describe('generateAutoManifest — JVM facts', () => { manifest: { dotnet: { reachability: { javaHome: '/jdk' } } }, }, } as SocketJson) - const context = { - workDir: { - dir: '/w', - entries: new Map(), - purpose: 'reachability' as const, - }, - } await generateAutoManifest({ - context, + context: REACHABILITY_SCAN, cwd: '/tmp/repo', detected: { ...baseDetected, gradle: true, count: 1 }, outputKind: 'text', @@ -524,7 +510,7 @@ describe('generateAutoManifest — JVM facts', () => { vi.mocked(runManifestFacts).mockClear() await expect( generateAutoManifest({ - context, + context: REACHABILITY_SCAN, cwd: '/tmp/repo', detected: { ...baseDetected, dotnet: true, gradle: true, count: 2 }, outputKind: 'text', @@ -547,13 +533,7 @@ describe('generateAutoManifest — JVM facts', () => { await expect( generateAutoManifest({ - context: { - workDir: { - dir: '/w', - entries: new Map(), - purpose: 'reachability' as const, - }, - }, + context: REACHABILITY_SCAN, cwd: '/tmp/repo', detected: { ...baseDetected, gradle: true, count: 1 }, outputKind: 'text', diff --git a/test/socket-facts-projects.mts b/test/socket-facts-projects.mts index f516c0106..0462829ee 100644 --- a/test/socket-facts-projects.mts +++ b/test/socket-facts-projects.mts @@ -1,6 +1,10 @@ import path from 'node:path' -import type { SocketFactsProject } from '../src/commands/manifest/run-manifest-facts.mts' +import type { + SocketFactsProject, + SocketFactsRunOptions, +} from '../src/commands/manifest/run-manifest-facts.mts' +import type { ReachabilitySettings } from '../src/utils/socket-json.mts' // A project of the build at `buildRoot`, its build files relative to its own // directory. @@ -20,3 +24,13 @@ export function mavenProject( ): SocketFactsProject { return socketFactsProject(buildRoot, subprojectDir, [pomFile]) } + +// The reachability settings each tool's runs were sent, from the calls of a +// mocked `runManifestFacts`. +export function reachabilityByTool( + calls: ReadonlyArray, +): Record { + return Object.fromEntries( + calls.map(({ 0: opts }) => [opts.ecosystem, opts.reachability]), + ) +} From 5ce087038df7385d0f3938c264af04e1d293a6d0 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Fri, 27 Nov 2026 10:39:33 +0100 Subject: [PATCH 10/12] Check skips without resolving a skipped tool's bin resolveEcosystemConfig resolves the bin, which fails on a bad SOCKET_CLI_*_PATH override, so asking it whether a tool is skipped could fail a scan over a tool it skips. The skip checks call getSkipReason, which the config's skipReason comes from. --- .../manifest/generate-recursive-manifests.mts | 4 ++-- .../manifest/generate_auto_manifest.mts | 6 ++++-- .../manifest/generate_auto_manifest.test.mts | 21 +++++++++++++++++++ 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index 5853d9641..5973a7bab 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -96,7 +96,7 @@ export type EcosystemBuildConfig = { // root here, on top of its existing root-only ecosystem-wide meaning for // auto/gradle/etc. facts:false has no pom-mode equivalent here (facts-only), // so it skips too. -function getSkipReason( +export function getSkipReason( ecosystem: BuildTool, section: | { disabled?: boolean | undefined; facts?: boolean | undefined } @@ -773,7 +773,7 @@ export async function generateRecursiveManifests({ const settings = resolveSettings(tool, root) if ( readsReachabilitySettings(context) && - !resolveEcosystemConfig(tool, root.dir, settings.sockJson).skipReason + !getSkipReason(tool, settings.sockJson.defaults?.manifest?.[tool]) ) { settings.reachability() } diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index 30595039a..e75da68d9 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -4,6 +4,7 @@ import { convertDotnetToFacts } from './convert-dotnet-to-facts.mts' import { convertGradleToMaven } from './convert_gradle_to_maven.mts' import { convertSbtToMaven } from './convert_sbt_to_maven.mts' import { + getSkipReason, resolveEcosystemConfig, socketFactsRunOptions, } from './generate-recursive-manifests.mts' @@ -102,9 +103,10 @@ export async function generateAutoManifest({ resolveEcosystemConfig(tool, cwd, sockJson) // Read only by a reachability scan for the tools that generate facts, so - // checked only for those, and before any build runs. + // checked only for those, and before any build runs. Not `configOf`: it + // resolves the bin, which can fail for a tool the scan skips. const generatesFacts = (tool: BuildTool) => - detected[tool] && !configOf(tool).skipReason + detected[tool] && !getSkipReason(tool, sockJson.defaults?.manifest?.[tool]) const reachabilityChain = readsReachabilitySettings(context) ? readSocketJsonChain(cwd) : undefined diff --git a/src/commands/manifest/generate_auto_manifest.test.mts b/src/commands/manifest/generate_auto_manifest.test.mts index 7cb4bf463..02f0fda37 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -542,6 +542,27 @@ describe('generateAutoManifest — JVM facts', () => { ).resolves.toBeDefined() }) + it('does not resolve the bin of a tool the scan skips', async () => { + vi.stubEnv('SOCKET_CLI_MAVEN_PATH', '/no/such/mvn') + useSettings({ + defaults: { manifest: { maven: { disabled: true } } }, + } as SocketJson) + + try { + await expect( + generateAutoManifest({ + context: REACHABILITY_SCAN, + cwd: '/tmp/repo', + detected: { ...baseDetected, maven: true, count: 1 }, + outputKind: 'text', + verbose: false, + }), + ).resolves.toBeDefined() + } finally { + vi.unstubAllEnvs() + } + }) + it('sends the reachability settings a parent socket.json cascades to, unless cwd clears them', async () => { const parent = { dir: '/tmp', From 203de49a99ba659a28e22a317a133a613d7fea4d Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Fri, 27 Nov 2026 10:44:14 +0100 Subject: [PATCH 11/12] Check a chain's reachability settings in one place The resolver and cascadedReachability share one chain check, and the socket.json merge loops over BUILD_TOOLS, so a new build tool merges field by field too. --- src/commands/manifest/build-root-config.mts | 46 ++++++++++----------- src/utils/socket-json.mts | 3 +- 2 files changed, 25 insertions(+), 24 deletions(-) diff --git a/src/commands/manifest/build-root-config.mts b/src/commands/manifest/build-root-config.mts index 4c8cf578c..d56b54a3a 100644 --- a/src/commands/manifest/build-root-config.mts +++ b/src/commands/manifest/build-root-config.mts @@ -110,17 +110,25 @@ function checkReachability( } } -// An invalid setting raises an InputError naming the file. -function checkSocketJsonReachability( +// An invalid setting raises an InputError naming the file. Checks each +// socket.json once per `checked`. +function checkChainReachability( tool: BuildTool, - { dir, sockJson }: SocketJsonInDir, + chain: readonly SocketJsonInDir[], + checked: Set = new Set(), ): void { - checkReachability( - tool, - sockJson.defaults?.manifest?.[tool]?.reachability, - `defaults.manifest.${tool}.reachability`, - socketJsonPath(dir), - ) + for (const { dir, sockJson } of chain) { + const key = `${tool}\0${dir}` + if (!checked.has(key)) { + checkReachability( + tool, + sockJson.defaults?.manifest?.[tool]?.reachability, + `defaults.manifest.${tool}.reachability`, + socketJsonPath(dir), + ) + checked.add(key) + } + } } // Gradle and sbt name a build by any build file of its directory. @@ -334,19 +342,13 @@ export function createBuildRootSettingsResolver( disabledBy = directorySkip ? sectionDisabledBy : entryDisabledBy } - let reachability: { settings: ReachabilitySettings | undefined } | undefined + let cached: { settings: ReachabilitySettings | undefined } | undefined return { disabledBy, entryKey, reachability: () => { - if (!reachability) { - for (const file of chain) { - const key = `${tool}\0${file.dir}` - if (!reachabilityChecked.has(key)) { - checkSocketJsonReachability(tool, file) - reachabilityChecked.add(key) - } - } + if (!cached) { + checkChainReachability(tool, chain, reachabilityChecked) if (entryKey && entry) { checkReachability( tool, @@ -355,13 +357,13 @@ export function createBuildRootSettingsResolver( socketJsonPath(root.dir), ) } - reachability = { + cached = { settings: settingsInEffect( parseReachability(tool, section['reachability']).settings, ), } } - return reachability.settings + return cached.settings }, sockJson: { ...merged, @@ -405,9 +407,7 @@ export function cascadedReachability( tool: BuildTool, chain: readonly SocketJsonInDir[], ): ReachabilitySettings | undefined { - for (const file of chain) { - checkSocketJsonReachability(tool, file) - } + checkChainReachability(tool, chain) return settingsInEffect( parseReachability( tool, diff --git a/src/utils/socket-json.mts b/src/utils/socket-json.mts index decf9cb16..6e46345fd 100644 --- a/src/utils/socket-json.mts +++ b/src/utils/socket-json.mts @@ -26,6 +26,7 @@ import { formatErrorWithDetail } from './errors.mts' import { findUp } from './fs.mts' import { logger } from './logger.mts' import { isRecord } from './objects.mts' +import { BUILD_TOOLS } from '../commands/manifest/scripts/build-tool.mts' import { SOCKET_JSON, SOCKET_WEBSITE_URL } from '../constants.mts' import type { BuildTool } from '../commands/manifest/scripts/build-tool.mts' @@ -271,7 +272,7 @@ function mergeManifestDefaults( if (overrideManifest.conda) { mergedManifest.conda = { ...baseManifest?.conda, ...overrideManifest.conda } } - for (const tool of ['dotnet', 'gradle', 'maven', 'sbt'] as const) { + for (const tool of BUILD_TOOLS) { if (overrideManifest[tool]) { Object.assign(mergedManifest, { [tool]: mergeBuildToolDefaults( From 070172b9e74c51a5a18ef50a49f2a9038307bcfa Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Fri, 27 Nov 2026 10:54:46 +0100 Subject: [PATCH 12/12] Apply the reachability settings to dynamic SBOM inference only --auto-manifest no longer reads or sends them. The dynamic SBOM inference walk puts a build's settings on its EcosystemBuildConfig on a reachability scan, so they reach Coana by the one route every other build option takes. --- CHANGELOG.md | 2 +- src/commands/manifest/build-root-config.mts | 17 +- .../manifest/build-root-config.test.mts | 21 -- .../manifest/convert-dotnet-to-facts.mts | 4 - .../manifest/generate-recursive-manifests.mts | 50 +++-- .../generate-recursive-manifests.test.mts | 7 +- .../manifest/generate_auto_manifest.mts | 32 +-- .../manifest/generate_auto_manifest.test.mts | 198 ++---------------- test/socket-facts-projects.mts | 16 +- 9 files changed, 48 insertions(+), 299 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bb944df0..e2a321023 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added - Socket facts for a self-contained .NET build include its runtime packs. -- Tune reachability per build tool in `socket.json`: `reachability.build` compiles the project before the analysis, `reachability.javaHome` (Maven, Gradle, sbt) sets the JDK the analysis assumes, and `reachability.runtimeVersion` (.NET) sets the runtime it starts on. +- Tune reachability per build tool in `socket.json` for `--dynamic-sbom-inference` scans: `reachability.build` compiles the project before the analysis, `reachability.javaHome` (Maven, Gradle, sbt) sets the JDK the analysis assumes, and `reachability.runtimeVersion` (.NET) sets the runtime it starts on. ### Changed - Updated the Coana CLI to v `15.15.4`. diff --git a/src/commands/manifest/build-root-config.mts b/src/commands/manifest/build-root-config.mts index d56b54a3a..fb7a84257 100644 --- a/src/commands/manifest/build-root-config.mts +++ b/src/commands/manifest/build-root-config.mts @@ -115,7 +115,7 @@ function checkReachability( function checkChainReachability( tool: BuildTool, chain: readonly SocketJsonInDir[], - checked: Set = new Set(), + checked: Set, ): void { for (const { dir, sockJson } of chain) { const key = `${tool}\0${dir}` @@ -400,18 +400,3 @@ export function displayPath(file: string): string { export function socketJsonPath(dir: string): string { return displayPath(path.join(dir, SOCKET_JSON)) } - -// The `reachability` settings of `tool` that `chain` cascades to, checked in -// every socket.json that sets them. -export function cascadedReachability( - tool: BuildTool, - chain: readonly SocketJsonInDir[], -): ReachabilitySettings | undefined { - checkChainReachability(tool, chain) - return settingsInEffect( - parseReachability( - tool, - mergeSocketJsonChain(chain).defaults?.manifest?.[tool]?.reachability, - ).settings, - ) -} diff --git a/src/commands/manifest/build-root-config.test.mts b/src/commands/manifest/build-root-config.test.mts index d70c783b4..4a6f2fb6c 100644 --- a/src/commands/manifest/build-root-config.test.mts +++ b/src/commands/manifest/build-root-config.test.mts @@ -5,7 +5,6 @@ import path from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { - cascadedReachability, createBuildRootSettingsResolver, describeDisabledBy, displayPath, @@ -418,23 +417,3 @@ describe('createBuildRootSettingsResolver', () => { }) }) }) - -describe('cascadedReachability', () => { - it("checks each socket.json's section for the tool alone", () => { - const sockJson = { - defaults: { - manifest: { - dotnet: { reachability: { runtimeVersion: 'latest' } }, - gradle: { reachability: { build: 'compile' } }, - }, - }, - } as any - - expect(cascadedReachability('gradle', [{ dir: '/r', sockJson }])).toEqual({ - build: 'compile', - }) - expect(() => - cascadedReachability('dotnet', [{ dir: '/r', sockJson }]), - ).toThrow(InputError) - }) -}) diff --git a/src/commands/manifest/convert-dotnet-to-facts.mts b/src/commands/manifest/convert-dotnet-to-facts.mts index 7b1fae10c..57cc73374 100644 --- a/src/commands/manifest/convert-dotnet-to-facts.mts +++ b/src/commands/manifest/convert-dotnet-to-facts.mts @@ -10,7 +10,6 @@ import type { RunManifestFactsOutcome, SocketFactsContext, } from './run-manifest-facts.mts' -import type { ReachabilitySettings } from '../../utils/socket-json.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 @@ -22,7 +21,6 @@ export async function convertDotnetToFacts({ entryFile, excludePaths, hints, - reachability, }: { config: EcosystemBuildConfig context?: SocketFactsContext | undefined @@ -31,7 +29,6 @@ export async function convertDotnetToFacts({ entryFile?: string | undefined excludePaths?: string[] | undefined hints?: BuildOptionHints | undefined - reachability?: ReachabilitySettings | undefined }): Promise { const entries = entryFile ? [entryFile] : findDotnetEntries(cwd) if (!entries.length) { @@ -54,7 +51,6 @@ export async function convertDotnetToFacts({ ecosystem: 'dotnet', excludePaths, hints, - reachability, root: { dir, entryFile: entry }, }) if (outcome === 'covered') { diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index 5973a7bab..a39020928 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -87,6 +87,8 @@ export type EcosystemBuildConfig = { ignoreUnresolved: boolean includeConfigs: string javaHome: string | undefined + // Set only by the dynamic SBOM inference walk, on a reachability scan. + reachability?: ReachabilitySettings | undefined // Set when this build root should be skipped entirely (never invoked). skipReason: string | undefined verbose: boolean @@ -96,7 +98,7 @@ export type EcosystemBuildConfig = { // root here, on top of its existing root-only ecosystem-wide meaning for // auto/gradle/etc. facts:false has no pom-mode equivalent here (facts-only), // so it skips too. -export function getSkipReason( +function getSkipReason( ecosystem: BuildTool, section: | { disabled?: boolean | undefined; facts?: boolean | undefined } @@ -114,6 +116,18 @@ export function getSkipReason( return undefined } +// What a build reads: its settings on a reachability scan, unless skipped. +function reachabilityOf( + context: SocketFactsContext, + tool: BuildTool, + settings: ResolvedBuildRootSettings, +): ReachabilitySettings | undefined { + return readsReachabilitySettings(context) && + !getSkipReason(tool, settings.sockJson.defaults?.manifest?.[tool]) + ? settings.reachability() + : undefined +} + type Candidate = { index: number // A build of its own (see hasRootMarker): covered only by the builds that @@ -178,13 +192,11 @@ export function socketFactsRunOptions( excludeBase, excludePaths, hints, - reachability, }: { context?: SocketFactsContext | undefined excludeBase: string | undefined excludePaths: string[] | undefined hints?: BuildOptionHints | undefined - reachability?: ReachabilitySettings | undefined }, ): SocketFactsRunOptions { return { @@ -201,7 +213,7 @@ export function socketFactsRunOptions( ignoreUnresolved: config.ignoreUnresolved, includeConfigs: config.includeConfigs, javaHome: config.javaHome, - reachability, + reachability: config.reachability, verbose: config.verbose, } } @@ -262,12 +274,13 @@ async function walkTool( ctx.resolveSettings(ecosystem, root) const configs = new Map() const configFor = (candidate: Candidate): EcosystemBuildConfig => { - const { entryKey, sockJson } = resolvedFor(candidate) + const resolved = resolvedFor(candidate) const { dir } = candidate.root // Builds sharing a directory and its settings resolve them once. - return getOrInsert(configs, `${dir}\0${entryKey ?? ''}`, () => - resolveEcosystemConfig(ecosystem, dir, sockJson), - ) + return getOrInsert(configs, `${dir}\0${resolved.entryKey ?? ''}`, () => ({ + ...resolveEcosystemConfig(ecosystem, dir, resolved.sockJson), + reachability: reachabilityOf(ctx.context, ecosystem, resolved), + })) } // 'load' when the build's own entry skips it, 'skip' when a directory @@ -663,16 +676,9 @@ async function runCandidate( candidate: Candidate, options: SocketFactsRunOptions, ): Promise { - const reachability = readsReachabilitySettings(ctx.context) - ? ctx.resolveSettings(options.ecosystem, candidate.root).reachability() - : undefined // A run a later build turns out to cover is dropped before its facts are // placed. - const result = await runManifestFacts({ - ...options, - reachability, - staged: true, - }) + const result = await runManifestFacts({ ...options, staged: true }) if (result === null) { return undefined } @@ -696,7 +702,6 @@ export async function buildUncoveredRoot({ excludeBase, excludePaths, hints, - reachability, root, }: { config: EcosystemBuildConfig @@ -708,7 +713,6 @@ export async function buildUncoveredRoot({ excludeBase?: string | undefined excludePaths?: string[] | undefined hints?: BuildOptionHints | undefined - reachability?: ReachabilitySettings | undefined root: BuildRoot }): Promise { const options: SocketFactsRunOptions = { @@ -723,7 +727,7 @@ export async function buildUncoveredRoot({ if (await isRootCovered(covered, ecosystem, root, options)) { return 'covered' } - const result = await runManifestFacts({ ...options, reachability }) + const result = await runManifestFacts(options) if (result) { addMembership(covered, await membershipOf(result.projects)) } @@ -770,13 +774,7 @@ export async function generateRecursiveManifests({ // Invalid settings fail the scan before any build runs. for (const { 0: tool, 1: roots } of candidatesByTool) { for (const root of roots) { - const settings = resolveSettings(tool, root) - if ( - readsReachabilitySettings(context) && - !getSkipReason(tool, settings.sockJson.defaults?.manifest?.[tool]) - ) { - settings.reachability() - } + reachabilityOf(context, tool, resolveSettings(tool, root)) } } // A failure another build excuses leaves the exit code it set. diff --git a/src/commands/manifest/generate-recursive-manifests.test.mts b/src/commands/manifest/generate-recursive-manifests.test.mts index 3383f64bc..407c38dab 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -27,7 +27,6 @@ import { import { buildRootPath } from './scripts/build-tool.mts' import { mavenProject, - reachabilityByTool, socketFactsProject, } from '../../../test/socket-facts-projects.mts' import { testPath } from '../../../test/utils.mts' @@ -140,7 +139,11 @@ function relOf(dir: string): string { } function sentReachability() { - return reachabilityByTool(vi.mocked(runManifestFacts).mock.calls) + return Object.fromEntries( + vi + .mocked(runManifestFacts) + .mock.calls.map(({ 0: opts }) => [opts.ecosystem, opts.reachability]), + ) } describe('generateRecursiveManifests', () => { diff --git a/src/commands/manifest/generate_auto_manifest.mts b/src/commands/manifest/generate_auto_manifest.mts index e75da68d9..5367b04c3 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -1,19 +1,13 @@ import { extractBazelToMaven } from './bazel/extract_bazel_to_maven.mts' -import { cascadedReachability } from './build-root-config.mts' import { convertDotnetToFacts } from './convert-dotnet-to-facts.mts' import { convertGradleToMaven } from './convert_gradle_to_maven.mts' import { convertSbtToMaven } from './convert_sbt_to_maven.mts' import { - getSkipReason, resolveEcosystemConfig, socketFactsRunOptions, } from './generate-recursive-manifests.mts' import { handleManifestConda } from './handle-manifest-conda.mts' -import { - readsReachabilitySettings, - runManifestFacts, -} from './run-manifest-facts.mts' -import { BUILD_TOOLS } from './scripts/build-tool.mts' +import { runManifestFacts } from './run-manifest-facts.mts' import { ENVIRONMENT_YML, REQUIREMENTS_TXT, @@ -21,10 +15,7 @@ import { } from '../../constants.mts' import { InputError } from '../../utils/errors.mts' import { logger } from '../../utils/logger.mts' -import { - readOrDefaultSocketJson, - readSocketJsonChain, -} from '../../utils/socket-json.mts' +import { readOrDefaultSocketJson } from '../../utils/socket-json.mts' import type { GeneratableManifests } from './detect-manifest-actions.mts' import type { EcosystemBuildConfig } from './generate-recursive-manifests.mts' @@ -102,23 +93,6 @@ export async function generateAutoManifest({ const configOf = (tool: BuildTool) => resolveEcosystemConfig(tool, cwd, sockJson) - // Read only by a reachability scan for the tools that generate facts, so - // checked only for those, and before any build runs. Not `configOf`: it - // resolves the bin, which can fail for a tool the scan skips. - const generatesFacts = (tool: BuildTool) => - detected[tool] && !getSkipReason(tool, sockJson.defaults?.manifest?.[tool]) - const reachabilityChain = readsReachabilitySettings(context) - ? readSocketJsonChain(cwd) - : undefined - const reachabilityByTool = new Map( - reachabilityChain - ? BUILD_TOOLS.filter(generatesFacts).map(tool => [ - tool, - cascadedReachability(tool, reachabilityChain), - ]) - : [], - ) - const generateFacts = async ( tool: BuildTool, config: EcosystemBuildConfig, @@ -129,7 +103,6 @@ export async function generateAutoManifest({ excludeBase: cwd, excludePaths, hints, - reachability: reachabilityByTool.get(tool), }), ) abortFactsRunIfFailed(tool, outcome) @@ -197,7 +170,6 @@ export async function generateAutoManifest({ cwd, excludePaths, hints, - reachability: reachabilityByTool.get('dotnet'), }) abortFactsRunIfFailed('dotnet', outcome) } diff --git a/src/commands/manifest/generate_auto_manifest.test.mts b/src/commands/manifest/generate_auto_manifest.test.mts index 02f0fda37..78257258d 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -29,7 +29,6 @@ vi.mock('./handle-manifest-conda.mts', () => ({ vi.mock('../../utils/socket-json.mts', async importOriginal => ({ ...(await importOriginal()), readOrDefaultSocketJson: vi.fn(() => ({})), - readSocketJsonChain: vi.fn(() => []), })) import { extractBazelToMaven } from './bazel/extract_bazel_to_maven.mts' @@ -38,29 +37,11 @@ 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 { reachabilityByTool } from '../../../test/socket-facts-projects.mts' import { logger } from '../../utils/logger.mts' -import { - readOrDefaultSocketJson, - readSocketJsonChain, -} from '../../utils/socket-json.mts' +import { readOrDefaultSocketJson } from '../../utils/socket-json.mts' -import type { SocketFactsContext } from './run-manifest-facts.mts' import type { SocketJson } from '../../utils/socket-json.mts' -// What both of auto-manifest's socket.json reads see: cwd's own file, and -// the chain of `parents` down to it. -function useSettings( - sockJson: SocketJson, - parents: Array<{ dir: string; sockJson: SocketJson }> = [], -): void { - vi.mocked(readOrDefaultSocketJson).mockReturnValue(sockJson) - vi.mocked(readSocketJsonChain).mockReturnValue([ - ...parents, - { dir: '/tmp/repo', sockJson }, - ]) -} - const baseDetected = { bazel: false, cdxgen: false, @@ -73,24 +54,6 @@ const baseDetected = { sbt: false, } -const REACHABILITY_SCAN: SocketFactsContext = { - workDir: { dir: '/w', entries: new Map(), purpose: 'reachability' }, -} - -// The reachability settings a reachability scan of a Maven build at -// /tmp/repo sends. -async function mavenReachabilitySent(): Promise { - vi.mocked(runManifestFacts).mockClear() - await generateAutoManifest({ - context: REACHABILITY_SCAN, - cwd: '/tmp/repo', - detected: { ...baseDetected, maven: true, count: 1 }, - outputKind: 'text', - verbose: false, - }) - return vi.mocked(runManifestFacts).mock.calls[0]?.[0].reachability -} - describe('generateAutoManifest — bazel branch', () => { beforeEach(() => { vi.mocked(extractBazelToMaven).mockClear() @@ -371,7 +334,7 @@ function callFor(ecosystem: string) { describe('generateAutoManifest — JVM facts', () => { beforeEach(() => { vi.mocked(runManifestFacts).mockReset() - useSettings({} as SocketJson) + vi.mocked(readOrDefaultSocketJson).mockReturnValue({} as SocketJson) }) it('runs Maven where the scan starts, leaving it to find its POM', async () => { @@ -448,164 +411,31 @@ describe('generateAutoManifest — JVM facts', () => { }, ) - it("sends each tool's reachability settings on a reachability scan only", async () => { - useSettings({ + it('neither sends nor checks the reachability settings, which only dynamic SBOM inference reads', async () => { + vi.mocked(readOrDefaultSocketJson).mockReturnValue({ defaults: { manifest: { - dotnet: { reachability: { runtimeVersion: '8.0' } }, - gradle: { reachability: { build: 'compile' } }, - maven: { bin: 'mvn', reachability: { javaHome: '$MAVEN_JDK' } }, - sbt: { reachability: { build: 'none', javaHome: null } }, + dotnet: { reachability: { runtimeVersion: 'latest' } }, + maven: { reachability: { build: 'compile' } }, }, }, } as SocketJson) - const detected = { - ...baseDetected, - dotnet: true, - gradle: true, - maven: true, - sbt: true, - } - await generateAutoManifest({ - context: REACHABILITY_SCAN, - cwd: '/tmp/repo', - detected, - outputKind: 'text', - verbose: false, - }) - expect(reachabilityByTool(vi.mocked(runManifestFacts).mock.calls)).toEqual({ - gradle: { build: 'compile' }, - maven: { javaHome: '$MAVEN_JDK' }, - sbt: { build: 'none' }, - }) - expect(vi.mocked(convertDotnetToFacts).mock.calls[0]?.[0]).toMatchObject({ - reachability: { runtimeVersion: '8.0' }, - }) + vi.mocked(convertDotnetToFacts).mockClear() - vi.mocked(runManifestFacts).mockClear() await generateAutoManifest({ - cwd: '/tmp/repo', - detected, - outputKind: 'text', - verbose: false, - }) - expect( - vi.mocked(runManifestFacts).mock.calls.map(([opts]) => opts.reachability), - ).toEqual([undefined, undefined, undefined]) - }) - - it("fails a reachability scan on an invalid setting of a detected tool, before any build, not of another's", async () => { - useSettings({ - defaults: { - manifest: { dotnet: { reachability: { javaHome: '/jdk' } } }, + context: { + workDir: { dir: '/w', entries: new Map(), purpose: 'reachability' }, }, - } as SocketJson) - await generateAutoManifest({ - context: REACHABILITY_SCAN, cwd: '/tmp/repo', - detected: { ...baseDetected, gradle: true, count: 1 }, + detected: { ...baseDetected, dotnet: true, maven: true, count: 2 }, outputKind: 'text', verbose: false, }) - vi.mocked(runManifestFacts).mockClear() - await expect( - generateAutoManifest({ - context: REACHABILITY_SCAN, - cwd: '/tmp/repo', - detected: { ...baseDetected, dotnet: true, gradle: true, count: 2 }, - outputKind: 'text', - verbose: false, - }), - ).rejects.toThrow( - /dotnet\.reachability\.javaHome` in .* is not a reachability setting of dotnet builds/, - ) - expect(runManifestFacts).not.toHaveBeenCalled() - }) - it('does not check the settings of a tool that generates pom files', async () => { - useSettings({ - defaults: { - manifest: { - gradle: { facts: false, reachability: { runtimeVersion: '8.0' } }, - }, - }, - } as SocketJson) - - await expect( - generateAutoManifest({ - context: REACHABILITY_SCAN, - cwd: '/tmp/repo', - detected: { ...baseDetected, gradle: true, count: 1 }, - outputKind: 'text', - verbose: false, - }), - ).resolves.toBeDefined() - }) - - it('does not resolve the bin of a tool the scan skips', async () => { - vi.stubEnv('SOCKET_CLI_MAVEN_PATH', '/no/such/mvn') - useSettings({ - defaults: { manifest: { maven: { disabled: true } } }, - } as SocketJson) - - try { - await expect( - generateAutoManifest({ - context: REACHABILITY_SCAN, - cwd: '/tmp/repo', - detected: { ...baseDetected, maven: true, count: 1 }, - outputKind: 'text', - verbose: false, - }), - ).resolves.toBeDefined() - } finally { - vi.unstubAllEnvs() - } - }) - - it('sends the reachability settings a parent socket.json cascades to, unless cwd clears them', async () => { - const parent = { - dir: '/tmp', - sockJson: { - defaults: { - manifest: { - maven: { reachability: { build: 'compile', javaHome: '/jdk-17' } }, - }, - }, - } as SocketJson, - } - - useSettings({} as SocketJson, [parent]) - expect(await mavenReachabilitySent()).toEqual({ - build: 'compile', - javaHome: '/jdk-17', - }) - - useSettings( - { - defaults: { manifest: { maven: { reachability: { javaHome: null } } } }, - } as SocketJson, - [parent], - ) - expect(await mavenReachabilitySent()).toEqual({ build: 'compile' }) - }) - - it('fails a reachability scan on an invalid setting a parent socket.json cascades to', async () => { - useSettings({} as SocketJson, [ - { - dir: '/tmp', - sockJson: { - defaults: { - manifest: { maven: { reachability: { build: 'always' } } }, - }, - } as SocketJson, - }, - ]) - - await expect(mavenReachabilitySent()).rejects.toThrow( - /maven\.reachability\.build` in .*tmp.socket\.json is "always"/, - ) - expect(runManifestFacts).not.toHaveBeenCalled() + expect(callFor('maven')?.reachability).toBeUndefined() + expect( + vi.mocked(convertDotnetToFacts).mock.calls[0]?.[0].config, + ).not.toHaveProperty('reachability') }) }) diff --git a/test/socket-facts-projects.mts b/test/socket-facts-projects.mts index 0462829ee..f516c0106 100644 --- a/test/socket-facts-projects.mts +++ b/test/socket-facts-projects.mts @@ -1,10 +1,6 @@ import path from 'node:path' -import type { - SocketFactsProject, - SocketFactsRunOptions, -} from '../src/commands/manifest/run-manifest-facts.mts' -import type { ReachabilitySettings } from '../src/utils/socket-json.mts' +import type { SocketFactsProject } from '../src/commands/manifest/run-manifest-facts.mts' // A project of the build at `buildRoot`, its build files relative to its own // directory. @@ -24,13 +20,3 @@ export function mavenProject( ): SocketFactsProject { return socketFactsProject(buildRoot, subprojectDir, [pomFile]) } - -// The reachability settings each tool's runs were sent, from the calls of a -// mocked `runManifestFacts`. -export function reachabilityByTool( - calls: ReadonlyArray, -): Record { - return Object.fromEntries( - calls.map(({ 0: opts }) => [opts.ecosystem, opts.reachability]), - ) -}