// 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 { CommandLineAction, type ICommandLineActionOptions } from '@rushstack/ts-command-line'; import { AlreadyReportedError } from '@rushstack/node-core-library'; import { Colorize, type ITerminal } from '@rushstack/terminal'; import type { IScopedReporter } from '@rushstack/rush-reporter'; import type { RushConfiguration } from '../../api/RushConfiguration'; import { EventHooksManager } from '../../logic/EventHooksManager'; import { acquireRepositoryLockAsync, type IRepositoryLockResult } from '../../logic/RepositoryLockWait'; import { RushCommandLineParser } from '../RushCommandLineParser'; import { Utilities } from '../../utilities/Utilities'; import type { RushGlobalFolder } from '../../api/RushGlobalFolder'; import type { RushSession } from '../../pluginFramework/RushSession'; import { _isRushSessionOperationStreamEnabled } from '../../pluginFramework/RushSession'; import type { IRushCommand } from '../../pluginFramework/RushLifeCycle'; import { measureAsyncFn } from '../../utilities/performance'; const PERF_PREFIX: string = 'rush:action'; export interface IBaseRushActionOptions extends ICommandLineActionOptions { /** * By default, Rush operations acquire a lock file which prevents multiple commands from executing simultaneously * in the same repo folder. (For example, it would be a mistake to run "rush install" and "rush build" at the * same time.) If your command makes sense to run concurrently with other operations, * set safeForSimultaneousRushProcesses=true to disable this protection. In particular, this is needed for * custom scripts that invoke other Rush commands. */ safeForSimultaneousRushProcesses?: boolean; /** * The rush parser. */ parser: RushCommandLineParser; } /** * The base class for a few specialized Rush command-line actions that * can be used without a rush.json configuration. */ export abstract class BaseConfiglessRushAction extends CommandLineAction implements IRushCommand { #safeForSimultaneousRushProcesses: boolean; protected readonly rushConfiguration: RushConfiguration | undefined; protected readonly terminal: ITerminal; protected readonly rushSession: RushSession; protected readonly reporter: IScopedReporter | undefined; protected readonly rushGlobalFolder: RushGlobalFolder; protected readonly parser: RushCommandLineParser; public constructor(options: IBaseRushActionOptions) { super(options); const { parser, safeForSimultaneousRushProcesses } = options; this.parser = parser; const { rushConfiguration, terminal, rushSession, rushGlobalFolder } = parser; this.#safeForSimultaneousRushProcesses = !!safeForSimultaneousRushProcesses; this.rushConfiguration = rushConfiguration; this.terminal = terminal; this.rushSession = rushSession; this.reporter = rushSession.getReporter({ commandName: this.actionName }); this.rushGlobalFolder = rushGlobalFolder; } protected override async onExecuteAsync(): Promise { this.#ensureEnvironment(); if (this.rushConfiguration) { if (!this.#safeForSimultaneousRushProcesses) { const { lock, holderSentence }: IRepositoryLockResult = await acquireRepositoryLockAsync({ lockFolder: this.rushConfiguration.commonTempFolder, wait: this.parser.repositoryLockWait, terminal: this.terminal }); if (!lock) { const message: string = 'Another Rush command is already running in this repository.' + (holderSentence ? ` ${holderSentence}` : ''); if (_isRushSessionOperationStreamEnabled(this.rushSession)) { this.terminal.writeErrorLine(message); throw new AlreadyReportedError(); } this.terminal.writeLine(Colorize.red(message)); process.exit(1); } } } if ( !RushCommandLineParser.shouldRestrictConsoleOutput() && !_isRushSessionOperationStreamEnabled(this.rushSession) ) { this.terminal.write(`Starting "rush ${this.actionName}"\n`); } await measureAsyncFn(`${PERF_PREFIX}:runAsync`, () => this.runAsync()); } /** * All Rush actions need to implement this method. This method runs after * environment has been set up by the base class. */ protected abstract runAsync(): Promise; #ensureEnvironment(): void { if (this.rushConfiguration) { // eslint-disable-next-line dot-notation let environmentPath: string | undefined = process.env['PATH']; environmentPath = path.join(this.rushConfiguration.commonTempFolder, 'node_modules', '.bin') + path.delimiter + environmentPath; // eslint-disable-next-line dot-notation process.env['PATH'] = environmentPath; } } } /** * The base class that most Rush command-line actions should extend. */ export abstract class BaseRushAction extends BaseConfiglessRushAction { #eventHooksManager: EventHooksManager | undefined; protected get eventHooksManager(): EventHooksManager { if (!this.#eventHooksManager) { this.#eventHooksManager = new EventHooksManager(this.rushConfiguration); } return this.#eventHooksManager; } declare protected readonly rushConfiguration: RushConfiguration; protected override async onExecuteAsync(): Promise { await this.initializePluginsAsync(); return super.onExecuteAsync(); } /** Initializes the native command plugins without CLI environment or process-lock side effects. */ protected async initializePluginsAsync(): Promise { if (!this.rushConfiguration) { throw Utilities.getRushConfigNotFoundError(); } this.#throwPluginErrorIfNeed(); await measureAsyncFn(`${PERF_PREFIX}:initializePluginsAsync`, () => this.parser.pluginManager.tryInitializeAssociatedCommandPluginsAsync(this.actionName) ); this.#throwPluginErrorIfNeed(); const { hooks: sessionHooks } = this.rushSession; await measureAsyncFn(`${PERF_PREFIX}:initializePlugins`, async () => { if (sessionHooks.initialize.isUsed()) { // Avoid the cost of compiling the hook if it wasn't tapped. await sessionHooks.initialize.promise(this); } }); } /** * If an error is encountered while trying to load plugins, it is saved in the `PluginManager.error` * property, so we can defer throwing it until when `_throwPluginErrorIfNeed()` is called. */ #throwPluginErrorIfNeed(): void { // If the plugin configuration is broken, these three commands are used to fix the problem: // // "rush update" // "rush init-autoinstaller" // "rush update-autoinstaller" // // In addition, the "rush setup" command is designed to help new users configure their access // to a private NPM registry, which means it can't rely on plugins that might live in that // registry. // // Thus we do not report plugin errors when invoking these commands. if (!['update', 'init-autoinstaller', 'update-autoinstaller', 'setup'].includes(this.actionName)) { const pluginError: Error | undefined = this.parser.pluginManager.error; if (pluginError) { throw pluginError; } } } }