Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions common/changes/@microsoft/rush/rushx-script-shell_2026-11-23.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"changes": [
{
"packageName": "@microsoft/rush",
"comment": "Honor the script-shell setting in common/config/rush/.npmrc when rushx runs a package script.",
"type": "minor"
}
],
"packageName": "@microsoft/rush",
"email": "2280792+doomfrawen@users.noreply.github.com"
}
4 changes: 4 additions & 0 deletions common/config/rush/browser-approved-packages.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@
"name": "dependency-path",
"allowedCategories": [ "libraries" ]
},
{
"name": "ini",
"allowedCategories": [ "libraries" ]
},
{
"name": "office-ui-fabric-core",
"allowedCategories": [ "libraries" ]
Expand Down
7 changes: 7 additions & 0 deletions common/config/subspaces/build-tests-subspace/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// DO NOT MODIFY THIS FILE MANUALLY BUT DO COMMIT IT. It is generated and used by Rush.
{
"pnpmShrinkwrapHash": "51cb42ed20d4c81b4e56806e900a7783e200ffee",
"pnpmShrinkwrapHash": "26e3ddd89cc271ee8165b9430b5b82b054dc01cd",
"preferredVersionsHash": "550b4cee0bef4e97db6c6aad726df5149d20e7d9",
"packageJsonInjectedDependenciesHash": "293debc6ed16567f5567a7748229a73be6647cc6"
"packageJsonInjectedDependenciesHash": "400579fe4f2de7eb21192076cccd9dbe96dd64da"
}
17 changes: 17 additions & 0 deletions common/config/subspaces/default/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion common/config/subspaces/default/repo-state.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// DO NOT MODIFY THIS FILE MANUALLY BUT DO COMMIT IT. It is generated and used by Rush.
{
"pnpmShrinkwrapHash": "88560f6b240f7b9d9e6e5b80ae1363a7e5ef018f",
"pnpmShrinkwrapHash": "5311d01c8d3613680242f768b7cbf592200d6f5c",
"preferredVersionsHash": "029c99bd6e65c5e1f25e2848340509811ff9753c"
}
2 changes: 2 additions & 0 deletions libraries/rush-lib/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
"git-repo-info": "~2.1.0",
"https-proxy-agent": "~5.0.0",
"ignore": "~5.1.6",
"ini": "~4.1.3",
"@inquirer/checkbox": "~5.1.3",
"@inquirer/confirm": "~6.0.11",
"@inquirer/input": "~5.0.11",
Expand All @@ -90,6 +91,7 @@
"@rushstack/operation-graph": "workspace:*",
"@rushstack/webpack-deep-imports-plugin": "workspace:*",
"@rushstack/webpack-preserve-dynamic-require-plugin": "workspace:*",
"@types/ini": "4.1.1",
"@types/js-yaml": "4.0.9",
"@types/npm-package-arg": "6.1.0",
"@types/object-hash": "~3.0.6",
Expand Down
49 changes: 47 additions & 2 deletions libraries/rush-lib/src/cli/RushXCommandLine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import * as path from 'node:path';
import type * as childProcess from 'node:child_process';

import { parse as parseIni } from 'ini';
import { type ILogMessageCallbackOptions, pnpmSyncCopyAsync } from 'pnpm-sync-lib';

import {
Expand All @@ -25,6 +26,7 @@ import {
} from '@rushstack/terminal';

import { Utilities, type ILifecycleCommandOptions } from '../utilities/Utilities';
import { expandNpmrcValue, trimNpmrcFileLines } from '../utilities/npmrcUtilities';
import { ProjectCommandSet } from '../logic/ProjectCommandSet';
import { type ILaunchOptions, Rush } from '../api/Rush';
import { RushConfiguration } from '../api/RushConfiguration';
Expand All @@ -36,7 +38,11 @@ import { EnvironmentConfiguration, EnvironmentVariableNames } from '../api/Envir
import { RushConstants } from '../logic/RushConstants';
import { PnpmSyncUtilities } from '../utilities/PnpmSyncUtilities';
import { initializeDotEnv, loadDotEnvForEnvironment } from '../logic/dotenv';
import { escapeArgumentIfNeeded } from '../utilities/executionUtilities';
import {
escapeArgumentIfNeeded,
IS_WINDOWS,
quoteShellArgumentIfNeeded
} from '../utilities/executionUtilities';

/** Native Rushx arguments. Options after the command belong to the script. @beta */
export interface IRushXCommandLineArguments {
Expand Down Expand Up @@ -332,10 +338,14 @@ async function _launchRushXInternalAsync(
throw Error(errorMessage);
}

const scriptShell: string | undefined =
rushConfiguration && _getScriptShell(rushConfiguration, execution?.environment ?? process.env);
let commandWithArgs: string = scriptBody;
let commandWithArgsForDisplay: string = scriptBody;
if (commandArgs.length > 0) {
const escapedRemainingArgs: string[] = commandArgs.map((x) => escapeArgumentIfNeeded(x));
const escapedRemainingArgs: string[] = commandArgs.map((arg) =>
scriptShell ? _quoteScriptShellArgument(arg, scriptShell) : escapeArgumentIfNeeded(arg)
);
commandWithArgs += ' ' + escapedRemainingArgs.join(' ');

// Display it nicely without the extra quotes
Expand All @@ -349,6 +359,7 @@ async function _launchRushXInternalAsync(
const packageFolder: string = path.dirname(packageJsonFilePath);

const lifecycleOptions: ILifecycleCommandOptions = {
scriptShell,
rushConfiguration: lifecycleConfiguration,
workingDirectory: packageFolder,
// If there is a rush.json then use its .npmrc from the temp folder.
Expand Down Expand Up @@ -397,6 +408,40 @@ async function _launchRushXInternalAsync(
}
}

function _quoteScriptShellArgument(argument: string, shell: string): string {
const shellName: string = path.win32
.basename(shell)
.toLowerCase()
.replace(/\.exe$/, '');
if (shellName === 'pwsh' || shellName === 'powershell') {
// Quoting a simple parameter name such as -Force would turn it into a positional argument.
if (/^[A-Za-z0-9_./-]+$/.test(argument)) return argument;
// PowerShell accepts both ASCII and typographic single quotes as string delimiters.
return `'${argument.replace(/['\u2018\u2019\u201a\u201b]/g, '$&$&')}'`;
}
return quoteShellArgumentIfNeeded(argument, IS_WINDOWS && shellName === 'cmd');
}

function _getScriptShell(
rushConfiguration: RushConfiguration,
environment: NodeJS.ProcessEnv
): string | undefined {
let npmrc: string;
try {
npmrc = FileSystem.readFile(path.join(rushConfiguration.commonRushConfigFolder, '.npmrc'));
} catch (error) {
if (FileSystem.isNotExistError(error as Error)) return undefined;
throw error;
}

// Match the .npmrc that Rush provides to the package manager: a missing variable disables that line.
const lines: string[] = trimNpmrcFileLines(npmrc.split('\n'), environment, rushConfiguration.isPnpm);
const shell: unknown = parseIni(lines.join('\n'))['script-shell'];
return typeof shell === 'string' && shell
? expandNpmrcValue(shell, environment, rushConfiguration.isPnpm)
: undefined;
}

function _getLifecycleConfiguration(
configuration: RushConfiguration | undefined,
execution: IRushXCommandOptions | undefined
Expand Down
50 changes: 46 additions & 4 deletions libraries/rush-lib/src/cli/test/RushXCommandLine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ jest.mock('../../logic/dotenv', () => ({
initializeDotEnv: () => {}
}));

import { PackageJsonLookup } from '@rushstack/node-core-library';
import * as path from 'node:path';

import { FileSystem, PackageJsonLookup } from '@rushstack/node-core-library';

import { Utilities } from '../../utilities/Utilities';
import { Rush, type ILaunchOptions } from '../../api/Rush';
Expand Down Expand Up @@ -57,12 +59,12 @@ describe(RushXCommandLine.name, () => {
} as RushConfigurationProject
];
rushConfiguration = {
commonRushConfigFolder: '',
commonRushConfigFolder: 'common/config/rush',
rushJsonFolder: '',
commonTempFolder: 'common/temp',
projects,
tryGetProjectForPath(path: string): RushConfigurationProject | undefined {
return projects.find((project) => project.projectFolder === path);
tryGetProjectForPath(projectPath: string): RushConfigurationProject | undefined {
return projects.find((project) => project.projectFolder === projectPath);
}
} as RushConfiguration;
jest.spyOn(RushConfiguration, 'tryFindRushJsonLocation').mockReturnValue('/Users/jdoe/bigrepo');
Expand Down Expand Up @@ -135,6 +137,46 @@ describe(RushXCommandLine.name, () => {
expect(logMock!.mock.calls).toMatchSnapshot();
});

it('uses the repository .npmrc shell and quotes arguments for it', async () => {
jest.replaceProperty(process, 'env', { RUSHX_TEST_SHELL: '/path with spaces/bash' });
const readFile = jest
.spyOn(FileSystem, 'readFile')
.mockReturnValue(
[
'; script-shell=ignored',
'script-shell=other',
'script-shell = "${RUSHX_TEST_SHELL}"',
'script-shell=${RUSHX_UNSET_SHELL}'
].join('\n')
);
executeLifecycleCommandMock!.mockReturnValue(0);
process.argv = ['node', 'startx.js', 'build', 'argument with spaces', '$literal', "it's", ''];

await RushXCommandLine.launchRushXAsync('0.0.0', { isManaged: true });

expect(readFile).toHaveBeenCalledWith(path.join('common/config/rush', '.npmrc'));
expect(executeLifecycleCommandMock).toHaveBeenCalledWith(
"an acme project build command 'argument with spaces' '$literal' 'it'\\''s' ''",
expect.objectContaining({ scriptShell: '/path with spaces/bash' })
);
});

it.each(['pwsh', 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\PowerShell.exe'])(
'quotes literal arguments for %s',
async (shell: string) => {
jest.spyOn(FileSystem, 'readFile').mockReturnValue(`script-shell=${shell}`);
executeLifecycleCommandMock!.mockReturnValue(0);
process.argv = ['node', 'startx.js', 'build', '-Switch', 'plain', "O'Brien", 'it’s', '$literal', ''];

await RushXCommandLine.launchRushXAsync('0.0.0', { isManaged: true });

expect(executeLifecycleCommandMock).toHaveBeenCalledWith(
"an acme project build command -Switch plain 'O''Brien' 'it’’s' '$literal' ''",
expect.objectContaining({ scriptShell: shell })
);
}
);

it('fails if the package does not contain a matching script', () => {
process.argv = ['node', 'startx.js', 'asdf'];
executeLifecycleCommandMock!.mockReturnValue(0);
Expand Down
17 changes: 15 additions & 2 deletions libraries/rush-lib/src/utilities/Utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ export interface IInstallPackageInDirectoryOptions {
}

export interface ILifecycleCommandOptions {
/**
* An explicit shell for executing the lifecycle script, as configured by rushx's script-shell setting.
*/
scriptShell?: string;

/**
* Rush configuration paths used to prepare the lifecycle environment, if running in a Rush repo.
*/
Expand Down Expand Up @@ -491,7 +496,7 @@ export class Utilities {
}

/**
* Executes the command using cmd if running on windows, or using sh if running on a non-windows OS.
* Executes the command using the configured script shell, defaulting to cmd.exe on Windows and sh on POSIX.
* @param command - the command to run on shell
* @param options - options for how the command should be run
*/
Expand Down Expand Up @@ -525,7 +530,7 @@ export class Utilities {
}

/**
* Executes the command using cmd if running on windows, or using sh if running on a non-windows OS.
* Executes the command using the configured script shell, defaulting to cmd.exe on Windows and sh on POSIX.
* @param command - the command to run on shell
* @param options - options for how the command should be run
*/
Expand Down Expand Up @@ -769,6 +774,14 @@ function _executeLifecycleCommandInternal<TCommandResult>(
Object.assign(spawnOptions, SubprocessTerminator.RECOMMENDED_OPTIONS);
}

if (options.scriptShell) {
// Let Node pass the complete script to this shell using its native switches (including cmd.exe's /d /s /c).
return spawnFunction(commandAndArgs, [], {
...spawnOptions,
shell: IS_WINDOWS ? path.win32.normalize(options.scriptShell) : options.scriptShell
});
}

const { command, args } = Utilities._convertCommandAndArgsToShell(
commandAndArgs,
IS_WINDOWS,
Expand Down
14 changes: 14 additions & 0 deletions libraries/rush-lib/src/utilities/npmrcUtilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,20 @@ interface IEnvironmentVariableExpansionResult {
hasUndefinedVariable: boolean;
}

/** Resolves a setting with the same environment variable syntax as Rush's generated .npmrc. */
export function expandNpmrcValue(
value: string,
env: NodeJS.ProcessEnv,
supportEnvVarFallbackSyntax: boolean
): string | undefined {
const { expandedText, hasUndefinedVariable } = _expandEnvironmentVariables(
value,
env,
supportEnvVarFallbackSyntax
);
return hasUndefinedVariable ? undefined : expandedText;
}

// This finds environment variable tokens that look like "${VAR_NAME}"
const ENVIRONMENT_VARIABLE_REGEX: RegExp = /\$\{([^\}]+)\}/g;

Expand Down
14 changes: 14 additions & 0 deletions libraries/rush-lib/src/utilities/test/Utilities.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,20 @@ describe(Utilities.name, () => {
}
});

it('runs the script directly in the configured shell instead of wrapping it in the platform default', () => {
const spawn = jest.fn().mockReturnValue(new ChildProcess());
Utilities.executeLifecycleCommandAsync('echo $0', {
rushConfiguration: undefined,
workingDirectory: process.cwd(),
initCwd: process.cwd(),
handleOutput: false,
environmentPathOptions: {},
scriptShell: 'bash',
spawn
});
expect(spawn).toHaveBeenCalledWith('echo $0', [], expect.objectContaining({ shell: 'bash' }));
});

it('does not pass the daemon routing and host settings to lifecycle commands', () => {
const spawn = jest
.fn<ChildProcess, [string, ReadonlyArray<string>, SpawnOptions]>()
Expand Down