From 9f5b244ab1903074b48faa82e66a57ef7a60b64c Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 15:40:51 +0100 Subject: [PATCH 1/6] 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 | 43 +++- .../generate-recursive-manifests.test.mts | 151 ++++++++++++++ .../manifest/generate_auto_manifest.mts | 19 +- .../manifest/generate_auto_manifest.test.mts | 109 +++++++++- 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, 803 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 97a0ba578..6309ae460 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 d492b685a..fd5d9313a 100644 --- a/src/commands/manifest/build-root-config.mts +++ b/src/commands/manifest/build-root-config.mts @@ -4,16 +4,20 @@ import path from 'node:path' import { buildRootPath, isBuildFile } from './discover-manifest-roots.mts' import { BUILD_FILES, BUILD_TOOLS } 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, @@ -33,10 +37,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 => { @@ -62,6 +133,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) { @@ -176,9 +268,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 } } @@ -194,6 +288,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: { @@ -226,6 +334,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 654bd8e97..c4dd878c1 100644 --- a/src/commands/manifest/convert-dotnet-to-facts.mts +++ b/src/commands/manifest/convert-dotnet-to-facts.mts @@ -9,6 +9,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' @@ -23,6 +24,7 @@ export async function convertDotnetToFacts({ entryFile, excludePaths, hints, + reachability, }: { config: EcosystemBuildConfig context?: SocketFactsContext | undefined @@ -31,6 +33,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) { @@ -53,6 +56,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 fbf17ea1d..83d48bddc 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -48,6 +48,7 @@ import type { LoadedBuild } from './load-build.mts' import type { BuildOption, BuildOptionHints, + ReachabilitySettings, RunManifestFactsOutcome, RunManifestFactsResult, SocketFactsContext, @@ -95,15 +96,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 @@ -210,11 +216,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 { @@ -231,6 +239,7 @@ export function socketFactsRunOptions( ignoreUnresolved: config.ignoreUnresolved, includeConfigs: config.includeConfigs, javaHome: config.javaHome, + reachability, verbose: config.verbose, } } @@ -708,6 +717,11 @@ async function runCandidate( dirConfig: EcosystemBuildConfig, ): Promise { const options = runOptions(ctx, ecosystem, candidate, dirConfig) + if (ctx.context.workDir.withFiles) { + options.reachability = ctx + .resolveSettings(ecosystem, candidate.root) + .reachability() + } const result = await runManifestFacts(options) if (result === null) { return undefined @@ -732,6 +746,7 @@ export async function buildUncoveredRoot({ excludeBase, excludePaths, hints, + reachability, root, }: { config: EcosystemBuildConfig @@ -743,6 +758,7 @@ export async function buildUncoveredRoot({ excludeBase?: string | undefined excludePaths?: string[] | undefined hints?: BuildOptionHints | undefined + reachability?: ReachabilitySettings | undefined root: BuildRoot }): Promise { if ( @@ -761,6 +777,7 @@ export async function buildUncoveredRoot({ excludeBase, excludePaths, hints, + reachability, }), cwd: cwd ?? root.dir, }) @@ -811,7 +828,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. @@ -868,7 +891,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), } } @@ -882,7 +905,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), } } @@ -896,7 +919,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), } } @@ -909,7 +932,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 52c39e628..45eeaa44a 100644 --- a/src/commands/manifest/generate-recursive-manifests.test.mts +++ b/src/commands/manifest/generate-recursive-manifests.test.mts @@ -165,6 +165,14 @@ function mavenProject(subprojectDir: string) { } } +function sentReachability() { + return Object.fromEntries( + vi + .mocked(runManifestFacts) + .mock.calls.map(([opts]) => [opts.ecosystem, opts.reachability]), + ) +} + describe('generateRecursiveManifests', () => { beforeEach(() => { vi.mocked(runManifestFacts).mockReset() @@ -885,6 +893,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 73c71be81..318a8c4b6 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -1,10 +1,12 @@ import path from 'node:path' 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' @@ -15,7 +17,7 @@ import { keepFacts, runManifestFacts, } from './run-manifest-facts.mts' -import { resolveBuildToolBin } from './scripts/build-tool.mts' +import { BUILD_TOOLS, resolveBuildToolBin } from './scripts/build-tool.mts' import { ENVIRONMENT_YML, REQUIREMENTS_TXT, @@ -106,6 +108,19 @@ export async function generateAutoManifest({ logger.info(`Using this ${SOCKET_JSON} for defaults:`, 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, root: BuildRoot, @@ -117,6 +132,7 @@ export async function generateAutoManifest({ excludeBase: cwd, excludePaths, hints, + reachability: reachabilityByTool.get(tool), }), ) if (outcome) { @@ -205,6 +221,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 74c9c76e3..2f6811286 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -30,7 +30,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(() => ({})), })) @@ -414,6 +415,112 @@ describe('generateAutoManifest — JVM facts', () => { }, ) + 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() + }) + it('places the facts of each build it generates, with its sidecar entry', async () => { const cwd = await fs.realpath( await fs.mkdtemp(path.join(tmpdir(), 'auto-manifest-keep-')), diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 32acbeedc..cbb934bad 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' @@ -81,6 +82,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 } @@ -108,6 +117,7 @@ type SocketFactsRequest = { ignoreUnresolved: boolean includeConfigs?: string | undefined javaHome?: string | undefined + reachability?: ReachabilitySettings | undefined verbose: boolean } excludeBase: string @@ -208,6 +218,7 @@ export type SocketFactsRequestOptions = { includeConfigs?: string | undefined // As written: Coana expands `$VAR` references itself. javaHome?: string | undefined + reachability?: ReachabilitySettings | undefined verbose?: boolean | undefined } @@ -231,6 +242,7 @@ function toSocketFactsRequest({ ignoreUnresolved = false, includeConfigs, javaHome, + reachability, verbose = false, }: SocketFactsRequestOptions): CResult { let resolvedBin: string @@ -259,6 +271,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 ff1dff73c..c6f8f6b62 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 fc51c687acbeb85c0c6152a2bc952681f89f3919 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 24 Nov 2026 14:27:53 +0100 Subject: [PATCH 2/6] Read the reachability settings for a reachability resolution --- .../manifest/generate-recursive-manifests.mts | 4 ++-- .../manifest/generate_auto_manifest.mts | 2 +- .../manifest/generate_auto_manifest.test.mts | 18 +++++++++++++++--- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/commands/manifest/generate-recursive-manifests.mts b/src/commands/manifest/generate-recursive-manifests.mts index 83d48bddc..5a339d453 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -717,7 +717,7 @@ async function runCandidate( dirConfig: EcosystemBuildConfig, ): Promise { const options = runOptions(ctx, ecosystem, candidate, dirConfig) - if (ctx.context.workDir.withFiles) { + if (ctx.context.workDir.purpose === 'reachability') { options.reachability = ctx .resolveSettings(ecosystem, candidate.root) .reachability() @@ -830,7 +830,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 318a8c4b6..1095470ea 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -113,7 +113,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 2f6811286..a7ee4818e 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -433,7 +433,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', @@ -475,7 +479,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, @@ -511,7 +519,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 f59a12c323752fa0362287984d71a1620928dff6 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 13:41:38 +0100 Subject: [PATCH 3/6] 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 5a339d453..99b3d7510 100644 --- a/src/commands/manifest/generate-recursive-manifests.mts +++ b/src/commands/manifest/generate-recursive-manifests.mts @@ -96,7 +96,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 7791dfec0e18b0bf885d20c6ee9b5a4607e12bc6 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 13:41:51 +0100 Subject: [PATCH 4/6] 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 fd5d9313a..5908c044b 100644 --- a/src/commands/manifest/build-root-config.mts +++ b/src/commands/manifest/build-root-config.mts @@ -37,8 +37,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 @@ -334,8 +334,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 cbb934bad..471c0e80e 100644 --- a/src/commands/manifest/run-manifest-facts.mts +++ b/src/commands/manifest/run-manifest-facts.mts @@ -82,8 +82,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 a098b380d8f86cfab78094c73bd780aa007e97e9 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 13:42:01 +0100 Subject: [PATCH 5/6] 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 5908c044b..0fee09645 100644 --- a/src/commands/manifest/build-root-config.mts +++ b/src/commands/manifest/build-root-config.mts @@ -362,7 +362,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 80ca89d1d88af5eaf3400e4c8c8837771bd06b0c Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 14:07:21 +0100 Subject: [PATCH 6/6] 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 | 88 +++++++++++++++++-- 3 files changed, 117 insertions(+), 19 deletions(-) diff --git a/src/commands/manifest/build-root-config.mts b/src/commands/manifest/build-root-config.mts index 0fee09645..bfd685c25 100644 --- a/src/commands/manifest/build-root-config.mts +++ b/src/commands/manifest/build-root-config.mts @@ -289,17 +289,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: { @@ -362,6 +361,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 1095470ea..849314faf 100644 --- a/src/commands/manifest/generate_auto_manifest.mts +++ b/src/commands/manifest/generate_auto_manifest.mts @@ -1,7 +1,7 @@ import path from 'node:path' 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' @@ -25,7 +25,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 { BuildRoot } from './discover-manifest-roots.mts' @@ -112,11 +115,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 a7ee4818e..5182ca305 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -33,6 +33,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' @@ -42,10 +43,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, @@ -58,6 +75,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() @@ -338,7 +371,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 () => { @@ -416,7 +449,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' } }, @@ -473,7 +506,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' } } }, }, @@ -508,7 +541,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' } }, @@ -533,6 +566,51 @@ 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() + }) + it('places the facts of each build it generates, with its sidecar entry', async () => { const cwd = await fs.realpath( await fs.mkdtemp(path.join(tmpdir(), 'auto-manifest-keep-')),