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/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 2aa513fdf..f67a8f837 100644 --- a/src/commands/manifest/setup-manifest-config.mts +++ b/src/commands/manifest/setup-manifest-config.mts @@ -1,18 +1,63 @@ import fs from 'node:fs' import path from 'node:path' +import { isDeepStrictEqual } from 'node:util' +import { + DOTNET_RUNTIME_VERSION_FORMAT, + parseReachability, + reachabilityFieldsOf, +} 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 { readSocketJsonSync, 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 { ManifestDefaults } from '../../utils/socket-json.mts' +import type { + ManifestDefaults, + ReachabilityDefaults, + ReachabilityField, +} from '../../utils/socket-json.mts' + +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 +> // 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 @@ -624,16 +669,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? Enter ${DOTNET_RUNTIME_VERSION_FORMAT}.` + + (current ? ' (Backspace to leave default)' : ''), + default: current, + required: false, + validate: (value: string) => + !value || + !parseReachability('dotnet', { runtimeVersion: value }).problems.length || + `Enter ${DOTNET_RUNTIME_VERSION_FORMAT}.`, + }) +} + async function askForVerboseFlag( current: boolean | undefined, ): Promise { @@ -715,6 +779,138 @@ async function askForIgnoreUnresolvedFlag( }) } +// 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[], + inherited: unknown, +): void { + for (const { field, value } of problems) { + let parent: unknown + let setting: string + let reason: string + if (field === undefined) { + parent = inherited + setting = 'reachability' + reason = 'is not an object' + } else { + parent = isRecord(inherited) ? inherited[field] : undefined + 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 keeps the value in effect; "none" overrides an inherited +// "compile". +export async function setupReachability( + tool: BuildTool, + config: { reachability?: ReachabilityDefaults | undefined }, + inheritedReachability: unknown, +): Promise> { + const { problems, settings: reachability } = parseReachability( + tool, + config.reachability, + ) + warnInvalidReachability(tool, problems, inheritedReachability) + const { settings: inherited } = parseReachability(tool, inheritedReachability) + // An invalid value of its own leaves the inherited one in effect. + const effective = { ...inherited, ...reachability } + + 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: effective.build === 'compile', + }) + if (wantsBuild === undefined) { + return canceledByUser() + } + if (wantsBuild) { + reachability.build = 'compile' + } else if (inherited.build === 'compile') { + reachability.build = 'none' + } else { + delete reachability.build + } + + // 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}${current === inherited[field] ? ', which it inherits' : ''}` + : 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 (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) { + config.reachability = reachability + } else { + delete config.reachability + } + 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..7143cbac7 100644 --- a/src/commands/manifest/setup-manifest-config.test.mts +++ b/src/commands/manifest/setup-manifest-config.test.mts @@ -1,4 +1,4 @@ -import { 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,10 +13,30 @@ import { setupDotnet, setupGradle, setupMaven, + setupReachability, setupSbt, } from './setup-manifest-config.mts' +import { + BUILD_QUESTION, + JDK_PROMPT, + JDK_QUESTION, + RUNTIME_PROMPT, + RUNTIME_QUESTION, + answerPrompts, +} from '../../../test/setup-prompts.mts' +import { logger } from '../../utils/logger.mts' import { input, select } from '../../utils/prompts.mts' +import type { BuildTool } from './scripts/build-tool.mts' +import type { ReachabilityDefaults } from '../../utils/socket-json.mts' + +afterEach(() => { + vi.restoreAllMocks() + answerPrompts() + vi.mocked(input).mockClear() + vi.mocked(select).mockClear() +}) + describe('setup wizards', () => { it.for([ ['dotnet', setupDotnet], @@ -60,11 +80,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({}) @@ -73,11 +89,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 }) @@ -89,6 +101,324 @@ describe('setupGradle/setupMaven/setupSbt', () => { }) }) +describe('setup wizards without dynamic SBOM inference', () => { + it.for([ + ['dotnet', setupDotnet], + ['gradle', setupGradle], + ['maven', setupMaven], + ['sbt', setupSbt], + ] as const)( + '%s never asks for the reachability settings, leaving them as they are', + async ({ 1: setup }) => { + const { messages } = answerPrompts() + const config: Record = { + reachability: { build: 'compile' }, + } + + await setup(config) + + 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' }) + }, + ) + + it('writes nothing on a no and never asks for the JDK', async () => { + const { asked } = answerPrompts({ + [JDK_PROMPT]: '/never-asked', + [JDK_QUESTION]: false, + }) + + 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 }) + + expect(await step('maven', { javaHome: '/opt/jdk-17' })).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-11' }, + { javaHome: '/opt/jdk-11' }, + 'Keep /opt/jdk-11 as the JDK for reachability analysis, which it inherits', + ], + [ + { 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 }) => { + const { noChoice } = answerPrompts({ [JDK_QUESTION]: false }) + + await step('maven', reachability, inherited) + + expect(noChoice(JDK_QUESTION)).toEqual([label]) + }, + ) + + it.for([ + { + name: 'its own JDK', + inherited: undefined, + left: undefined, + offered: '/opt/jdk-17', + }, + { + name: 'an inherited JDK', + 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 ({ inherited, left, offered }) => { + const { shown } = answerPrompts({ + [JDK_PROMPT]: '', + [JDK_QUESTION]: true, + }) + + expect( + await step('maven', { javaHome: '/opt/jdk-17' }, inherited), + ).toEqual(left) + expect(shown(JDK_PROMPT)).toEqual([offered]) + }, + ) +}) + +describe('reachability build step', () => { + it.for(['dotnet', 'gradle', 'maven', 'sbt'] as const)( + '%s writes compile to reachability.build after a yes', + async tool => { + answerPrompts({ [BUILD_QUESTION]: true }) + + expect(await step(tool, undefined)).toEqual({ build: 'compile' }) + }, + ) + + it.for(['dotnet', 'gradle', 'maven', 'sbt'] as const)( + '%s leaves reachability.build unset after a no at the top level, never writing none', + async tool => { + answerPrompts({ [BUILD_QUESTION]: false }) + + expect(await step(tool, undefined)).toBeUndefined() + }, + ) + + it.for(['dotnet', 'gradle', 'maven', 'sbt'] as const)( + '%s writes none after a no when the project inherits compile', + async tool => { + const { shown } = answerPrompts({ [BUILD_QUESTION]: false }) + + expect( + await step(tool, { build: 'compile' }, { build: 'compile' }), + ).toEqual({ build: 'none' }) + expect(shown(BUILD_QUESTION)).toEqual([true]) + }, + ) + + it('leaves the build unset after a no when the project inherits none', async () => { + answerPrompts({ [BUILD_QUESTION]: false }) + + 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 }) + + expect( + await step('maven', { build: 'compile', javaHome: '/opt/jdk-17' }), + ).toEqual({ javaHome: '/opt/jdk-17' }) + expect(shown(BUILD_QUESTION)).toEqual([true]) + }) + + it('removes a written none after a no', async () => { + const { shown } = answerPrompts({ [BUILD_QUESTION]: false }) + + expect(await step('dotnet', { build: 'none' })).toBeUndefined() + expect(shown(BUILD_QUESTION)).toEqual([false]) + }) + + it('never asks dotnet for a reachability JDK', async () => { + const { messages } = answerPrompts({ [BUILD_QUESTION]: true }) + + expect(await step('dotnet', undefined)).toEqual({ build: 'compile' }) + expect(messages).toContain(BUILD_QUESTION) + expect(messages.some(m => m.includes('Java'))).toBe(false) + }) +}) + +describe('reachability runtime step', () => { + it('writes the runtime named after a yes to reachability.runtimeVersion', async () => { + answerPrompts({ [RUNTIME_PROMPT]: '8.0', [RUNTIME_QUESTION]: true }) + + expect(await step('dotnet', undefined)).toEqual({ 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 } = answerPrompts({ + [RUNTIME_PROMPT]: '8.0', + [RUNTIME_QUESTION]: true, + }) + + await step('dotnet', undefined) + + const result = await asked[RUNTIME_PROMPT]?.[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 { shown } = answerPrompts({ + [RUNTIME_PROMPT]: '', + [RUNTIME_QUESTION]: true, + }) + + expect( + await step( + 'dotnet', + { runtimeVersion: '9.0' }, + { runtimeVersion: '9.0' }, + ), + ).toEqual({ runtimeVersion: null }) + expect(shown(RUNTIME_PROMPT)).toEqual(['9.0']) + }) + + it('never asks a JVM build tool for a .NET runtime', async () => { + const { messages } = answerPrompts() + + await step('maven', undefined) + + expect(messages).not.toContain(RUNTIME_QUESTION) + }) +}) + +describe('reachability settings written invalid', () => { + 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) + + 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, saying where to fix it', async () => { + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => logger) + const { shown } = answerPrompts({ [BUILD_QUESTION]: false }) + const inherited = { build: 'always', javaHome: 17 } + + expect(await step('gradle', inherited, inherited)).toBeUndefined() + expect(shown(BUILD_QUESTION)).toEqual([false]) + 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('replaces its own invalid values and names the inherited ones', async () => { + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => logger) + const inherited = { build: 'compile', javaHome: 17 } + + await step('gradle', { ...inherited, build: 'always' }, inherited) + + expect(warn.mock.calls.map(c => c[0])).toEqual([ + expect.stringContaining('Replacing `reachability.build`'), + expect.stringContaining( + '`reachability.javaHome` (17), which this build inherits', + ), + ]) + }) + + 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 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', + ]) + }) +}) + 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..b1016609d 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' @@ -36,6 +37,7 @@ import { setupDotnet, setupGradle, setupMaven, + setupReachability, setupSbt, } from './setup-manifest-config.mts' import { SOCKET_JSON } from '../../constants.mts' @@ -44,6 +46,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, @@ -89,6 +92,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, @@ -315,6 +340,14 @@ function draftCascade(draft: SettingsDraft, dir: string): SocketJson { return mergeSocketJsonChain(draftChain(draft, dir)) } +// What `dir`'s own socket.json inherits. +function draftParentCascade(draft: SettingsDraft, dir: string): SocketJson { + const own = path.resolve(dir) + return mergeSocketJsonChain( + draftChain(draft, dir).filter(file => file.dir !== own), + ) +} + function resolveDraftSettings( draft: SettingsDraft, ecosystem: BuildTool, @@ -448,7 +481,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 = { @@ -459,18 +494,23 @@ async function configureBuild( } const seeded = Object.keys(seed) - const result = await runEcosystemWizard(ecosystem, seed) + const result = await runEcosystemWizard( + ecosystem, + seed, + 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) @@ -804,36 +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'>) - } - if (ecosystem === 'gradle') { - return await setupGradle(config as ManifestDefaults<'gradle'>, { + result = await setupDotnet(config as ManifestDefaults<'dotnet'>) + } else if (ecosystem === 'gradle') { + result = await setupGradle(config as ManifestDefaults<'gradle'>, { + factsOnly: true, + }) + } else if (ecosystem === 'maven') { + result = await setupMaven(config as ManifestDefaults<'maven'>) + } else { + result = await setupSbt(config as ManifestDefaults<'sbt'>, { 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 + if (!result.ok || result.data.canceled) { + return result } - delete manifest[ecosystem] - return false + return await setupReachability(ecosystem, config, inheritedReachability) } async function askYesNo(message: string): Promise { @@ -900,16 +935,33 @@ 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 = { + ...getEcosystemSection(draftCascade(draft, cwd), ecosystem), + } + const inherited = getEcosystemSection( + draftParentCascade(draft, cwd), + ecosystem, + ) // eslint-disable-next-line no-await-in-loop - const result = await runEcosystemWizard(ecosystem, section) + const result = await runEcosystemWizard( + ecosystem, + section, + 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 f0157e99c..401ae4788 100644 --- a/src/commands/manifest/setup-recursive-manifest-config.test.mts +++ b/src/commands/manifest/setup-recursive-manifest-config.test.mts @@ -17,26 +17,33 @@ 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', () => ({ 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, + JDK_QUESTION, + answerPrompts, +} from '../../../test/setup-prompts.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' @@ -158,6 +165,19 @@ 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 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) + vi.mocked(setupReachability).mockImplementation(actual.setupReachability) + return answerPrompts(Object.fromEntries(answers)) +} + describe('setupRecursiveManifestConfig', () => { let repo = '' let asked: string[] = [] @@ -204,7 +224,6 @@ describe('setupRecursiveManifestConfig', () => { } return rule[1] as never }) - beforeEach(async () => { repo = await fs.realpath( await fs.mkdtemp(path.join(tmpdir(), 'setup-recursive-')), @@ -225,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) @@ -552,6 +576,199 @@ 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('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', { + maven: { + mavenOpts: '-B', + reachability: { build: 'always', javaHome: 17 }, + }, + }) + loads({ 'pom.xml': ['api'], 'legacy/pom.xml': ['old'] }) + await useRealMavenWizard([ + ['This project (maven)', 'inherit'], + ['Review the', true], + ['legacy (maven)', 'configure'], + ['legacy/tool (maven)', 'inherit'], + ['Write it?', true], + ]) + + 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 { + await fs.rm(file('legacy/pom.xml')) + await writeSettings('.', { + maven: { reachability: { build: 'compile', javaHome: '/opt/jdk-17' } }, + }) + loads({}) + const { messages } = await useRealMavenWizard([ + ['Configure Maven defaults for any nested projects?', true], + ['old (maven)', 'inherit'], + ['tool (maven)', 'inherit'], + ['Write it?', true], + ]) + + const result = await setupRecursiveManifestConfig(file('legacy'), false) + expect(result).toEqual({ ok: true, data: { canceled: false } }) + expect(messages).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' }, + }) + }) + + // 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') + + 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 } }, diff --git a/test/setup-prompts.mts b/test/setup-prompts.mts new file mode 100644 index 000000000..5460c6af4 --- /dev/null +++ b/test/setup-prompts.mts @@ -0,0 +1,56 @@ +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 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?' + +type Prompt = { + choices?: ReadonlyArray<{ description?: unknown; name?: unknown }> | undefined + 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. + // The description of the "no" choice of each prompt answered under `key`. + noChoice: (key: string) => unknown[] + 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, + noChoice: key => + (asked[key] ?? []).map( + prompt => + prompt.choices?.find(choice => choice.name === 'no')?.description, + ), + shown: key => (asked[key] ?? []).map(prompt => prompt.default), + } +}