Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/code/node/cli.ts
5221 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import { ChildProcess, spawn, SpawnOptions, StdioOptions } from 'child_process';
7
import { chmodSync, existsSync, readFileSync, statSync, truncateSync, unlinkSync } from 'fs';
8
import { homedir, tmpdir } from 'os';
9
import type { ProfilingSession, Target } from 'v8-inspect-profiler';
10
import { Event } from '../../base/common/event.js';
11
import { isAbsolute, resolve, join, dirname } from '../../base/common/path.js';
12
import { IProcessEnvironment, isMacintosh, isWindows } from '../../base/common/platform.js';
13
import { randomPort } from '../../base/common/ports.js';
14
import { whenDeleted, writeFileSync } from '../../base/node/pfs.js';
15
import { findFreePort } from '../../base/node/ports.js';
16
import { watchFileContents } from '../../platform/files/node/watcher/nodejs/nodejsWatcherLib.js';
17
import { NativeParsedArgs } from '../../platform/environment/common/argv.js';
18
import { buildHelpMessage, buildStdinMessage, buildVersionMessage, NATIVE_CLI_COMMANDS, OPTIONS } from '../../platform/environment/node/argv.js';
19
import { addArg, parseCLIProcessArgv } from '../../platform/environment/node/argvHelper.js';
20
import { getStdinFilePath, hasStdinWithoutTty, readFromStdin, stdinDataListener } from '../../platform/environment/node/stdin.js';
21
import { createWaitMarkerFileSync } from '../../platform/environment/node/wait.js';
22
import product from '../../platform/product/common/product.js';
23
import { CancellationTokenSource } from '../../base/common/cancellation.js';
24
import { isUNC, randomPath } from '../../base/common/extpath.js';
25
import { Utils } from '../../platform/profiling/common/profiling.js';
26
import { FileAccess } from '../../base/common/network.js';
27
import { cwd } from '../../base/common/process.js';
28
import { addUNCHostToAllowlist } from '../../base/node/unc.js';
29
import { URI } from '../../base/common/uri.js';
30
import { DeferredPromise } from '../../base/common/async.js';
31
32
function shouldSpawnCliProcess(argv: NativeParsedArgs): boolean {
33
return !!argv['install-source']
34
|| !!argv['list-extensions']
35
|| !!argv['install-extension']
36
|| !!argv['uninstall-extension']
37
|| !!argv['update-extensions']
38
|| !!argv['locate-extension']
39
|| !!argv['add-mcp']
40
|| !!argv['telemetry'];
41
}
42
43
export async function main(argv: string[]): Promise<void> {
44
let args: NativeParsedArgs;
45
46
try {
47
args = parseCLIProcessArgv(argv);
48
} catch (err) {
49
console.error(err.message);
50
return;
51
}
52
53
for (const subcommand of NATIVE_CLI_COMMANDS) {
54
if (args[subcommand]) {
55
if (!product.tunnelApplicationName) {
56
console.error(`'${subcommand}' command not supported in ${product.applicationName}`);
57
return;
58
}
59
const env: IProcessEnvironment = {
60
...process.env
61
};
62
// bootstrap-esm.js determines the electron environment based
63
// on the following variable. For the server we need to unset
64
// it to prevent importing any electron specific modules.
65
// Refs https://github.com/microsoft/vscode/issues/221883
66
delete env['ELECTRON_RUN_AS_NODE'];
67
68
const tunnelArgs = argv.slice(argv.indexOf(subcommand) + 1); // all arguments behind `tunnel`
69
return new Promise((resolve, reject) => {
70
let tunnelProcess: ChildProcess;
71
const stdio: StdioOptions = ['ignore', 'pipe', 'pipe'];
72
if (process.env['VSCODE_DEV']) {
73
tunnelProcess = spawn('cargo', ['run', '--', subcommand, ...tunnelArgs], { cwd: join(getAppRoot(), 'cli'), stdio, env });
74
} else {
75
const appPath = process.platform === 'darwin'
76
// ./Contents/MacOS/Code => ./Contents/Resources/app/bin/code-tunnel-insiders
77
? join(dirname(dirname(process.execPath)), 'Resources', 'app')
78
: dirname(process.execPath);
79
const tunnelCommand = join(appPath, 'bin', `${product.tunnelApplicationName}${isWindows ? '.exe' : ''}`);
80
tunnelProcess = spawn(tunnelCommand, [subcommand, ...tunnelArgs], { cwd: cwd(), stdio, env });
81
}
82
83
tunnelProcess.stdout!.pipe(process.stdout);
84
tunnelProcess.stderr!.pipe(process.stderr);
85
tunnelProcess.on('exit', resolve);
86
tunnelProcess.on('error', reject);
87
});
88
}
89
}
90
91
// Help (general)
92
if (args.help) {
93
const executable = `${product.applicationName}${isWindows ? '.exe' : ''}`;
94
console.log(buildHelpMessage(product.nameLong, executable, product.version, OPTIONS));
95
}
96
97
// Help (chat)
98
else if (args.chat?.help) {
99
const executable = `${product.applicationName}${isWindows ? '.exe' : ''}`;
100
console.log(buildHelpMessage(product.nameLong, executable, product.version, OPTIONS.chat.options, { isChat: true }));
101
}
102
103
// Version Info
104
else if (args.version) {
105
console.log(buildVersionMessage(product.version, product.commit));
106
}
107
108
// Shell integration
109
else if (args['locate-shell-integration-path']) {
110
let file: string;
111
switch (args['locate-shell-integration-path']) {
112
// Usage: `[[ "$TERM_PROGRAM" == "vscode" ]] && . "$(code --locate-shell-integration-path bash)"`
113
case 'bash': file = 'shellIntegration-bash.sh'; break;
114
// Usage: `if ($env:TERM_PROGRAM -eq "vscode") { . "$(code --locate-shell-integration-path pwsh)" }`
115
case 'pwsh': file = 'shellIntegration.ps1'; break;
116
// Usage: `[[ "$TERM_PROGRAM" == "vscode" ]] && . "$(code --locate-shell-integration-path zsh)"`
117
case 'zsh': file = 'shellIntegration-rc.zsh'; break;
118
// Usage: `string match -q "$TERM_PROGRAM" "vscode"; and . (code --locate-shell-integration-path fish)`
119
case 'fish': file = 'shellIntegration.fish'; break;
120
default: throw new Error('Error using --locate-shell-integration-path: Invalid shell type');
121
}
122
console.log(join(getAppRoot(), 'out', 'vs', 'workbench', 'contrib', 'terminal', 'common', 'scripts', file));
123
}
124
125
// Extensions Management
126
else if (shouldSpawnCliProcess(args)) {
127
128
// We do not bundle `cliProcessMain.js` into this file because
129
// it is rather large and only needed for very few CLI operations.
130
// This has the downside that we need to know if we run OSS or
131
// built, because our location on disk is different if built.
132
133
let cliProcessMain: string;
134
if (process.env['VSCODE_DEV']) {
135
cliProcessMain = './cliProcessMain.js';
136
} else {
137
cliProcessMain = './vs/code/node/cliProcessMain.js';
138
}
139
140
const cli = await import(cliProcessMain);
141
await cli.main(args);
142
143
return;
144
}
145
146
// Write File
147
else if (args['file-write']) {
148
const argsFile = args._[0];
149
if (!argsFile || !isAbsolute(argsFile) || !existsSync(argsFile) || !statSync(argsFile).isFile()) {
150
throw new Error('Using --file-write with invalid arguments.');
151
}
152
153
let source: string | undefined;
154
let target: string | undefined;
155
try {
156
const argsContents: { source: string; target: string } = JSON.parse(readFileSync(argsFile, 'utf8'));
157
source = argsContents.source;
158
target = argsContents.target;
159
} catch (error) {
160
throw new Error('Using --file-write with invalid arguments.');
161
}
162
163
// Windows: set the paths as allowed UNC paths given
164
// they are explicitly provided by the user as arguments
165
if (isWindows) {
166
for (const path of [source, target]) {
167
if (typeof path === 'string' && isUNC(path)) {
168
addUNCHostToAllowlist(URI.file(path).authority);
169
}
170
}
171
}
172
173
// Validate
174
if (
175
!source || !target || source === target || // make sure source and target are provided and are not the same
176
!isAbsolute(source) || !isAbsolute(target) || // make sure both source and target are absolute paths
177
!existsSync(source) || !statSync(source).isFile() || // make sure source exists as file
178
!existsSync(target) || !statSync(target).isFile() // make sure target exists as file
179
) {
180
throw new Error('Using --file-write with invalid arguments.');
181
}
182
183
try {
184
185
// Check for readonly status and chmod if so if we are told so
186
let targetMode = 0;
187
let restoreMode = false;
188
if (args['file-chmod']) {
189
targetMode = statSync(target).mode;
190
if (!(targetMode & 0o200 /* File mode indicating writable by owner */)) {
191
chmodSync(target, targetMode | 0o200);
192
restoreMode = true;
193
}
194
}
195
196
// Write source to target
197
const data = readFileSync(source);
198
if (isWindows) {
199
// On Windows we use a different strategy of saving the file
200
// by first truncating the file and then writing with r+ mode.
201
// This helps to save hidden files on Windows
202
// (see https://github.com/microsoft/vscode/issues/931) and
203
// prevent removing alternate data streams
204
// (see https://github.com/microsoft/vscode/issues/6363)
205
truncateSync(target, 0);
206
writeFileSync(target, data, { flag: 'r+' });
207
} else {
208
writeFileSync(target, data);
209
}
210
211
// Restore previous mode as needed
212
if (restoreMode) {
213
chmodSync(target, targetMode);
214
}
215
} catch (error) {
216
error.message = `Error using --file-write: ${error.message}`;
217
throw error;
218
}
219
}
220
221
// Just Code
222
else {
223
const env: IProcessEnvironment = {
224
...process.env,
225
'ELECTRON_NO_ATTACH_CONSOLE': '1'
226
};
227
228
delete env['ELECTRON_RUN_AS_NODE'];
229
230
const processCallbacks: ((child: ChildProcess) => Promise<void>)[] = [];
231
232
if (args.verbose) {
233
env['ELECTRON_ENABLE_LOGGING'] = '1';
234
}
235
236
if (args.verbose || args.status) {
237
processCallbacks.push(async child => {
238
child.stdout?.on('data', (data: Buffer) => console.log(data.toString('utf8').trim()));
239
child.stderr?.on('data', (data: Buffer) => console.log(data.toString('utf8').trim()));
240
241
await Event.toPromise(Event.fromNodeEventEmitter(child, 'exit'));
242
});
243
}
244
245
// Handle --transient option
246
if (args['transient']) {
247
const tempParentDir = randomPath(tmpdir(), 'vscode');
248
const tempUserDataDir = join(tempParentDir, 'data');
249
const tempExtensionsDir = join(tempParentDir, 'extensions');
250
251
addArg(argv, '--user-data-dir', tempUserDataDir);
252
addArg(argv, '--extensions-dir', tempExtensionsDir);
253
254
console.log(`State is temporarily stored. Relaunch this state with: ${product.applicationName} --user-data-dir "${tempUserDataDir}" --extensions-dir "${tempExtensionsDir}"`);
255
}
256
257
const hasReadStdinArg = args._.some(arg => arg === '-') || args.chat?._.some(arg => arg === '-');
258
if (hasReadStdinArg) {
259
// remove the "-" argument when we read from stdin
260
args._ = args._.filter(a => a !== '-');
261
argv = argv.filter(a => a !== '-');
262
}
263
264
let stdinFilePath: string | undefined;
265
if (hasStdinWithoutTty()) {
266
267
// Read from stdin: we require a single "-" argument to be passed in order to start reading from
268
// stdin. We do this because there is no reliable way to find out if data is piped to stdin. Just
269
// checking for stdin being connected to a TTY is not enough (https://github.com/microsoft/vscode/issues/40351)
270
271
if (hasReadStdinArg) {
272
stdinFilePath = getStdinFilePath();
273
274
try {
275
const readFromStdinDone = new DeferredPromise<void>();
276
await readFromStdin(stdinFilePath, !!args.verbose, () => readFromStdinDone.complete());
277
if (!args.wait) {
278
279
// if `--wait` is not provided, we keep this process alive
280
// for at least as long as the stdin stream is open to
281
// ensure that we read all the data.
282
// the downside is that the Code CLI process will then not
283
// terminate until stdin is closed, but users can always
284
// pass `--wait` to prevent that from happening (this is
285
// actually what we enforced until v1.85.x but then was
286
// changed to not enforce it anymore).
287
// a solution in the future would possibly be to exit, when
288
// the Code process exits. this would require some careful
289
// solution though in case Code is already running and this
290
// is a second instance telling the first instance what to
291
// open.
292
293
processCallbacks.push(() => readFromStdinDone.p);
294
}
295
296
if (args.chat) {
297
// Make sure to add tmp file as context to chat
298
addArg(argv, '--add-file', stdinFilePath);
299
} else {
300
// Make sure to open tmp file as editor but ignore
301
// it in the "recently open" list
302
addArg(argv, stdinFilePath);
303
addArg(argv, '--skip-add-to-recently-opened');
304
}
305
306
console.log(`Reading from stdin via: ${stdinFilePath}`);
307
} catch (e) {
308
console.log(`Failed to create file to read via stdin: ${e.toString()}`);
309
stdinFilePath = undefined;
310
}
311
} else {
312
313
// If the user pipes data via stdin but forgot to add the "-" argument, help by printing a message
314
// if we detect that data flows into via stdin after a certain timeout.
315
processCallbacks.push(_ => stdinDataListener(1000).then(dataReceived => {
316
if (dataReceived) {
317
console.log(buildStdinMessage(product.applicationName, !!args.chat));
318
}
319
}));
320
}
321
}
322
323
// If we are started with --wait create a random temporary file
324
// and pass it over to the starting instance. We can use this file
325
// to wait for it to be deleted to monitor that the edited file
326
// is closed and then exit the waiting process.
327
let waitMarkerFilePath: string | undefined;
328
if (args.wait) {
329
waitMarkerFilePath = createWaitMarkerFileSync(args.verbose);
330
if (waitMarkerFilePath) {
331
addArg(argv, '--waitMarkerFilePath', waitMarkerFilePath);
332
}
333
334
// When running with --wait, we want to continue running CLI process
335
// until either:
336
// - the wait marker file has been deleted (e.g. when closing the editor)
337
// - the launched process terminates (e.g. due to a crash)
338
processCallbacks.push(async child => {
339
let childExitPromise;
340
if (isMacintosh) {
341
// On macOS, we resolve the following promise only when the child,
342
// i.e. the open command, exited with a signal or error. Otherwise, we
343
// wait for the marker file to be deleted or for the child to error.
344
childExitPromise = new Promise<void>(resolve => {
345
// Only resolve this promise if the child (i.e. open) exited with an error
346
child.on('exit', (code, signal) => {
347
if (code !== 0 || signal) {
348
resolve();
349
}
350
});
351
});
352
} else {
353
// On other platforms, we listen for exit in case the child exits before the
354
// marker file is deleted.
355
childExitPromise = Event.toPromise(Event.fromNodeEventEmitter(child, 'exit'));
356
}
357
try {
358
await Promise.race([
359
whenDeleted(waitMarkerFilePath!),
360
Event.toPromise(Event.fromNodeEventEmitter(child, 'error')),
361
childExitPromise
362
]);
363
} finally {
364
if (stdinFilePath) {
365
unlinkSync(stdinFilePath); // Make sure to delete the tmp stdin file if we have any
366
}
367
}
368
});
369
}
370
371
// If we have been started with `--prof-startup` we need to find free ports to profile
372
// the main process, the renderer, and the extension host. We also disable v8 cached data
373
// to get better profile traces. Last, we listen on stdout for a signal that tells us to
374
// stop profiling.
375
if (args['prof-startup']) {
376
const profileHost = '127.0.0.1';
377
const portMain = await findFreePort(randomPort(), 10, 3000);
378
const portRenderer = await findFreePort(portMain + 1, 10, 3000);
379
const portExthost = await findFreePort(portRenderer + 1, 10, 3000);
380
381
// fail the operation when one of the ports couldn't be acquired.
382
if (portMain * portRenderer * portExthost === 0) {
383
throw new Error('Failed to find free ports for profiler. Make sure to shutdown all instances of the editor first.');
384
}
385
386
const filenamePrefix = randomPath(homedir(), 'prof');
387
388
addArg(argv, `--inspect-brk=${profileHost}:${portMain}`);
389
addArg(argv, `--remote-debugging-port=${profileHost}:${portRenderer}`);
390
addArg(argv, `--inspect-brk-extensions=${profileHost}:${portExthost}`);
391
addArg(argv, `--prof-startup-prefix`, filenamePrefix);
392
addArg(argv, `--no-cached-data`);
393
394
writeFileSync(filenamePrefix, argv.slice(-6).join('|'));
395
396
processCallbacks.push(async _child => {
397
398
class Profiler {
399
static async start(name: string, filenamePrefix: string, opts: { port: number; tries?: number; target?: (targets: Target[]) => Target }) {
400
const profiler = await import('v8-inspect-profiler');
401
402
let session: ProfilingSession;
403
try {
404
session = await profiler.startProfiling({ ...opts, host: profileHost });
405
} catch (err) {
406
console.error(`FAILED to start profiling for '${name}' on port '${opts.port}'`);
407
}
408
409
return {
410
async stop() {
411
if (!session) {
412
return;
413
}
414
let suffix = '';
415
const result = await session.stop();
416
if (!process.env['VSCODE_DEV']) {
417
// when running from a not-development-build we remove
418
// absolute filenames because we don't want to reveal anything
419
// about users. We also append the `.txt` suffix to make it
420
// easier to attach these files to GH issues
421
result.profile = Utils.rewriteAbsolutePaths(result.profile, 'piiRemoved');
422
suffix = '.txt';
423
}
424
425
writeFileSync(`${filenamePrefix}.${name}.cpuprofile${suffix}`, JSON.stringify(result.profile, undefined, 4));
426
}
427
};
428
}
429
}
430
431
try {
432
// load and start profiler
433
const mainProfileRequest = Profiler.start('main', filenamePrefix, { port: portMain });
434
const extHostProfileRequest = Profiler.start('extHost', filenamePrefix, { port: portExthost, tries: 300 });
435
const rendererProfileRequest = Profiler.start('renderer', filenamePrefix, {
436
port: portRenderer,
437
tries: 200,
438
target: function (targets) {
439
return targets.filter(target => {
440
if (!target.webSocketDebuggerUrl) {
441
return false;
442
}
443
if (target.type === 'page') {
444
return target.url.indexOf('workbench/workbench.html') > 0 || target.url.indexOf('workbench/workbench-dev.html') > 0;
445
} else {
446
return true;
447
}
448
})[0];
449
}
450
});
451
452
const main = await mainProfileRequest;
453
const extHost = await extHostProfileRequest;
454
const renderer = await rendererProfileRequest;
455
456
// wait for the renderer to delete the marker file
457
await whenDeleted(filenamePrefix);
458
459
// stop profiling
460
await main.stop();
461
await renderer.stop();
462
await extHost.stop();
463
464
// re-create the marker file to signal that profiling is done
465
writeFileSync(filenamePrefix, '');
466
467
} catch (e) {
468
console.error('Failed to profile startup. Make sure to quit Code first.');
469
}
470
});
471
}
472
473
const options: SpawnOptions = {
474
detached: true,
475
env
476
};
477
478
if (!args.verbose) {
479
options['stdio'] = 'ignore';
480
}
481
482
let child: ChildProcess;
483
if (!isMacintosh) {
484
if (!args.verbose && args.status) {
485
options['stdio'] = ['ignore', 'pipe', 'ignore']; // restore ability to see output when --status is used
486
}
487
// We spawn process.execPath directly
488
child = spawn(process.execPath, argv.slice(2), options);
489
} else {
490
// On macOS, we spawn using the open command to obtain behavior
491
// similar to if the app was launched from the dock
492
// https://github.com/microsoft/vscode/issues/102975
493
494
// The following args are for the open command itself, rather than for VS Code:
495
// -n creates a new instance.
496
// Without -n, the open command re-opens the existing instance as-is.
497
// -g starts the new instance in the background.
498
// Later, Electron brings the instance to the foreground.
499
// This way, Mac does not automatically try to foreground the new instance, which causes
500
// focusing issues when the new instance only sends data to a previous instance and then closes.
501
const spawnArgs = ['-n', '-g'];
502
// -a opens the given application.
503
spawnArgs.push('-a', process.execPath); // -a: opens a specific application
504
505
if (args.verbose || args.status) {
506
spawnArgs.push('--wait-apps'); // `open --wait-apps`: blocks until the launched app is closed (even if they were already running)
507
508
// The open command only allows for redirecting stderr and stdout to files,
509
// so we make it redirect those to temp files, and then use a logger to
510
// redirect the file output to the console
511
for (const outputType of args.verbose ? ['stdout', 'stderr'] : ['stdout']) {
512
513
// Tmp file to target output to
514
const tmpName = randomPath(tmpdir(), `code-${outputType}`);
515
writeFileSync(tmpName, '');
516
spawnArgs.push(`--${outputType}`, tmpName);
517
518
// Listener to redirect content to stdout/stderr
519
processCallbacks.push(async child => {
520
try {
521
const stream = outputType === 'stdout' ? process.stdout : process.stderr;
522
523
const cts = new CancellationTokenSource();
524
child.on('close', () => {
525
// We must dispose the token to stop watching,
526
// but the watcher might still be reading data.
527
setTimeout(() => cts.dispose(true), 200);
528
});
529
await watchFileContents(tmpName, chunk => stream.write(chunk), () => { /* ignore */ }, cts.token);
530
} finally {
531
unlinkSync(tmpName);
532
}
533
});
534
}
535
}
536
537
for (const e in env) {
538
// Ignore the _ env var, because the open command
539
// ignores it anyway.
540
// Pass the rest of the env vars in to fix
541
// https://github.com/microsoft/vscode/issues/134696.
542
if (e !== '_') {
543
spawnArgs.push('--env');
544
spawnArgs.push(`${e}=${env[e]}`);
545
}
546
}
547
548
spawnArgs.push('--args', ...argv.slice(2)); // pass on our arguments
549
550
if (env['VSCODE_DEV']) {
551
// If we're in development mode, replace the . arg with the
552
// vscode source arg. Because the OSS app isn't bundled,
553
// it needs the full vscode source arg to launch properly.
554
const curdir = '.';
555
const launchDirIndex = spawnArgs.indexOf(curdir);
556
if (launchDirIndex !== -1) {
557
spawnArgs[launchDirIndex] = resolve(curdir);
558
}
559
}
560
561
// We already passed over the env variables
562
// using the --env flags, so we can leave them out here.
563
// Also, we don't need to pass env._, which is different from argv._
564
child = spawn('open', spawnArgs, { ...options, env: {} });
565
}
566
567
await Promise.all(processCallbacks.map(callback => callback(child)));
568
}
569
}
570
571
function getAppRoot() {
572
return dirname(FileAccess.asFileUri('').fsPath);
573
}
574
575
function eventuallyExit(code: number): void {
576
setTimeout(() => process.exit(code), 0);
577
}
578
579
main(process.argv)
580
.then(() => eventuallyExit(0))
581
.then(null, err => {
582
console.error(err.message || err.stack || err);
583
eventuallyExit(1);
584
});
585
586