Repository navigation
Expand file tree
/
Copy pathRushCommandSelector.ts
More file actions
246 lines (232 loc) · 8.19 KB
/
Copy pathRushCommandSelector.ts
File metadata and controls
246 lines (232 loc) · 8.19 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
// 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 { StringDecoder } from 'node:string_decoder';
import {
LegacyFallbackSink,
OldEngineOutputAdapter,
REPORTER_PROTOCOL_VERSION,
resolveReporterCompatibility,
type IReporterCompatibilityDecision
} from '@rushstack/rush-reporter';
import type { IRushFrontendLaunchOptions } from './IRushFrontendLaunchOptions';
type CommandName = 'rush' | 'rush-pnpm' | 'rushx' | undefined;
/**
* Both "rush" and "rushx" share the same src/start.ts entry point. This makes it
* a little easier for them to share all the same startup checks and version selector
* logic. RushCommandSelector looks at argv to determine whether we're doing "rush"
* or "rushx" behavior, and then invokes the appropriate entry point in the selected
* @microsoft/rush-lib.
*/
export class RushCommandSelector {
public static failIfNotInvokedAsRush(version: string): void {
const commandName: CommandName = _getCommandName();
if (commandName !== 'rush' && commandName !== undefined) {
_failWithError(
`This repository is using Rush version ${version} which does not support the ${commandName} command`
);
}
}
public static execute(
launcherVersion: string,
selectedRushLib: typeof import('@microsoft/rush-lib'),
options: IRushFrontendLaunchOptions
): void {
const { Rush } = selectedRushLib;
if (!Rush) {
// This should be impossible unless we somehow loaded an unexpected version
_failWithError(`Unable to find the "Rush" entry point in @microsoft/rush-lib`);
}
const commandName: CommandName = _getCommandName();
const engineProtocolMajor: number | undefined = (
Rush as typeof Rush & { readonly _reporterProtocolMajor?: number }
)._reporterProtocolMajor;
const compatibility: IReporterCompatibilityDecision = resolveReporterCompatibility(
{ protocolMajor: REPORTER_PROTOCOL_VERSION.major, hasManager: true },
{
supportsStructuredSink: engineProtocolMajor !== undefined,
protocolMajor: engineProtocolMajor
}
);
let effectiveOptions: IRushFrontendLaunchOptions = options;
let restoreEngineOutput: (() => void) | undefined;
if (compatibility.mode !== 'structured' && engineProtocolMajor !== undefined && options.reporterEnabled) {
if (options.reporterSelectionReason === 'explicit --reporter') {
throw new Error(
`The selected Rush engine uses reporter protocol major ${engineProtocolMajor}, but this ` +
`frontend supports major ${REPORTER_PROTOCOL_VERSION.major}. Update global Rush or use ` +
'--reporter=legacy.'
);
}
effectiveOptions = {
...options,
reporter: {
...options.reporter,
eventSink: new LegacyFallbackSink()
},
reporterEnabled: false,
reporterSelectionReason: 'bootstrap compatibility fallback'
};
} else if (options.reporterEnabled) {
restoreEngineOutput = _observeEngineOutput(options, Rush.version);
effectiveOptions = {
...options,
reporterCloseAsync: async () => {
restoreEngineOutput?.();
await options.reporterCloseAsync();
}
};
}
try {
if (commandName === 'rush-pnpm') {
if (!Rush.launchRushPnpm) {
_failWithError(
`This repository is using Rush version ${Rush.version}` +
` which does not support the "rush-pnpm" command`
);
}
Rush.launchRushPnpm(launcherVersion, {
isManaged: options.isManaged,
alreadyReportedNodeTooNewError: options.alreadyReportedNodeTooNewError
});
} else if (commandName === 'rushx') {
if (!Rush.launchRushX) {
_failWithError(
`This repository is using Rush version ${Rush.version}` +
` which does not support the "rushx" command`
);
}
Rush.launchRushX(launcherVersion, effectiveOptions);
} else {
Rush.launch(launcherVersion, effectiveOptions);
}
} catch (error) {
restoreEngineOutput?.();
throw error;
}
}
}
function _observeEngineOutput(options: IRushFrontendLaunchOptions, engineVersion: string): () => void {
const captureState: { inProgress: boolean } = { inProgress: false };
const adapter: OldEngineOutputAdapter = new OldEngineOutputAdapter({
sink: options.reporter.eventSink,
sessionId: options.reporter.sessionId,
source: { packageName: '@microsoft/rush-lib', packageVersion: engineVersion }
});
const restoreStdout: () => void = _observeStream(
process.stdout,
'stdout',
adapter,
process.stdout.write.bind(process.stdout),
(options.reporterStdoutIsReserved ?? options.reporterStdoutIsMachineReadable) !== true,
captureState
);
const restoreStderr: () => void = _observeStream(
process.stderr,
'stderr',
adapter,
process.stderr.write.bind(process.stderr),
true,
captureState
);
let restored: boolean = false;
const restore: () => void = () => {
if (restored) {
return;
}
restored = true;
process.removeListener('beforeExit', restore);
process.removeListener('exit', restore);
restoreStdout();
restoreStderr();
};
process.once('beforeExit', restore);
process.once('exit', restore);
return restore;
}
function _observeStream(
stream: NodeJS.WriteStream,
streamName: 'stdout' | 'stderr',
adapter: OldEngineOutputAdapter,
legacyWrite: typeof process.stdout.write,
renderLive: boolean,
captureState: { inProgress: boolean }
): () => void {
const marker: symbol = Symbol.for(`rush.reporter.old-engine-output.${streamName}`);
const markedStream: NodeJS.WriteStream & { [key: symbol]: boolean | undefined } =
stream as NodeJS.WriteStream & { [key: symbol]: boolean | undefined };
if (markedStream[marker]) {
return () => {};
}
markedStream[marker] = true;
const decoder: StringDecoder = new StringDecoder('utf8');
const originalWrite: typeof stream.write = stream.write;
function captureText(text: string): void {
if (text) {
captureState.inProgress = true;
try {
adapter.capture(streamName, text, renderLive);
} finally {
captureState.inProgress = false;
}
}
}
stream.write = ((
chunk: string | Uint8Array,
encodingOrCallback?: BufferEncoding | ((error?: Error | null) => void),
callback?: (error?: Error | null) => void
): boolean => {
// Reporter writes can reenter either stream while an old-engine write is captured.
if (captureState.inProgress) {
return typeof encodingOrCallback === 'function'
? legacyWrite(chunk, encodingOrCallback)
: legacyWrite(chunk, encodingOrCallback, callback);
}
const text: string =
typeof chunk === 'string'
? chunk
: decoder.write(Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength));
captureText(text);
if (!renderLive) {
const writeCallback: ((error?: Error | null) => void) | undefined =
typeof encodingOrCallback === 'function' ? encodingOrCallback : callback;
if (writeCallback) {
process.nextTick(writeCallback);
}
return true;
}
if (typeof encodingOrCallback === 'function') {
return legacyWrite(chunk, encodingOrCallback);
}
return legacyWrite(chunk, encodingOrCallback, callback);
}) as typeof stream.write;
return () => {
try {
captureText(decoder.end());
} finally {
stream.write = originalWrite;
delete markedStream[marker];
}
};
}
function _failWithError(message: string): never {
throw new Error(message);
}
function _getCommandName(): CommandName {
if (process.argv.length >= 2) {
// Example:
// argv[0]: "C:\\Program Files\\nodejs\\node.exe"
// argv[1]: "C:\\Program Files\\nodejs\\node_modules\\@microsoft\\rush\\bin\\rushx"
const basename: string = path.basename(process.argv[1]).toUpperCase();
if (basename === 'RUSH') {
return 'rush';
}
if (basename === 'RUSH-PNPM') {
return 'rush-pnpm';
}
if (basename === 'RUSHX') {
return 'rushx';
}
}
return undefined;
}