forked from microsoft/rushstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRushXCommandLine.ts
More file actions
277 lines (230 loc) · 9.44 KB
/
Copy pathRushXCommandLine.ts
File metadata and controls
277 lines (230 loc) · 9.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import colors from 'colors/safe';
import * as os from 'os';
import * as path from 'path';
import { PackageJsonLookup, IPackageJson, Text } from '@rushstack/node-core-library';
import { DEFAULT_CONSOLE_WIDTH, PrintUtilities } from '@rushstack/terminal';
import { Utilities } from '../utilities/Utilities';
import { ProjectCommandSet } from '../logic/ProjectCommandSet';
import { Rush } from '../api/Rush';
import { RushConfiguration } from '../api/RushConfiguration';
import { NodeJsCompatibility } from '../logic/NodeJsCompatibility';
import { RushStartupBanner } from './RushStartupBanner';
/**
* @internal
*/
export interface ILaunchRushXInternalOptions {
isManaged: boolean;
alreadyReportedNodeTooNewError?: boolean;
}
interface IRushXCommandLineArguments {
/**
* Flag indicating whether to suppress any rushx startup information.
*/
quiet: boolean;
/**
* Flag indicating whether the user has asked for help.
*/
help: boolean;
/**
* The command to run (i.e., the target "script" in package.json.)
*/
commandName: string;
/**
* Any additional arguments/parameters passed after the command name.
*/
commandArgs: string[];
}
export class RushXCommandLine {
public static launchRushX(launcherVersion: string, isManaged: boolean): void {
RushXCommandLine._launchRushXInternal(launcherVersion, { isManaged });
}
/**
* @internal
*/
public static _launchRushXInternal(launcherVersion: string, options: ILaunchRushXInternalOptions): void {
// Node.js can sometimes accidentally terminate with a zero exit code (e.g. for an uncaught
// promise exception), so we start with the assumption that the exit code is 1
// and set it to 0 only on success.
process.exitCode = 1;
const args: IRushXCommandLineArguments = this._getCommandLineArguments();
if (!args.quiet) {
RushStartupBanner.logStreamlinedBanner(Rush.version, options.isManaged);
}
try {
// Are we in a Rush repo?
let rushConfiguration: RushConfiguration | undefined = undefined;
if (RushConfiguration.tryFindRushJsonLocation()) {
rushConfiguration = RushConfiguration.loadFromDefaultLocation({ showVerbose: false });
}
NodeJsCompatibility.warnAboutCompatibilityIssues({
isRushLib: true,
alreadyReportedNodeTooNewError: !!options.alreadyReportedNodeTooNewError,
rushConfiguration
});
// Find the governing package.json for this folder:
const packageJsonLookup: PackageJsonLookup = new PackageJsonLookup();
const packageJsonFilePath: string | undefined = packageJsonLookup.tryGetPackageJsonFilePathFor(
process.cwd()
);
if (!packageJsonFilePath) {
console.log(colors.red('This command should be used inside a project folder.'));
console.log(
`Unable to find a package.json file in the current working directory or any of its parents.`
);
return;
}
if (rushConfiguration && !rushConfiguration.tryGetProjectForPath(process.cwd())) {
// GitHub #2713: Users reported confusion resulting from a situation where "rush install"
// did not install the project's dependencies, because the project was not registered.
console.log(
colors.yellow(
'Warning: You are invoking "rushx" inside a Rush repository, but this project is not registered in rush.json.'
)
);
}
const packageJson: IPackageJson = packageJsonLookup.loadPackageJson(packageJsonFilePath);
const projectCommandSet: ProjectCommandSet = new ProjectCommandSet(packageJson);
if (args.help) {
RushXCommandLine._showUsage(packageJson, projectCommandSet);
return;
}
const scriptBody: string | undefined = projectCommandSet.tryGetScriptBody(args.commandName);
if (scriptBody === undefined) {
console.log(
colors.red(
`Error: The command "${args.commandName}" is not defined in the` +
` package.json file for this project.`
)
);
if (projectCommandSet.commandNames.length > 0) {
console.log(
os.EOL +
'Available commands for this project are: ' +
projectCommandSet.commandNames.map((x) => `"${x}"`).join(', ')
);
}
console.log(`Use ${colors.yellow('"rushx --help"')} for more information.`);
return;
}
let commandWithArgs: string = scriptBody;
let commandWithArgsForDisplay: string = scriptBody;
if (args.commandArgs.length > 0) {
// This approach is based on what NPM 7 now does:
// https://github.com/npm/run-script/blob/47a4d539fb07220e7215cc0e482683b76407ef9b/lib/run-script-pkg.js#L34
const escapedRemainingArgs: string[] = args.commandArgs.map((x) => Utilities.escapeShellParameter(x));
commandWithArgs += ' ' + escapedRemainingArgs.join(' ');
// Display it nicely without the extra quotes
commandWithArgsForDisplay += ' ' + args.commandArgs.join(' ');
}
if (!args.quiet) {
console.log('> ' + JSON.stringify(commandWithArgsForDisplay) + os.EOL);
}
const packageFolder: string = path.dirname(packageJsonFilePath);
const exitCode: number = Utilities.executeLifecycleCommand(commandWithArgs, {
rushConfiguration,
workingDirectory: packageFolder,
// If there is a rush.json then use its .npmrc from the temp folder.
// Otherwise look for npmrc in the project folder.
initCwd: rushConfiguration ? rushConfiguration.commonTempFolder : packageFolder,
handleOutput: false,
environmentPathOptions: {
includeProjectBin: true
}
});
if (exitCode > 0) {
console.log(colors.red(`The script failed with exit code ${exitCode}`));
}
process.exitCode = exitCode;
} catch (error) {
console.log(colors.red('Error: ' + (error as Error).message));
}
}
private static _getCommandLineArguments(): IRushXCommandLineArguments {
// 0 = node.exe
// 1 = rushx
const args: string[] = process.argv.slice(2);
const unknownArgs: string[] = [];
let help: boolean = false;
let quiet: boolean = false;
let commandName: string = '';
const commandArgs: string[] = [];
for (let index: number = 0; index < args.length; index++) {
const argValue: string = args[index];
if (!commandName) {
if (argValue === '-q' || argValue === '--quiet') {
quiet = true;
} else if (argValue === '-h' || argValue === '--help') {
help = true;
} else if (argValue.startsWith('-')) {
unknownArgs.push(args[index]);
} else {
commandName = args[index];
}
} else {
commandArgs.push(args[index]);
}
}
if (!commandName) {
help = true;
}
if (unknownArgs.length > 0) {
// Future TODO: Instead of just displaying usage info, we could display a
// specific error about the unknown flag the user tried to pass to rushx.
help = true;
}
return {
help,
quiet,
commandName,
commandArgs
};
}
private static _showUsage(packageJson: IPackageJson, projectCommandSet: ProjectCommandSet): void {
console.log('usage: rushx [-h]');
console.log(' rushx [-q/--quiet] <command> ...' + os.EOL);
console.log('Optional arguments:');
console.log(' -h, --help Show this help message and exit.');
console.log(' -q, --quiet Hide rushx startup information.' + os.EOL);
if (projectCommandSet.commandNames.length > 0) {
console.log(`Project commands for ${colors.cyan(packageJson.name)}:`);
// Calculate the length of the longest script name, for formatting
let maxLength: number = 0;
for (const commandName of projectCommandSet.commandNames) {
maxLength = Math.max(maxLength, commandName.length);
}
for (const commandName of projectCommandSet.commandNames) {
const escapedScriptBody: string = JSON.stringify(projectCommandSet.getScriptBody(commandName));
// The length of the string e.g. " command: "
const firstPartLength: number = 2 + maxLength + 2;
// The length for truncating the escaped escapedScriptBody so it doesn't wrap
// to the next line
const consoleWidth: number = PrintUtilities.getConsoleWidth() || DEFAULT_CONSOLE_WIDTH;
const truncateLength: number = Math.max(0, consoleWidth - firstPartLength) - 1;
console.log(
// Example: " command: "
' ' +
colors.cyan(Text.padEnd(commandName + ':', maxLength + 2)) +
// Example: "do some thin..."
Text.truncateWithEllipsis(escapedScriptBody, truncateLength)
);
}
if (projectCommandSet.malformedScriptNames.length > 0) {
console.log(
os.EOL +
colors.yellow(
'Warning: Some "scripts" entries in the package.json file' +
' have malformed names: ' +
projectCommandSet.malformedScriptNames.map((x) => `"${x}"`).join(', ')
)
);
}
} else {
console.log(colors.yellow('Warning: No commands are defined yet for this project.'));
console.log(
'You can define a command by adding a "scripts" table to the project\'s package.json file.'
);
}
}
}