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..bfd685c25 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 + // 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 } +// 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,19 @@ export function createBuildRootSettingsResolver( return { disabledBy, entryKey, + reachability: () => { + 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: { ...merged, defaults: { @@ -226,6 +333,54 @@ 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)) } + +// 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, + { 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..99b3d7510 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,19 @@ 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, - 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 +215,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 +238,7 @@ export function socketFactsRunOptions( ignoreUnresolved: config.ignoreUnresolved, includeConfigs: config.includeConfigs, javaHome: config.javaHome, + reachability, verbose: config.verbose, } } @@ -708,6 +716,11 @@ async function runCandidate( dirConfig: EcosystemBuildConfig, ): Promise { const options = runOptions(ctx, ecosystem, candidate, dirConfig) + if (ctx.context.workDir.purpose === 'reachability') { + options.reachability = ctx + .resolveSettings(ecosystem, candidate.root) + .reachability() + } const result = await runManifestFacts(options) if (result === null) { return undefined @@ -732,6 +745,7 @@ export async function buildUncoveredRoot({ excludeBase, excludePaths, hints, + reachability, root, }: { config: EcosystemBuildConfig @@ -743,6 +757,7 @@ export async function buildUncoveredRoot({ excludeBase?: string | undefined excludePaths?: string[] | undefined hints?: BuildOptionHints | undefined + reachability?: ReachabilitySettings | undefined root: BuildRoot }): Promise { if ( @@ -761,6 +776,7 @@ export async function buildUncoveredRoot({ excludeBase, excludePaths, hints, + reachability, }), cwd: cwd ?? root.dir, }) @@ -811,7 +827,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?.purpose === 'reachability' && + !getSkipReason(tool, settings.sockJson.defaults?.manifest?.[tool]) + ) { + settings.reachability() + } } } // A failure another build excuses leaves the exit code it set. @@ -868,7 +890,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 +904,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 +918,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 +931,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..849314faf 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 { 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' @@ -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, @@ -23,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' @@ -106,6 +111,23 @@ 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 reachabilityChain = + context?.workDir?.purpose === 'reachability' + ? readSocketJsonChain(cwd) + : undefined + const reachabilityByTool = new Map( + reachabilityChain + ? BUILD_TOOLS.filter(generatesFacts).map(tool => [ + tool, + cascadedReachability(tool, reachabilityChain), + ]) + : [], + ) + const generateFacts = async ( tool: BuildTool, root: BuildRoot, @@ -117,6 +139,7 @@ export async function generateAutoManifest({ excludeBase: cwd, excludePaths, hints, + reachability: reachabilityByTool.get(tool), }), ) if (outcome) { @@ -205,6 +228,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..5182ca305 100644 --- a/src/commands/manifest/generate_auto_manifest.test.mts +++ b/src/commands/manifest/generate_auto_manifest.test.mts @@ -30,8 +30,10 @@ 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(() => ({})), + readSocketJsonChain: vi.fn(() => []), })) import { extractBazelToMaven } from './bazel/extract_bazel_to_maven.mts' @@ -41,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, @@ -57,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() @@ -337,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 () => { @@ -414,6 +448,169 @@ describe('generateAutoManifest — JVM facts', () => { }, ) + it("sends each tool's reachability settings on a reachability scan only", async () => { + useSettings({ + 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(), + purpose: 'reachability' as const, + } + 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 () => { + useSettings({ + defaults: { + manifest: { dotnet: { reachability: { javaHome: '/jdk' } } }, + }, + } as SocketJson) + const context = { + workDir: { + dir: '/w', + entries: new Map(), + purpose: 'reachability' as const, + }, + } + 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 () => { + useSettings({ + defaults: { + manifest: { + gradle: { facts: false, reachability: { runtimeVersion: '8.0' } }, + }, + }, + } as SocketJson) + + await expect( + generateAutoManifest({ + context: { + workDir: { + dir: '/w', + entries: new Map(), + purpose: 'reachability' as const, + }, + }, + cwd: '/tmp/repo', + detected: { ...baseDetected, gradle: true, count: 1 }, + outputKind: 'text', + verbose: false, + }), + ).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-')), diff --git a/src/commands/manifest/run-manifest-facts.mts b/src/commands/manifest/run-manifest-facts.mts index 32acbeedc..471c0e80e 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,13 @@ 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 } @@ -108,6 +116,7 @@ type SocketFactsRequest = { ignoreUnresolved: boolean includeConfigs?: string | undefined javaHome?: string | undefined + reachability?: ReachabilitySettings | undefined verbose: boolean } excludeBase: string @@ -208,6 +217,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 +241,7 @@ function toSocketFactsRequest({ ignoreUnresolved = false, includeConfigs, javaHome, + reachability, verbose = false, }: SocketFactsRequestOptions): CResult { let resolvedBin: string @@ -259,6 +270,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..f74c2314f 100644 --- a/src/utils/socket-json.mts +++ b/src/utils/socket-json.mts @@ -25,10 +25,32 @@ 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 + +// Controls whether reachability analysis builds the project first. +// Defaults to "none". +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 + // 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 +97,7 @@ export interface SocketJson { excludeConfigs?: string | undefined | null includeConfigs?: string | undefined | null ignoreUnresolved?: boolean | undefined + reachability?: DotnetReachabilityDefaults | undefined verbose?: boolean | undefined } gradle?: { @@ -93,6 +116,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 +132,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 +151,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 +212,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 +246,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', + ) + }) })