diff --git a/packages/nx/src/utils/executor-options.spec.ts b/packages/nx/src/utils/executor-options.spec.ts new file mode 100644 index 000000000..1e17db9b0 --- /dev/null +++ b/packages/nx/src/utils/executor-options.spec.ts @@ -0,0 +1,138 @@ +import { ExecutorContext, TargetConfiguration } from '@nx/devkit'; +import { combineOptionsForExecutor } from 'nx/src/devkit-internals'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import prepareSchema from '../executors/build/prepare.schema.json'; + +const { promptMock, spawnMock } = vi.hoisted(() => ({ promptMock: vi.fn(), spawnMock: vi.fn() })); +vi.mock('enquirer', () => ({ prompt: promptMock })); +vi.mock('child_process', () => ({ default: { spawn: spawnMock } })); + +import { commonExecutor } from './executors'; +import { ExecutorSchema } from './types'; + +const prepareTarget: TargetConfiguration = { + executor: '@nativescript/nx:prepare', + options: { + noHmr: true, + production: true, + uglify: true, + release: true, + forDevice: true, + prepare: true, + provision: 'Options Profile', + android: { + keyStorePath: './options.keystore', + keyStoreAlias: 'options-alias', + }, + }, + configurations: { + prod: { + uglify: false, + provision: 'Prod Profile', + android: { + keyStoreAlias: 'prod-alias', + keyStorePassword: 'prod-password', + }, + }, + }, +}; + +async function runPrepare(cliOverrides: Record, configurationName?: string, target = prepareTarget): Promise { + const options = combineOptionsForExecutor( + cliOverrides, + configurationName, + structuredClone(target), + prepareSchema as unknown as Parameters[3], + 'app', + '', + ) as ExecutorSchema; + const context = { + root: '/workspace', + cwd: '/workspace', + isVerbose: false, + projectName: 'app', + targetName: 'prepare', + configurationName, + projectsConfigurations: { version: 2, projects: { app: { root: 'apps/app', targets: { prepare: structuredClone(target) } } } }, + } as unknown as ExecutorContext; + + await commonExecutor(options, context); + expect(spawnMock).toHaveBeenCalledTimes(1); + return spawnMock.mock.calls[0][1]; +} + +describe('commonExecutor option precedence', () => { + const originalIsTTY = process.stdin.isTTY; + + beforeEach(() => { + Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); + promptMock.mockReset(); + spawnMock.mockReset(); + spawnMock.mockImplementation(() => ({ + on: (event: string, listener: (code: number) => void) => event === 'close' && setImmediate(() => listener(0)), + kill: vi.fn(), + })); + vi.spyOn(console, 'log').mockImplementation(() => undefined); + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + }); + + afterEach(() => { + Object.defineProperty(process.stdin, 'isTTY', { value: originalIsTTY, configurable: true }); + vi.restoreAllMocks(); + }); + + it('applies project.json options when nothing is passed on the CLI', async () => { + const args = await runPrepare({ platform: 'ios' }); + expect(args).toEqual( + expect.arrayContaining(['prepare', 'ios', '--no-hmr', '--env.uglify', '--env.production', '--for-device', '--release', '--provision=Options Profile']), + ); + }); + + it('lets a boolean false on the CLI override true in options', async () => { + const args = await runPrepare({ platform: 'ios', noHmr: false, release: false }); + expect(args).not.toContain('--no-hmr'); + expect(args).not.toContain('--release'); + expect(args).toContain('--env.uglify'); + }); + + it('lets a string on the CLI override a string in options', async () => { + const args = await runPrepare({ platform: 'ios', provision: 'CLI Profile' }); + expect(args).toContain('--provision=CLI Profile'); + expect(args).not.toContain('--provision=Options Profile'); + }); + + it('applies the configuration over options', async () => { + const args = await runPrepare({ platform: 'ios' }, 'prod'); + expect(args).toContain('--provision=Prod Profile'); + expect(args).not.toContain('--env.uglify'); + expect(args).toContain('--no-hmr'); + }); + + it('lets the CLI override the configuration', async () => { + const args = await runPrepare({ platform: 'ios', uglify: true, provision: 'CLI Profile', noHmr: false }, 'prod'); + expect(args).toContain('--env.uglify'); + expect(args).toContain('--provision=CLI Profile'); + expect(args).not.toContain('--no-hmr'); + }); + + it('combines nested platform options from options, configuration and the CLI', async () => { + const args = await runPrepare({ platform: 'android' }, 'prod'); + expect(args).toEqual(expect.arrayContaining(['--key-store-path=./options.keystore', '--key-store-alias=prod-alias', '--key-store-password=prod-password'])); + + spawnMock.mockClear(); + const withCli = await runPrepare({ platform: 'android', android: { keyStorePassword: 'cli-password' } }, 'prod'); + expect(withCli).toEqual( + expect.arrayContaining(['--key-store-path=./options.keystore', '--key-store-alias=prod-alias', '--key-store-password=cli-password']), + ); + }); + + it('lets the CLI override a configuration chosen at the prompt', async () => { + Object.defineProperty(process.stdin, 'isTTY', { value: true, configurable: true }); + promptMock.mockResolvedValue({ configurationName: 'prod' }); + const args = await runPrepare({ platform: 'ios', provision: 'CLI Profile', noHmr: false }); + expect(promptMock).toHaveBeenCalledTimes(1); + expect(args).toContain('--provision=CLI Profile'); + expect(args).not.toContain('--no-hmr'); + expect(args).not.toContain('--env.uglify'); + }); +}); diff --git a/packages/nx/src/utils/executors.ts b/packages/nx/src/utils/executors.ts index b4d5df293..25f9dd812 100644 --- a/packages/nx/src/utils/executors.ts +++ b/packages/nx/src/utils/executors.ts @@ -1,10 +1,11 @@ -import { ExecutorContext } from '@nx/devkit'; +import { ExecutorContext, TargetConfiguration } from '@nx/devkit'; import childProcess from 'child_process'; import { prompt } from 'enquirer'; import { XMLBuilder, XMLParser } from 'fast-xml-parser'; import { readFileSync, writeFileSync } from 'fs-extra'; import { resolve as nodeResolve } from 'path'; import { build, parse } from 'plist'; +import { isDeepStrictEqual } from 'util'; import { Platform } from '../schemas/base.schema'; import { mergeDeep } from '../schemas/deep-merge'; import { COMMANDS } from './commands'; @@ -60,6 +61,35 @@ export async function selectConfiguration( return configurationName; } +/** + * Nx resolves executor options as schema defaults < target options < configuration < CLI with a + * shallow merge, so a nested object such as `android` or `ios` replaces the one below it wholesale. + * This rebuilds the same precedence with a deep merge. + * + * Nx does not tell the executor which options came from the CLI, so a key counts as a CLI override + * when its value differs from what `nxTarget` and `nxConfigurationName` (the target and configuration + * Nx resolved from) produce on their own. A key that neither of those sets is ambiguous between a CLI + * flag and a schema default; it only loses to a configuration Nx did not apply (one chosen at the prompt). + */ +function mergeTargetOptions( + options: ExecutorSchema, + nxTarget: TargetConfiguration | undefined, + nxConfigurationName: string | undefined, + target: TargetConfiguration, + configurationName: string | undefined, +): ExecutorSchema { + const nxResolved = { ...nxTarget?.options, ...(nxConfigurationName ? nxTarget?.configurations?.[nxConfigurationName] : undefined) }; + const configuration = (configurationName && target.configurations?.[configurationName]) || {}; + + const cliOverrides: Partial = {}; + for (const key of Object.keys(options)) { + const fromCli = key in nxResolved ? !isDeepStrictEqual(options[key], nxResolved[key]) : !(key in configuration); + if (fromCli) cliOverrides[key] = options[key]; + } + + return mergeDeep({}, options, target.options, configuration, cliOverrides); +} + export function commonExecutor(options: ExecutorSchema, context: ExecutorContext): Promise<{ success: boolean }> { // global vars const isWindows = process.platform === 'win32'; @@ -100,12 +130,10 @@ export function commonExecutor(options: ExecutorSchema, context: ExecutorContext const targetPlatformOptions = targetOptions[options.platform]; // const targetDescription = JSON.parse(process.argv.find((arg) => arg.indexOf('targetDescription') !== -1)); - // fix for nx overwriting android and ios sub properties - mergeDeep(options, targetOptions); - const configurationName = await selectConfiguration(target.configurations, context.configurationName); - // fix for nx overwriting android and ios sub properties - if (configurationName) mergeDeep(options, target.configurations[configurationName]); + // Nx resolved `options` from the invoked target, which need not be the one named after the command. + const nxTarget = (context.targetName && projectConfig.targets[context.targetName]) || target; + Object.assign(options, mergeTargetOptions(options, nxTarget, context.configurationName, target, configurationName)); const nsOptions = prepareNsOptions(options, projectCwd); const additionalArgs: string[] = []; // Assuming any extra flags are handled here