diff --git a/CHANGELOG.md b/CHANGELOG.md index 6309ae460..00da2810d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added - Socket facts for a self-contained .NET build include its runtime packs. - Tune reachability per build tool in `socket.json`: `reachability.build` compiles the project before the analysis, `reachability.javaHome` (Maven, Gradle, sbt) sets the JDK the analysis assumes, and `reachability.runtimeVersion` (.NET) sets the runtime it starts on. +- `socket manifest setup` and `socket manifest setup --dynamic-sbom-inference` ask for the reachability settings, so there is no need to edit `socket.json` by hand. ### Changed - Updated the Coana CLI to v `15.15.4`. diff --git a/src/commands/manifest/setup-manifest-config.mts b/src/commands/manifest/setup-manifest-config.mts index 2aa513fdf..afc5d8a8d 100644 --- a/src/commands/manifest/setup-manifest-config.mts +++ b/src/commands/manifest/setup-manifest-config.mts @@ -1,19 +1,42 @@ 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. 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) + 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 +215,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 +345,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 +375,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 +419,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 +434,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 +480,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 +521,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 +564,10 @@ export async function setupSbt( return canceledByUser() } + if (generatesFacts) { + return await setupReachability('sbt', config, options) + } + return notCanceled() } @@ -624,16 +673,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 +783,192 @@ 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( + 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] +} + +// 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 = {}, +): 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 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-manifest-config.test.mts b/src/commands/manifest/setup-manifest-config.test.mts index 997237ac7..a9ab9f08d 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 @@ -9,13 +13,21 @@ 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, setupSbt, } from './setup-manifest-config.mts' +import { logger } from '../../utils/logger.mts' import { input, select } from '../../utils/prompts.mts' +import { + getDefaultSocketJson, + readSocketJsonChain, + writeSocketJson, +} from '../../utils/socket-json.mts' describe('setup wizards', () => { it.for([ @@ -89,6 +101,655 @@ 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], + ['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 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], + ['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 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') + 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 ?? '') + vi.mocked(input).mockReset() + vi.mocked(input).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' }, + }) + }) + + 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', () => { + 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 400ded19a..18b7cf140 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' @@ -38,6 +39,7 @@ import { joinAnd } from '../../utils/arrays.mts' import { loadSocketConfig } from '../../utils/config.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, @@ -56,6 +58,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, @@ -83,6 +86,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, @@ -451,18 +476,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) @@ -813,33 +841,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 setupSbt(config as ManifestDefaults<'sbt'>, { factsOnly: true }) -} - -// 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 + return await setupMaven(config as ManifestDefaults<'maven'>, options) } - delete manifest[ecosystem] - return false + return await setupSbt(config as ManifestDefaults<'sbt'>, { + ...options, + factsOnly: true, + }) } async function askYesNo(message: string): Promise { @@ -906,16 +925,29 @@ 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, + ) // 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 } - 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 8fdcddc50..43d3488f7 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', () => ({ @@ -35,7 +36,7 @@ import { setupRecursiveManifestConfig, } from './setup-recursive-manifest-config.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 { SocketFactsProject } from './run-manifest-facts.mts' @@ -561,6 +562,211 @@ 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', + }) + }) + + // 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.' + + // 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 } },