diff --git a/apps/heft/src/cli/HeftActionRunner.ts b/apps/heft/src/cli/HeftActionRunner.ts index 1d61e1db0ac..55eac1744ee 100644 --- a/apps/heft/src/cli/HeftActionRunner.ts +++ b/apps/heft/src/cli/HeftActionRunner.ts @@ -313,6 +313,8 @@ export class HeftActionRunner { // executed, and the session should be populated with the executing parameters. this.#internalHeftSession.parameterManager = this.parameterManager; + this.parameterManager.validateParameters(); + initializeHeft(this.#heftConfiguration, terminal, this.parameterManager.defaultParameters.verbose); const operations: ReadonlySet> = diff --git a/apps/heft/src/configuration/HeftPluginDefinition.ts b/apps/heft/src/configuration/HeftPluginDefinition.ts index 822ef3453e3..786c1f06953 100644 --- a/apps/heft/src/configuration/HeftPluginDefinition.ts +++ b/apps/heft/src/configuration/HeftPluginDefinition.ts @@ -35,6 +35,18 @@ export interface IBaseParameterJson { * If true, then this parameter must be included on the command line. */ required?: boolean; + /** + * If false, reject an active parameter when running with `--clean`, before any plugins run or outputs + * are deleted. Defaults to true. A parameter is active when its flag is true, its list is nonempty, + * or its scalar value is defined, including default values. + */ + allowWithClean?: boolean; + /** + * If false, reject an active parameter in watch mode, before any plugins run or outputs are deleted. + * Defaults to true. A parameter is active when its flag is true, its list is nonempty, or its scalar + * value is defined, including default values. + */ + allowInWatchMode?: boolean; } /** diff --git a/apps/heft/src/pluginFramework/HeftParameterManager.ts b/apps/heft/src/pluginFramework/HeftParameterManager.ts index 17538c851f9..d8e66b2b2fa 100644 --- a/apps/heft/src/pluginFramework/HeftParameterManager.ts +++ b/apps/heft/src/pluginFramework/HeftParameterManager.ts @@ -195,6 +195,23 @@ export class HeftParameterManager { } } + /** + * Validate effective parameter values after parsing and before executing the action. + */ + public validateParameters(): void { + const defaultParameters: IHeftDefaultParameters = this.defaultParameters; + this.#parametersByDefinition.forEach((parameters, pluginDefinition) => { + pluginDefinition.pluginParameters.forEach((definition) => { + validateParameter( + parameters.get(definition.longName)!, + definition, + pluginDefinition, + defaultParameters + ); + }); + }); + } + /** * Get the finalized parameters for the specified plugin definition. */ @@ -397,3 +414,42 @@ export class HeftParameterManager { return parameter as T; } } + +export function validateParameter( + parameter: CommandLineParameter, + definition: IParameterJson, + pluginDefinition: HeftPluginDefinitionBase, + { clean, watch }: Pick +): void { + const disallowedWithClean: boolean = clean && definition.allowWithClean === false; + const disallowedInWatchMode: boolean = watch && definition.allowInWatchMode === false; + if (!disallowedWithClean && !disallowedInWatchMode) { + return; + } + + let isActive: boolean; + switch (parameter.kind) { + case CommandLineParameterKind.Flag: + isActive = parameter.value; + break; + case CommandLineParameterKind.ChoiceList: + case CommandLineParameterKind.IntegerList: + case CommandLineParameterKind.StringList: + isActive = parameter.values.length > 0; + break; + default: + isActive = parameter.value !== undefined; + break; + } + if (isActive) { + const parameterName: string = parameter.scopedLongName || parameter.longName; + const mode: string = disallowedWithClean ? '--clean' : 'watch mode'; + const remedy: string = disallowedWithClean ? 'without --clean' : 'in a non-watch action'; + throw new Error( + `Parameter ${JSON.stringify(parameterName)} from plugin ` + + `${JSON.stringify(pluginDefinition.pluginName)} in package ` + + `${JSON.stringify(pluginDefinition.pluginPackageName)} cannot be used with ${mode}. ` + + `Run ${remedy}, or remove the parameter (including any configured default value).` + ); + } +} diff --git a/apps/heft/src/pluginFramework/tests/HeftParameterManager.test.ts b/apps/heft/src/pluginFramework/tests/HeftParameterManager.test.ts new file mode 100644 index 00000000000..4d598962778 --- /dev/null +++ b/apps/heft/src/pluginFramework/tests/HeftParameterManager.test.ts @@ -0,0 +1,322 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. +// See LICENSE in the project root for license information. + +import { JsonSchema } from '@rushstack/node-core-library'; +import { + AliasCommandLineAction, + DynamicCommandLineAction, + DynamicCommandLineParser, + type CommandLineFlagParameter +} from '@rushstack/ts-command-line'; + +import { HeftParameterManager, validateParameter } from '../HeftParameterManager'; +import { HeftTaskPluginDefinition, type IParameterJson } from '../../configuration/HeftPluginDefinition'; +import heftPluginSchema from '../../schemas/heft-plugin.schema.json'; + +interface IParameterTestCase { + parameter: IParameterJson; + args: string[]; +} + +const PARAMETER_TEST_CASES: IParameterTestCase[] = [ + { + parameter: { parameterKind: 'flag', longName: '--value', description: 'A flag.' }, + args: ['--value'] + }, + { + parameter: { + parameterKind: 'choice', + longName: '--value', + description: 'A choice.', + alternatives: [{ name: 'first', description: 'First choice.' }] + }, + args: ['--value', 'first'] + }, + { + parameter: { + parameterKind: 'choiceList', + longName: '--value', + description: 'A choice list.', + alternatives: [{ name: 'first', description: 'First choice.' }] + }, + args: ['--value', 'first'] + }, + { + parameter: { + parameterKind: 'integer', + longName: '--value', + description: 'An integer.', + argumentName: 'VALUE' + }, + args: ['--value', '0'] + }, + { + parameter: { + parameterKind: 'integerList', + longName: '--value', + description: 'An integer list.', + argumentName: 'VALUE' + }, + args: ['--value', '0'] + }, + { + parameter: { + parameterKind: 'string', + longName: '--value', + description: 'A string.', + argumentName: 'VALUE' + }, + args: ['--value', ''] + }, + { + parameter: { + parameterKind: 'stringList', + longName: '--value', + description: 'A string list.', + argumentName: 'VALUE' + }, + args: ['--value', ''] + } +]; + +function createPlugin( + parameter: IParameterJson, + parameterScope: string = 'test-scope' +): HeftTaskPluginDefinition { + return HeftTaskPluginDefinition.loadFromObject({ + heftPluginDefinitionJson: { + pluginName: 'test-plugin', + parameterScope, + entryPoint: 'unused.js', + parameters: [parameter] + }, + packageName: 'test-package', + packageRoot: __dirname + }); +} + +async function parseAsync( + plugins: HeftTaskPluginDefinition[], + args: string[], + aliasDefaults?: string[] +): Promise { + const parser: DynamicCommandLineParser = new DynamicCommandLineParser({ + toolFilename: 'heft-test', + toolDescription: 'Test parameter preflight.' + }); + const action: DynamicCommandLineAction = new DynamicCommandLineAction({ + actionName: 'run', + summary: 'Run a test.', + documentation: 'Run a test.' + }); + parser.addAction(action); + const clean = action.defineFlagParameter({ parameterLongName: '--clean', description: 'Clean outputs.' }); + const watch = action.defineFlagParameter({ parameterLongName: '--watch', description: 'Watch files.' }); + const manager: HeftParameterManager = new HeftParameterManager({ + getIsClean: () => clean.value, + getIsWatch: () => watch.value, + getIsDebug: () => false, + getIsVerbose: () => false, + getIsProduction: () => false, + getLocales: () => [] + }); + for (const plugin of plugins) { + manager.addPluginParameters(plugin); + } + manager.finalizeParameters(action); + if (aliasDefaults) { + parser.addAction( + new AliasCommandLineAction({ + toolFilename: 'heft-test', + aliasName: 'alias', + targetAction: action, + defaultParameters: aliasDefaults + }) + ); + } + await parser.executeWithoutErrorHandlingAsync([aliasDefaults ? 'alias' : 'run', ...args]); + return manager; +} + +describe(HeftParameterManager.name, () => { + describe.each(PARAMETER_TEST_CASES)('$parameter.parameterKind', ({ parameter, args }) => { + it.each(['--clean', '--watch'])('rejects an active restricted value with %s', async (mode) => { + const manager: HeftParameterManager = await parseAsync( + [createPlugin({ ...parameter, allowWithClean: false, allowInWatchMode: false })], + [mode, ...args] + ); + expect(() => manager.validateParameters()).toThrow( + `Parameter "--test-scope:value" from plugin "test-plugin" in package "test-package" cannot be used with ${ + mode === '--clean' ? '--clean' : 'watch mode' + }. Run ${mode === '--clean' ? 'without --clean' : 'in a non-watch action'}` + ); + }); + + it.each(['--clean', '--watch'])('allows an inactive restricted value with %s', async (mode) => { + const manager: HeftParameterManager = await parseAsync( + [createPlugin({ ...parameter, allowWithClean: false, allowInWatchMode: false })], + [mode] + ); + expect(() => manager.validateParameters()).not.toThrow(); + }); + + it('allows an active restricted value without either mode', async () => { + const manager: HeftParameterManager = await parseAsync( + [createPlugin({ ...parameter, allowWithClean: false, allowInWatchMode: false })], + args + ); + expect(() => manager.validateParameters()).not.toThrow(); + }); + + it.each([undefined, true])('preserves behavior when restrictions are %s', async (restriction) => { + const manager: HeftParameterManager = await parseAsync( + [createPlugin({ ...parameter, allowWithClean: restriction, allowInWatchMode: restriction })], + ['--clean', '--watch', ...args] + ); + expect(() => manager.validateParameters()).not.toThrow(); + }); + + it('does not restrict the other mode', async () => { + const cleanOnly: HeftParameterManager = await parseAsync( + [createPlugin({ ...parameter, allowWithClean: false })], + ['--watch', ...args] + ); + const watchOnly: HeftParameterManager = await parseAsync( + [createPlugin({ ...parameter, allowInWatchMode: false })], + ['--clean', ...args] + ); + expect(() => cleanOnly.validateParameters()).not.toThrow(); + expect(() => watchOnly.validateParameters()).not.toThrow(); + }); + + it.each([ + { allowWithClean: true, allowInWatchMode: false, allowedMode: '--clean', rejectedMode: '--watch' }, + { allowWithClean: false, allowInWatchMode: true, allowedMode: '--watch', rejectedMode: '--clean' } + ])( + 'allows $allowedMode and rejects $rejectedMode when both restrictions are explicit', + async ({ allowWithClean, allowInWatchMode, allowedMode, rejectedMode }) => { + const plugin: HeftTaskPluginDefinition = createPlugin({ + ...parameter, + allowWithClean, + allowInWatchMode + }); + const allowed: HeftParameterManager = await parseAsync([plugin], [allowedMode, ...args]); + const rejected: HeftParameterManager = await parseAsync([plugin], [rejectedMode, ...args]); + expect(() => allowed.validateParameters()).not.toThrow(); + expect(() => rejected.validateParameters()).toThrow( + `cannot be used with ${rejectedMode === '--clean' ? '--clean' : 'watch mode'}` + ); + } + ); + }); + + it.each([ + { + parameterKind: 'integer', + longName: '--value', + description: 'Default zero.', + argumentName: 'VALUE', + defaultValue: 0 + }, + { + parameterKind: 'string', + longName: '--value', + description: 'Default empty string.', + argumentName: 'VALUE', + defaultValue: '' + }, + { + parameterKind: 'choice', + longName: '--value', + description: 'Default choice.', + alternatives: [{ name: 'first', description: 'First choice.' }], + defaultValue: 'first' + } + ])('checks the effective default for $parameterKind', async (parameter) => { + for (const mode of ['--clean', '--watch']) { + const manager: HeftParameterManager = await parseAsync( + [createPlugin({ ...parameter, allowWithClean: false, allowInWatchMode: false })], + [mode] + ); + expect(() => manager.validateParameters()).toThrow('--test-scope:value'); + } + }); + + it('checks scoped values independently when long names collide', async () => { + const parameter: IParameterJson = { + parameterKind: 'flag', + longName: '--value', + description: 'A flag.' + }; + const plugins: HeftTaskPluginDefinition[] = [ + createPlugin({ ...parameter, allowWithClean: false }, 'restricted'), + createPlugin(parameter, 'unrestricted') + ]; + const allowed: HeftParameterManager = await parseAsync(plugins, ['--clean', '--unrestricted:value']); + expect(() => allowed.validateParameters()).not.toThrow(); + const rejected: HeftParameterManager = await parseAsync(plugins, ['--clean', '--restricted:value']); + expect(() => rejected.validateParameters()).toThrow('--restricted:value'); + }); + + it('checks short names and alias defaults using parsed values', async () => { + const plugin: HeftTaskPluginDefinition = createPlugin({ + parameterKind: 'flag', + longName: '--value', + shortName: '-x', + description: 'A flag.', + allowWithClean: false + }); + const manager: HeftParameterManager = await parseAsync([plugin], [], ['--clean', '-x']); + expect(() => manager.validateParameters()).toThrow('--test-scope:value'); + }); +}); + +describe(validateParameter.name, () => { + it.each([ + { clean: true, watch: true, mode: '--clean', remedy: 'without --clean' }, + { clean: false, watch: true, mode: 'watch mode', remedy: 'in a non-watch action' } + ])('reports an unscoped parameter with $mode', async ({ clean, watch, mode, remedy }) => { + const definition: IParameterJson = { + parameterKind: 'flag', + longName: '--value', + description: 'A flag.', + allowWithClean: false, + allowInWatchMode: false + }; + const plugin: HeftTaskPluginDefinition = createPlugin(definition); + const parser: DynamicCommandLineParser = new DynamicCommandLineParser({ + toolFilename: 'heft-test', + toolDescription: 'Test single parameter validation.' + }); + const parameter: CommandLineFlagParameter = parser.defineFlagParameter({ + parameterLongName: definition.longName, + description: definition.description + }); + await parser.executeWithoutErrorHandlingAsync(['--value']); + + expect(() => validateParameter(parameter, definition, plugin, { clean, watch })).toThrow( + `Parameter "--value" from plugin "test-plugin" in package "test-package" cannot be used with ${mode}. ` + + `Run ${remedy}, or remove the parameter (including any configured default value).` + ); + }); +}); + +describe('plugin parameter restriction schema', () => { + const schema: JsonSchema = JsonSchema.fromLoadedObject(heftPluginSchema); + it.each(PARAMETER_TEST_CASES)('validates metadata on $parameter.parameterKind', ({ parameter }) => { + const validate = (extra: object): void => + schema.validateObject( + { + taskPlugins: [ + { pluginName: 'test-plugin', entryPoint: 'unused.js', parameters: [{ ...parameter, ...extra }] } + ] + }, + 'heft-plugin.json' + ); + expect(() => validate({ allowWithClean: false, allowInWatchMode: false })).not.toThrow(); + expect(() => validate({ allowWithClean: true, allowInWatchMode: true })).not.toThrow(); + expect(() => validate({ allowWithClean: 'false' })).toThrow(); + expect(() => validate({ allowInWatchMode: 'false' })).toThrow(); + expect(() => validate({ unknownRestriction: false })).toThrow(); + }); +}); diff --git a/apps/heft/src/schemas/heft-plugin.schema.json b/apps/heft/src/schemas/heft-plugin.schema.json index 37dd45012d7..f701d696bd6 100644 --- a/apps/heft/src/schemas/heft-plugin.schema.json +++ b/apps/heft/src/schemas/heft-plugin.schema.json @@ -42,6 +42,16 @@ "title": "Required", "description": "If true, then this parameter must be included on the command line", "type": "boolean" + }, + "allowWithClean": { + "title": "Allow With Clean", + "description": "If false, reject an active parameter with --clean before plugins run or outputs are deleted. Defaults to true. Flags are active when true, lists when nonempty, and scalars when defined, including default values.", + "type": "boolean" + }, + "allowInWatchMode": { + "title": "Allow In Watch Mode", + "description": "If false, reject an active parameter in watch mode before plugins run or outputs are deleted. Defaults to true. Flags are active when true, lists when nonempty, and scalars when defined, including default values.", + "type": "boolean" } } }, @@ -99,6 +109,8 @@ "shortName": { "$ref": "#/definitions/anything" }, "description": { "$ref": "#/definitions/anything" }, "required": { "$ref": "#/definitions/anything" }, + "allowWithClean": { "$ref": "#/definitions/anything" }, + "allowInWatchMode": { "$ref": "#/definitions/anything" }, "alternatives": { "$ref": "#/definitions/anything" }, "defaultValue": { "$ref": "#/definitions/anything" } @@ -155,6 +167,8 @@ "shortName": { "$ref": "#/definitions/anything" }, "description": { "$ref": "#/definitions/anything" }, "required": { "$ref": "#/definitions/anything" }, + "allowWithClean": { "$ref": "#/definitions/anything" }, + "allowInWatchMode": { "$ref": "#/definitions/anything" }, "alternatives": { "$ref": "#/definitions/anything" } } @@ -185,7 +199,9 @@ "longName": { "$ref": "#/definitions/anything" }, "shortName": { "$ref": "#/definitions/anything" }, "description": { "$ref": "#/definitions/anything" }, - "required": { "$ref": "#/definitions/anything" } + "required": { "$ref": "#/definitions/anything" }, + "allowWithClean": { "$ref": "#/definitions/anything" }, + "allowInWatchMode": { "$ref": "#/definitions/anything" } } } ] @@ -226,6 +242,8 @@ "shortName": { "$ref": "#/definitions/anything" }, "description": { "$ref": "#/definitions/anything" }, "required": { "$ref": "#/definitions/anything" }, + "allowWithClean": { "$ref": "#/definitions/anything" }, + "allowInWatchMode": { "$ref": "#/definitions/anything" }, "argumentName": { "$ref": "#/definitions/anything" }, "defaultValue": { "$ref": "#/definitions/anything" } @@ -264,6 +282,8 @@ "shortName": { "$ref": "#/definitions/anything" }, "description": { "$ref": "#/definitions/anything" }, "required": { "$ref": "#/definitions/anything" }, + "allowWithClean": { "$ref": "#/definitions/anything" }, + "allowInWatchMode": { "$ref": "#/definitions/anything" }, "argumentName": { "$ref": "#/definitions/anything" } } @@ -306,6 +326,8 @@ "shortName": { "$ref": "#/definitions/anything" }, "description": { "$ref": "#/definitions/anything" }, "required": { "$ref": "#/definitions/anything" }, + "allowWithClean": { "$ref": "#/definitions/anything" }, + "allowInWatchMode": { "$ref": "#/definitions/anything" }, "argumentName": { "$ref": "#/definitions/anything" }, "defaultValue": { "$ref": "#/definitions/anything" } @@ -344,6 +366,8 @@ "shortName": { "$ref": "#/definitions/anything" }, "description": { "$ref": "#/definitions/anything" }, "required": { "$ref": "#/definitions/anything" }, + "allowWithClean": { "$ref": "#/definitions/anything" }, + "allowInWatchMode": { "$ref": "#/definitions/anything" }, "argumentName": { "$ref": "#/definitions/anything" } } diff --git a/apps/heft/src/test/ParameterPreflight.test.ts b/apps/heft/src/test/ParameterPreflight.test.ts new file mode 100644 index 00000000000..373758fb113 --- /dev/null +++ b/apps/heft/src/test/ParameterPreflight.test.ts @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. +// See LICENSE in the project root for license information. + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { spawnSync, type SpawnSyncReturns } from 'node:child_process'; + +import { FileSystem } from '@rushstack/node-core-library'; + +describe('Heft parameter preflight', () => { + let projectFolder: string; + const packageName: string = 'parameter-preflight-fixture'; + + beforeEach(() => { + projectFolder = fs.mkdtempSync(path.join(__dirname, 'parameter-preflight-')); + fs.mkdirSync(path.join(projectFolder, 'config')); + FileSystem.writeFile( + path.join(projectFolder, 'package.json'), + JSON.stringify({ name: packageName, version: '1.0.0' }) + ); + FileSystem.writeFile( + path.join(projectFolder, 'heft-plugin.json'), + JSON.stringify({ + lifecyclePlugins: [ + { + pluginName: 'lifecycle', + entryPoint: '../fixtures/PreflightLifecyclePlugin.js', + parameters: [ + { + parameterKind: 'flag', + longName: '--restricted-lifecycle', + description: 'A restricted lifecycle parameter.', + allowWithClean: false, + allowInWatchMode: false + } + ] + } + ], + taskPlugins: [ + { pluginName: 'build', entryPoint: '../fixtures/PreflightTaskPlugin.js' }, + { + pluginName: 'test', + entryPoint: '../fixtures/PreflightTaskPlugin.js', + parameterScope: 'test-scope', + parameters: [ + { + parameterKind: 'string', + longName: '--restricted', + description: 'A restricted parameter.', + argumentName: 'VALUE', + allowWithClean: false, + allowInWatchMode: false + } + ] + } + ] + }) + ); + FileSystem.writeFile( + path.join(projectFolder, 'config', 'heft.json'), + JSON.stringify({ + heftPlugins: [{ pluginPackage: packageName, pluginName: 'lifecycle' }], + aliasesByName: { + 'restricted-clean': { + actionName: 'run', + defaultParameters: ['--to', 'test', '--', '--clean', '--restricted', 'value'] + } + }, + phasesByName: { + build: { + cleanFiles: [{ sourcePath: 'build-output' }], + tasksByName: { + compile: { taskPlugin: { pluginPackage: packageName, pluginName: 'build' } } + } + }, + test: { + phaseDependencies: ['build'], + tasksByName: { + check: { taskPlugin: { pluginPackage: packageName, pluginName: 'test' } } + } + } + } + }) + ); + fs.mkdirSync(path.join(projectFolder, 'build-output')); + fs.writeFileSync(path.join(projectFolder, 'build-output', 'sentinel'), 'keep build output'); + fs.writeFileSync(path.join(projectFolder, 'lifecycle-output'), 'keep lifecycle output'); + }); + + afterEach(() => { + fs.rmSync(projectFolder, { recursive: true, force: true }); + }); + + function runHeft(args: string[]): SpawnSyncReturns { + const result: SpawnSyncReturns = spawnSync( + process.execPath, + [path.join(__dirname, '..', 'start.js'), ...args], + { cwd: projectFolder, encoding: 'utf8', timeout: 15000 } + ); + // A watch loop must exit on its own, rather than requiring the timeout to kill it. + expect(result.error).toBeUndefined(); + expect(result.signal).toBeNull(); + return result; + } + + it.each([ + ['run', '--to', 'test', '--', '--clean', '--restricted', 'value'], + ['run', '--to', 'test', '--', '--clean', '--test-scope:restricted', 'value'], + ['restricted-clean'], + ['run-watch', '--to', 'test', '--', '--restricted', 'value'], + ['test-watch', '--restricted', 'value'], + ['run-watch', '--to', 'test', '--', '--clean', '--restricted', 'value'] + ])('rejects before lifecycle, dependency cleaning, plugin application, or watching: %j', (...args) => { + const result: SpawnSyncReturns = runHeft(args); + expect(result.status).toBe(1); + expect(result.stderr).toContain( + 'Parameter "--test-scope:restricted" from plugin "test" in package "parameter-preflight-fixture"' + ); + expect(result.stderr).toContain( + args.includes('--clean') || args[0] === 'restricted-clean' + ? 'cannot be used with --clean' + : 'cannot be used with watch mode' + ); + expect(result.stdout).not.toContain('Waiting for changes'); + expect(fs.readFileSync(path.join(projectFolder, 'build-output', 'sentinel'), 'utf8')).toBe( + 'keep build output' + ); + expect(fs.readFileSync(path.join(projectFolder, 'lifecycle-output'), 'utf8')).toBe( + 'keep lifecycle output' + ); + for (const marker of ['lifecycle-applied', 'lifecycle-started', 'compile-applied', 'check-applied']) { + expect(result.stdout).not.toContain(marker); + } + }); + + it('also preflights lifecycle parameters', () => { + const result: SpawnSyncReturns = runHeft([ + 'run', + '--to', + 'test', + '--', + '--clean', + '--restricted-lifecycle' + ]); + expect(result.status).toBe(1); + expect(result.stderr).toContain('--lifecycle:restricted-lifecycle'); + expect(result.stdout).not.toContain('lifecycle-applied'); + expect(fs.existsSync(path.join(projectFolder, 'build-output', 'sentinel'))).toBe(true); + }); + + it('cleans dependency outputs and runs both phases when the restricted parameter is inactive', () => { + const result: SpawnSyncReturns = runHeft(['run', '--to', 'test', '--', '--clean']); + expect(result.stderr).toBe(''); + expect(result.status).toBe(0); + expect(fs.existsSync(path.join(projectFolder, 'build-output', 'sentinel'))).toBe(false); + expect(fs.existsSync(path.join(projectFolder, 'lifecycle-output'))).toBe(false); + for (const marker of [ + 'lifecycle-applied', + 'lifecycle-started', + 'compile-applied', + 'check-applied', + 'compile-ran', + 'check-ran' + ]) { + expect(result.stdout).toContain(marker); + } + }); + + it('allows an active restricted parameter in an ordinary run without cleaning', () => { + const result: SpawnSyncReturns = runHeft(['test', '--restricted', 'value']); + expect(result.stderr).toBe(''); + expect(result.status).toBe(0); + expect(result.stdout).toContain('check-ran'); + expect(fs.existsSync(path.join(projectFolder, 'build-output', 'sentinel'))).toBe(true); + }); + + it('leaves the standalone clean command unchanged', () => { + const result: SpawnSyncReturns = runHeft(['clean', '--to', 'test']); + expect(result.stderr).toBe(''); + expect(result.status).toBe(0); + expect(fs.existsSync(path.join(projectFolder, 'build-output', 'sentinel'))).toBe(false); + expect(result.stdout).not.toContain('lifecycle-applied'); + }); +}); diff --git a/apps/heft/src/test/fixtures/PreflightLifecyclePlugin.ts b/apps/heft/src/test/fixtures/PreflightLifecyclePlugin.ts new file mode 100644 index 00000000000..f527a1456b3 --- /dev/null +++ b/apps/heft/src/test/fixtures/PreflightLifecyclePlugin.ts @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. +// See LICENSE in the project root for license information. + +import * as fs from 'node:fs'; +import * as path from 'node:path'; + +import type { IHeftLifecyclePlugin } from '../../pluginFramework/IHeftPlugin'; +import type { IHeftLifecycleSession } from '../../pluginFramework/HeftLifecycleSession'; +import type { HeftConfiguration } from '../../configuration/HeftConfiguration'; + +export default class PreflightLifecyclePlugin implements IHeftLifecyclePlugin { + public apply(session: IHeftLifecycleSession, configuration: HeftConfiguration): void { + session.logger.terminal.writeLine('lifecycle-applied'); + session.hooks.toolStart.tap('preflight-test', () => { + session.logger.terminal.writeLine('lifecycle-started'); + }); + session.hooks.clean.tap('preflight-test', () => { + fs.unlinkSync(path.join(configuration.buildFolderPath, 'lifecycle-output')); + }); + } +} diff --git a/apps/heft/src/test/fixtures/PreflightTaskPlugin.ts b/apps/heft/src/test/fixtures/PreflightTaskPlugin.ts new file mode 100644 index 00000000000..d2834e8b55d --- /dev/null +++ b/apps/heft/src/test/fixtures/PreflightTaskPlugin.ts @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. +// See LICENSE in the project root for license information. + +import type { IHeftTaskPlugin } from '../../pluginFramework/IHeftPlugin'; +import type { IHeftTaskSession } from '../../pluginFramework/HeftTaskSession'; + +export default class PreflightTaskPlugin implements IHeftTaskPlugin { + public apply(session: IHeftTaskSession): void { + session.logger.terminal.writeLine(`${session.taskName}-applied`); + session.hooks.run.tap('preflight-test', () => { + session.logger.terminal.writeLine(`${session.taskName}-ran`); + }); + } +} diff --git a/common/changes/@rushstack/heft/parameter-mode-preflight_2026-09-14-20-45.json b/common/changes/@rushstack/heft/parameter-mode-preflight_2026-09-14-20-45.json new file mode 100644 index 00000000000..e84d1344ba9 --- /dev/null +++ b/common/changes/@rushstack/heft/parameter-mode-preflight_2026-09-14-20-45.json @@ -0,0 +1,10 @@ +{ + "changes": [ + { + "packageName": "@rushstack/heft", + "comment": "Add allowWithClean and allowInWatchMode plugin parameter metadata to reject incompatible active parameters before running lifecycle hooks, cleaning outputs, or entering watch mode.", + "type": "minor" + } + ], + "packageName": "@rushstack/heft" +}