From ef56f0e3a428087029a37e162745b562b665c6b3 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Tue, 17 Nov 2026 15:49:06 +0100 Subject: [PATCH 01/10] Ask for the reachability settings in the setup wizards `socket manifest setup` and `socket manifest setup --dynamic-sbom-inference` ask, for each build tool that generates facts: - whether to build the project before reachability analysis. A no writes "none" only to override an inherited "compile", and otherwise leaves the setting unset; - Maven, Gradle and sbt: whether to use a different JDK for the analysis, showing the one in effect, inherited or not; - .NET: whether to start a framework-dependent build's analysis on a given runtime, taking major.minor or major.minor.patch[-prerelease]. The wizards read socket.json as written, so they run under an invalid reachability value: they warn about what a build tool cannot take and replace it with the answers, and ignore an invalid inherited value for their defaults. --- CHANGELOG.md | 1 + .../manifest/setup-manifest-config.mts | 277 +++++++- .../manifest/setup-manifest-config.test.mts | 610 +++++++++++++++++- .../setup-recursive-manifest-config.mts | 54 +- .../setup-recursive-manifest-config.test.mts | 160 ++++- 5 files changed, 1080 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b3ae6fcec..c422236e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,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` for `--dynamic-sbom-inference` scans: `reachability.build` compiles the project before the analysis, `reachability.javaHome` (Maven, Gradle, sbt) sets the JDK the analysis assumes, and `reachability.runtimeVersion` (.NET) sets the runtime it starts on. +- `socket manifest setup --dynamic-sbom-inference` asks for the reachability settings, so there is no need to edit `socket.json` by hand. ### Changed - Updated the Coana CLI to v `15.15.5`. diff --git a/src/commands/manifest/setup-manifest-config.mts b/src/commands/manifest/setup-manifest-config.mts index 2aa513fdf..4f76f0e00 100644 --- a/src/commands/manifest/setup-manifest-config.mts +++ b/src/commands/manifest/setup-manifest-config.mts @@ -1,19 +1,41 @@ import fs from 'node:fs' import path from 'node:path' +import { isDeepStrictEqual } from 'node:util' +import { reachabilityProblem } from './build-root-config.mts' import { detectManifestActions } from './detect-manifest-actions.mts' import { REQUIREMENTS_TXT, SOCKET_JSON } from '../../constants.mts' import { debugDir } from '../../utils/debug.mts' import { logger } from '../../utils/logger.mts' +import { isRecord } from '../../utils/objects.mts' import { input, select } from '../../utils/prompts.mts' import { + mergeSocketJsonChain, + readSocketJsonChain, readSocketJsonSync, writeSocketJson, } from '../../utils/socket-json.mts' +import type { BuildTool } from './scripts/build-tool.mts' import type { CResult } from '../../types.mts' import type { ManifestDefaults } from '../../utils/socket-json.mts' +export type ReachabilityStepOptions = { + // What the project inherits from ancestor socket.json files, as written. + inheritedReachability?: unknown +} + +// As written, so that the wizard can replace an invalid value. +function inheritedReachabilityOf(cwd: string, tool: BuildTool): unknown { + const dir = path.resolve(cwd) + const parent = path.dirname(dir) + return parent === dir + ? undefined + : mergeSocketJsonChain(readSocketJsonChain(parent)).defaults?.manifest?.[ + tool + ]?.reachability +} + // Whether the prompt was canceled. A blank answer clears a value set before // with null rather than deleting the key, so it doesn't silently start // inheriting an ancestor's value again. @@ -192,28 +214,36 @@ export async function setupManifestConfig( if (!sockJson.defaults.manifest.dotnet) { sockJson.defaults.manifest.dotnet = {} } - result = await setupDotnet(sockJson.defaults.manifest.dotnet) + result = await setupDotnet(sockJson.defaults.manifest.dotnet, { + inheritedReachability: inheritedReachabilityOf(cwd, 'dotnet'), + }) break } case 'gradle': { if (!sockJson.defaults.manifest.gradle) { sockJson.defaults.manifest.gradle = {} } - result = await setupGradle(sockJson.defaults.manifest.gradle) + result = await setupGradle(sockJson.defaults.manifest.gradle, { + inheritedReachability: inheritedReachabilityOf(cwd, 'gradle'), + }) break } case 'maven': { if (!sockJson.defaults.manifest.maven) { sockJson.defaults.manifest.maven = {} } - result = await setupMaven(sockJson.defaults.manifest.maven) + result = await setupMaven(sockJson.defaults.manifest.maven, { + inheritedReachability: inheritedReachabilityOf(cwd, 'maven'), + }) break } case 'sbt': { if (!sockJson.defaults.manifest.sbt) { sockJson.defaults.manifest.sbt = {} } - result = await setupSbt(sockJson.defaults.manifest.sbt) + result = await setupSbt(sockJson.defaults.manifest.sbt, { + inheritedReachability: inheritedReachabilityOf(cwd, 'sbt'), + }) break } default: { @@ -314,6 +344,7 @@ async function setupConda( export async function setupDotnet( config: ManifestDefaults<'dotnet'>, + options: ReachabilityStepOptions = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'dotnet'))) { return canceledByUser() @@ -343,14 +374,17 @@ export async function setupDotnet( return canceledByUser() } - return notCanceled() + return await setupReachability('dotnet', config, options) } export async function setupGradle( config: ManifestDefaults<'gradle'>, // Set by the recursive dynamic-sbom-inference wizard, which has no // pom-mode equivalent - skips the facts/pom question entirely. - { factsOnly = false }: { factsOnly?: boolean } = {}, + { + factsOnly = false, + ...options + }: ReachabilityStepOptions & { factsOnly?: boolean } = {}, ): Promise> { if ( applyAnswer(config, 'bin', await askForBin(config.bin || '', './gradlew')) @@ -384,10 +418,11 @@ export async function setupGradle( return canceledByUser() } } + const generatesFacts = factsOnly || config.facts !== false // The config filters and --ignore-unresolved only apply to facts generation // (the default); skip them when pom generation (--pom) is selected. - if (factsOnly || config.facts !== false) { + if (generatesFacts) { const factsOptions = await setupFactsOptions(config) if (!factsOptions.ok || factsOptions.data.canceled) { return factsOptions @@ -398,11 +433,16 @@ export async function setupGradle( return canceledByUser() } + if (generatesFacts) { + return await setupReachability('gradle', config, options) + } + return notCanceled() } export async function setupMaven( config: ManifestDefaults<'maven'>, + options: ReachabilityStepOptions = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'mvn'))) { return canceledByUser() @@ -439,13 +479,16 @@ export async function setupMaven( return canceledByUser() } - return notCanceled() + return await setupReachability('maven', config, options) } export async function setupSbt( config: ManifestDefaults<'sbt'>, // See setupGradle's matching parameter for why. - { factsOnly = false }: { factsOnly?: boolean } = {}, + { + factsOnly = false, + ...options + }: ReachabilityStepOptions & { factsOnly?: boolean } = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'sbt'))) { return canceledByUser() @@ -477,11 +520,12 @@ export async function setupSbt( return canceledByUser() } } + const generatesFacts = factsOnly || config.facts !== false // Socket facts is the default. The pom output questions (stdout/outfile) // only apply when pom generation (--pom) is explicitly selected; otherwise // ask the facts-only options. - if (!factsOnly && config.facts === false) { + if (!generatesFacts) { const stdout = await askForStdout(config.stdout) if (stdout === undefined) { return canceledByUser() @@ -519,6 +563,10 @@ export async function setupSbt( return canceledByUser() } + if (generatesFacts) { + return await setupReachability('sbt', config, options) + } + return notCanceled() } @@ -624,16 +672,35 @@ async function askForBin( }) } -async function askForJavaHome(defaultName = ''): Promise { +async function askForJavaHome( + defaultName = '', + question = 'What JDK should this build tool use? Leave blank to use the JDK already on PATH/JAVA_HOME.', +): Promise { return await input({ message: - 'What JDK should this build tool use? Leave blank to use the JDK already on PATH/JAVA_HOME. Supports $VAR/${VAR}.' + + `${question} Supports $VAR/\${VAR}.` + (defaultName ? ' (Backspace to leave default)' : ''), default: defaultName, required: false, }) } +async function askForRuntimeVersion( + current: string, +): Promise { + return await input({ + message: + 'Which .NET runtime? major.minor, such as 8.0, starts on its latest installed patch; major.minor.patch[-prerelease], such as 8.0.11, on exactly that one.' + + (current ? ' (Backspace to leave default)' : ''), + default: current, + required: false, + validate: (value: string) => + !value || + !reachabilityProblem('dotnet', 'runtimeVersion', value) || + 'Enter major.minor, such as 8.0, or major.minor.patch[-prerelease], such as 8.0.11.', + }) +} + async function askForVerboseFlag( current: boolean | undefined, ): Promise { @@ -715,6 +782,192 @@ async function askForIgnoreUnresolvedFlag( }) } +// The fields of `value` that `tool`'s builds take, warning about the rest the +// answers replace; an inherited invalid value is its own socket.json's to fix. +function validReachability( + tool: BuildTool, + value: unknown, + inherited: unknown, +): Record { + if (value === undefined) { + return {} + } + if (!isRecord(value)) { + if (!isDeepStrictEqual(value, inherited)) { + logger.warn( + `Replacing \`reachability\` (${JSON.stringify(value)}), which is not an object.`, + ) + } + return {} + } + const inheritedFields = isRecord(inherited) ? inherited : {} + const valid: Record = {} + for (const { 0: field, 1: setting } of Object.entries(value)) { + if (reachabilityProblem(tool, field, setting)) { + if ( + !Object.hasOwn(inheritedFields, field) || + !isDeepStrictEqual(setting, inheritedFields[field]) + ) { + logger.warn( + `Replacing \`reachability.${field}\` (${JSON.stringify(setting)}), which ${tool} builds cannot take.`, + ) + } + } else { + valid[field] = setting + } + } + return valid +} + +// The value in effect: this socket.json's own, null included, else the +// inherited one. +function effectiveValue( + own: Record, + inherited: Record, + field: string, +): unknown { + return Object.hasOwn(own, field) ? own[field] : inherited[field] +} + +// A "no" to a value's question keeps the value in effect; "none" is written +// only to override an inherited "compile". +async function setupReachability( + tool: BuildTool, + config: { reachability?: unknown }, + { inheritedReachability }: ReachabilityStepOptions = {}, +): Promise> { + const reachability = validReachability( + tool, + config.reachability, + inheritedReachability, + ) + // Invalid inherited values are their own socket.json's to fix. + const inherited = Object.fromEntries( + Object.entries( + isRecord(inheritedReachability) ? inheritedReachability : {}, + ).filter( + ({ 0: field, 1: value }) => !reachabilityProblem(tool, field, value), + ), + ) + + const wantsBuild = await select({ + message: + 'Build project before reachability analysis? Note: A failed build fails the scan.', + choices: [ + { + name: 'no', + value: false, + description: 'Analyze the project without building it', + }, + { + name: 'yes', + value: true, + description: 'Compile the project before reachability analysis', + }, + ], + default: effectiveValue(reachability, inherited, 'build') === 'compile', + }) + if (wantsBuild === undefined || wantsBuild === null) { + return canceledByUser() + } + if (wantsBuild) { + reachability['build'] = 'compile' + } else if (inherited['build'] === 'compile') { + reachability['build'] = 'none' + } else { + delete reachability['build'] + } + + const value = + tool === 'dotnet' + ? await setupReachabilityValue( + reachability, + inherited, + 'runtimeVersion', + { + ask: askForRuntimeVersion, + change: + 'Start the reachability analysis of a framework-dependent .NET build on a given runtime?', + keep: 'as the .NET runtime', + set: 'Set the runtime the analysis starts on', + unset: + "Let the analysis take the runtime the build's dotnet rolls forward to", + }, + ) + : await setupReachabilityValue(reachability, inherited, 'javaHome', { + ask: current => + askForJavaHome( + current, + 'What JDK should reachability analysis use?', + ), + change: 'Use a different Java for reachability analysis?', + keep: 'as the JDK for reachability analysis', + set: 'Set the JDK reachability analysis uses', + unset: 'Leave the JDK for reachability analysis unset', + }) + if (!value.ok || value.data.canceled) { + return value + } + + if (Object.keys(reachability).length) { + config.reachability = reachability + } else { + delete config.reachability + } + return notCanceled() +} + +async function setupReachabilityValue( + reachability: Record, + inherited: Record, + field: 'javaHome' | 'runtimeVersion', + prompts: { + ask: (current: string) => Promise + change: string + keep: string + set: string + unset: string + }, +): Promise> { + const effective = effectiveValue(reachability, inherited, field) as + | string + | null + | undefined + const wantsValue = await select({ + message: prompts.change, + choices: [ + { + name: 'no', + value: false, + description: effective + ? `Keep ${effective} ${prompts.keep}${Object.hasOwn(reachability, field) ? '' : ', as a parent socket.json sets it'}` + : prompts.unset, + }, + { + name: 'yes', + value: true, + description: prompts.set, + }, + ], + default: !!effective, + }) + if (wantsValue === undefined || wantsValue === null) { + return canceledByUser() + } + if (!wantsValue) { + return notCanceled() + } + const answer = await prompts.ask(effective || '') + if (applyAnswer(reachability as Record, field, answer)) { + return canceledByUser() + } + // A blank answer must also clear an inherited value, not fall back to it. + if (answer === '' && inherited[field]) { + reachability[field] = null + } + return notCanceled() +} + // Prompts for the facts-only options every facts generator shares: the config // include/exclude filters and --ignore-unresolved. Mutates `config` in place. async function setupFactsOptions( diff --git a/src/commands/manifest/setup-manifest-config.test.mts b/src/commands/manifest/setup-manifest-config.test.mts index 997237ac7..f1b6d84b9 100644 --- a/src/commands/manifest/setup-manifest-config.test.mts +++ b/src/commands/manifest/setup-manifest-config.test.mts @@ -1,4 +1,8 @@ -import { describe, expect, it, vi } from 'vitest' +import { promises as fs } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' // Simulates a real prompt: pressing Enter with nothing typed returns // whatever `default` was shown - the same contract inquirer honors. This is @@ -12,10 +16,16 @@ vi.mock('../../utils/prompts.mts', () => ({ import { setupDotnet, setupGradle, + setupManifestConfig, setupMaven, setupSbt, } from './setup-manifest-config.mts' +import { logger } from '../../utils/logger.mts' import { input, select } from '../../utils/prompts.mts' +import { + getDefaultSocketJson, + writeSocketJson, +} from '../../utils/socket-json.mts' describe('setup wizards', () => { it.for([ @@ -89,6 +99,604 @@ describe('setupGradle/setupMaven/setupSbt', () => { }) }) +describe('reachability step', () => { + const REACHABILITY_QUESTION = + 'Use a different Java for reachability analysis?' + + // Answers the reachability question with `wantsJavaHome` and its JDK prompt + // with `javaHome`; every other prompt keeps its default. + function answerReachability(wantsJavaHome: boolean, javaHome = ''): void { + vi.mocked(select).mockImplementation(async ({ default: def, message }) => + message === REACHABILITY_QUESTION ? wantsJavaHome : (def ?? ''), + ) + vi.mocked(input).mockImplementation(async ({ default: def, message }) => + message.startsWith('What JDK should reachability analysis use?') + ? javaHome + : (def ?? ''), + ) + } + + afterEach(() => { + vi.mocked(input).mockReset() + vi.mocked(input).mockImplementation(async ({ default: def }) => def ?? '') + vi.mocked(select).mockReset() + vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') + }) + + it.for([ + ['gradle', setupGradle], + ['maven', setupMaven], + ['sbt', setupSbt], + ] as const)( + '%s writes the JDK named after a yes to reachability.javaHome', + async ({ 1: setup }) => { + answerReachability(true, '$JAVA17_HOME') + const config: Record = { javaHome: '/opt/jdk-11' } + + const result = await setup(config) + + expect(result).toEqual({ ok: true, data: { canceled: false } }) + expect(config).toEqual({ + javaHome: '/opt/jdk-11', + reachability: { javaHome: '$JAVA17_HOME' }, + }) + }, + ) + + it('writes nothing on a no and never asks for the JDK', async () => { + answerReachability(false, '/never-asked') + const config: Record = {} + + await setupMaven(config) + + expect(config).toEqual({}) + expect( + vi + .mocked(input) + .mock.calls.some(([{ message }]) => message.includes('reachability')), + ).toBe(false) + }) + + it('leaves a value it shows as is on a no, neither clearing nor restating it', async () => { + answerReachability(false) + const config: Record = { + reachability: { javaHome: '/opt/jdk-17' }, + } + + await setupMaven(config) + + expect(config['reachability']).toEqual({ javaHome: '/opt/jdk-17' }) + }) + + it.for([ + [ + { javaHome: '/opt/jdk-17' }, + {}, + 'Keep /opt/jdk-17 as the JDK for reachability analysis', + ], + [{}, {}, 'Leave the JDK for reachability analysis unset'], + [ + { javaHome: '/opt/jdk-17' }, + { javaHome: '/opt/jdk-17' }, + 'Keep /opt/jdk-17 as the JDK for reachability analysis', + ], + [ + {}, + { javaHome: '/opt/jdk-11' }, + 'Keep /opt/jdk-11 as the JDK for reachability analysis, as a parent socket.json sets it', + ], + [ + { javaHome: null }, + { javaHome: '/opt/jdk-11' }, + 'Leave the JDK for reachability analysis unset', + ], + ] as const)( + 'labels the no to the JDK %j, inheriting %j, by what it does', + async ({ 0: reachability, 1: inherited, 2: label }) => { + answerReachability(false) + + await setupMaven( + { reachability: { ...reachability } }, + { inheritedReachability: inherited }, + ) + + const asked = vi + .mocked(select) + .mock.calls.find(([{ message }]) => message === REACHABILITY_QUESTION) + expect( + asked?.[0].choices.find( + choice => typeof choice === 'object' && choice.name === 'no', + ), + ).toMatchObject({ description: label }) + }, + ) + + it('offers the shown value as the default and clears it on a blank answer', async () => { + vi.mocked(select).mockImplementation(async ({ default: def, message }) => + message === REACHABILITY_QUESTION ? true : (def ?? ''), + ) + const shown: unknown[] = [] + vi.mocked(input).mockImplementation(async ({ default: def, message }) => { + if (message.startsWith('What JDK should reachability analysis use?')) { + shown.push(def) + return '' + } + return def ?? '' + }) + const config: Record = { + reachability: { javaHome: '/opt/jdk-17' }, + } + + await setupGradle(config, { factsOnly: true }) + + expect(shown).toEqual(['/opt/jdk-17']) + expect(config['reachability']).toEqual({ javaHome: null }) + }) + + it('offers an inherited JDK as the default and clears it on a blank answer', async () => { + vi.mocked(select).mockImplementation(async ({ default: def, message }) => + message === REACHABILITY_QUESTION ? true : (def ?? ''), + ) + const shown: unknown[] = [] + vi.mocked(input).mockImplementation(async ({ default: def, message }) => { + if (message.startsWith('What JDK should reachability analysis use?')) { + shown.push(def) + return '' + } + return def ?? '' + }) + const config: Record = {} + + await setupMaven(config, { + inheritedReachability: { javaHome: '/opt/jdk-11' }, + }) + + expect(shown).toEqual(['/opt/jdk-11']) + expect(config['reachability']).toEqual({ javaHome: null }) + }) + + it('does not ask in pom mode, where no facts reach a reachability run', async () => { + const messages: string[] = [] + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + messages.push(message) + return def ?? '' + }) + + await setupGradle({ facts: false }) + await setupSbt({ facts: false }) + + expect(messages).not.toContain(REACHABILITY_QUESTION) + }) +}) + +describe('reachability build step', () => { + const BUILD_QUESTION = + 'Build project before reachability analysis? Note: A failed build fails the scan.' + + // Answers the build question with `wantsBuild`; every other prompt keeps + // its default. Returns the build question's shown default per call. + function answerBuild(wantsBuild: boolean): unknown[] { + const shown: unknown[] = [] + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + if (message === BUILD_QUESTION) { + shown.push(def) + return wantsBuild + } + return def ?? '' + }) + return shown + } + + afterEach(() => { + vi.mocked(select).mockReset() + vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') + }) + + it.for([ + ['dotnet', setupDotnet], + ['gradle', setupGradle], + ['maven', setupMaven], + ['sbt', setupSbt], + ] as const)( + '%s writes compile to reachability.build after a yes', + async ({ 1: setup }) => { + answerBuild(true) + const config: Record = {} + + const result = await setup(config) + + expect(result).toEqual({ ok: true, data: { canceled: false } }) + expect(config).toEqual({ reachability: { build: 'compile' } }) + }, + ) + + it.for([ + ['dotnet', setupDotnet], + ['gradle', setupGradle], + ['maven', setupMaven], + ['sbt', setupSbt], + ] as const)( + '%s leaves reachability.build unset after a no at the top level, never writing none', + async ({ 1: setup }) => { + answerBuild(false) + const config: Record = {} + + await setup(config) + + expect(config).toEqual({}) + }, + ) + + it.for([ + ['dotnet', setupDotnet], + ['gradle', setupGradle], + ['maven', setupMaven], + ['sbt', setupSbt], + ] as const)( + '%s writes none after a no when the project inherits compile', + async ({ 1: setup }) => { + const shown = answerBuild(false) + const config: Record = { + reachability: { build: 'compile' }, + } + + await setup(config, { inheritedReachability: { build: 'compile' } }) + + expect(shown).toEqual([true]) + expect(config).toEqual({ reachability: { build: 'none' } }) + }, + ) + + it('leaves the build unset after a no when the project inherits none', async () => { + answerBuild(false) + const config: Record = { reachability: { build: 'none' } } + + await setupGradle(config, { inheritedReachability: { build: 'none' } }) + + expect(config).toEqual({}) + }) + + it('unsets a build it shows as the default after a no, keeping the JDK', async () => { + const shown = answerBuild(false) + const config: Record = { + reachability: { build: 'compile', javaHome: '/opt/jdk-17' }, + } + + await setupMaven(config) + + expect(shown).toEqual([true]) + expect(config['reachability']).toEqual({ javaHome: '/opt/jdk-17' }) + }) + + it('removes a written none after a no', async () => { + const shown = answerBuild(false) + const config: Record = { reachability: { build: 'none' } } + + await setupDotnet(config) + + expect(shown).toEqual([false]) + expect(config).toEqual({}) + }) + + it('never asks dotnet for a reachability JDK', async () => { + const messages: string[] = [] + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + messages.push(message) + return message === BUILD_QUESTION ? true : (def ?? '') + }) + const config: Record = {} + + await setupDotnet(config) + + expect(messages).toContain(BUILD_QUESTION) + expect(messages.some(m => m.includes('Java'))).toBe(false) + expect(config).toEqual({ reachability: { build: 'compile' } }) + }) + + it('does not ask in pom mode, where no facts reach a reachability run', async () => { + const messages: string[] = [] + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + messages.push(message) + return def ?? '' + }) + + await setupGradle({ facts: false }) + await setupSbt({ facts: false }) + + expect(messages).not.toContain(BUILD_QUESTION) + }) +}) + +describe('reachability runtime step', () => { + const RUNTIME_QUESTION = + 'Start the reachability analysis of a framework-dependent .NET build on a given runtime?' + + // Answers the runtime question with `wantsRuntime` and its prompt with + // `runtimeVersion`; records each runtime prompt. + function answerRuntime(wantsRuntime: boolean, runtimeVersion = '') { + const asked: Array[0]> = [] + vi.mocked(select).mockImplementation(async ({ default: def, message }) => + message === RUNTIME_QUESTION ? wantsRuntime : (def ?? ''), + ) + vi.mocked(input).mockImplementation(async config => { + if (config.message.startsWith('Which .NET runtime?')) { + asked.push(config) + return runtimeVersion + } + return config.default ?? '' + }) + return asked + } + + afterEach(() => { + vi.mocked(input).mockReset() + vi.mocked(input).mockImplementation(async ({ default: def }) => def ?? '') + vi.mocked(select).mockReset() + vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') + }) + + it('writes the runtime named after a yes to reachability.runtimeVersion', async () => { + answerRuntime(true, '8.0') + const config: Record = {} + + expect(await setupDotnet(config)).toEqual({ + ok: true, + data: { canceled: false }, + }) + expect(config).toEqual({ reachability: { runtimeVersion: '8.0' } }) + }) + + it.for([ + ['8.0', true], + ['8.0.11', true], + ['', true], + ['net8.0', false], + ['8', false], + ] as const)('takes %j as an answer: %j', async ({ 0: answer, 1: valid }) => { + const asked = answerRuntime(true, '8.0') + + await setupDotnet({}) + + const result = await asked[0]!.validate!(answer) + if (valid) { + expect(result).toBe(true) + } else { + expect(result).toEqual(expect.stringContaining('major.minor')) + } + }) + + it('offers an inherited runtime as the default and clears it on a blank answer', async () => { + const asked = answerRuntime(true, '') + const config: Record = {} + + await setupDotnet(config, { + inheritedReachability: { runtimeVersion: '9.0' }, + }) + + expect(asked.map(({ default: def }) => def)).toEqual(['9.0']) + expect(config).toEqual({ reachability: { runtimeVersion: null } }) + }) + + it('never asks a JVM build tool for a .NET runtime', async () => { + const messages: string[] = [] + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + messages.push(message) + return def ?? '' + }) + + await setupMaven({}) + + expect(messages).not.toContain(RUNTIME_QUESTION) + }) +}) + +describe('reachability settings written invalid', () => { + afterEach(() => { + vi.mocked(select).mockReset() + vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') + vi.restoreAllMocks() + }) + + it.for([ + [ + 'maven', + { build: 'always', java_home: '/jdk', javaHome: '/opt/jdk-17' }, + { javaHome: '/opt/jdk-17' }, + ['reachability.build', 'reachability.java_home'], + ], + [ + 'dotnet', + { javaHome: '/jdk', runtimeVersion: 'net8.0' }, + undefined, + ['reachability.javaHome', 'reachability.runtimeVersion'], + ], + ['gradle', 'compile', undefined, ['`reachability`']], + ] as const)( + '%s replaces %j, keeping only what its builds take', + async ({ 0: tool, 1: reachability, 2: kept, 3: warned }) => { + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => logger) + const config: Record = { reachability } + const setup = { + dotnet: setupDotnet, + gradle: setupGradle, + maven: setupMaven, + }[tool] + + expect(await setup(config)).toEqual({ + ok: true, + data: { canceled: false }, + }) + + expect(config['reachability']).toEqual(kept) + for (const field of warned) { + expect(warn).toHaveBeenCalledWith(expect.stringContaining(field)) + } + }, + ) + + it('ignores an invalid inherited value for its defaults', async () => { + const shown: unknown[] = [] + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + if (message.startsWith('Build project before reachability analysis?')) { + shown.push(def) + } + return def ?? '' + }) + const config: Record = {} + + await setupGradle(config, { + inheritedReachability: { build: 'always', javaHome: 17 }, + }) + + expect(shown).toEqual([false]) + expect(config).toEqual({}) + }) + + it('does not claim to replace an invalid value the merged settings inherit', async () => { + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => logger) + const inheritedReachability = { build: 'compile', javaHome: 17 } + const config: Record = { + reachability: { ...inheritedReachability, build: 'always' }, + } + + await setupGradle(config, { factsOnly: true, inheritedReachability }) + + expect(warn.mock.calls.map(c => c[0])).toEqual([ + expect.stringContaining('reachability.build'), + ]) + }) +}) + +describe('setupManifestConfig', () => { + const BUILD_QUESTION = + 'Build project before reachability analysis? Note: A failed build fails the scan.' + let parent = '' + + beforeEach(async () => { + parent = await fs.realpath( + await fs.mkdtemp(path.join(tmpdir(), 'setup-manifest-config-')), + ) + }) + afterEach(async () => { + vi.mocked(select).mockReset() + vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') + await fs.rm(parent, { recursive: true, force: true }) + }) + + it('writes none after a no under an ancestor socket.json that sets compile, showing compile as the default', async () => { + await writeSocketJson(parent, { + ...getDefaultSocketJson(), + defaults: { manifest: { maven: { reachability: { build: 'compile' } } } }, + }) + const cwd = path.join(parent, 'app') + await fs.mkdir(cwd) + const shown: unknown[] = [] + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + if (message === 'Select ecosystem manifest generator to configure') { + return 'maven' + } + if (message === BUILD_QUESTION) { + shown.push(def) + return false + } + if (message.startsWith('Do you want to write the new config')) { + return true + } + return def ?? '' + }) + vi.spyOn(logger, 'log').mockImplementation(() => logger) + vi.spyOn(logger, 'info').mockImplementation(() => logger) + + expect(await setupManifestConfig(cwd)).toEqual({ + ok: true, + data: undefined, + }) + + expect(shown).toEqual([true]) + const written = JSON.parse( + await fs.readFile(path.join(cwd, 'socket.json'), 'utf8'), + ) + expect(written.defaults.manifest.maven).toEqual({ + reachability: { build: 'none' }, + }) + }) +}) + +describe('setupManifestConfig with an invalid ancestor socket.json', () => { + let parent = '' + + beforeEach(async () => { + parent = await fs.realpath( + await fs.mkdtemp(path.join(tmpdir(), 'setup-manifest-config-')), + ) + await fs.writeFile( + path.join(parent, 'socket.json'), + JSON.stringify({ + version: 1, + defaults: { manifest: { maven: { reachability: { javaHome: 17 } } } }, + }), + ) + }) + afterEach(async () => { + vi.mocked(select).mockReset() + vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') + await fs.rm(parent, { recursive: true, force: true }) + }) + + it('configures a build beneath it, replacing what it cannot take', async () => { + const cwd = path.join(parent, 'app') + await fs.mkdir(cwd) + await fs.writeFile( + path.join(cwd, 'socket.json'), + JSON.stringify({ + version: 1, + defaults: { + manifest: { maven: { reachability: { build: 'always' } } }, + }, + }), + ) + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + if (message === 'Select ecosystem manifest generator to configure') { + return 'maven' + } + if (message.startsWith('Do you want to write the new config')) { + return true + } + return def ?? '' + }) + vi.spyOn(logger, 'log').mockImplementation(() => logger) + vi.spyOn(logger, 'info').mockImplementation(() => logger) + vi.spyOn(logger, 'warn').mockImplementation(() => logger) + + expect(await setupManifestConfig(cwd)).toEqual({ + ok: true, + data: undefined, + }) + + const written = JSON.parse( + await fs.readFile(path.join(cwd, 'socket.json'), 'utf8'), + ) + expect(written.defaults.manifest.maven).toEqual({}) + }) + + it('exits without reading it when no build tool is chosen', async () => { + const cwd = path.join(parent, 'app') + await fs.mkdir(cwd) + vi.mocked(select).mockImplementation(async ({ default: def, message }) => + message === 'Select ecosystem manifest generator to configure' + ? '' + : (def ?? ''), + ) + vi.spyOn(logger, 'log').mockImplementation(() => logger) + vi.spyOn(logger, 'info').mockImplementation(() => logger) + + await expect(setupManifestConfig(cwd)).resolves.toMatchObject({ + ok: true, + data: { canceled: true }, + }) + }) +}) + describe('setupDotnet', () => { it('preserves explicit nulls on a blank re-prompt', async () => { const config: Record = { bin: null, dotnetOpts: null } diff --git a/src/commands/manifest/setup-recursive-manifest-config.mts b/src/commands/manifest/setup-recursive-manifest-config.mts index b80c4050a..b7ec46a37 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.mts @@ -44,6 +44,7 @@ import { loadSocketConfig } from '../../utils/config.mts' import { realpathOrResolved } from '../../utils/fs.mts' import { getOrInsert } from '../../utils/get-or-insert.mts' import { logger } from '../../utils/logger.mts' +import { isRecord } from '../../utils/objects.mts' import { select } from '../../utils/prompts.mts' import { mergeSocketJsonChain, @@ -62,6 +63,7 @@ import type { import type { BuildRoot, Membership } from './discover-manifest-roots.mts' import type { LoadedBuild } from './load-build.mts' import type { BuildTool } from './scripts/build-tool.mts' +import type { ReachabilityStepOptions } from './setup-manifest-config.mts' import type { CResult } from '../../types.mts' import type { ManifestDefaults, @@ -89,6 +91,28 @@ function notCanceled(): CResult<{ canceled: boolean }> { return { ok: true, data: { canceled: false } } } +// A nested section (`reachability`) compares field by field, as the cascade +// merges it. +function changedFields( + seed: Record, + inherited: Record, +): Record { + const changed: Record = {} + for (const key of Object.keys(seed)) { + const value = seed[key] + const base = inherited[key] + if (isRecord(value) && isRecord(base)) { + const nested = changedFields(value, base) + if (Object.keys(nested).length) { + changed[key] = nested + } + } else if (value !== base) { + changed[key] = value + } + } + return changed +} + function getEcosystemSection( sockJson: SocketJson, ecosystem: BuildTool, @@ -459,18 +483,21 @@ async function configureBuild( } const seeded = Object.keys(seed) - const result = await runEcosystemWizard(ecosystem, seed) + const result = await runEcosystemWizard(ecosystem, seed, { + inheritedReachability: inherited['reachability'], + }) if (!result.ok || result.data.canceled) { return result } const before = JSON.stringify(target) + const changed = changedFields(seed, inherited) // An answer the wizard removed leaves the field to inheritance. for (const field of new Set([...seeded, ...Object.keys(seed)])) { - if (!Object.hasOwn(seed, field) || seed[field] === inherited[field]) { - delete target[field] + if (Object.hasOwn(changed, field)) { + target[field] = changed[field] } else { - target[field] = seed[field] + delete target[field] } } const label = buildLabel(cwd, build) @@ -807,19 +834,24 @@ async function reviewBuild( async function runEcosystemWizard( ecosystem: BuildTool, config: Record, + options: ReachabilityStepOptions = {}, ): Promise> { if (ecosystem === 'dotnet') { - return await setupDotnet(config as ManifestDefaults<'dotnet'>) + return await setupDotnet(config as ManifestDefaults<'dotnet'>, options) } if (ecosystem === 'gradle') { return await setupGradle(config as ManifestDefaults<'gradle'>, { + ...options, factsOnly: true, }) } if (ecosystem === 'maven') { - return await setupMaven(config as ManifestDefaults<'maven'>) + return await setupMaven(config as ManifestDefaults<'maven'>, options) } - return await setupSbt(config as ManifestDefaults<'sbt'>, { factsOnly: true }) + return await setupSbt(config as ManifestDefaults<'sbt'>, { + ...options, + factsOnly: true, + }) } // Accepting every prompt's default leaves an ecosystem's section empty (see @@ -902,8 +934,14 @@ async function setupRootDefaults( const manifest = manifestOf(own) const section = { ...getEcosystemSection(own, ecosystem) } manifest[ecosystem] = section + const inherited = getEcosystemSection( + draftCascade(draft, path.dirname(cwd)), + ecosystem, + ) // eslint-disable-next-line no-await-in-loop - const result = await runEcosystemWizard(ecosystem, section) + const result = await runEcosystemWizard(ecosystem, section, { + inheritedReachability: inherited['reachability'], + }) if (!result.ok || result.data.canceled) { return result } diff --git a/src/commands/manifest/setup-recursive-manifest-config.test.mts b/src/commands/manifest/setup-recursive-manifest-config.test.mts index f0157e99c..7d0b955b7 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.test.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.test.mts @@ -17,6 +17,7 @@ vi.mock('./run-manifest-facts.mts', async importOriginal => ({ listBuildProjects: vi.fn(), })) vi.mock('../../utils/prompts.mts', () => ({ + input: vi.fn(), select: vi.fn(), })) vi.mock('./setup-manifest-config.mts', () => ({ @@ -36,7 +37,7 @@ import { } from './setup-recursive-manifest-config.mts' import { mavenProject } from '../../../test/socket-facts-projects.mts' import { logger } from '../../utils/logger.mts' -import { select } from '../../utils/prompts.mts' +import { input, select } from '../../utils/prompts.mts' import type { BuildRoot } from './discover-manifest-roots.mts' import type { SocketJson } from '../../utils/socket-json.mts' @@ -552,6 +553,163 @@ describe('setupRecursiveManifestConfig', () => { expect((await readSettings('legacy')).defaults?.manifest?.maven).toEqual({}) }) + it('writes an inherited reachability setting only where it differs, field by field', async () => { + await writeSettings('.', { + maven: { reachability: { javaHome: '/opt/jdk-17' } }, + }) + loads({ 'pom.xml': ['api'], 'legacy/pom.xml': ['old'] }) + vi.mocked(setupMaven).mockResolvedValue({ + ok: true, + data: { canceled: false }, + }) + const answers: Answers = [ + ['This project (maven)', 'inherit'], + ['Review the', true], + ['legacy (maven)', 'configure'], + ['legacy/tool (maven)', 'inherit'], + ['Write it?', true], + ] + answer(answers) + + await setupRecursiveManifestConfig(repo, false) + expect(existsSync(file('legacy/socket.json'))).toBe(false) + + vi.mocked(setupMaven).mockImplementation(async config => { + config.reachability = { javaHome: null } + return { ok: true, data: { canceled: false } } + }) + answer(answers) + + await setupRecursiveManifestConfig(repo, false) + expect((await readSettings('legacy')).defaults?.manifest?.maven).toEqual({ + reachability: { javaHome: null }, + }) + }) + + it('seeds reachability with both the inherited and the own fields', async () => { + await writeSettings('.', { + maven: { reachability: { javaHome: '/opt/jdk-17' } }, + }) + await writeSettings('legacy', { maven: { reachability: { other: 'x' } } }) + loads({ 'pom.xml': ['api'], 'legacy/pom.xml': ['old'] }) + let seeded: unknown + vi.mocked(setupMaven).mockImplementation(async config => { + seeded = structuredClone(config) + return { ok: true, data: { canceled: false } } + }) + answer([ + ['This project (maven)', 'inherit'], + ['Review the', true], + ['legacy (maven)', 'configure'], + ['legacy/tool (maven)', 'inherit'], + ]) + + await setupRecursiveManifestConfig(repo, false) + + expect(seeded).toEqual({ + reachability: { javaHome: '/opt/jdk-17', other: 'x' }, + }) + expect((await readSettings('legacy')).defaults?.manifest?.maven).toEqual({ + reachability: { other: 'x' }, + }) + }) + + it('loads and configures a build whose socket.json sets an invalid reachability value, replacing it', async () => { + const actual = await vi.importActual< + typeof import('./setup-manifest-config.mts') + >('./setup-manifest-config.mts') + vi.mocked(setupMaven).mockImplementation(actual.setupMaven) + vi.mocked(input).mockImplementation(async ({ default: def }) => def ?? '') + vi.spyOn(logger, 'warn').mockImplementation(() => logger) + await writeSettings('legacy', { + maven: { + mavenOpts: '-B', + reachability: { build: 'always', javaHome: 17 }, + }, + }) + loads({ 'pom.xml': ['api'], 'legacy/pom.xml': ['old'] }) + const rules: Answers = [ + ['This project (maven)', 'inherit'], + ['Review the', true], + ['legacy (maven)', 'configure'], + ['legacy/tool (maven)', 'inherit'], + ['Write it?', true], + ] + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + const rule = rules.find(({ 0: start }) => message.startsWith(start)) + return (rule ? rule[1] : (def ?? '')) as never + }) + + expect(await setupRecursiveManifestConfig(repo, false)).toEqual({ + ok: true, + data: { canceled: false }, + }) + + expect((await readSettings('legacy')).defaults?.manifest?.maven).toEqual({ + mavenOpts: '-B', + }) + }) + + describe('after a no to building before reachability analysis', () => { + const BUILD_QUESTION = + 'Build project before reachability analysis? Note: A failed build fails the scan.' + + // Runs the real Maven wizard for legacy under a parent with `parentBuild`, + // answering no to the build question and the defaults elsewhere. + async function configureUnder( + parentBuild: 'compile' | 'none' | undefined, + ): Promise { + const actual = await vi.importActual< + typeof import('./setup-manifest-config.mts') + >('./setup-manifest-config.mts') + vi.mocked(setupMaven).mockImplementation(actual.setupMaven) + vi.mocked(input).mockImplementation(async ({ default: def }) => def ?? '') + await writeSettings( + '.', + parentBuild ? { maven: { reachability: { build: parentBuild } } } : {}, + ) + loads({ 'pom.xml': ['api'], 'legacy/pom.xml': ['old'] }) + const rules: Answers = [ + ['This project (maven)', 'inherit'], + ['Review the', true], + ['legacy (maven)', 'configure'], + ['legacy/tool (maven)', 'inherit'], + ['Write it?', true], + ] + vi.mocked(select).mockImplementation( + async ({ default: def, message }) => { + asked.push(message) + if (message === BUILD_QUESTION) { + return false as never + } + const rule = rules.find(({ 0: start }) => message.startsWith(start)) + return (rule ? rule[1] : (def ?? '')) as never + }, + ) + + const result = await setupRecursiveManifestConfig(repo, false) + expect(result).toEqual({ ok: true, data: { canceled: false } }) + expect(asked).toContain(BUILD_QUESTION) + } + + it('writes none under a parent that sets compile', async () => { + await configureUnder('compile') + + expect((await readSettings('legacy')).defaults?.manifest?.maven).toEqual({ + reachability: { build: 'none' }, + }) + }) + + it.for(['none', undefined] as const)( + 'leaves the build unset under a parent whose build is %s', + async parentBuild => { + await configureUnder(parentBuild) + + expect(existsSync(file('legacy/socket.json'))).toBe(false) + }, + ) + }) + it('loads a build left skipped under its own name, so its modules are not asked about', async () => { await writeSettings('legacy', { builds: { 'pom.xml': { disabled: true } }, From 237823e7ada231f9b57aacdba6df9cdcf13557d6 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 13:41:24 +0100 Subject: [PATCH 02/10] Keep directory defaults to what differs from the parent `socket manifest setup --dynamic-sbom-inference` wrote every accepted default of a directory's section into its socket.json, so accepting an inherited reachability value pinned it there. It now keeps only the fields that differ from what the directory inherits, as it does for a build. --- .../setup-recursive-manifest-config.mts | 30 +++++------- .../setup-recursive-manifest-config.test.mts | 48 +++++++++++++++++++ 2 files changed, 60 insertions(+), 18 deletions(-) diff --git a/src/commands/manifest/setup-recursive-manifest-config.mts b/src/commands/manifest/setup-recursive-manifest-config.mts index b7ec46a37..cc11a4fef 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.mts @@ -1,5 +1,6 @@ import { existsSync } from 'node:fs' import path from 'node:path' +import { isDeepStrictEqual } from 'node:util' import micromatch from 'micromatch' @@ -854,20 +855,6 @@ async function runEcosystemWizard( }) } -// Accepting every prompt's default leaves an ecosystem's section empty (see -// askForBin in setup-manifest-config.mts); an empty one changes nothing. -function dropIfEmpty( - manifest: Record, - ecosystem: BuildTool, -): boolean { - const section = manifest[ecosystem] as Record | undefined - if (section && Object.keys(section).length) { - return true - } - delete manifest[ecosystem] - return false -} - async function askYesNo(message: string): Promise { return (await select({ message, @@ -932,8 +919,8 @@ async function setupRootDefaults( } const own = draftSettings(draft, cwd) const manifest = manifestOf(own) - const section = { ...getEcosystemSection(own, ecosystem) } - manifest[ecosystem] = section + const before = getEcosystemSection(own, ecosystem) + const section = { ...before } const inherited = getEcosystemSection( draftCascade(draft, path.dirname(cwd)), ecosystem, @@ -945,9 +932,16 @@ async function setupRootDefaults( if (!result.ok || result.data.canceled) { return result } - if (dropIfEmpty(manifest, ecosystem)) { - stageSettings(draft, cwd, own, `configure ${label} defaults`) + const changed = changedFields(section, inherited) + if (isDeepStrictEqual(changed, before)) { + continue + } + if (Object.keys(changed).length) { + manifest[ecosystem] = changed + } else { + delete manifest[ecosystem] } + stageSettings(draft, cwd, own, `configure ${label} defaults`) } return notCanceled() } diff --git a/src/commands/manifest/setup-recursive-manifest-config.test.mts b/src/commands/manifest/setup-recursive-manifest-config.test.mts index 7d0b955b7..261cedcc5 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.test.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.test.mts @@ -650,6 +650,54 @@ describe('setupRecursiveManifestConfig', () => { }) }) + // Runs the real Maven wizard for the defaults of legacy, which holds only + // nested projects, accepting every default under a parent's reachability. + async function acceptDefaultsUnder(): Promise { + const actual = await vi.importActual< + typeof import('./setup-manifest-config.mts') + >('./setup-manifest-config.mts') + vi.mocked(setupMaven).mockImplementation(actual.setupMaven) + vi.mocked(input).mockImplementation(async ({ default: def }) => def ?? '') + await fs.rm(file('legacy/pom.xml')) + await writeSettings('.', { + maven: { reachability: { build: 'compile', javaHome: '/opt/jdk-17' } }, + }) + loads({}) + const rules: Answers = [ + ['Configure Maven defaults for any nested projects?', true], + ['old (maven)', 'inherit'], + ['tool (maven)', 'inherit'], + ['Write it?', true], + ] + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + asked.push(message) + const rule = rules.find(({ 0: start }) => message.startsWith(start)) + return (rule ? rule[1] : (def ?? '')) as never + }) + + const result = await setupRecursiveManifestConfig(file('legacy'), false) + expect(result).toEqual({ ok: true, data: { canceled: false } }) + expect(asked).toContain('Configure Maven defaults for any nested projects?') + } + + it('leaves accepted inherited values in directory defaults to the parent', async () => { + await acceptDefaultsUnder() + + expect(existsSync(file('legacy/socket.json'))).toBe(false) + }) + + it('keeps a directory default that differs from the inherited value', async () => { + await writeSettings('legacy', { + maven: { reachability: { build: 'none' } }, + }) + + await acceptDefaultsUnder() + + expect((await readSettings('legacy')).defaults?.manifest?.maven).toEqual({ + reachability: { build: 'none' }, + }) + }) + describe('after a no to building before reachability analysis', () => { const BUILD_QUESTION = 'Build project before reachability analysis? Note: A failed build fails the scan.' From 057fb8ea1f7633d11d2054ddfd09d14c192fd079 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 13:41:40 +0100 Subject: [PATCH 03/10] Reword the reachability wizard's comments --- src/commands/manifest/setup-manifest-config.mts | 13 +++++++------ .../manifest/setup-manifest-config.test.mts | 12 ++++++------ 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/commands/manifest/setup-manifest-config.mts b/src/commands/manifest/setup-manifest-config.mts index 4f76f0e00..afc5d8a8d 100644 --- a/src/commands/manifest/setup-manifest-config.mts +++ b/src/commands/manifest/setup-manifest-config.mts @@ -25,7 +25,8 @@ export type ReachabilityStepOptions = { inheritedReachability?: unknown } -// As written, so that the wizard can replace an invalid value. +// As written. The wizard leaves invalid inherited values out of its defaults +// and replaces invalid values only in this directory's socket.json. function inheritedReachabilityOf(cwd: string, tool: BuildTool): unknown { const dir = path.resolve(cwd) const parent = path.dirname(dir) @@ -782,8 +783,8 @@ async function askForIgnoreUnresolvedFlag( }) } -// The fields of `value` that `tool`'s builds take, warning about the rest the -// answers replace; an inherited invalid value is its own socket.json's to fix. +// The wizard warns about invalid local values and replaces them with the answers. +// Invalid inherited values need to be fixed in the socket.json that sets them. function validReachability( tool: BuildTool, value: unknown, @@ -829,8 +830,8 @@ function effectiveValue( return Object.hasOwn(own, field) ? own[field] : inherited[field] } -// A "no" to a value's question keeps the value in effect; "none" is written -// only to override an inherited "compile". +// Answering no to a value prompt keeps the effective value. +// The wizard writes "none" to override an inherited "compile". async function setupReachability( tool: BuildTool, config: { reachability?: unknown }, @@ -961,7 +962,7 @@ async function setupReachabilityValue( if (applyAnswer(reachability as Record, field, answer)) { return canceledByUser() } - // A blank answer must also clear an inherited value, not fall back to it. + // A blank answer writes null to clear an inherited value. if (answer === '' && inherited[field]) { reachability[field] = null } diff --git a/src/commands/manifest/setup-manifest-config.test.mts b/src/commands/manifest/setup-manifest-config.test.mts index f1b6d84b9..2a18a179b 100644 --- a/src/commands/manifest/setup-manifest-config.test.mts +++ b/src/commands/manifest/setup-manifest-config.test.mts @@ -103,8 +103,8 @@ describe('reachability step', () => { const REACHABILITY_QUESTION = 'Use a different Java for reachability analysis?' - // Answers the reachability question with `wantsJavaHome` and its JDK prompt - // with `javaHome`; every other prompt keeps its default. + // Answers the JDK choice with `wantsJavaHome` and the path prompt with `javaHome`. + // Other prompts keep their defaults. function answerReachability(wantsJavaHome: boolean, javaHome = ''): void { vi.mocked(select).mockImplementation(async ({ default: def, message }) => message === REACHABILITY_QUESTION ? wantsJavaHome : (def ?? ''), @@ -273,8 +273,8 @@ describe('reachability build step', () => { const BUILD_QUESTION = 'Build project before reachability analysis? Note: A failed build fails the scan.' - // Answers the build question with `wantsBuild`; every other prompt keeps - // its default. Returns the build question's shown default per call. + // Answers the build prompt with `wantsBuild` and accepts the other defaults. + // Returns the build prompt's displayed default for each call. function answerBuild(wantsBuild: boolean): unknown[] { const shown: unknown[] = [] vi.mocked(select).mockImplementation(async ({ default: def, message }) => { @@ -411,8 +411,8 @@ describe('reachability runtime step', () => { const RUNTIME_QUESTION = 'Start the reachability analysis of a framework-dependent .NET build on a given runtime?' - // Answers the runtime question with `wantsRuntime` and its prompt with - // `runtimeVersion`; records each runtime prompt. + // Answers the runtime choice with `wantsRuntime` and the version prompt with `runtimeVersion`. + // Records each runtime prompt. function answerRuntime(wantsRuntime: boolean, runtimeVersion = '') { const asked: Array[0]> = [] vi.mocked(select).mockImplementation(async ({ default: def, message }) => From 872cf8b12074719dc714df496f06f9983a7318ca Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Wed, 25 Nov 2026 14:10:01 +0100 Subject: [PATCH 04/10] Test the JDK a scan reads after the wizard keeps or clears a parent's Answering no to a different JDK in a directory under a socket.json that sets one writes nothing, and the scan there reads the parent's JDK; answering yes with a blank JDK writes null, and the scan reads none. --- .../manifest/setup-manifest-config.test.mts | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/src/commands/manifest/setup-manifest-config.test.mts b/src/commands/manifest/setup-manifest-config.test.mts index 2a18a179b..a9ab9f08d 100644 --- a/src/commands/manifest/setup-manifest-config.test.mts +++ b/src/commands/manifest/setup-manifest-config.test.mts @@ -13,6 +13,7 @@ vi.mock('../../utils/prompts.mts', () => ({ select: vi.fn(async ({ default: def }: { default?: string }) => def ?? ''), })) +import { cascadedReachability } from './build-root-config.mts' import { setupDotnet, setupGradle, @@ -24,6 +25,7 @@ import { logger } from '../../utils/logger.mts' import { input, select } from '../../utils/prompts.mts' import { getDefaultSocketJson, + readSocketJsonChain, writeSocketJson, } from '../../utils/socket-json.mts' @@ -580,6 +582,8 @@ describe('setupManifestConfig', () => { afterEach(async () => { vi.mocked(select).mockReset() vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') + vi.mocked(input).mockReset() + vi.mocked(input).mockImplementation(async ({ default: def }) => def ?? '') await fs.rm(parent, { recursive: true, force: true }) }) @@ -620,6 +624,55 @@ describe('setupManifestConfig', () => { reachability: { build: 'none' }, }) }) + + it.for([ + [ + 'keeps the parent JDK for a scan here after a no', + false, + { + javaHome: '/opt/jdk-17', + }, + ], + [ + 'clears the parent JDK for a scan here after a blank JDK', + true, + undefined, + ], + ] as const)('%s', async ({ 1: wantsJavaHome, 2: scanned }) => { + await writeSocketJson(parent, { + ...getDefaultSocketJson(), + defaults: { + manifest: { maven: { reachability: { javaHome: '/opt/jdk-17' } } }, + }, + }) + const cwd = path.join(parent, 'app') + await fs.mkdir(cwd) + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + if (message === 'Select ecosystem manifest generator to configure') { + return 'maven' + } + if (message === 'Use a different Java for reachability analysis?') { + return wantsJavaHome + } + if (message.startsWith('Do you want to write the new config')) { + return true + } + return def ?? '' + }) + vi.mocked(input).mockImplementation(async ({ default: def, message }) => + message.startsWith('What JDK should reachability analysis use?') + ? '' + : (def ?? ''), + ) + vi.spyOn(logger, 'log').mockImplementation(() => logger) + vi.spyOn(logger, 'info').mockImplementation(() => logger) + + await setupManifestConfig(cwd) + + expect(cascadedReachability('maven', readSocketJsonChain(cwd))).toEqual( + scanned, + ) + }) }) describe('setupManifestConfig with an invalid ancestor socket.json', () => { From 4d2bda6da0c1883b85b04448f6342d2644d62e02 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Fri, 27 Nov 2026 10:31:29 +0100 Subject: [PATCH 05/10] Drive the wizard's reachability step from the settings table The step asks about each field the tool takes, from the table the scan checks, and reads both its own and the inherited value through the same parse, so it no longer filters them twice. The value in effect is the merge a scan makes. A blank answer writes null only when there is a value to clear, and the .NET runtime version format is written once. --- src/commands/manifest/build-root-config.mts | 102 +++--- .../manifest/setup-manifest-config.mts | 306 +++++++++--------- .../setup-recursive-manifest-config.mts | 31 +- 3 files changed, 221 insertions(+), 218 deletions(-) diff --git a/src/commands/manifest/build-root-config.mts b/src/commands/manifest/build-root-config.mts index fb7a84257..4a8d94a90 100644 --- a/src/commands/manifest/build-root-config.mts +++ b/src/commands/manifest/build-root-config.mts @@ -59,7 +59,7 @@ const DOTNET_RUNTIME_VERSION = new RegExp( `^${NUMBER}\\.${NUMBER}(?:\\.${NUMBER}(?:-${PRERELEASE_IDENTIFIER}(?:\\.${PRERELEASE_IDENTIFIER})*)?)?$`, ) -const DOTNET_RUNTIME_VERSION_FORMAT = +export const DOTNET_RUNTIME_VERSION_FORMAT = 'major.minor, such as "8.0", for its latest installed patch, or major.minor.patch[-prerelease], such as "8.0.11", for exactly that runtime' const REACHABILITY_FIELDS = { @@ -87,11 +87,12 @@ const REACHABILITY_FIELDS = { } > -type ReachabilityProblem = { +export type ReachabilityProblem = { // Undefined when the value is not an object. field: string | undefined // Why the tool rejects it, and the remedy. problem: string + value: unknown } function checkReachability( @@ -156,50 +157,6 @@ function ownEntryKeys( ) } -// The valid fields of `value`, nulls kept, and the problem with each other one. -function parseReachability( - tool: BuildTool, - value: unknown, -): { problems: ReachabilityProblem[]; settings: ReachabilityDefaults } { - const settings: ReachabilityDefaults = {} - if (value === undefined) { - return { problems: [], settings } - } - if (!isRecord(value)) { - return { - problems: [ - { - field: undefined, - problem: `is ${JSON.stringify(value)}; set it to an object, or remove it.`, - }, - ], - settings, - } - } - const fields = REACHABILITY_FIELDS_BY_TOOL[tool] - const problems: ReachabilityProblem[] = [] - for (const { 0: name, 1: fieldValue } of Object.entries(value)) { - const field = fields.find(f => f === name) - if (!field) { - problems.push({ - field: name, - problem: `is not a reachability setting of ${tool} builds, which take ${joinAnd(fields)}; remove it.`, - }) - } else if ( - fieldValue === null || - REACHABILITY_FIELDS[field].takes(fieldValue) - ) { - Object.assign(settings, { [field]: fieldValue }) - } else { - problems.push({ - field, - problem: `is ${JSON.stringify(fieldValue)}; set it to ${REACHABILITY_FIELDS[field].expected}, to null to clear an inherited value, or remove it.`, - }) - } - } - return { problems, settings } -} - // Without the fields a socket.json cleared with null. function settingsInEffect( settings: ReachabilityDefaults, @@ -397,6 +354,59 @@ export function displayPath(file: string): string { return rel.startsWith('..') || path.isAbsolute(rel) ? file : rel || '.' } +// The valid fields of `value`, nulls kept, and the problem with each other one. +export function parseReachability( + tool: BuildTool, + value: unknown, +): { problems: ReachabilityProblem[]; settings: ReachabilityDefaults } { + const settings: ReachabilityDefaults = {} + if (value === undefined) { + return { problems: [], settings } + } + if (!isRecord(value)) { + return { + problems: [ + { + field: undefined, + problem: `is ${JSON.stringify(value)}; set it to an object, or remove it.`, + value, + }, + ], + settings, + } + } + const fields = reachabilityFieldsOf(tool) + const problems: ReachabilityProblem[] = [] + for (const { 0: name, 1: fieldValue } of Object.entries(value)) { + const field = fields.find(f => f === name) + if (!field) { + problems.push({ + field: name, + problem: `is not a reachability setting of ${tool} builds, which take ${joinAnd(fields)}; remove it.`, + value: fieldValue, + }) + } else if ( + fieldValue === null || + REACHABILITY_FIELDS[field].takes(fieldValue) + ) { + Object.assign(settings, { [field]: fieldValue }) + } else { + problems.push({ + field, + problem: `is ${JSON.stringify(fieldValue)}; set it to ${REACHABILITY_FIELDS[field].expected}, to null to clear an inherited value, or remove it.`, + value: fieldValue, + }) + } + } + return { problems, settings } +} + +export function reachabilityFieldsOf( + tool: BuildTool, +): readonly ReachabilityField[] { + return REACHABILITY_FIELDS_BY_TOOL[tool] +} + export function socketJsonPath(dir: string): string { return displayPath(path.join(dir, SOCKET_JSON)) } diff --git a/src/commands/manifest/setup-manifest-config.mts b/src/commands/manifest/setup-manifest-config.mts index afc5d8a8d..708599dca 100644 --- a/src/commands/manifest/setup-manifest-config.mts +++ b/src/commands/manifest/setup-manifest-config.mts @@ -2,8 +2,13 @@ import fs from 'node:fs' import path from 'node:path' import { isDeepStrictEqual } from 'node:util' -import { reachabilityProblem } from './build-root-config.mts' +import { + DOTNET_RUNTIME_VERSION_FORMAT, + parseReachability, + reachabilityFieldsOf, +} from './build-root-config.mts' import { detectManifestActions } from './detect-manifest-actions.mts' +import { BUILD_TOOLS } from './scripts/build-tool.mts' import { REQUIREMENTS_TXT, SOCKET_JSON } from '../../constants.mts' import { debugDir } from '../../utils/debug.mts' import { logger } from '../../utils/logger.mts' @@ -18,13 +23,44 @@ import { import type { BuildTool } from './scripts/build-tool.mts' import type { CResult } from '../../types.mts' -import type { ManifestDefaults } from '../../utils/socket-json.mts' +import type { + ManifestDefaults, + ReachabilityDefaults, + ReachabilityField, +} from '../../utils/socket-json.mts' -export type ReachabilityStepOptions = { - // What the project inherits from ancestor socket.json files, as written. - inheritedReachability?: unknown +type ValuePrompts = { + ask: (current: string) => Promise + change: string + keep: string + set: string + unset: string } +const REACHABILITY_VALUE_PROMPTS = { + __proto__: null, + javaHome: { + ask: current => + askForJavaHome(current, 'What JDK should reachability analysis use?'), + change: 'Use a different Java for reachability analysis?', + keep: 'as the JDK for reachability analysis', + set: 'Set the JDK reachability analysis uses', + unset: 'Leave the JDK for reachability analysis unset', + }, + runtimeVersion: { + ask: askForRuntimeVersion, + change: + 'Start the reachability analysis of a framework-dependent .NET build on a given runtime?', + keep: 'as the .NET runtime', + set: 'Set the runtime the analysis starts on', + unset: + "Let the analysis take the runtime the build's dotnet rolls forward to", + }, +} satisfies { __proto__: null } & Record< + Exclude, + ValuePrompts +> + // As written. The wizard leaves invalid inherited values out of its defaults // and replaces invalid values only in this directory's socket.json. function inheritedReachabilityOf(cwd: string, tool: BuildTool): unknown { @@ -202,6 +238,11 @@ export async function setupManifestConfig( sockJson.defaults.manifest = {} } + const tool = BUILD_TOOLS.find(t => t === targetEco) + const inheritedReachability = tool + ? inheritedReachabilityOf(cwd, tool) + : undefined + let result: CResult<{ canceled: boolean }> switch (targetEco) { case 'conda': { @@ -216,7 +257,7 @@ export async function setupManifestConfig( sockJson.defaults.manifest.dotnet = {} } result = await setupDotnet(sockJson.defaults.manifest.dotnet, { - inheritedReachability: inheritedReachabilityOf(cwd, 'dotnet'), + inheritedReachability, }) break } @@ -225,7 +266,7 @@ export async function setupManifestConfig( sockJson.defaults.manifest.gradle = {} } result = await setupGradle(sockJson.defaults.manifest.gradle, { - inheritedReachability: inheritedReachabilityOf(cwd, 'gradle'), + inheritedReachability, }) break } @@ -234,7 +275,7 @@ export async function setupManifestConfig( sockJson.defaults.manifest.maven = {} } result = await setupMaven(sockJson.defaults.manifest.maven, { - inheritedReachability: inheritedReachabilityOf(cwd, 'maven'), + inheritedReachability, }) break } @@ -243,7 +284,7 @@ export async function setupManifestConfig( sockJson.defaults.manifest.sbt = {} } result = await setupSbt(sockJson.defaults.manifest.sbt, { - inheritedReachability: inheritedReachabilityOf(cwd, 'sbt'), + inheritedReachability, }) break } @@ -345,7 +386,8 @@ async function setupConda( export async function setupDotnet( config: ManifestDefaults<'dotnet'>, - options: ReachabilityStepOptions = {}, + // What the project inherits from ancestor socket.json files, as written. + { inheritedReachability }: { inheritedReachability?: unknown } = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'dotnet'))) { return canceledByUser() @@ -375,7 +417,7 @@ export async function setupDotnet( return canceledByUser() } - return await setupReachability('dotnet', config, options) + return await setupReachability('dotnet', config, inheritedReachability) } export async function setupGradle( @@ -384,8 +426,8 @@ export async function setupGradle( // pom-mode equivalent - skips the facts/pom question entirely. { factsOnly = false, - ...options - }: ReachabilityStepOptions & { factsOnly?: boolean } = {}, + inheritedReachability, + }: { factsOnly?: boolean; inheritedReachability?: unknown } = {}, ): Promise> { if ( applyAnswer(config, 'bin', await askForBin(config.bin || '', './gradlew')) @@ -435,7 +477,7 @@ export async function setupGradle( } if (generatesFacts) { - return await setupReachability('gradle', config, options) + return await setupReachability('gradle', config, inheritedReachability) } return notCanceled() @@ -443,7 +485,8 @@ export async function setupGradle( export async function setupMaven( config: ManifestDefaults<'maven'>, - options: ReachabilityStepOptions = {}, + // See setupDotnet's matching parameter. + { inheritedReachability }: { inheritedReachability?: unknown } = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'mvn'))) { return canceledByUser() @@ -480,7 +523,7 @@ export async function setupMaven( return canceledByUser() } - return await setupReachability('maven', config, options) + return await setupReachability('maven', config, inheritedReachability) } export async function setupSbt( @@ -488,8 +531,8 @@ export async function setupSbt( // See setupGradle's matching parameter for why. { factsOnly = false, - ...options - }: ReachabilityStepOptions & { factsOnly?: boolean } = {}, + inheritedReachability, + }: { factsOnly?: boolean; inheritedReachability?: unknown } = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'sbt'))) { return canceledByUser() @@ -565,7 +608,7 @@ export async function setupSbt( } if (generatesFacts) { - return await setupReachability('sbt', config, options) + return await setupReachability('sbt', config, inheritedReachability) } return notCanceled() @@ -691,14 +734,14 @@ async function askForRuntimeVersion( ): Promise { return await input({ message: - 'Which .NET runtime? major.minor, such as 8.0, starts on its latest installed patch; major.minor.patch[-prerelease], such as 8.0.11, on exactly that one.' + + `Which .NET runtime? Enter ${DOTNET_RUNTIME_VERSION_FORMAT}.` + (current ? ' (Backspace to leave default)' : ''), default: current, required: false, validate: (value: string) => !value || - !reachabilityProblem('dotnet', 'runtimeVersion', value) || - 'Enter major.minor, such as 8.0, or major.minor.patch[-prerelease], such as 8.0.11.', + !parseReachability('dotnet', { runtimeVersion: value }).problems.length || + `Enter ${DOTNET_RUNTIME_VERSION_FORMAT}.`, }) } @@ -783,73 +826,47 @@ async function askForIgnoreUnresolvedFlag( }) } -// The wizard warns about invalid local values and replaces them with the answers. -// Invalid inherited values need to be fixed in the socket.json that sets them. -function validReachability( +// The wizard replaces invalid local values with the answers. Invalid +// inherited values need to be fixed in the socket.json that sets them. +function warnInvalidReachability( tool: BuildTool, value: unknown, inherited: unknown, -): Record { - if (value === undefined) { - return {} - } - if (!isRecord(value)) { - if (!isDeepStrictEqual(value, inherited)) { - logger.warn( - `Replacing \`reachability\` (${JSON.stringify(value)}), which is not an object.`, - ) - } - return {} - } - const inheritedFields = isRecord(inherited) ? inherited : {} - const valid: Record = {} - for (const { 0: field, 1: setting } of Object.entries(value)) { - if (reachabilityProblem(tool, field, setting)) { - if ( - !Object.hasOwn(inheritedFields, field) || - !isDeepStrictEqual(setting, inheritedFields[field]) - ) { - logger.warn( - `Replacing \`reachability.${field}\` (${JSON.stringify(setting)}), which ${tool} builds cannot take.`, - ) - } - } else { - valid[field] = setting +): void { + for (const problem of parseReachability(tool, value).problems) { + const { field } = problem + const parent = + field === undefined + ? inherited + : isRecord(inherited) + ? inherited[field] + : undefined + if (isDeepStrictEqual(problem.value, parent)) { + continue } + logger.warn( + field === undefined + ? `Replacing \`reachability\` (${JSON.stringify(problem.value)}), which is not an object.` + : `Replacing \`reachability.${field}\` (${JSON.stringify(problem.value)}), which ${tool} builds cannot take.`, + ) } - return valid -} - -// The value in effect: this socket.json's own, null included, else the -// inherited one. -function effectiveValue( - own: Record, - inherited: Record, - field: string, -): unknown { - return Object.hasOwn(own, field) ? own[field] : inherited[field] } // Answering no to a value prompt keeps the effective value. // The wizard writes "none" to override an inherited "compile". async function setupReachability( tool: BuildTool, - config: { reachability?: unknown }, - { inheritedReachability }: ReachabilityStepOptions = {}, + config: { reachability?: ReachabilityDefaults | undefined }, + inheritedReachability: unknown, ): Promise> { - const reachability = validReachability( + warnInvalidReachability(tool, config.reachability, inheritedReachability) + const { settings: reachability } = parseReachability( tool, config.reachability, - inheritedReachability, - ) - // Invalid inherited values are their own socket.json's to fix. - const inherited = Object.fromEntries( - Object.entries( - isRecord(inheritedReachability) ? inheritedReachability : {}, - ).filter( - ({ 0: field, 1: value }) => !reachabilityProblem(tool, field, value), - ), ) + const { settings: inherited } = parseReachability(tool, inheritedReachability) + // As a scan merges them. + const effective = { ...inherited, ...reachability } const wantsBuild = await select({ message: @@ -866,48 +883,68 @@ async function setupReachability( description: 'Compile the project before reachability analysis', }, ], - default: effectiveValue(reachability, inherited, 'build') === 'compile', + default: effective.build === 'compile', }) - if (wantsBuild === undefined || wantsBuild === null) { + if (wantsBuild === undefined) { return canceledByUser() } if (wantsBuild) { - reachability['build'] = 'compile' - } else if (inherited['build'] === 'compile') { - reachability['build'] = 'none' + reachability.build = 'compile' + } else if (inherited.build === 'compile') { + reachability.build = 'none' } else { - delete reachability['build'] + delete reachability.build } - const value = - tool === 'dotnet' - ? await setupReachabilityValue( - reachability, - inherited, - 'runtimeVersion', - { - ask: askForRuntimeVersion, - change: - 'Start the reachability analysis of a framework-dependent .NET build on a given runtime?', - keep: 'as the .NET runtime', - set: 'Set the runtime the analysis starts on', - unset: - "Let the analysis take the runtime the build's dotnet rolls forward to", - }, - ) - : await setupReachabilityValue(reachability, inherited, 'javaHome', { - ask: current => - askForJavaHome( - current, - 'What JDK should reachability analysis use?', - ), - change: 'Use a different Java for reachability analysis?', - keep: 'as the JDK for reachability analysis', - set: 'Set the JDK reachability analysis uses', - unset: 'Leave the JDK for reachability analysis unset', - }) - if (!value.ok || value.data.canceled) { - return value + // Whether the prompt was canceled. + const askValue = async ( + field: Exclude, + ): Promise => { + const prompts = REACHABILITY_VALUE_PROMPTS[field] + const current = effective[field] + const wantsValue = await select({ + message: prompts.change, + choices: [ + { + name: 'no', + value: false, + description: current + ? `Keep ${current} ${prompts.keep}${Object.hasOwn(reachability, field) ? '' : ', as a parent socket.json sets it'}` + : prompts.unset, + }, + { + name: 'yes', + value: true, + description: prompts.set, + }, + ], + default: !!current, + }) + if (wantsValue === undefined) { + return true + } + if (!wantsValue) { + return false + } + const answer = await prompts.ask(current || '') + if (answer === undefined) { + return true + } + if (answer) { + reachability[field] = answer + } else if (reachability[field] || inherited[field]) { + // Clears the value rather than inheriting it again. + reachability[field] = null + } else { + delete reachability[field] + } + return false + } + for (const field of reachabilityFieldsOf(tool)) { + // eslint-disable-next-line no-await-in-loop + if (field !== 'build' && (await askValue(field))) { + return canceledByUser() + } } if (Object.keys(reachability).length) { @@ -918,57 +955,6 @@ async function setupReachability( return notCanceled() } -async function setupReachabilityValue( - reachability: Record, - inherited: Record, - field: 'javaHome' | 'runtimeVersion', - prompts: { - ask: (current: string) => Promise - change: string - keep: string - set: string - unset: string - }, -): Promise> { - const effective = effectiveValue(reachability, inherited, field) as - | string - | null - | undefined - const wantsValue = await select({ - message: prompts.change, - choices: [ - { - name: 'no', - value: false, - description: effective - ? `Keep ${effective} ${prompts.keep}${Object.hasOwn(reachability, field) ? '' : ', as a parent socket.json sets it'}` - : prompts.unset, - }, - { - name: 'yes', - value: true, - description: prompts.set, - }, - ], - default: !!effective, - }) - if (wantsValue === undefined || wantsValue === null) { - return canceledByUser() - } - if (!wantsValue) { - return notCanceled() - } - const answer = await prompts.ask(effective || '') - if (applyAnswer(reachability as Record, field, answer)) { - return canceledByUser() - } - // A blank answer writes null to clear an inherited value. - if (answer === '' && inherited[field]) { - reachability[field] = null - } - return notCanceled() -} - // Prompts for the facts-only options every facts generator shares: the config // include/exclude filters and --ignore-unresolved. Mutates `config` in place. async function setupFactsOptions( diff --git a/src/commands/manifest/setup-recursive-manifest-config.mts b/src/commands/manifest/setup-recursive-manifest-config.mts index cc11a4fef..6aa7dc63e 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.mts @@ -64,7 +64,6 @@ import type { import type { BuildRoot, Membership } from './discover-manifest-roots.mts' import type { LoadedBuild } from './load-build.mts' import type { BuildTool } from './scripts/build-tool.mts' -import type { ReachabilityStepOptions } from './setup-manifest-config.mts' import type { CResult } from '../../types.mts' import type { ManifestDefaults, @@ -484,9 +483,11 @@ async function configureBuild( } const seeded = Object.keys(seed) - const result = await runEcosystemWizard(ecosystem, seed, { - inheritedReachability: inherited['reachability'], - }) + const result = await runEcosystemWizard( + ecosystem, + seed, + inherited['reachability'], + ) if (!result.ok || result.data.canceled) { return result } @@ -835,23 +836,27 @@ async function reviewBuild( async function runEcosystemWizard( ecosystem: BuildTool, config: Record, - options: ReachabilityStepOptions = {}, + inheritedReachability: unknown, ): Promise> { if (ecosystem === 'dotnet') { - return await setupDotnet(config as ManifestDefaults<'dotnet'>, options) + return await setupDotnet(config as ManifestDefaults<'dotnet'>, { + inheritedReachability, + }) } if (ecosystem === 'gradle') { return await setupGradle(config as ManifestDefaults<'gradle'>, { - ...options, factsOnly: true, + inheritedReachability, }) } if (ecosystem === 'maven') { - return await setupMaven(config as ManifestDefaults<'maven'>, options) + return await setupMaven(config as ManifestDefaults<'maven'>, { + inheritedReachability, + }) } return await setupSbt(config as ManifestDefaults<'sbt'>, { - ...options, factsOnly: true, + inheritedReachability, }) } @@ -926,9 +931,11 @@ async function setupRootDefaults( ecosystem, ) // eslint-disable-next-line no-await-in-loop - const result = await runEcosystemWizard(ecosystem, section, { - inheritedReachability: inherited['reachability'], - }) + const result = await runEcosystemWizard( + ecosystem, + section, + inherited['reachability'], + ) if (!result.ok || result.data.canceled) { return result } From fdbbcb4c32f1de79abd49a7aeaaeb1d87ed41371 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Fri, 27 Nov 2026 10:31:35 +0100 Subject: [PATCH 06/10] Share the wizard tests' prompt answering --- .../manifest/setup-manifest-config.test.mts | 383 ++++++------------ .../setup-recursive-manifest-config.test.mts | 61 +-- 2 files changed, 155 insertions(+), 289 deletions(-) diff --git a/src/commands/manifest/setup-manifest-config.test.mts b/src/commands/manifest/setup-manifest-config.test.mts index a9ab9f08d..f4532d65a 100644 --- a/src/commands/manifest/setup-manifest-config.test.mts +++ b/src/commands/manifest/setup-manifest-config.test.mts @@ -29,6 +29,58 @@ import { writeSocketJson, } from '../../utils/socket-json.mts' +const BUILD_QUESTION = + 'Build project before reachability analysis? Note: A failed build fails the scan.' +const ECOSYSTEM_QUESTION = 'Select ecosystem manifest generator to configure' +const JDK_PROMPT = 'What JDK should reachability analysis use?' +const JDK_QUESTION = 'Use a different Java for reachability analysis?' +const RUNTIME_PROMPT = 'Which .NET runtime?' +const RUNTIME_QUESTION = + 'Start the reachability analysis of a framework-dependent .NET build on a given runtime?' +const WRITE_QUESTION = 'Do you want to write the new config' + +type Prompt = { + default?: unknown + message: string + validate?: ((value: string) => unknown) | undefined +} + +// Answers each prompt whose message starts with a key of `answers` with its +// value, and every other prompt with its default. Records every prompt's +// message, and each answered prompt under its key. +function answerPrompts(answers: Record = {}): { + asked: Record + messages: string[] + // The defaults the prompts answered under `key` showed. + shown: (key: string) => unknown[] +} { + const asked: Record = {} + const messages: string[] = [] + const answer = (prompt: Prompt): any => { + messages.push(prompt.message) + const key = Object.keys(answers).find(k => prompt.message.startsWith(k)) + if (key === undefined) { + return prompt.default ?? '' + } + ;(asked[key] ??= []).push(prompt) + return answers[key] + } + vi.mocked(input).mockImplementation(async prompt => answer(prompt)) + vi.mocked(select).mockImplementation(async prompt => answer(prompt)) + return { + asked, + messages, + shown: key => (asked[key] ?? []).map(prompt => prompt.default), + } +} + +afterEach(() => { + vi.restoreAllMocks() + answerPrompts() + vi.mocked(input).mockClear() + vi.mocked(select).mockClear() +}) + describe('setup wizards', () => { it.for([ ['dotnet', setupDotnet], @@ -72,11 +124,7 @@ describe('setupGradle/setupMaven/setupSbt', () => { }) it('asks the facts/pom question by default', async () => { - const messages: string[] = [] - vi.mocked(select).mockImplementation(async ({ default: def, message }) => { - messages.push(message) - return def ?? '' - }) + const { messages } = answerPrompts() await setupGradle({}) await setupSbt({}) @@ -85,11 +133,7 @@ describe('setupGradle/setupMaven/setupSbt', () => { }) it('skips the facts/pom question entirely when factsOnly is set, going straight to facts-only options', async () => { - const messages: string[] = [] - vi.mocked(select).mockImplementation(async ({ default: def, message }) => { - messages.push(message) - return def ?? '' - }) + const { messages } = answerPrompts() await setupGradle({}, { factsOnly: true }) await setupSbt({}, { factsOnly: true }) @@ -102,29 +146,6 @@ describe('setupGradle/setupMaven/setupSbt', () => { }) describe('reachability step', () => { - const REACHABILITY_QUESTION = - 'Use a different Java for reachability analysis?' - - // Answers the JDK choice with `wantsJavaHome` and the path prompt with `javaHome`. - // Other prompts keep their defaults. - function answerReachability(wantsJavaHome: boolean, javaHome = ''): void { - vi.mocked(select).mockImplementation(async ({ default: def, message }) => - message === REACHABILITY_QUESTION ? wantsJavaHome : (def ?? ''), - ) - vi.mocked(input).mockImplementation(async ({ default: def, message }) => - message.startsWith('What JDK should reachability analysis use?') - ? javaHome - : (def ?? ''), - ) - } - - afterEach(() => { - vi.mocked(input).mockReset() - vi.mocked(input).mockImplementation(async ({ default: def }) => def ?? '') - vi.mocked(select).mockReset() - vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') - }) - it.for([ ['gradle', setupGradle], ['maven', setupMaven], @@ -132,7 +153,7 @@ describe('reachability step', () => { ] as const)( '%s writes the JDK named after a yes to reachability.javaHome', async ({ 1: setup }) => { - answerReachability(true, '$JAVA17_HOME') + answerPrompts({ [JDK_PROMPT]: '$JAVA17_HOME', [JDK_QUESTION]: true }) const config: Record = { javaHome: '/opt/jdk-11' } const result = await setup(config) @@ -146,21 +167,20 @@ describe('reachability step', () => { ) it('writes nothing on a no and never asks for the JDK', async () => { - answerReachability(false, '/never-asked') + const { asked } = answerPrompts({ + [JDK_PROMPT]: '/never-asked', + [JDK_QUESTION]: false, + }) const config: Record = {} await setupMaven(config) expect(config).toEqual({}) - expect( - vi - .mocked(input) - .mock.calls.some(([{ message }]) => message.includes('reachability')), - ).toBe(false) + expect(asked[JDK_PROMPT]).toBeUndefined() }) it('leaves a value it shows as is on a no, neither clearing nor restating it', async () => { - answerReachability(false) + answerPrompts({ [JDK_QUESTION]: false }) const config: Record = { reachability: { javaHome: '/opt/jdk-17' }, } @@ -195,105 +215,64 @@ describe('reachability step', () => { ] as const)( 'labels the no to the JDK %j, inheriting %j, by what it does', async ({ 0: reachability, 1: inherited, 2: label }) => { - answerReachability(false) + const { asked } = answerPrompts({ [JDK_QUESTION]: false }) await setupMaven( { reachability: { ...reachability } }, { inheritedReachability: inherited }, ) - const asked = vi - .mocked(select) - .mock.calls.find(([{ message }]) => message === REACHABILITY_QUESTION) - expect( - asked?.[0].choices.find( - choice => typeof choice === 'object' && choice.name === 'no', - ), - ).toMatchObject({ description: label }) + expect(asked[JDK_QUESTION]).toEqual([ + expect.objectContaining({ + choices: expect.arrayContaining([ + expect.objectContaining({ description: label, name: 'no' }), + ]), + }), + ]) }, ) - it('offers the shown value as the default and clears it on a blank answer', async () => { - vi.mocked(select).mockImplementation(async ({ default: def, message }) => - message === REACHABILITY_QUESTION ? true : (def ?? ''), - ) - const shown: unknown[] = [] - vi.mocked(input).mockImplementation(async ({ default: def, message }) => { - if (message.startsWith('What JDK should reachability analysis use?')) { - shown.push(def) - return '' - } - return def ?? '' - }) - const config: Record = { - reachability: { javaHome: '/opt/jdk-17' }, - } - - await setupGradle(config, { factsOnly: true }) - - expect(shown).toEqual(['/opt/jdk-17']) - expect(config['reachability']).toEqual({ javaHome: null }) - }) - - it('offers an inherited JDK as the default and clears it on a blank answer', async () => { - vi.mocked(select).mockImplementation(async ({ default: def, message }) => - message === REACHABILITY_QUESTION ? true : (def ?? ''), - ) - const shown: unknown[] = [] - vi.mocked(input).mockImplementation(async ({ default: def, message }) => { - if (message.startsWith('What JDK should reachability analysis use?')) { - shown.push(def) - return '' - } - return def ?? '' - }) - const config: Record = {} - - await setupMaven(config, { + it.for([ + { + name: 'the shown value', + config: { reachability: { javaHome: '/opt/jdk-17' } }, + inheritedReachability: undefined, + shown: '/opt/jdk-17', + }, + { + name: 'an inherited JDK', + config: {}, inheritedReachability: { javaHome: '/opt/jdk-11' }, - }) + shown: '/opt/jdk-11', + }, + ])( + 'offers $name as the default and clears it on a blank answer', + async ({ config, inheritedReachability, shown }) => { + const { asked } = answerPrompts({ + [JDK_PROMPT]: '', + [JDK_QUESTION]: true, + }) + const written: Record = structuredClone(config) - expect(shown).toEqual(['/opt/jdk-11']) - expect(config['reachability']).toEqual({ javaHome: null }) - }) + await setupMaven(written, { inheritedReachability }) + + expect(asked[JDK_PROMPT]?.map(p => p.default)).toEqual([shown]) + expect(written['reachability']).toEqual({ javaHome: null }) + }, + ) it('does not ask in pom mode, where no facts reach a reachability run', async () => { - const messages: string[] = [] - vi.mocked(select).mockImplementation(async ({ default: def, message }) => { - messages.push(message) - return def ?? '' - }) + const { messages } = answerPrompts() await setupGradle({ facts: false }) await setupSbt({ facts: false }) - expect(messages).not.toContain(REACHABILITY_QUESTION) + expect(messages).not.toContain(BUILD_QUESTION) + expect(messages).not.toContain(JDK_QUESTION) }) }) describe('reachability build step', () => { - const BUILD_QUESTION = - 'Build project before reachability analysis? Note: A failed build fails the scan.' - - // Answers the build prompt with `wantsBuild` and accepts the other defaults. - // Returns the build prompt's displayed default for each call. - function answerBuild(wantsBuild: boolean): unknown[] { - const shown: unknown[] = [] - vi.mocked(select).mockImplementation(async ({ default: def, message }) => { - if (message === BUILD_QUESTION) { - shown.push(def) - return wantsBuild - } - return def ?? '' - }) - return shown - } - - afterEach(() => { - vi.mocked(select).mockReset() - vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') - }) - it.for([ ['dotnet', setupDotnet], ['gradle', setupGradle], @@ -302,7 +281,7 @@ describe('reachability build step', () => { ] as const)( '%s writes compile to reachability.build after a yes', async ({ 1: setup }) => { - answerBuild(true) + answerPrompts({ [BUILD_QUESTION]: true }) const config: Record = {} const result = await setup(config) @@ -320,7 +299,7 @@ describe('reachability build step', () => { ] as const)( '%s leaves reachability.build unset after a no at the top level, never writing none', async ({ 1: setup }) => { - answerBuild(false) + answerPrompts({ [BUILD_QUESTION]: false }) const config: Record = {} await setup(config) @@ -337,20 +316,20 @@ describe('reachability build step', () => { ] as const)( '%s writes none after a no when the project inherits compile', async ({ 1: setup }) => { - const shown = answerBuild(false) + const { shown } = answerPrompts({ [BUILD_QUESTION]: false }) const config: Record = { reachability: { build: 'compile' }, } await setup(config, { inheritedReachability: { build: 'compile' } }) - expect(shown).toEqual([true]) + expect(shown(BUILD_QUESTION)).toEqual([true]) expect(config).toEqual({ reachability: { build: 'none' } }) }, ) it('leaves the build unset after a no when the project inherits none', async () => { - answerBuild(false) + answerPrompts({ [BUILD_QUESTION]: false }) const config: Record = { reachability: { build: 'none' } } await setupGradle(config, { inheritedReachability: { build: 'none' } }) @@ -359,33 +338,29 @@ describe('reachability build step', () => { }) it('unsets a build it shows as the default after a no, keeping the JDK', async () => { - const shown = answerBuild(false) + const { shown } = answerPrompts({ [BUILD_QUESTION]: false }) const config: Record = { reachability: { build: 'compile', javaHome: '/opt/jdk-17' }, } await setupMaven(config) - expect(shown).toEqual([true]) + expect(shown(BUILD_QUESTION)).toEqual([true]) expect(config['reachability']).toEqual({ javaHome: '/opt/jdk-17' }) }) it('removes a written none after a no', async () => { - const shown = answerBuild(false) + const { shown } = answerPrompts({ [BUILD_QUESTION]: false }) const config: Record = { reachability: { build: 'none' } } await setupDotnet(config) - expect(shown).toEqual([false]) + expect(shown(BUILD_QUESTION)).toEqual([false]) expect(config).toEqual({}) }) it('never asks dotnet for a reachability JDK', async () => { - const messages: string[] = [] - vi.mocked(select).mockImplementation(async ({ default: def, message }) => { - messages.push(message) - return message === BUILD_QUESTION ? true : (def ?? '') - }) + const { messages } = answerPrompts({ [BUILD_QUESTION]: true }) const config: Record = {} await setupDotnet(config) @@ -394,51 +369,11 @@ describe('reachability build step', () => { expect(messages.some(m => m.includes('Java'))).toBe(false) expect(config).toEqual({ reachability: { build: 'compile' } }) }) - - it('does not ask in pom mode, where no facts reach a reachability run', async () => { - const messages: string[] = [] - vi.mocked(select).mockImplementation(async ({ default: def, message }) => { - messages.push(message) - return def ?? '' - }) - - await setupGradle({ facts: false }) - await setupSbt({ facts: false }) - - expect(messages).not.toContain(BUILD_QUESTION) - }) }) describe('reachability runtime step', () => { - const RUNTIME_QUESTION = - 'Start the reachability analysis of a framework-dependent .NET build on a given runtime?' - - // Answers the runtime choice with `wantsRuntime` and the version prompt with `runtimeVersion`. - // Records each runtime prompt. - function answerRuntime(wantsRuntime: boolean, runtimeVersion = '') { - const asked: Array[0]> = [] - vi.mocked(select).mockImplementation(async ({ default: def, message }) => - message === RUNTIME_QUESTION ? wantsRuntime : (def ?? ''), - ) - vi.mocked(input).mockImplementation(async config => { - if (config.message.startsWith('Which .NET runtime?')) { - asked.push(config) - return runtimeVersion - } - return config.default ?? '' - }) - return asked - } - - afterEach(() => { - vi.mocked(input).mockReset() - vi.mocked(input).mockImplementation(async ({ default: def }) => def ?? '') - vi.mocked(select).mockReset() - vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') - }) - it('writes the runtime named after a yes to reachability.runtimeVersion', async () => { - answerRuntime(true, '8.0') + answerPrompts({ [RUNTIME_PROMPT]: '8.0', [RUNTIME_QUESTION]: true }) const config: Record = {} expect(await setupDotnet(config)).toEqual({ @@ -455,11 +390,14 @@ describe('reachability runtime step', () => { ['net8.0', false], ['8', false], ] as const)('takes %j as an answer: %j', async ({ 0: answer, 1: valid }) => { - const asked = answerRuntime(true, '8.0') + const { asked } = answerPrompts({ + [RUNTIME_PROMPT]: '8.0', + [RUNTIME_QUESTION]: true, + }) await setupDotnet({}) - const result = await asked[0]!.validate!(answer) + const result = await asked[RUNTIME_PROMPT]?.[0]?.validate?.(answer) if (valid) { expect(result).toBe(true) } else { @@ -468,23 +406,22 @@ describe('reachability runtime step', () => { }) it('offers an inherited runtime as the default and clears it on a blank answer', async () => { - const asked = answerRuntime(true, '') + const { shown } = answerPrompts({ + [RUNTIME_PROMPT]: '', + [RUNTIME_QUESTION]: true, + }) const config: Record = {} await setupDotnet(config, { inheritedReachability: { runtimeVersion: '9.0' }, }) - expect(asked.map(({ default: def }) => def)).toEqual(['9.0']) + expect(shown(RUNTIME_PROMPT)).toEqual(['9.0']) expect(config).toEqual({ reachability: { runtimeVersion: null } }) }) it('never asks a JVM build tool for a .NET runtime', async () => { - const messages: string[] = [] - vi.mocked(select).mockImplementation(async ({ default: def, message }) => { - messages.push(message) - return def ?? '' - }) + const { messages } = answerPrompts() await setupMaven({}) @@ -493,12 +430,6 @@ describe('reachability runtime step', () => { }) describe('reachability settings written invalid', () => { - afterEach(() => { - vi.mocked(select).mockReset() - vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') - vi.restoreAllMocks() - }) - it.for([ [ 'maven', @@ -537,20 +468,14 @@ describe('reachability settings written invalid', () => { ) it('ignores an invalid inherited value for its defaults', async () => { - const shown: unknown[] = [] - vi.mocked(select).mockImplementation(async ({ default: def, message }) => { - if (message.startsWith('Build project before reachability analysis?')) { - shown.push(def) - } - return def ?? '' - }) + const { shown } = answerPrompts({ [BUILD_QUESTION]: false }) const config: Record = {} await setupGradle(config, { inheritedReachability: { build: 'always', javaHome: 17 }, }) - expect(shown).toEqual([false]) + expect(shown(BUILD_QUESTION)).toEqual([false]) expect(config).toEqual({}) }) @@ -570,8 +495,6 @@ describe('reachability settings written invalid', () => { }) describe('setupManifestConfig', () => { - const BUILD_QUESTION = - 'Build project before reachability analysis? Note: A failed build fails the scan.' let parent = '' beforeEach(async () => { @@ -580,10 +503,6 @@ describe('setupManifestConfig', () => { ) }) afterEach(async () => { - vi.mocked(select).mockReset() - vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') - vi.mocked(input).mockReset() - vi.mocked(input).mockImplementation(async ({ default: def }) => def ?? '') await fs.rm(parent, { recursive: true, force: true }) }) @@ -594,19 +513,10 @@ describe('setupManifestConfig', () => { }) const cwd = path.join(parent, 'app') await fs.mkdir(cwd) - const shown: unknown[] = [] - vi.mocked(select).mockImplementation(async ({ default: def, message }) => { - if (message === 'Select ecosystem manifest generator to configure') { - return 'maven' - } - if (message === BUILD_QUESTION) { - shown.push(def) - return false - } - if (message.startsWith('Do you want to write the new config')) { - return true - } - return def ?? '' + const { shown } = answerPrompts({ + [BUILD_QUESTION]: false, + [ECOSYSTEM_QUESTION]: 'maven', + [WRITE_QUESTION]: true, }) vi.spyOn(logger, 'log').mockImplementation(() => logger) vi.spyOn(logger, 'info').mockImplementation(() => logger) @@ -616,7 +526,7 @@ describe('setupManifestConfig', () => { data: undefined, }) - expect(shown).toEqual([true]) + expect(shown(BUILD_QUESTION)).toEqual([true]) const written = JSON.parse( await fs.readFile(path.join(cwd, 'socket.json'), 'utf8'), ) @@ -647,23 +557,12 @@ describe('setupManifestConfig', () => { }) const cwd = path.join(parent, 'app') await fs.mkdir(cwd) - vi.mocked(select).mockImplementation(async ({ default: def, message }) => { - if (message === 'Select ecosystem manifest generator to configure') { - return 'maven' - } - if (message === 'Use a different Java for reachability analysis?') { - return wantsJavaHome - } - if (message.startsWith('Do you want to write the new config')) { - return true - } - return def ?? '' + answerPrompts({ + [ECOSYSTEM_QUESTION]: 'maven', + [JDK_PROMPT]: '', + [JDK_QUESTION]: wantsJavaHome, + [WRITE_QUESTION]: true, }) - vi.mocked(input).mockImplementation(async ({ default: def, message }) => - message.startsWith('What JDK should reachability analysis use?') - ? '' - : (def ?? ''), - ) vi.spyOn(logger, 'log').mockImplementation(() => logger) vi.spyOn(logger, 'info').mockImplementation(() => logger) @@ -691,8 +590,6 @@ describe('setupManifestConfig with an invalid ancestor socket.json', () => { ) }) afterEach(async () => { - vi.mocked(select).mockReset() - vi.mocked(select).mockImplementation(async ({ default: def }) => def ?? '') await fs.rm(parent, { recursive: true, force: true }) }) @@ -708,15 +605,7 @@ describe('setupManifestConfig with an invalid ancestor socket.json', () => { }, }), ) - vi.mocked(select).mockImplementation(async ({ default: def, message }) => { - if (message === 'Select ecosystem manifest generator to configure') { - return 'maven' - } - if (message.startsWith('Do you want to write the new config')) { - return true - } - return def ?? '' - }) + answerPrompts({ [ECOSYSTEM_QUESTION]: 'maven', [WRITE_QUESTION]: true }) vi.spyOn(logger, 'log').mockImplementation(() => logger) vi.spyOn(logger, 'info').mockImplementation(() => logger) vi.spyOn(logger, 'warn').mockImplementation(() => logger) @@ -735,11 +624,7 @@ describe('setupManifestConfig with an invalid ancestor socket.json', () => { it('exits without reading it when no build tool is chosen', async () => { const cwd = path.join(parent, 'app') await fs.mkdir(cwd) - vi.mocked(select).mockImplementation(async ({ default: def, message }) => - message === 'Select ecosystem manifest generator to configure' - ? '' - : (def ?? ''), - ) + answerPrompts({ [ECOSYSTEM_QUESTION]: '' }) vi.spyOn(logger, 'log').mockImplementation(() => logger) vi.spyOn(logger, 'info').mockImplementation(() => logger) diff --git a/src/commands/manifest/setup-recursive-manifest-config.test.mts b/src/commands/manifest/setup-recursive-manifest-config.test.mts index 261cedcc5..8d6acd010 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.test.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.test.mts @@ -205,6 +205,20 @@ describe('setupRecursiveManifestConfig', () => { } return rule[1] as never }) + // Runs the real Maven wizard, answering the prompts `answers` matches and + // every other one with its default. + const useRealMavenWizard = async (answers: Answers) => { + const actual = await vi.importActual< + typeof import('./setup-manifest-config.mts') + >('./setup-manifest-config.mts') + vi.mocked(setupMaven).mockImplementation(actual.setupMaven) + vi.mocked(input).mockImplementation(async ({ default: def }) => def ?? '') + vi.mocked(select).mockImplementation(async ({ default: def, message }) => { + asked.push(message) + const rule = answers.find(({ 0: start }) => message.startsWith(start)) + return (rule ? rule[1] : (def ?? '')) as never + }) + } beforeEach(async () => { repo = await fs.realpath( @@ -615,11 +629,6 @@ describe('setupRecursiveManifestConfig', () => { }) it('loads and configures a build whose socket.json sets an invalid reachability value, replacing it', async () => { - const actual = await vi.importActual< - typeof import('./setup-manifest-config.mts') - >('./setup-manifest-config.mts') - vi.mocked(setupMaven).mockImplementation(actual.setupMaven) - vi.mocked(input).mockImplementation(async ({ default: def }) => def ?? '') vi.spyOn(logger, 'warn').mockImplementation(() => logger) await writeSettings('legacy', { maven: { @@ -628,17 +637,13 @@ describe('setupRecursiveManifestConfig', () => { }, }) loads({ 'pom.xml': ['api'], 'legacy/pom.xml': ['old'] }) - const rules: Answers = [ + await useRealMavenWizard([ ['This project (maven)', 'inherit'], ['Review the', true], ['legacy (maven)', 'configure'], ['legacy/tool (maven)', 'inherit'], ['Write it?', true], - ] - vi.mocked(select).mockImplementation(async ({ default: def, message }) => { - const rule = rules.find(({ 0: start }) => message.startsWith(start)) - return (rule ? rule[1] : (def ?? '')) as never - }) + ]) expect(await setupRecursiveManifestConfig(repo, false)).toEqual({ ok: true, @@ -653,27 +658,17 @@ describe('setupRecursiveManifestConfig', () => { // Runs the real Maven wizard for the defaults of legacy, which holds only // nested projects, accepting every default under a parent's reachability. async function acceptDefaultsUnder(): Promise { - const actual = await vi.importActual< - typeof import('./setup-manifest-config.mts') - >('./setup-manifest-config.mts') - vi.mocked(setupMaven).mockImplementation(actual.setupMaven) - vi.mocked(input).mockImplementation(async ({ default: def }) => def ?? '') await fs.rm(file('legacy/pom.xml')) await writeSettings('.', { maven: { reachability: { build: 'compile', javaHome: '/opt/jdk-17' } }, }) loads({}) - const rules: Answers = [ + await useRealMavenWizard([ ['Configure Maven defaults for any nested projects?', true], ['old (maven)', 'inherit'], ['tool (maven)', 'inherit'], ['Write it?', true], - ] - vi.mocked(select).mockImplementation(async ({ default: def, message }) => { - asked.push(message) - const rule = rules.find(({ 0: start }) => message.startsWith(start)) - return (rule ? rule[1] : (def ?? '')) as never - }) + ]) const result = await setupRecursiveManifestConfig(file('legacy'), false) expect(result).toEqual({ ok: true, data: { canceled: false } }) @@ -707,33 +702,19 @@ describe('setupRecursiveManifestConfig', () => { async function configureUnder( parentBuild: 'compile' | 'none' | undefined, ): Promise { - const actual = await vi.importActual< - typeof import('./setup-manifest-config.mts') - >('./setup-manifest-config.mts') - vi.mocked(setupMaven).mockImplementation(actual.setupMaven) - vi.mocked(input).mockImplementation(async ({ default: def }) => def ?? '') await writeSettings( '.', parentBuild ? { maven: { reachability: { build: parentBuild } } } : {}, ) loads({ 'pom.xml': ['api'], 'legacy/pom.xml': ['old'] }) - const rules: Answers = [ + await useRealMavenWizard([ + [BUILD_QUESTION, false], ['This project (maven)', 'inherit'], ['Review the', true], ['legacy (maven)', 'configure'], ['legacy/tool (maven)', 'inherit'], ['Write it?', true], - ] - vi.mocked(select).mockImplementation( - async ({ default: def, message }) => { - asked.push(message) - if (message === BUILD_QUESTION) { - return false as never - } - const rule = rules.find(({ 0: start }) => message.startsWith(start)) - return (rule ? rule[1] : (def ?? '')) as never - }, - ) + ]) const result = await setupRecursiveManifestConfig(repo, false) expect(result).toEqual({ ok: true, data: { canceled: false } }) From 0843f99ab6ebe47268f59b6f2ca7f5c8c4082090 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Fri, 27 Nov 2026 10:40:34 +0100 Subject: [PATCH 07/10] Inherit nothing at the filesystem root in the recursive wizard The parent of / is / itself, so the cascade a socket.json there was compared against held its own settings, and the wizard dropped every field it kept as inherited. --- .../manifest/setup-recursive-manifest-config.mts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/commands/manifest/setup-recursive-manifest-config.mts b/src/commands/manifest/setup-recursive-manifest-config.mts index 6aa7dc63e..b8b82c2f9 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.mts @@ -48,6 +48,7 @@ import { logger } from '../../utils/logger.mts' import { isRecord } from '../../utils/objects.mts' import { select } from '../../utils/prompts.mts' import { + getDefaultSocketJson, mergeSocketJsonChain, readOrDefaultSocketJson, readSocketJsonChain, @@ -339,6 +340,13 @@ function draftCascade(draft: SettingsDraft, dir: string): SocketJson { return mergeSocketJsonChain(draftChain(draft, dir)) } +// What `dir`'s own socket.json inherits; nothing at the filesystem root, the +// parent of itself. +function draftParentCascade(draft: SettingsDraft, dir: string): SocketJson { + const parent = path.dirname(dir) + return parent === dir ? getDefaultSocketJson() : draftCascade(draft, parent) +} + function resolveDraftSettings( draft: SettingsDraft, ecosystem: BuildTool, @@ -472,7 +480,9 @@ async function configureBuild( ? { ...builds[key] } : { ...getEcosystemSection(own, ecosystem) } const inherited = getEcosystemSection( - draftCascade(draft, intoEntry ? root.dir : path.dirname(root.dir)), + intoEntry + ? draftCascade(draft, root.dir) + : draftParentCascade(draft, root.dir), ecosystem, ) const seed: Record = { @@ -927,7 +937,7 @@ async function setupRootDefaults( const before = getEcosystemSection(own, ecosystem) const section = { ...before } const inherited = getEcosystemSection( - draftCascade(draft, path.dirname(cwd)), + draftParentCascade(draft, cwd), ecosystem, ) // eslint-disable-next-line no-await-in-loop From 907797f43321e34b13c263f45f1bf6ed23fe3542 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Fri, 27 Nov 2026 10:46:40 +0100 Subject: [PATCH 08/10] Parse the wizard's own reachability value once The warning takes the parse's problems, the step's options keep one local type, and what a directory inherits is its chain without its own socket.json, which needs no case for the filesystem root. --- .../manifest/setup-manifest-config.mts | 58 +++++++++---------- .../setup-recursive-manifest-config.mts | 10 ++-- 2 files changed, 33 insertions(+), 35 deletions(-) diff --git a/src/commands/manifest/setup-manifest-config.mts b/src/commands/manifest/setup-manifest-config.mts index 708599dca..06b042b81 100644 --- a/src/commands/manifest/setup-manifest-config.mts +++ b/src/commands/manifest/setup-manifest-config.mts @@ -21,6 +21,7 @@ import { writeSocketJson, } from '../../utils/socket-json.mts' +import type { ReachabilityProblem } from './build-root-config.mts' import type { BuildTool } from './scripts/build-tool.mts' import type { CResult } from '../../types.mts' import type { @@ -29,6 +30,11 @@ import type { ReachabilityField, } from '../../utils/socket-json.mts' +type ReachabilityStepOptions = { + // What the project inherits from ancestor socket.json files, as written. + inheritedReachability?: unknown +} + type ValuePrompts = { ask: (current: string) => Promise change: string @@ -65,12 +71,9 @@ const REACHABILITY_VALUE_PROMPTS = { // and replaces invalid values only in this directory's socket.json. function inheritedReachabilityOf(cwd: string, tool: BuildTool): unknown { const dir = path.resolve(cwd) - const parent = path.dirname(dir) - return parent === dir - ? undefined - : mergeSocketJsonChain(readSocketJsonChain(parent)).defaults?.manifest?.[ - tool - ]?.reachability + return mergeSocketJsonChain( + readSocketJsonChain(dir).filter(file => file.dir !== dir), + ).defaults?.manifest?.[tool]?.reachability } // Whether the prompt was canceled. A blank answer clears a value set before @@ -386,8 +389,7 @@ async function setupConda( export async function setupDotnet( config: ManifestDefaults<'dotnet'>, - // What the project inherits from ancestor socket.json files, as written. - { inheritedReachability }: { inheritedReachability?: unknown } = {}, + { inheritedReachability }: ReachabilityStepOptions = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'dotnet'))) { return canceledByUser() @@ -427,7 +429,7 @@ export async function setupGradle( { factsOnly = false, inheritedReachability, - }: { factsOnly?: boolean; inheritedReachability?: unknown } = {}, + }: ReachabilityStepOptions & { factsOnly?: boolean } = {}, ): Promise> { if ( applyAnswer(config, 'bin', await askForBin(config.bin || '', './gradlew')) @@ -485,8 +487,7 @@ export async function setupGradle( export async function setupMaven( config: ManifestDefaults<'maven'>, - // See setupDotnet's matching parameter. - { inheritedReachability }: { inheritedReachability?: unknown } = {}, + { inheritedReachability }: ReachabilityStepOptions = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'mvn'))) { return canceledByUser() @@ -532,7 +533,7 @@ export async function setupSbt( { factsOnly = false, inheritedReachability, - }: { factsOnly?: boolean; inheritedReachability?: unknown } = {}, + }: ReachabilityStepOptions & { factsOnly?: boolean } = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'sbt'))) { return canceledByUser() @@ -830,25 +831,22 @@ async function askForIgnoreUnresolvedFlag( // inherited values need to be fixed in the socket.json that sets them. function warnInvalidReachability( tool: BuildTool, - value: unknown, + problems: readonly ReachabilityProblem[], inherited: unknown, ): void { - for (const problem of parseReachability(tool, value).problems) { - const { field } = problem - const parent = - field === undefined - ? inherited - : isRecord(inherited) - ? inherited[field] - : undefined - if (isDeepStrictEqual(problem.value, parent)) { - continue + for (const { field, value } of problems) { + let parent: unknown + let message: string + if (field === undefined) { + parent = inherited + message = `Replacing \`reachability\` (${JSON.stringify(value)}), which is not an object.` + } else { + parent = isRecord(inherited) ? inherited[field] : undefined + message = `Replacing \`reachability.${field}\` (${JSON.stringify(value)}), which ${tool} builds cannot take.` + } + if (!isDeepStrictEqual(value, parent)) { + logger.warn(message) } - logger.warn( - field === undefined - ? `Replacing \`reachability\` (${JSON.stringify(problem.value)}), which is not an object.` - : `Replacing \`reachability.${field}\` (${JSON.stringify(problem.value)}), which ${tool} builds cannot take.`, - ) } } @@ -859,11 +857,11 @@ async function setupReachability( config: { reachability?: ReachabilityDefaults | undefined }, inheritedReachability: unknown, ): Promise> { - warnInvalidReachability(tool, config.reachability, inheritedReachability) - const { settings: reachability } = parseReachability( + const { problems, settings: reachability } = parseReachability( tool, config.reachability, ) + warnInvalidReachability(tool, problems, inheritedReachability) const { settings: inherited } = parseReachability(tool, inheritedReachability) // As a scan merges them. const effective = { ...inherited, ...reachability } diff --git a/src/commands/manifest/setup-recursive-manifest-config.mts b/src/commands/manifest/setup-recursive-manifest-config.mts index b8b82c2f9..3fc4c9f65 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.mts @@ -48,7 +48,6 @@ import { logger } from '../../utils/logger.mts' import { isRecord } from '../../utils/objects.mts' import { select } from '../../utils/prompts.mts' import { - getDefaultSocketJson, mergeSocketJsonChain, readOrDefaultSocketJson, readSocketJsonChain, @@ -340,11 +339,12 @@ function draftCascade(draft: SettingsDraft, dir: string): SocketJson { return mergeSocketJsonChain(draftChain(draft, dir)) } -// What `dir`'s own socket.json inherits; nothing at the filesystem root, the -// parent of itself. +// What `dir`'s own socket.json inherits. function draftParentCascade(draft: SettingsDraft, dir: string): SocketJson { - const parent = path.dirname(dir) - return parent === dir ? getDefaultSocketJson() : draftCascade(draft, parent) + const own = path.resolve(dir) + return mergeSocketJsonChain( + draftChain(draft, dir).filter(file => file.dir !== own), + ) } function resolveDraftSettings( From 28018e3ecadb4dda08bfec8b12eb261fa5c03ab5 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Fri, 27 Nov 2026 10:46:48 +0100 Subject: [PATCH 09/10] Share the wizard prompt answering across both wizard tests --- .../manifest/setup-manifest-config.test.mts | 65 ++++----------- .../setup-recursive-manifest-config.test.mts | 83 +++++++++---------- test/setup-prompts.mts | 51 ++++++++++++ 3 files changed, 105 insertions(+), 94 deletions(-) create mode 100644 test/setup-prompts.mts diff --git a/src/commands/manifest/setup-manifest-config.test.mts b/src/commands/manifest/setup-manifest-config.test.mts index f4532d65a..02bd3c07c 100644 --- a/src/commands/manifest/setup-manifest-config.test.mts +++ b/src/commands/manifest/setup-manifest-config.test.mts @@ -21,6 +21,16 @@ import { setupMaven, setupSbt, } from './setup-manifest-config.mts' +import { + BUILD_QUESTION, + ECOSYSTEM_QUESTION, + JDK_PROMPT, + JDK_QUESTION, + RUNTIME_PROMPT, + RUNTIME_QUESTION, + WRITE_QUESTION, + answerPrompts, +} from '../../../test/setup-prompts.mts' import { logger } from '../../utils/logger.mts' import { input, select } from '../../utils/prompts.mts' import { @@ -29,51 +39,6 @@ import { writeSocketJson, } from '../../utils/socket-json.mts' -const BUILD_QUESTION = - 'Build project before reachability analysis? Note: A failed build fails the scan.' -const ECOSYSTEM_QUESTION = 'Select ecosystem manifest generator to configure' -const JDK_PROMPT = 'What JDK should reachability analysis use?' -const JDK_QUESTION = 'Use a different Java for reachability analysis?' -const RUNTIME_PROMPT = 'Which .NET runtime?' -const RUNTIME_QUESTION = - 'Start the reachability analysis of a framework-dependent .NET build on a given runtime?' -const WRITE_QUESTION = 'Do you want to write the new config' - -type Prompt = { - default?: unknown - message: string - validate?: ((value: string) => unknown) | undefined -} - -// Answers each prompt whose message starts with a key of `answers` with its -// value, and every other prompt with its default. Records every prompt's -// message, and each answered prompt under its key. -function answerPrompts(answers: Record = {}): { - asked: Record - messages: string[] - // The defaults the prompts answered under `key` showed. - shown: (key: string) => unknown[] -} { - const asked: Record = {} - const messages: string[] = [] - const answer = (prompt: Prompt): any => { - messages.push(prompt.message) - const key = Object.keys(answers).find(k => prompt.message.startsWith(k)) - if (key === undefined) { - return prompt.default ?? '' - } - ;(asked[key] ??= []).push(prompt) - return answers[key] - } - vi.mocked(input).mockImplementation(async prompt => answer(prompt)) - vi.mocked(select).mockImplementation(async prompt => answer(prompt)) - return { - asked, - messages, - shown: key => (asked[key] ?? []).map(prompt => prompt.default), - } -} - afterEach(() => { vi.restoreAllMocks() answerPrompts() @@ -237,18 +202,18 @@ describe('reachability step', () => { name: 'the shown value', config: { reachability: { javaHome: '/opt/jdk-17' } }, inheritedReachability: undefined, - shown: '/opt/jdk-17', + offered: '/opt/jdk-17', }, { name: 'an inherited JDK', config: {}, inheritedReachability: { javaHome: '/opt/jdk-11' }, - shown: '/opt/jdk-11', + offered: '/opt/jdk-11', }, ])( 'offers $name as the default and clears it on a blank answer', - async ({ config, inheritedReachability, shown }) => { - const { asked } = answerPrompts({ + async ({ config, inheritedReachability, offered }) => { + const { shown } = answerPrompts({ [JDK_PROMPT]: '', [JDK_QUESTION]: true, }) @@ -256,7 +221,7 @@ describe('reachability step', () => { await setupMaven(written, { inheritedReachability }) - expect(asked[JDK_PROMPT]?.map(p => p.default)).toEqual([shown]) + expect(shown(JDK_PROMPT)).toEqual([offered]) expect(written['reachability']).toEqual({ javaHome: null }) }, ) diff --git a/src/commands/manifest/setup-recursive-manifest-config.test.mts b/src/commands/manifest/setup-recursive-manifest-config.test.mts index 8d6acd010..61fab006c 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.test.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.test.mts @@ -35,6 +35,7 @@ import { scanBuildRoots, setupRecursiveManifestConfig, } from './setup-recursive-manifest-config.mts' +import { BUILD_QUESTION, answerPrompts } from '../../../test/setup-prompts.mts' import { mavenProject } from '../../../test/socket-facts-projects.mts' import { logger } from '../../utils/logger.mts' import { input, select } from '../../utils/prompts.mts' @@ -159,6 +160,16 @@ type Answers = Array<[string, unknown]> type Choice = { description?: string; name: string; value: string } +// Runs the real Maven wizard, answering the prompts `answers` matches and +// every other one with its default. Returns every prompt's message. +async function useRealMavenWizard(answers: Answers): Promise { + const actual = await vi.importActual< + typeof import('./setup-manifest-config.mts') + >('./setup-manifest-config.mts') + vi.mocked(setupMaven).mockImplementation(actual.setupMaven) + return answerPrompts(Object.fromEntries(answers)).messages +} + describe('setupRecursiveManifestConfig', () => { let repo = '' let asked: string[] = [] @@ -205,21 +216,6 @@ describe('setupRecursiveManifestConfig', () => { } return rule[1] as never }) - // Runs the real Maven wizard, answering the prompts `answers` matches and - // every other one with its default. - const useRealMavenWizard = async (answers: Answers) => { - const actual = await vi.importActual< - typeof import('./setup-manifest-config.mts') - >('./setup-manifest-config.mts') - vi.mocked(setupMaven).mockImplementation(actual.setupMaven) - vi.mocked(input).mockImplementation(async ({ default: def }) => def ?? '') - vi.mocked(select).mockImplementation(async ({ default: def, message }) => { - asked.push(message) - const rule = answers.find(({ 0: start }) => message.startsWith(start)) - return (rule ? rule[1] : (def ?? '')) as never - }) - } - beforeEach(async () => { repo = await fs.realpath( await fs.mkdtemp(path.join(tmpdir(), 'setup-recursive-')), @@ -663,7 +659,7 @@ describe('setupRecursiveManifestConfig', () => { maven: { reachability: { build: 'compile', javaHome: '/opt/jdk-17' } }, }) loads({}) - await useRealMavenWizard([ + const messages = await useRealMavenWizard([ ['Configure Maven defaults for any nested projects?', true], ['old (maven)', 'inherit'], ['tool (maven)', 'inherit'], @@ -672,7 +668,9 @@ describe('setupRecursiveManifestConfig', () => { const result = await setupRecursiveManifestConfig(file('legacy'), false) expect(result).toEqual({ ok: true, data: { canceled: false } }) - expect(asked).toContain('Configure Maven defaults for any nested projects?') + expect(messages).toContain( + 'Configure Maven defaults for any nested projects?', + ) } it('leaves accepted inherited values in directory defaults to the parent', async () => { @@ -693,34 +691,31 @@ describe('setupRecursiveManifestConfig', () => { }) }) - describe('after a no to building before reachability analysis', () => { - const BUILD_QUESTION = - 'Build project before reachability analysis? Note: A failed build fails the scan.' - - // Runs the real Maven wizard for legacy under a parent with `parentBuild`, - // answering no to the build question and the defaults elsewhere. - async function configureUnder( - parentBuild: 'compile' | 'none' | undefined, - ): Promise { - await writeSettings( - '.', - parentBuild ? { maven: { reachability: { build: parentBuild } } } : {}, - ) - loads({ 'pom.xml': ['api'], 'legacy/pom.xml': ['old'] }) - await useRealMavenWizard([ - [BUILD_QUESTION, false], - ['This project (maven)', 'inherit'], - ['Review the', true], - ['legacy (maven)', 'configure'], - ['legacy/tool (maven)', 'inherit'], - ['Write it?', true], - ]) - - const result = await setupRecursiveManifestConfig(repo, false) - expect(result).toEqual({ ok: true, data: { canceled: false } }) - expect(asked).toContain(BUILD_QUESTION) - } + // Runs the real Maven wizard for legacy under a parent with `parentBuild`, + // answering no to the build question and the defaults elsewhere. + async function configureUnder( + parentBuild: 'compile' | 'none' | undefined, + ): Promise { + await writeSettings( + '.', + parentBuild ? { maven: { reachability: { build: parentBuild } } } : {}, + ) + loads({ 'pom.xml': ['api'], 'legacy/pom.xml': ['old'] }) + const messages = await useRealMavenWizard([ + [BUILD_QUESTION, false], + ['This project (maven)', 'inherit'], + ['Review the', true], + ['legacy (maven)', 'configure'], + ['legacy/tool (maven)', 'inherit'], + ['Write it?', true], + ]) + const result = await setupRecursiveManifestConfig(repo, false) + expect(result).toEqual({ ok: true, data: { canceled: false } }) + expect(messages).toContain(BUILD_QUESTION) + } + + describe('after a no to building before reachability analysis', () => { it('writes none under a parent that sets compile', async () => { await configureUnder('compile') diff --git a/test/setup-prompts.mts b/test/setup-prompts.mts new file mode 100644 index 000000000..3c5e4c623 --- /dev/null +++ b/test/setup-prompts.mts @@ -0,0 +1,51 @@ +import { vi } from 'vitest' + +import { input, select } from '../src/utils/prompts.mts' + +// Wizard prompts, as far as answerPrompts matches them. +export const BUILD_QUESTION = + 'Build project before reachability analysis? Note: A failed build fails the scan.' +export const ECOSYSTEM_QUESTION = + 'Select ecosystem manifest generator to configure' +export const JDK_PROMPT = 'What JDK should reachability analysis use?' +export const JDK_QUESTION = 'Use a different Java for reachability analysis?' +export const RUNTIME_PROMPT = 'Which .NET runtime?' +export const RUNTIME_QUESTION = + 'Start the reachability analysis of a framework-dependent .NET build on a given runtime?' +export const WRITE_QUESTION = 'Do you want to write the new config' + +type Prompt = { + default?: unknown + message: string + validate?: ((value: string) => unknown) | undefined +} + +// For a test that mocks src/utils/prompts.mts. +// Answers each prompt whose message starts with a key of `answers` with its +// value, and every other prompt with its default. Records every prompt's +// message, and each answered prompt under its key. +export function answerPrompts(answers: Record = {}): { + asked: Record + messages: string[] + // The defaults the prompts answered under `key` showed. + shown: (key: string) => unknown[] +} { + const asked: Record = {} + const messages: string[] = [] + const answer = (prompt: Prompt): any => { + messages.push(prompt.message) + const key = Object.keys(answers).find(k => prompt.message.startsWith(k)) + if (key === undefined) { + return prompt.default ?? '' + } + ;(asked[key] ??= []).push(prompt) + return answers[key] + } + vi.mocked(input).mockImplementation(async prompt => answer(prompt)) + vi.mocked(select).mockImplementation(async prompt => answer(prompt)) + return { + asked, + messages, + shown: key => (asked[key] ?? []).map(prompt => prompt.default), + } +} From 19f71503c778ee3205d2ef1e3234bdba13efeb37 Mon Sep 17 00:00:00 2001 From: Jeppe Fredsgaard Blaabjerg Date: Fri, 27 Nov 2026 10:59:58 +0100 Subject: [PATCH 10/10] Ask for the reachability settings only with --dynamic-sbom-inference Only dynamic SBOM inference scans read them, so plain `socket manifest setup` no longer asks. The recursive wizard runs the step after each build tool's questions with the settings in effect and what they inherit, and writes only what differs from the inherited value, for directory defaults as for builds. A value that equals the inherited one is labelled as inherited, and an invalid inherited value is named, to be fixed in the socket.json that sets it. --- .../manifest/setup-manifest-config.mts | 102 ++--- .../manifest/setup-manifest-config.test.mts | 433 +++++------------- .../setup-recursive-manifest-config.mts | 33 +- .../setup-recursive-manifest-config.test.mts | 49 +- test/setup-prompts.mts | 11 +- 5 files changed, 224 insertions(+), 404 deletions(-) diff --git a/src/commands/manifest/setup-manifest-config.mts b/src/commands/manifest/setup-manifest-config.mts index 06b042b81..f67a8f837 100644 --- a/src/commands/manifest/setup-manifest-config.mts +++ b/src/commands/manifest/setup-manifest-config.mts @@ -8,15 +8,12 @@ import { reachabilityFieldsOf, } from './build-root-config.mts' import { detectManifestActions } from './detect-manifest-actions.mts' -import { BUILD_TOOLS } from './scripts/build-tool.mts' import { REQUIREMENTS_TXT, SOCKET_JSON } from '../../constants.mts' import { debugDir } from '../../utils/debug.mts' import { logger } from '../../utils/logger.mts' import { isRecord } from '../../utils/objects.mts' import { input, select } from '../../utils/prompts.mts' import { - mergeSocketJsonChain, - readSocketJsonChain, readSocketJsonSync, writeSocketJson, } from '../../utils/socket-json.mts' @@ -30,11 +27,6 @@ import type { ReachabilityField, } from '../../utils/socket-json.mts' -type ReachabilityStepOptions = { - // What the project inherits from ancestor socket.json files, as written. - inheritedReachability?: unknown -} - type ValuePrompts = { ask: (current: string) => Promise change: string @@ -67,15 +59,6 @@ const REACHABILITY_VALUE_PROMPTS = { ValuePrompts > -// As written. The wizard leaves invalid inherited values out of its defaults -// and replaces invalid values only in this directory's socket.json. -function inheritedReachabilityOf(cwd: string, tool: BuildTool): unknown { - const dir = path.resolve(cwd) - return mergeSocketJsonChain( - readSocketJsonChain(dir).filter(file => file.dir !== dir), - ).defaults?.manifest?.[tool]?.reachability -} - // Whether the prompt was canceled. A blank answer clears a value set before // with null rather than deleting the key, so it doesn't silently start // inheriting an ancestor's value again. @@ -241,11 +224,6 @@ export async function setupManifestConfig( sockJson.defaults.manifest = {} } - const tool = BUILD_TOOLS.find(t => t === targetEco) - const inheritedReachability = tool - ? inheritedReachabilityOf(cwd, tool) - : undefined - let result: CResult<{ canceled: boolean }> switch (targetEco) { case 'conda': { @@ -259,36 +237,28 @@ export async function setupManifestConfig( if (!sockJson.defaults.manifest.dotnet) { sockJson.defaults.manifest.dotnet = {} } - result = await setupDotnet(sockJson.defaults.manifest.dotnet, { - inheritedReachability, - }) + result = await setupDotnet(sockJson.defaults.manifest.dotnet) break } case 'gradle': { if (!sockJson.defaults.manifest.gradle) { sockJson.defaults.manifest.gradle = {} } - result = await setupGradle(sockJson.defaults.manifest.gradle, { - inheritedReachability, - }) + result = await setupGradle(sockJson.defaults.manifest.gradle) break } case 'maven': { if (!sockJson.defaults.manifest.maven) { sockJson.defaults.manifest.maven = {} } - result = await setupMaven(sockJson.defaults.manifest.maven, { - inheritedReachability, - }) + result = await setupMaven(sockJson.defaults.manifest.maven) break } case 'sbt': { if (!sockJson.defaults.manifest.sbt) { sockJson.defaults.manifest.sbt = {} } - result = await setupSbt(sockJson.defaults.manifest.sbt, { - inheritedReachability, - }) + result = await setupSbt(sockJson.defaults.manifest.sbt) break } default: { @@ -389,7 +359,6 @@ async function setupConda( export async function setupDotnet( config: ManifestDefaults<'dotnet'>, - { inheritedReachability }: ReachabilityStepOptions = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'dotnet'))) { return canceledByUser() @@ -419,17 +388,14 @@ export async function setupDotnet( return canceledByUser() } - return await setupReachability('dotnet', config, inheritedReachability) + return notCanceled() } export async function setupGradle( config: ManifestDefaults<'gradle'>, // Set by the recursive dynamic-sbom-inference wizard, which has no // pom-mode equivalent - skips the facts/pom question entirely. - { - factsOnly = false, - inheritedReachability, - }: ReachabilityStepOptions & { factsOnly?: boolean } = {}, + { factsOnly = false }: { factsOnly?: boolean } = {}, ): Promise> { if ( applyAnswer(config, 'bin', await askForBin(config.bin || '', './gradlew')) @@ -463,11 +429,10 @@ export async function setupGradle( return canceledByUser() } } - const generatesFacts = factsOnly || config.facts !== false // The config filters and --ignore-unresolved only apply to facts generation // (the default); skip them when pom generation (--pom) is selected. - if (generatesFacts) { + if (factsOnly || config.facts !== false) { const factsOptions = await setupFactsOptions(config) if (!factsOptions.ok || factsOptions.data.canceled) { return factsOptions @@ -478,16 +443,11 @@ export async function setupGradle( return canceledByUser() } - if (generatesFacts) { - return await setupReachability('gradle', config, inheritedReachability) - } - return notCanceled() } export async function setupMaven( config: ManifestDefaults<'maven'>, - { inheritedReachability }: ReachabilityStepOptions = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'mvn'))) { return canceledByUser() @@ -524,16 +484,13 @@ export async function setupMaven( return canceledByUser() } - return await setupReachability('maven', config, inheritedReachability) + return notCanceled() } export async function setupSbt( config: ManifestDefaults<'sbt'>, // See setupGradle's matching parameter for why. - { - factsOnly = false, - inheritedReachability, - }: ReachabilityStepOptions & { factsOnly?: boolean } = {}, + { factsOnly = false }: { factsOnly?: boolean } = {}, ): Promise> { if (applyAnswer(config, 'bin', await askForBin(config.bin || '', 'sbt'))) { return canceledByUser() @@ -565,12 +522,11 @@ export async function setupSbt( return canceledByUser() } } - const generatesFacts = factsOnly || config.facts !== false // Socket facts is the default. The pom output questions (stdout/outfile) // only apply when pom generation (--pom) is explicitly selected; otherwise // ask the facts-only options. - if (!generatesFacts) { + if (!factsOnly && config.facts === false) { const stdout = await askForStdout(config.stdout) if (stdout === undefined) { return canceledByUser() @@ -608,10 +564,6 @@ export async function setupSbt( return canceledByUser() } - if (generatesFacts) { - return await setupReachability('sbt', config, inheritedReachability) - } - return notCanceled() } @@ -827,8 +779,8 @@ async function askForIgnoreUnresolvedFlag( }) } -// The wizard replaces invalid local values with the answers. Invalid -// inherited values need to be fixed in the socket.json that sets them. +// The wizard replaces invalid values with the answers, except one the build +// inherits: that one needs fixing in the socket.json that sets it. function warnInvalidReachability( tool: BuildTool, problems: readonly ReachabilityProblem[], @@ -836,23 +788,29 @@ function warnInvalidReachability( ): void { for (const { field, value } of problems) { let parent: unknown - let message: string + let setting: string + let reason: string if (field === undefined) { parent = inherited - message = `Replacing \`reachability\` (${JSON.stringify(value)}), which is not an object.` + setting = 'reachability' + reason = 'is not an object' } else { parent = isRecord(inherited) ? inherited[field] : undefined - message = `Replacing \`reachability.${field}\` (${JSON.stringify(value)}), which ${tool} builds cannot take.` - } - if (!isDeepStrictEqual(value, parent)) { - logger.warn(message) + setting = `reachability.${field}` + reason = `is not a value ${tool} builds take` } + const shown = `\`${setting}\` (${JSON.stringify(value)})` + logger.warn( + isDeepStrictEqual(value, parent) + ? `${shown}, which this build inherits, ${reason}; fix it in the socket.json that sets it, or reachability scans fail.` + : `Replacing ${shown}, which ${reason}.`, + ) } } -// Answering no to a value prompt keeps the effective value. -// The wizard writes "none" to override an inherited "compile". -async function setupReachability( +// Answering no keeps the value in effect; "none" overrides an inherited +// "compile". +export async function setupReachability( tool: BuildTool, config: { reachability?: ReachabilityDefaults | undefined }, inheritedReachability: unknown, @@ -863,7 +821,7 @@ async function setupReachability( ) warnInvalidReachability(tool, problems, inheritedReachability) const { settings: inherited } = parseReachability(tool, inheritedReachability) - // As a scan merges them. + // An invalid value of its own leaves the inherited one in effect. const effective = { ...inherited, ...reachability } const wantsBuild = await select({ @@ -907,7 +865,7 @@ async function setupReachability( name: 'no', value: false, description: current - ? `Keep ${current} ${prompts.keep}${Object.hasOwn(reachability, field) ? '' : ', as a parent socket.json sets it'}` + ? `Keep ${current} ${prompts.keep}${current === inherited[field] ? ', which it inherits' : ''}` : prompts.unset, }, { @@ -930,7 +888,7 @@ async function setupReachability( } if (answer) { reachability[field] = answer - } else if (reachability[field] || inherited[field]) { + } else if (inherited[field]) { // Clears the value rather than inheriting it again. reachability[field] = null } else { diff --git a/src/commands/manifest/setup-manifest-config.test.mts b/src/commands/manifest/setup-manifest-config.test.mts index 02bd3c07c..7143cbac7 100644 --- a/src/commands/manifest/setup-manifest-config.test.mts +++ b/src/commands/manifest/setup-manifest-config.test.mts @@ -1,8 +1,4 @@ -import { promises as fs } from 'node:fs' -import { tmpdir } from 'node:os' -import path from 'node:path' - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' // Simulates a real prompt: pressing Enter with nothing typed returns // whatever `default` was shown - the same contract inquirer honors. This is @@ -13,31 +9,26 @@ vi.mock('../../utils/prompts.mts', () => ({ select: vi.fn(async ({ default: def }: { default?: string }) => def ?? ''), })) -import { cascadedReachability } from './build-root-config.mts' import { setupDotnet, setupGradle, - setupManifestConfig, setupMaven, + setupReachability, setupSbt, } from './setup-manifest-config.mts' import { BUILD_QUESTION, - ECOSYSTEM_QUESTION, JDK_PROMPT, JDK_QUESTION, RUNTIME_PROMPT, RUNTIME_QUESTION, - WRITE_QUESTION, answerPrompts, } from '../../../test/setup-prompts.mts' import { logger } from '../../utils/logger.mts' import { input, select } from '../../utils/prompts.mts' -import { - getDefaultSocketJson, - readSocketJsonChain, - writeSocketJson, -} from '../../utils/socket-json.mts' + +import type { BuildTool } from './scripts/build-tool.mts' +import type { ReachabilityDefaults } from '../../utils/socket-json.mts' afterEach(() => { vi.restoreAllMocks() @@ -110,24 +101,57 @@ describe('setupGradle/setupMaven/setupSbt', () => { }) }) -describe('reachability step', () => { +describe('setup wizards without dynamic SBOM inference', () => { it.for([ + ['dotnet', setupDotnet], ['gradle', setupGradle], ['maven', setupMaven], ['sbt', setupSbt], ] as const)( - '%s writes the JDK named after a yes to reachability.javaHome', + '%s never asks for the reachability settings, leaving them as they are', async ({ 1: setup }) => { - answerPrompts({ [JDK_PROMPT]: '$JAVA17_HOME', [JDK_QUESTION]: true }) - const config: Record = { javaHome: '/opt/jdk-11' } + const { messages } = answerPrompts() + const config: Record = { + reachability: { build: 'compile' }, + } - const result = await setup(config) + await setup(config) - expect(result).toEqual({ ok: true, data: { canceled: false } }) - expect(config).toEqual({ - javaHome: '/opt/jdk-11', - reachability: { javaHome: '$JAVA17_HOME' }, - }) + for (const question of [BUILD_QUESTION, JDK_QUESTION, RUNTIME_QUESTION]) { + expect(messages).not.toContain(question) + } + expect(config['reachability']).toEqual({ build: 'compile' }) + }, + ) +}) + +// Runs the reachability step on the settings in effect, `reachability`. +// Returns what it leaves in their place. +async function step( + tool: BuildTool, + reachability: unknown, + inherited?: unknown, +): Promise { + // Invalid values are written as a user would. + const config = { + reachability: structuredClone(reachability) as + | ReachabilityDefaults + | undefined, + } + expect(await setupReachability(tool, config, inherited)).toEqual({ + ok: true, + data: { canceled: false }, + }) + return config.reachability +} + +describe('reachability step', () => { + it.for(['gradle', 'maven', 'sbt'] as const)( + '%s writes the JDK named after a yes to reachability.javaHome', + async tool => { + answerPrompts({ [JDK_PROMPT]: '$JAVA17_HOME', [JDK_QUESTION]: true }) + + expect(await step(tool, undefined)).toEqual({ javaHome: '$JAVA17_HOME' }) }, ) @@ -136,23 +160,17 @@ describe('reachability step', () => { [JDK_PROMPT]: '/never-asked', [JDK_QUESTION]: false, }) - const config: Record = {} - - await setupMaven(config) - expect(config).toEqual({}) + expect(await step('maven', undefined)).toBeUndefined() expect(asked[JDK_PROMPT]).toBeUndefined() }) it('leaves a value it shows as is on a no, neither clearing nor restating it', async () => { answerPrompts({ [JDK_QUESTION]: false }) - const config: Record = { - reachability: { javaHome: '/opt/jdk-17' }, - } - - await setupMaven(config) - expect(config['reachability']).toEqual({ javaHome: '/opt/jdk-17' }) + expect(await step('maven', { javaHome: '/opt/jdk-17' })).toEqual({ + javaHome: '/opt/jdk-17', + }) }) it.for([ @@ -163,14 +181,9 @@ describe('reachability step', () => { ], [{}, {}, 'Leave the JDK for reachability analysis unset'], [ - { javaHome: '/opt/jdk-17' }, - { javaHome: '/opt/jdk-17' }, - 'Keep /opt/jdk-17 as the JDK for reachability analysis', - ], - [ - {}, { javaHome: '/opt/jdk-11' }, - 'Keep /opt/jdk-11 as the JDK for reachability analysis, as a parent socket.json sets it', + { javaHome: '/opt/jdk-11' }, + 'Keep /opt/jdk-11 as the JDK for reachability analysis, which it inherits', ], [ { javaHome: null }, @@ -180,172 +193,112 @@ describe('reachability step', () => { ] as const)( 'labels the no to the JDK %j, inheriting %j, by what it does', async ({ 0: reachability, 1: inherited, 2: label }) => { - const { asked } = answerPrompts({ [JDK_QUESTION]: false }) - - await setupMaven( - { reachability: { ...reachability } }, - { inheritedReachability: inherited }, - ) - - expect(asked[JDK_QUESTION]).toEqual([ - expect.objectContaining({ - choices: expect.arrayContaining([ - expect.objectContaining({ description: label, name: 'no' }), - ]), - }), - ]) + const { noChoice } = answerPrompts({ [JDK_QUESTION]: false }) + + await step('maven', reachability, inherited) + + expect(noChoice(JDK_QUESTION)).toEqual([label]) }, ) it.for([ { - name: 'the shown value', - config: { reachability: { javaHome: '/opt/jdk-17' } }, - inheritedReachability: undefined, + name: 'its own JDK', + inherited: undefined, + left: undefined, offered: '/opt/jdk-17', }, { name: 'an inherited JDK', - config: {}, - inheritedReachability: { javaHome: '/opt/jdk-11' }, - offered: '/opt/jdk-11', + inherited: { javaHome: '/opt/jdk-17' }, + left: { javaHome: null }, + offered: '/opt/jdk-17', }, ])( 'offers $name as the default and clears it on a blank answer', - async ({ config, inheritedReachability, offered }) => { + async ({ inherited, left, offered }) => { const { shown } = answerPrompts({ [JDK_PROMPT]: '', [JDK_QUESTION]: true, }) - const written: Record = structuredClone(config) - - await setupMaven(written, { inheritedReachability }) + expect( + await step('maven', { javaHome: '/opt/jdk-17' }, inherited), + ).toEqual(left) expect(shown(JDK_PROMPT)).toEqual([offered]) - expect(written['reachability']).toEqual({ javaHome: null }) }, ) - - it('does not ask in pom mode, where no facts reach a reachability run', async () => { - const { messages } = answerPrompts() - - await setupGradle({ facts: false }) - await setupSbt({ facts: false }) - - expect(messages).not.toContain(BUILD_QUESTION) - expect(messages).not.toContain(JDK_QUESTION) - }) }) describe('reachability build step', () => { - it.for([ - ['dotnet', setupDotnet], - ['gradle', setupGradle], - ['maven', setupMaven], - ['sbt', setupSbt], - ] as const)( + it.for(['dotnet', 'gradle', 'maven', 'sbt'] as const)( '%s writes compile to reachability.build after a yes', - async ({ 1: setup }) => { + async tool => { answerPrompts({ [BUILD_QUESTION]: true }) - const config: Record = {} - - const result = await setup(config) - expect(result).toEqual({ ok: true, data: { canceled: false } }) - expect(config).toEqual({ reachability: { build: 'compile' } }) + expect(await step(tool, undefined)).toEqual({ build: 'compile' }) }, ) - it.for([ - ['dotnet', setupDotnet], - ['gradle', setupGradle], - ['maven', setupMaven], - ['sbt', setupSbt], - ] as const)( + it.for(['dotnet', 'gradle', 'maven', 'sbt'] as const)( '%s leaves reachability.build unset after a no at the top level, never writing none', - async ({ 1: setup }) => { + async tool => { answerPrompts({ [BUILD_QUESTION]: false }) - const config: Record = {} - - await setup(config) - expect(config).toEqual({}) + expect(await step(tool, undefined)).toBeUndefined() }, ) - it.for([ - ['dotnet', setupDotnet], - ['gradle', setupGradle], - ['maven', setupMaven], - ['sbt', setupSbt], - ] as const)( + it.for(['dotnet', 'gradle', 'maven', 'sbt'] as const)( '%s writes none after a no when the project inherits compile', - async ({ 1: setup }) => { + async tool => { const { shown } = answerPrompts({ [BUILD_QUESTION]: false }) - const config: Record = { - reachability: { build: 'compile' }, - } - - await setup(config, { inheritedReachability: { build: 'compile' } }) + expect( + await step(tool, { build: 'compile' }, { build: 'compile' }), + ).toEqual({ build: 'none' }) expect(shown(BUILD_QUESTION)).toEqual([true]) - expect(config).toEqual({ reachability: { build: 'none' } }) }, ) it('leaves the build unset after a no when the project inherits none', async () => { answerPrompts({ [BUILD_QUESTION]: false }) - const config: Record = { reachability: { build: 'none' } } - - await setupGradle(config, { inheritedReachability: { build: 'none' } }) - expect(config).toEqual({}) + expect( + await step('gradle', { build: 'none' }, { build: 'none' }), + ).toBeUndefined() }) it('unsets a build it shows as the default after a no, keeping the JDK', async () => { const { shown } = answerPrompts({ [BUILD_QUESTION]: false }) - const config: Record = { - reachability: { build: 'compile', javaHome: '/opt/jdk-17' }, - } - - await setupMaven(config) + expect( + await step('maven', { build: 'compile', javaHome: '/opt/jdk-17' }), + ).toEqual({ javaHome: '/opt/jdk-17' }) expect(shown(BUILD_QUESTION)).toEqual([true]) - expect(config['reachability']).toEqual({ javaHome: '/opt/jdk-17' }) }) it('removes a written none after a no', async () => { const { shown } = answerPrompts({ [BUILD_QUESTION]: false }) - const config: Record = { reachability: { build: 'none' } } - - await setupDotnet(config) + expect(await step('dotnet', { build: 'none' })).toBeUndefined() expect(shown(BUILD_QUESTION)).toEqual([false]) - expect(config).toEqual({}) }) it('never asks dotnet for a reachability JDK', async () => { const { messages } = answerPrompts({ [BUILD_QUESTION]: true }) - const config: Record = {} - - await setupDotnet(config) + expect(await step('dotnet', undefined)).toEqual({ build: 'compile' }) expect(messages).toContain(BUILD_QUESTION) expect(messages.some(m => m.includes('Java'))).toBe(false) - expect(config).toEqual({ reachability: { build: 'compile' } }) }) }) describe('reachability runtime step', () => { it('writes the runtime named after a yes to reachability.runtimeVersion', async () => { answerPrompts({ [RUNTIME_PROMPT]: '8.0', [RUNTIME_QUESTION]: true }) - const config: Record = {} - expect(await setupDotnet(config)).toEqual({ - ok: true, - data: { canceled: false }, - }) - expect(config).toEqual({ reachability: { runtimeVersion: '8.0' } }) + expect(await step('dotnet', undefined)).toEqual({ runtimeVersion: '8.0' }) }) it.for([ @@ -360,7 +313,7 @@ describe('reachability runtime step', () => { [RUNTIME_QUESTION]: true, }) - await setupDotnet({}) + await step('dotnet', undefined) const result = await asked[RUNTIME_PROMPT]?.[0]?.validate?.(answer) if (valid) { @@ -375,20 +328,21 @@ describe('reachability runtime step', () => { [RUNTIME_PROMPT]: '', [RUNTIME_QUESTION]: true, }) - const config: Record = {} - - await setupDotnet(config, { - inheritedReachability: { runtimeVersion: '9.0' }, - }) + expect( + await step( + 'dotnet', + { runtimeVersion: '9.0' }, + { runtimeVersion: '9.0' }, + ), + ).toEqual({ runtimeVersion: null }) expect(shown(RUNTIME_PROMPT)).toEqual(['9.0']) - expect(config).toEqual({ reachability: { runtimeVersion: null } }) }) it('never asks a JVM build tool for a .NET runtime', async () => { const { messages } = answerPrompts() - await setupMaven({}) + await step('maven', undefined) expect(messages).not.toContain(RUNTIME_QUESTION) }) @@ -413,190 +367,55 @@ describe('reachability settings written invalid', () => { '%s replaces %j, keeping only what its builds take', async ({ 0: tool, 1: reachability, 2: kept, 3: warned }) => { const warn = vi.spyOn(logger, 'warn').mockImplementation(() => logger) - const config: Record = { reachability } - const setup = { - dotnet: setupDotnet, - gradle: setupGradle, - maven: setupMaven, - }[tool] - - expect(await setup(config)).toEqual({ - ok: true, - data: { canceled: false }, - }) - expect(config['reachability']).toEqual(kept) + expect(await step(tool, reachability)).toEqual(kept) for (const field of warned) { expect(warn).toHaveBeenCalledWith(expect.stringContaining(field)) } }, ) - it('ignores an invalid inherited value for its defaults', async () => { + it('ignores an invalid inherited value for its defaults, saying where to fix it', async () => { + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => logger) const { shown } = answerPrompts({ [BUILD_QUESTION]: false }) - const config: Record = {} - - await setupGradle(config, { - inheritedReachability: { build: 'always', javaHome: 17 }, - }) + const inherited = { build: 'always', javaHome: 17 } + expect(await step('gradle', inherited, inherited)).toBeUndefined() expect(shown(BUILD_QUESTION)).toEqual([false]) - expect(config).toEqual({}) + expect(warn.mock.calls.map(c => c[0])).toEqual([ + expect.stringContaining( + '`reachability.build` ("always"), which this build inherits', + ), + expect.stringContaining( + '`reachability.javaHome` (17), which this build inherits', + ), + ]) }) - it('does not claim to replace an invalid value the merged settings inherit', async () => { + it('replaces its own invalid values and names the inherited ones', async () => { const warn = vi.spyOn(logger, 'warn').mockImplementation(() => logger) - const inheritedReachability = { build: 'compile', javaHome: 17 } - const config: Record = { - reachability: { ...inheritedReachability, build: 'always' }, - } + const inherited = { build: 'compile', javaHome: 17 } - await setupGradle(config, { factsOnly: true, inheritedReachability }) + await step('gradle', { ...inherited, build: 'always' }, inherited) expect(warn.mock.calls.map(c => c[0])).toEqual([ - expect.stringContaining('reachability.build'), + expect.stringContaining('Replacing `reachability.build`'), + expect.stringContaining( + '`reachability.javaHome` (17), which this build inherits', + ), ]) }) -}) - -describe('setupManifestConfig', () => { - let parent = '' - - beforeEach(async () => { - parent = await fs.realpath( - await fs.mkdtemp(path.join(tmpdir(), 'setup-manifest-config-')), - ) - }) - afterEach(async () => { - await fs.rm(parent, { recursive: true, force: true }) - }) - - it('writes none after a no under an ancestor socket.json that sets compile, showing compile as the default', async () => { - await writeSocketJson(parent, { - ...getDefaultSocketJson(), - defaults: { manifest: { maven: { reachability: { build: 'compile' } } } }, - }) - const cwd = path.join(parent, 'app') - await fs.mkdir(cwd) - const { shown } = answerPrompts({ - [BUILD_QUESTION]: false, - [ECOSYSTEM_QUESTION]: 'maven', - [WRITE_QUESTION]: true, - }) - vi.spyOn(logger, 'log').mockImplementation(() => logger) - vi.spyOn(logger, 'info').mockImplementation(() => logger) - - expect(await setupManifestConfig(cwd)).toEqual({ - ok: true, - data: undefined, - }) - - expect(shown(BUILD_QUESTION)).toEqual([true]) - const written = JSON.parse( - await fs.readFile(path.join(cwd, 'socket.json'), 'utf8'), - ) - expect(written.defaults.manifest.maven).toEqual({ - reachability: { build: 'none' }, - }) - }) - it.for([ - [ - 'keeps the parent JDK for a scan here after a no', - false, - { - javaHome: '/opt/jdk-17', - }, - ], - [ - 'clears the parent JDK for a scan here after a blank JDK', - true, - undefined, - ], - ] as const)('%s', async ({ 1: wantsJavaHome, 2: scanned }) => { - await writeSocketJson(parent, { - ...getDefaultSocketJson(), - defaults: { - manifest: { maven: { reachability: { javaHome: '/opt/jdk-17' } } }, - }, - }) - const cwd = path.join(parent, 'app') - await fs.mkdir(cwd) - answerPrompts({ - [ECOSYSTEM_QUESTION]: 'maven', - [JDK_PROMPT]: '', - [JDK_QUESTION]: wantsJavaHome, - [WRITE_QUESTION]: true, - }) - vi.spyOn(logger, 'log').mockImplementation(() => logger) - vi.spyOn(logger, 'info').mockImplementation(() => logger) - - await setupManifestConfig(cwd) - - expect(cascadedReachability('maven', readSocketJsonChain(cwd))).toEqual( - scanned, - ) - }) -}) - -describe('setupManifestConfig with an invalid ancestor socket.json', () => { - let parent = '' - - beforeEach(async () => { - parent = await fs.realpath( - await fs.mkdtemp(path.join(tmpdir(), 'setup-manifest-config-')), - ) - await fs.writeFile( - path.join(parent, 'socket.json'), - JSON.stringify({ - version: 1, - defaults: { manifest: { maven: { reachability: { javaHome: 17 } } } }, - }), - ) - }) - afterEach(async () => { - await fs.rm(parent, { recursive: true, force: true }) - }) - - it('configures a build beneath it, replacing what it cannot take', async () => { - const cwd = path.join(parent, 'app') - await fs.mkdir(cwd) - await fs.writeFile( - path.join(cwd, 'socket.json'), - JSON.stringify({ - version: 1, - defaults: { - manifest: { maven: { reachability: { build: 'always' } } }, - }, - }), - ) - answerPrompts({ [ECOSYSTEM_QUESTION]: 'maven', [WRITE_QUESTION]: true }) - vi.spyOn(logger, 'log').mockImplementation(() => logger) - vi.spyOn(logger, 'info').mockImplementation(() => logger) + it('shows the inherited value its own invalid value leaves in effect', async () => { vi.spyOn(logger, 'warn').mockImplementation(() => logger) + const { noChoice } = answerPrompts({ [JDK_QUESTION]: false }) - expect(await setupManifestConfig(cwd)).toEqual({ - ok: true, - data: undefined, - }) - - const written = JSON.parse( - await fs.readFile(path.join(cwd, 'socket.json'), 'utf8'), - ) - expect(written.defaults.manifest.maven).toEqual({}) - }) - - it('exits without reading it when no build tool is chosen', async () => { - const cwd = path.join(parent, 'app') - await fs.mkdir(cwd) - answerPrompts({ [ECOSYSTEM_QUESTION]: '' }) - vi.spyOn(logger, 'log').mockImplementation(() => logger) - vi.spyOn(logger, 'info').mockImplementation(() => logger) - - await expect(setupManifestConfig(cwd)).resolves.toMatchObject({ - ok: true, - data: { canceled: true }, - }) + expect( + await step('maven', { javaHome: 5 }, { javaHome: '/opt/jdk-11' }), + ).toBeUndefined() + expect(noChoice(JDK_QUESTION)).toEqual([ + 'Keep /opt/jdk-11 as the JDK for reachability analysis, which it inherits', + ]) }) }) diff --git a/src/commands/manifest/setup-recursive-manifest-config.mts b/src/commands/manifest/setup-recursive-manifest-config.mts index 3fc4c9f65..b1016609d 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.mts @@ -37,6 +37,7 @@ import { setupDotnet, setupGradle, setupMaven, + setupReachability, setupSbt, } from './setup-manifest-config.mts' import { SOCKET_JSON } from '../../constants.mts' @@ -843,31 +844,31 @@ async function reviewBuild( // just skips a project resolved to `facts: false` (see // generateRecursiveManifests' skipReason), so offering that choice here // would be misleading. +// `config` is the section in effect, `inheritedReachability` the +// `reachability` it inherits. async function runEcosystemWizard( ecosystem: BuildTool, config: Record, inheritedReachability: unknown, ): Promise> { + let result: CResult<{ canceled: boolean }> if (ecosystem === 'dotnet') { - return await setupDotnet(config as ManifestDefaults<'dotnet'>, { - inheritedReachability, + result = await setupDotnet(config as ManifestDefaults<'dotnet'>) + } else if (ecosystem === 'gradle') { + result = await setupGradle(config as ManifestDefaults<'gradle'>, { + factsOnly: true, }) - } - if (ecosystem === 'gradle') { - return await setupGradle(config as ManifestDefaults<'gradle'>, { + } else if (ecosystem === 'maven') { + result = await setupMaven(config as ManifestDefaults<'maven'>) + } else { + result = await setupSbt(config as ManifestDefaults<'sbt'>, { factsOnly: true, - inheritedReachability, }) } - if (ecosystem === 'maven') { - return await setupMaven(config as ManifestDefaults<'maven'>, { - inheritedReachability, - }) + if (!result.ok || result.data.canceled) { + return result } - return await setupSbt(config as ManifestDefaults<'sbt'>, { - factsOnly: true, - inheritedReachability, - }) + return await setupReachability(ecosystem, config, inheritedReachability) } async function askYesNo(message: string): Promise { @@ -935,7 +936,9 @@ async function setupRootDefaults( const own = draftSettings(draft, cwd) const manifest = manifestOf(own) const before = getEcosystemSection(own, ecosystem) - const section = { ...before } + const section = { + ...getEcosystemSection(draftCascade(draft, cwd), ecosystem), + } const inherited = getEcosystemSection( draftParentCascade(draft, cwd), ecosystem, diff --git a/src/commands/manifest/setup-recursive-manifest-config.test.mts b/src/commands/manifest/setup-recursive-manifest-config.test.mts index 61fab006c..401ae4788 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.test.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.test.mts @@ -24,18 +24,23 @@ vi.mock('./setup-manifest-config.mts', () => ({ setupDotnet: vi.fn(), setupGradle: vi.fn(), setupMaven: vi.fn(), + setupReachability: vi.fn(), setupSbt: vi.fn(), })) import { findBuildToolCandidates } from './discover-manifest-roots.mts' import { listBuildProjects } from './run-manifest-facts.mts' -import { setupMaven } from './setup-manifest-config.mts' +import { setupMaven, setupReachability } from './setup-manifest-config.mts' import { discoverBuildRoots, scanBuildRoots, setupRecursiveManifestConfig, } from './setup-recursive-manifest-config.mts' -import { BUILD_QUESTION, answerPrompts } from '../../../test/setup-prompts.mts' +import { + BUILD_QUESTION, + JDK_QUESTION, + answerPrompts, +} from '../../../test/setup-prompts.mts' import { mavenProject } from '../../../test/socket-facts-projects.mts' import { logger } from '../../utils/logger.mts' import { input, select } from '../../utils/prompts.mts' @@ -161,13 +166,16 @@ type Answers = Array<[string, unknown]> type Choice = { description?: string; name: string; value: string } // Runs the real Maven wizard, answering the prompts `answers` matches and -// every other one with its default. Returns every prompt's message. -async function useRealMavenWizard(answers: Answers): Promise { +// every other one with its default. Returns what answerPrompts records. +async function useRealMavenWizard( + answers: Answers, +): Promise> { const actual = await vi.importActual< typeof import('./setup-manifest-config.mts') >('./setup-manifest-config.mts') vi.mocked(setupMaven).mockImplementation(actual.setupMaven) - return answerPrompts(Object.fromEntries(answers)).messages + vi.mocked(setupReachability).mockImplementation(actual.setupReachability) + return answerPrompts(Object.fromEntries(answers)) } describe('setupRecursiveManifestConfig', () => { @@ -236,6 +244,11 @@ describe('setupRecursiveManifestConfig', () => { } vi.mocked(listBuildProjects).mockReset() vi.mocked(setupMaven).mockReset() + vi.mocked(setupReachability).mockReset() + vi.mocked(setupReachability).mockResolvedValue({ + ok: true, + data: { canceled: false }, + }) vi.spyOn(logger, 'log').mockImplementation(() => logger) vi.spyOn(logger, 'info').mockImplementation(() => logger) vi.spyOn(logger, 'success').mockImplementation(() => logger) @@ -624,6 +637,28 @@ describe('setupRecursiveManifestConfig', () => { }) }) + it('labels a JDK the build inherits as inherited', async () => { + await writeSettings('.', { + maven: { reachability: { javaHome: '/opt/jdk-17' } }, + }) + loads({ 'pom.xml': ['api'], 'legacy/pom.xml': ['old'] }) + const { noChoice } = await useRealMavenWizard([ + [JDK_QUESTION, false], + ['This project (maven)', 'inherit'], + ['Review the', true], + ['legacy (maven)', 'configure'], + ['legacy/tool (maven)', 'inherit'], + ['Write it?', true], + ]) + + await setupRecursiveManifestConfig(repo, false) + + expect(noChoice(JDK_QUESTION)).toEqual([ + 'Keep /opt/jdk-17 as the JDK for reachability analysis, which it inherits', + ]) + expect(existsSync(file('legacy/socket.json'))).toBe(false) + }) + it('loads and configures a build whose socket.json sets an invalid reachability value, replacing it', async () => { vi.spyOn(logger, 'warn').mockImplementation(() => logger) await writeSettings('legacy', { @@ -659,7 +694,7 @@ describe('setupRecursiveManifestConfig', () => { maven: { reachability: { build: 'compile', javaHome: '/opt/jdk-17' } }, }) loads({}) - const messages = await useRealMavenWizard([ + const { messages } = await useRealMavenWizard([ ['Configure Maven defaults for any nested projects?', true], ['old (maven)', 'inherit'], ['tool (maven)', 'inherit'], @@ -701,7 +736,7 @@ describe('setupRecursiveManifestConfig', () => { parentBuild ? { maven: { reachability: { build: parentBuild } } } : {}, ) loads({ 'pom.xml': ['api'], 'legacy/pom.xml': ['old'] }) - const messages = await useRealMavenWizard([ + const { messages } = await useRealMavenWizard([ [BUILD_QUESTION, false], ['This project (maven)', 'inherit'], ['Review the', true], diff --git a/test/setup-prompts.mts b/test/setup-prompts.mts index 3c5e4c623..5460c6af4 100644 --- a/test/setup-prompts.mts +++ b/test/setup-prompts.mts @@ -5,16 +5,14 @@ import { input, select } from '../src/utils/prompts.mts' // Wizard prompts, as far as answerPrompts matches them. export const BUILD_QUESTION = 'Build project before reachability analysis? Note: A failed build fails the scan.' -export const ECOSYSTEM_QUESTION = - 'Select ecosystem manifest generator to configure' export const JDK_PROMPT = 'What JDK should reachability analysis use?' export const JDK_QUESTION = 'Use a different Java for reachability analysis?' export const RUNTIME_PROMPT = 'Which .NET runtime?' export const RUNTIME_QUESTION = 'Start the reachability analysis of a framework-dependent .NET build on a given runtime?' -export const WRITE_QUESTION = 'Do you want to write the new config' type Prompt = { + choices?: ReadonlyArray<{ description?: unknown; name?: unknown }> | undefined default?: unknown message: string validate?: ((value: string) => unknown) | undefined @@ -28,6 +26,8 @@ export function answerPrompts(answers: Record = {}): { asked: Record messages: string[] // The defaults the prompts answered under `key` showed. + // The description of the "no" choice of each prompt answered under `key`. + noChoice: (key: string) => unknown[] shown: (key: string) => unknown[] } { const asked: Record = {} @@ -46,6 +46,11 @@ export function answerPrompts(answers: Record = {}): { return { asked, messages, + noChoice: key => + (asked[key] ?? []).map( + prompt => + prompt.choices?.find(choice => choice.name === 'no')?.description, + ), shown: key => (asked[key] ?? []).map(prompt => prompt.default), } }