// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import * as path from 'node:path'; import type { AsyncSeriesHook } from 'tapable'; import type { CommandLineParameter } from '@rushstack/ts-command-line'; import { FileSystem, type IPackageJson, AlreadyReportedError, } from '@rushstack/node-core-library'; import { Colorize } from '@rushstack/terminal'; import type { IGlobalCommand } from '../../pluginFramework/RushLifeCycle'; import { BaseScriptAction, type IBaseScriptActionOptions } from './BaseScriptAction'; import { Utilities } from '../../utilities/Utilities'; import { Stopwatch } from '../../utilities/Stopwatch'; import { Autoinstaller } from '../../logic/Autoinstaller'; import { RushConstants } from '../../logic/RushConstants'; import type { IGlobalCommandConfig, IShellCommandTokenContext } from '../../api/CommandLineConfiguration'; import { measureAsyncFn } from '../../utilities/performance'; import { type JsonFileLoadCache, loadJsonFile } from '../../utilities/JsonFileLoadCache'; /** * Constructor parameters for GlobalScriptAction. */ export interface IGlobalScriptActionOptions extends IBaseScriptActionOptions { shellCommand: string; autoinstallerName: string | undefined; providedByPlugin: boolean; /** The cache of a long-lived engine host, through which the action reads its autoinstaller's package.json. */ jsonFileLoadCache?: JsonFileLoadCache; } /** * This class implements custom commands that are run once globally for the entire repo * (versus bulk commands, which run separately for each project). The action executes * a user-defined script file. * * @remarks * Bulk commands can be defined via common/config/command-line.json. Rush's predefined "build" * and "rebuild" commands are also modeled as bulk commands, because they essentially just * invoke scripts from package.json in the same way as a custom command. */ export class GlobalScriptAction extends BaseScriptAction { readonly #shellCommand: string; readonly #autoinstallerName: string; readonly #autoinstallerFullPath: string; readonly #providedByPlugin: boolean; #customParametersByLongName: ReadonlyMap | undefined; #isHandled: boolean = false; public constructor(options: IGlobalScriptActionOptions) { super(options); const { shellCommand, providedByPlugin, autoinstallerName = '', jsonFileLoadCache } = options; this.#shellCommand = shellCommand; this.#providedByPlugin = providedByPlugin; this.#autoinstallerName = autoinstallerName; if (this.#autoinstallerName) { Autoinstaller.validateName(this.#autoinstallerName); // Example: .../common/autoinstallers/my-task this.#autoinstallerFullPath = path.join( this.rushConfiguration.commonAutoinstallersFolder, this.#autoinstallerName ); if (!FileSystem.exists(this.#autoinstallerFullPath)) { throw new Error( `The custom command "${this.actionName}" specifies an "autoinstallerName" setting` + ' but the path does not exist: ' + this.#autoinstallerFullPath ); } // Example: .../common/autoinstallers/my-task/package.json const packageJsonPath: string = path.join(this.#autoinstallerFullPath, 'package.json'); if (!FileSystem.exists(packageJsonPath)) { throw new Error( `The custom command "${this.actionName}" specifies an "autoinstallerName" setting` + ` whose package.json file was not found: ` + packageJsonPath ); } const packageName: string | undefined = loadJsonFile( jsonFileLoadCache, packageJsonPath, (packageJson) => (packageJson as IPackageJson).name ); if (packageName !== this.#autoinstallerName) { throw new Error( `The custom command "${this.actionName}" specifies an "autoinstallerName" setting,` + ` but the package.json file's "name" field is not "${this.#autoinstallerName}": ` + packageJsonPath ); } } else { this.#autoinstallerFullPath = ''; } this.defineScriptParameters(); } /** * {@inheritDoc IGlobalCommand.setHandled} */ public setHandled(): void { this.#isHandled = true; } /** * {@inheritDoc IGlobalCommand.getCustomParametersByLongName} */ public getCustomParametersByLongName( longName: string ): TParameter { if (!this.#customParametersByLongName) { const map: Map = new Map(); for (const [parameterJson, parameter] of this.customParameters) { map.set(parameterJson.longName, parameter); } this.#customParametersByLongName = map; } const parameter: CommandLineParameter | undefined = this.#customParametersByLongName.get(longName); if (!parameter) { throw new Error( `The command "${this.actionName}" does not have a custom parameter with long name "${longName}".` ); } return parameter as TParameter; } async #prepareAutoinstallerNameAsync(): Promise { const autoInstaller: Autoinstaller = new Autoinstaller({ autoinstallerName: this.#autoinstallerName, rushConfiguration: this.rushConfiguration, rushGlobalFolder: this.rushGlobalFolder }); await autoInstaller.prepareAsync(); } public async runAsync(): Promise { const { hooks: sessionHooks } = this.rushSession; if (sessionHooks.runAnyGlobalCustomCommand.isUsed()) { // Avoid the cost of compiling the hook if it wasn't tapped. await sessionHooks.runAnyGlobalCustomCommand.promise(this); } const hookForAction: AsyncSeriesHook | undefined = sessionHooks.runGlobalCustomCommand.get(this.actionName); if (hookForAction) { // Run the more specific hook for a command with this name after the general hook await hookForAction.promise(this); } // If a plugin hook called setHandled(), the command has been fully handled. // Skip the default shell command execution. if (this.#isHandled) { return; } if (this.#providedByPlugin) { throw new Error( `The custom command "${this.actionName}" is a "${RushConstants.globalPluginCommandKind}" command, ` + 'meaning its implementation must be provided entirely by a Rush plugin. However, no plugin ' + 'called setHandled() for this command. Ensure that the plugin defining this command is ' + 'properly installed and that it handles this command.' ); } if (this.#shellCommand === '') { throw new Error( `The custom command "${this.actionName}" has an empty "shellCommand" value, but no plugin ` + 'called setHandled() for this command. An empty "shellCommand" is intended for global ' + 'commands whose implementation is provided entirely by a Rush plugin.' ); } const additionalPathFolders: string[] = this.commandLineConfiguration?.additionalPathFolders.slice() || []; if (this.#autoinstallerName) { await measureAsyncFn('rush:globalScriptAction:prepareAutoinstaller', () => this.#prepareAutoinstallerNameAsync() ); const autoinstallerNameBinPath: string = path.join(this.#autoinstallerFullPath, 'node_modules', '.bin'); additionalPathFolders.push(autoinstallerNameBinPath); } // Collect all custom parameter values const customParameterValues: string[] = []; for (const tsCommandLineParameter of this.customParameters.values()) { tsCommandLineParameter.appendToArgList(customParameterValues); } for (let i: number = 0; i < customParameterValues.length; i++) { let customParameterValue: string = customParameterValues[i]; customParameterValue = customParameterValue.replace(/"/g, '\\"'); if (customParameterValue.indexOf(' ') >= 0) { customParameterValue = `"${customParameterValue}"`; } customParameterValues[i] = customParameterValue; } let shellCommand: string = this.#shellCommand; if (customParameterValues.length > 0) { shellCommand += ' ' + customParameterValues.join(' '); } const shellCommandTokenContext: IShellCommandTokenContext | undefined = this.commandLineConfiguration?.shellCommandTokenContext; if (shellCommandTokenContext) { shellCommand = this.#expandShellCommandWithTokens(shellCommand, shellCommandTokenContext); } this.#rejectAnyTokensInShellCommand(shellCommand, shellCommandTokenContext); const stopwatch: Stopwatch = Stopwatch.start(); const exitCode: number = Utilities.executeLifecycleCommand(shellCommand, { rushConfiguration: this.rushConfiguration, workingDirectory: this.rushConfiguration.rushJsonFolder, initCwd: this.rushConfiguration.commonTempFolder, handleOutput: false, environmentPathOptions: { includeRepoBin: true, additionalPathFolders: additionalPathFolders } }); process.exitCode = exitCode; stopwatch.stop(); if (this.parser.telemetry) { this.parser.telemetry.log({ name: this.actionName, durationInSeconds: stopwatch.duration, result: exitCode > 0 ? 'Failed' : 'Succeeded', extraData: { customParameterValue: customParameterValues.join(' ') } }); this.parser.flushTelemetry(); } if (exitCode > 0) { // eslint-disable-next-line no-console console.log('\n' + Colorize.red(`The script failed with exit code ${exitCode}`)); throw new AlreadyReportedError(); } } #expandShellCommandWithTokens( shellCommand: string, tokenContext: IShellCommandTokenContext ): string { let expandedShellCommand: string = shellCommand; for (const [token, tokenReplacement] of Object.entries(tokenContext)) { expandedShellCommand = expandedShellCommand.replaceAll(`<${token}>`, tokenReplacement); } return expandedShellCommand; } #rejectAnyTokensInShellCommand( shellCommand: string, tokenContext?: IShellCommandTokenContext ): void { if (shellCommand.indexOf('<') < 0 && shellCommand.indexOf('>') < 0) { return; } const tokenRegExp: RegExp = /(\<[^<]*?\>)/; const match: RegExpExecArray | null = tokenRegExp.exec(shellCommand); if (match) { throw new Error( `The "shellCommand" value contains an unrecognized token "${match[1]}".${ tokenContext ? ` Available tokens are ${Object.keys(tokenContext).join(', ')}.` : '' }` ); } throw new Error(`The "shellCommand" value contains extra token characters ("<" or ">"): ${shellCommand}`); } }