Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/code/electron-main/main.ts
3292 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 '../../platform/update/common/update.config.contribution.js';
7
8
import { app, dialog } from 'electron';
9
import { unlinkSync, promises } from 'fs';
10
import { URI } from '../../base/common/uri.js';
11
import { coalesce, distinct } from '../../base/common/arrays.js';
12
import { Promises } from '../../base/common/async.js';
13
import { toErrorMessage } from '../../base/common/errorMessage.js';
14
import { ExpectedError, setUnexpectedErrorHandler } from '../../base/common/errors.js';
15
import { IPathWithLineAndColumn, isValidBasename, parseLineAndColumnAware, sanitizeFilePath } from '../../base/common/extpath.js';
16
import { Event } from '../../base/common/event.js';
17
import { getPathLabel } from '../../base/common/labels.js';
18
import { Schemas } from '../../base/common/network.js';
19
import { basename, resolve } from '../../base/common/path.js';
20
import { mark } from '../../base/common/performance.js';
21
import { IProcessEnvironment, isMacintosh, isWindows, OS } from '../../base/common/platform.js';
22
import { cwd } from '../../base/common/process.js';
23
import { rtrim, trim } from '../../base/common/strings.js';
24
import { Promises as FSPromises } from '../../base/node/pfs.js';
25
import { ProxyChannel } from '../../base/parts/ipc/common/ipc.js';
26
import { Client as NodeIPCClient } from '../../base/parts/ipc/common/ipc.net.js';
27
import { connect as nodeIPCConnect, serve as nodeIPCServe, Server as NodeIPCServer, XDG_RUNTIME_DIR } from '../../base/parts/ipc/node/ipc.net.js';
28
import { CodeApplication } from './app.js';
29
import { localize } from '../../nls.js';
30
import { IConfigurationService } from '../../platform/configuration/common/configuration.js';
31
import { ConfigurationService } from '../../platform/configuration/common/configurationService.js';
32
import { IDiagnosticsMainService } from '../../platform/diagnostics/electron-main/diagnosticsMainService.js';
33
import { DiagnosticsService } from '../../platform/diagnostics/node/diagnosticsService.js';
34
import { NativeParsedArgs } from '../../platform/environment/common/argv.js';
35
import { EnvironmentMainService, IEnvironmentMainService } from '../../platform/environment/electron-main/environmentMainService.js';
36
import { addArg, parseMainProcessArgv } from '../../platform/environment/node/argvHelper.js';
37
import { createWaitMarkerFileSync } from '../../platform/environment/node/wait.js';
38
import { IFileService } from '../../platform/files/common/files.js';
39
import { FileService } from '../../platform/files/common/fileService.js';
40
import { DiskFileSystemProvider } from '../../platform/files/node/diskFileSystemProvider.js';
41
import { SyncDescriptor } from '../../platform/instantiation/common/descriptors.js';
42
import { IInstantiationService, ServicesAccessor } from '../../platform/instantiation/common/instantiation.js';
43
import { InstantiationService } from '../../platform/instantiation/common/instantiationService.js';
44
import { ServiceCollection } from '../../platform/instantiation/common/serviceCollection.js';
45
import { ILaunchMainService } from '../../platform/launch/electron-main/launchMainService.js';
46
import { ILifecycleMainService, LifecycleMainService } from '../../platform/lifecycle/electron-main/lifecycleMainService.js';
47
import { BufferLogger } from '../../platform/log/common/bufferLog.js';
48
import { ConsoleMainLogger, getLogLevel, ILoggerService, ILogService } from '../../platform/log/common/log.js';
49
import product from '../../platform/product/common/product.js';
50
import { IProductService } from '../../platform/product/common/productService.js';
51
import { IProtocolMainService } from '../../platform/protocol/electron-main/protocol.js';
52
import { ProtocolMainService } from '../../platform/protocol/electron-main/protocolMainService.js';
53
import { ITunnelService } from '../../platform/tunnel/common/tunnel.js';
54
import { TunnelService } from '../../platform/tunnel/node/tunnelService.js';
55
import { IRequestService } from '../../platform/request/common/request.js';
56
import { RequestService } from '../../platform/request/electron-utility/requestService.js';
57
import { ISignService } from '../../platform/sign/common/sign.js';
58
import { SignService } from '../../platform/sign/node/signService.js';
59
import { IStateReadService, IStateService } from '../../platform/state/node/state.js';
60
import { NullTelemetryService } from '../../platform/telemetry/common/telemetryUtils.js';
61
import { IThemeMainService } from '../../platform/theme/electron-main/themeMainService.js';
62
import { IUserDataProfilesMainService, UserDataProfilesMainService } from '../../platform/userDataProfile/electron-main/userDataProfile.js';
63
import { IPolicyService, NullPolicyService } from '../../platform/policy/common/policy.js';
64
import { NativePolicyService } from '../../platform/policy/node/nativePolicyService.js';
65
import { FilePolicyService } from '../../platform/policy/common/filePolicyService.js';
66
import { DisposableStore } from '../../base/common/lifecycle.js';
67
import { IUriIdentityService } from '../../platform/uriIdentity/common/uriIdentity.js';
68
import { UriIdentityService } from '../../platform/uriIdentity/common/uriIdentityService.js';
69
import { ILoggerMainService, LoggerMainService } from '../../platform/log/electron-main/loggerService.js';
70
import { LogService } from '../../platform/log/common/logService.js';
71
import { massageMessageBoxOptions } from '../../platform/dialogs/common/dialogs.js';
72
import { SaveStrategy, StateService } from '../../platform/state/node/stateService.js';
73
import { FileUserDataProvider } from '../../platform/userData/common/fileUserDataProvider.js';
74
import { addUNCHostToAllowlist, getUNCHost } from '../../base/node/unc.js';
75
import { ThemeMainService } from '../../platform/theme/electron-main/themeMainServiceImpl.js';
76
77
/**
78
* The main VS Code entry point.
79
*
80
* Note: This class can exist more than once for example when VS Code is already
81
* running and a second instance is started from the command line. It will always
82
* try to communicate with an existing instance to prevent that 2 VS Code instances
83
* are running at the same time.
84
*/
85
class CodeMain {
86
87
main(): void {
88
try {
89
this.startup();
90
} catch (error) {
91
console.error(error.message);
92
app.exit(1);
93
}
94
}
95
96
private async startup(): Promise<void> {
97
98
// Set the error handler early enough so that we are not getting the
99
// default electron error dialog popping up
100
setUnexpectedErrorHandler(err => console.error(err));
101
102
// Create services
103
const [instantiationService, instanceEnvironment, environmentMainService, configurationService, stateMainService, bufferLogger, productService, userDataProfilesMainService] = this.createServices();
104
105
try {
106
107
// Init services
108
try {
109
await this.initServices(environmentMainService, userDataProfilesMainService, configurationService, stateMainService, productService);
110
} catch (error) {
111
112
// Show a dialog for errors that can be resolved by the user
113
this.handleStartupDataDirError(environmentMainService, productService, error);
114
115
throw error;
116
}
117
118
// Startup
119
await instantiationService.invokeFunction(async accessor => {
120
const logService = accessor.get(ILogService);
121
const lifecycleMainService = accessor.get(ILifecycleMainService);
122
const fileService = accessor.get(IFileService);
123
const loggerService = accessor.get(ILoggerService);
124
125
// Create the main IPC server by trying to be the server
126
// If this throws an error it means we are not the first
127
// instance of VS Code running and so we would quit.
128
const mainProcessNodeIpcServer = await this.claimInstance(logService, environmentMainService, lifecycleMainService, instantiationService, productService, true);
129
130
// Write a lockfile to indicate an instance is running
131
// (https://github.com/microsoft/vscode/issues/127861#issuecomment-877417451)
132
FSPromises.writeFile(environmentMainService.mainLockfile, String(process.pid)).catch(err => {
133
logService.warn(`app#startup(): Error writing main lockfile: ${err.stack}`);
134
});
135
136
// Delay creation of spdlog for perf reasons (https://github.com/microsoft/vscode/issues/72906)
137
bufferLogger.logger = loggerService.createLogger('main', { name: localize('mainLog', "Main") });
138
139
// Lifecycle
140
Event.once(lifecycleMainService.onWillShutdown)(evt => {
141
fileService.dispose();
142
configurationService.dispose();
143
evt.join('instanceLockfile', promises.unlink(environmentMainService.mainLockfile).catch(() => { /* ignored */ }));
144
});
145
146
return instantiationService.createInstance(CodeApplication, mainProcessNodeIpcServer, instanceEnvironment).startup();
147
});
148
} catch (error) {
149
instantiationService.invokeFunction(this.quit, error);
150
}
151
}
152
153
private createServices(): [IInstantiationService, IProcessEnvironment, IEnvironmentMainService, ConfigurationService, StateService, BufferLogger, IProductService, UserDataProfilesMainService] {
154
const services = new ServiceCollection();
155
const disposables = new DisposableStore();
156
process.once('exit', () => disposables.dispose());
157
158
// Product
159
const productService = { _serviceBrand: undefined, ...product };
160
services.set(IProductService, productService);
161
162
// Environment
163
const environmentMainService = new EnvironmentMainService(this.resolveArgs(), productService);
164
const instanceEnvironment = this.patchEnvironment(environmentMainService); // Patch `process.env` with the instance's environment
165
services.set(IEnvironmentMainService, environmentMainService);
166
167
// Logger
168
const loggerService = new LoggerMainService(getLogLevel(environmentMainService), environmentMainService.logsHome);
169
services.set(ILoggerMainService, loggerService);
170
171
// Log: We need to buffer the spdlog logs until we are sure
172
// we are the only instance running, otherwise we'll have concurrent
173
// log file access on Windows (https://github.com/microsoft/vscode/issues/41218)
174
const bufferLogger = new BufferLogger(loggerService.getLogLevel());
175
const logService = disposables.add(new LogService(bufferLogger, [new ConsoleMainLogger(loggerService.getLogLevel())]));
176
services.set(ILogService, logService);
177
178
// Files
179
const fileService = new FileService(logService);
180
services.set(IFileService, fileService);
181
const diskFileSystemProvider = new DiskFileSystemProvider(logService);
182
fileService.registerProvider(Schemas.file, diskFileSystemProvider);
183
184
// URI Identity
185
const uriIdentityService = new UriIdentityService(fileService);
186
services.set(IUriIdentityService, uriIdentityService);
187
188
// State
189
const stateService = new StateService(SaveStrategy.DELAYED, environmentMainService, logService, fileService);
190
services.set(IStateReadService, stateService);
191
services.set(IStateService, stateService);
192
193
// User Data Profiles
194
const userDataProfilesMainService = new UserDataProfilesMainService(stateService, uriIdentityService, environmentMainService, fileService, logService);
195
services.set(IUserDataProfilesMainService, userDataProfilesMainService);
196
197
// Use FileUserDataProvider for user data to
198
// enable atomic read / write operations.
199
fileService.registerProvider(Schemas.vscodeUserData, new FileUserDataProvider(Schemas.file, diskFileSystemProvider, Schemas.vscodeUserData, userDataProfilesMainService, uriIdentityService, logService));
200
201
// Policy
202
let policyService: IPolicyService | undefined;
203
if (isWindows && productService.win32RegValueName) {
204
policyService = disposables.add(new NativePolicyService(logService, productService.win32RegValueName));
205
} else if (isMacintosh && productService.darwinBundleIdentifier) {
206
policyService = disposables.add(new NativePolicyService(logService, productService.darwinBundleIdentifier));
207
} else if (environmentMainService.policyFile) {
208
policyService = disposables.add(new FilePolicyService(environmentMainService.policyFile, fileService, logService));
209
} else {
210
policyService = new NullPolicyService();
211
}
212
services.set(IPolicyService, policyService);
213
214
// Configuration
215
const configurationService = new ConfigurationService(userDataProfilesMainService.defaultProfile.settingsResource, fileService, policyService, logService);
216
services.set(IConfigurationService, configurationService);
217
218
// Lifecycle
219
services.set(ILifecycleMainService, new SyncDescriptor(LifecycleMainService, undefined, false));
220
221
// Request
222
services.set(IRequestService, new SyncDescriptor(RequestService, undefined, true));
223
224
// Themes
225
services.set(IThemeMainService, new SyncDescriptor(ThemeMainService));
226
227
// Signing
228
services.set(ISignService, new SyncDescriptor(SignService, undefined, false /* proxied to other processes */));
229
230
// Tunnel
231
services.set(ITunnelService, new SyncDescriptor(TunnelService));
232
233
// Protocol (instantiated early and not using sync descriptor for security reasons)
234
services.set(IProtocolMainService, new ProtocolMainService(environmentMainService, userDataProfilesMainService, logService));
235
236
return [new InstantiationService(services, true), instanceEnvironment, environmentMainService, configurationService, stateService, bufferLogger, productService, userDataProfilesMainService];
237
}
238
239
private patchEnvironment(environmentMainService: IEnvironmentMainService): IProcessEnvironment {
240
const instanceEnvironment: IProcessEnvironment = {
241
VSCODE_IPC_HOOK: environmentMainService.mainIPCHandle
242
};
243
244
['VSCODE_NLS_CONFIG', 'VSCODE_PORTABLE'].forEach(key => {
245
const value = process.env[key];
246
if (typeof value === 'string') {
247
instanceEnvironment[key] = value;
248
}
249
});
250
251
Object.assign(process.env, instanceEnvironment);
252
253
return instanceEnvironment;
254
}
255
256
private async initServices(environmentMainService: IEnvironmentMainService, userDataProfilesMainService: UserDataProfilesMainService, configurationService: ConfigurationService, stateService: StateService, productService: IProductService): Promise<void> {
257
await Promises.settled<unknown>([
258
259
// Environment service (paths)
260
Promise.all<string | undefined>([
261
this.allowWindowsUNCPath(environmentMainService.extensionsPath), // enable extension paths on UNC drives...
262
environmentMainService.codeCachePath, // ...other user-data-derived paths should already be enlisted from `main.js`
263
environmentMainService.logsHome.with({ scheme: Schemas.file }).fsPath,
264
userDataProfilesMainService.defaultProfile.globalStorageHome.with({ scheme: Schemas.file }).fsPath,
265
environmentMainService.workspaceStorageHome.with({ scheme: Schemas.file }).fsPath,
266
environmentMainService.localHistoryHome.with({ scheme: Schemas.file }).fsPath,
267
environmentMainService.backupHome
268
].map(path => path ? promises.mkdir(path, { recursive: true }) : undefined)),
269
270
// State service
271
stateService.init(),
272
273
// Configuration service
274
configurationService.initialize()
275
]);
276
277
// Initialize user data profiles after initializing the state
278
userDataProfilesMainService.init();
279
}
280
281
private allowWindowsUNCPath(path: string): string {
282
if (isWindows) {
283
const host = getUNCHost(path);
284
if (host) {
285
addUNCHostToAllowlist(host);
286
}
287
}
288
289
return path;
290
}
291
292
private async claimInstance(logService: ILogService, environmentMainService: IEnvironmentMainService, lifecycleMainService: ILifecycleMainService, instantiationService: IInstantiationService, productService: IProductService, retry: boolean): Promise<NodeIPCServer> {
293
294
// Try to setup a server for running. If that succeeds it means
295
// we are the first instance to startup. Otherwise it is likely
296
// that another instance is already running.
297
let mainProcessNodeIpcServer: NodeIPCServer;
298
try {
299
mark('code/willStartMainServer');
300
mainProcessNodeIpcServer = await nodeIPCServe(environmentMainService.mainIPCHandle);
301
mark('code/didStartMainServer');
302
Event.once(lifecycleMainService.onWillShutdown)(() => mainProcessNodeIpcServer.dispose());
303
} catch (error) {
304
305
// Handle unexpected errors (the only expected error is EADDRINUSE that
306
// indicates another instance of VS Code is running)
307
if (error.code !== 'EADDRINUSE') {
308
309
// Show a dialog for errors that can be resolved by the user
310
this.handleStartupDataDirError(environmentMainService, productService, error);
311
312
// Any other runtime error is just printed to the console
313
throw error;
314
}
315
316
// Since we are the second instance, we do not want to show the dock
317
if (isMacintosh) {
318
app.dock?.hide();
319
}
320
321
// there's a running instance, let's connect to it
322
let client: NodeIPCClient<string>;
323
try {
324
client = await nodeIPCConnect(environmentMainService.mainIPCHandle, 'main');
325
} catch (error) {
326
327
// Handle unexpected connection errors by showing a dialog to the user
328
if (!retry || isWindows || error.code !== 'ECONNREFUSED') {
329
if (error.code === 'EPERM') {
330
this.showStartupWarningDialog(
331
localize('secondInstanceAdmin', "Another instance of {0} is already running as administrator.", productService.nameShort),
332
localize('secondInstanceAdminDetail', "Please close the other instance and try again."),
333
productService
334
);
335
}
336
337
throw error;
338
}
339
340
// it happens on Linux and OS X that the pipe is left behind
341
// let's delete it, since we can't connect to it and then
342
// retry the whole thing
343
try {
344
unlinkSync(environmentMainService.mainIPCHandle);
345
} catch (error) {
346
logService.warn('Could not delete obsolete instance handle', error);
347
348
throw error;
349
}
350
351
return this.claimInstance(logService, environmentMainService, lifecycleMainService, instantiationService, productService, false);
352
}
353
354
// Tests from CLI require to be the only instance currently
355
if (environmentMainService.extensionTestsLocationURI && !environmentMainService.debugExtensionHost.break) {
356
const msg = `Running extension tests from the command line is currently only supported if no other instance of ${productService.nameShort} is running.`;
357
logService.error(msg);
358
client.dispose();
359
360
throw new Error(msg);
361
}
362
363
// Show a warning dialog after some timeout if it takes long to talk to the other instance
364
// Skip this if we are running with --wait where it is expected that we wait for a while.
365
// Also skip when gathering diagnostics (--status) which can take a longer time.
366
let startupWarningDialogHandle: Timeout | undefined = undefined;
367
if (!environmentMainService.args.wait && !environmentMainService.args.status) {
368
startupWarningDialogHandle = setTimeout(() => {
369
this.showStartupWarningDialog(
370
localize('secondInstanceNoResponse', "Another instance of {0} is running but not responding", productService.nameShort),
371
localize('secondInstanceNoResponseDetail', "Please close all other instances and try again."),
372
productService
373
);
374
}, 10000);
375
}
376
377
const otherInstanceLaunchMainService = ProxyChannel.toService<ILaunchMainService>(client.getChannel('launch'), { disableMarshalling: true });
378
const otherInstanceDiagnosticsMainService = ProxyChannel.toService<IDiagnosticsMainService>(client.getChannel('diagnostics'), { disableMarshalling: true });
379
380
// Process Info
381
if (environmentMainService.args.status) {
382
return instantiationService.invokeFunction(async () => {
383
const diagnosticsService = new DiagnosticsService(NullTelemetryService, productService);
384
const mainDiagnostics = await otherInstanceDiagnosticsMainService.getMainDiagnostics();
385
const remoteDiagnostics = await otherInstanceDiagnosticsMainService.getRemoteDiagnostics({ includeProcesses: true, includeWorkspaceMetadata: true });
386
const diagnostics = await diagnosticsService.getDiagnostics(mainDiagnostics, remoteDiagnostics);
387
console.log(diagnostics);
388
389
throw new ExpectedError();
390
});
391
}
392
393
// Windows: allow to set foreground
394
if (isWindows) {
395
await this.windowsAllowSetForegroundWindow(otherInstanceLaunchMainService, logService);
396
}
397
398
// Send environment over...
399
logService.trace('Sending env to running instance...');
400
await otherInstanceLaunchMainService.start(environmentMainService.args, process.env as IProcessEnvironment);
401
402
// Cleanup
403
client.dispose();
404
405
// Now that we started, make sure the warning dialog is prevented
406
if (startupWarningDialogHandle) {
407
clearTimeout(startupWarningDialogHandle);
408
}
409
410
throw new ExpectedError('Sent env to running instance. Terminating...');
411
}
412
413
// Print --status usage info
414
if (environmentMainService.args.status) {
415
console.log(localize('statusWarning', "Warning: The --status argument can only be used if {0} is already running. Please run it again after {0} has started.", productService.nameShort));
416
417
throw new ExpectedError('Terminating...');
418
}
419
420
// dock might be hidden at this case due to a retry
421
if (isMacintosh) {
422
app.dock?.show();
423
}
424
425
// Set the VSCODE_PID variable here when we are sure we are the first
426
// instance to startup. Otherwise we would wrongly overwrite the PID
427
process.env['VSCODE_PID'] = String(process.pid);
428
429
return mainProcessNodeIpcServer;
430
}
431
432
private handleStartupDataDirError(environmentMainService: IEnvironmentMainService, productService: IProductService, error: NodeJS.ErrnoException): void {
433
if (error.code === 'EACCES' || error.code === 'EPERM') {
434
const directories = coalesce([environmentMainService.userDataPath, environmentMainService.extensionsPath, XDG_RUNTIME_DIR]).map(folder => getPathLabel(URI.file(folder), { os: OS, tildify: environmentMainService }));
435
436
this.showStartupWarningDialog(
437
localize('startupDataDirError', "Unable to write program user data."),
438
localize('startupUserDataAndExtensionsDirErrorDetail', "{0}\n\nPlease make sure the following directories are writeable:\n\n{1}", toErrorMessage(error), directories.join('\n')),
439
productService
440
);
441
}
442
}
443
444
private showStartupWarningDialog(message: string, detail: string, productService: IProductService): void {
445
446
// use sync variant here because we likely exit after this method
447
// due to startup issues and otherwise the dialog seems to disappear
448
// https://github.com/microsoft/vscode/issues/104493
449
450
dialog.showMessageBoxSync(massageMessageBoxOptions({
451
type: 'warning',
452
buttons: [localize({ key: 'close', comment: ['&& denotes a mnemonic'] }, "&&Close")],
453
message,
454
detail
455
}, productService).options);
456
}
457
458
private async windowsAllowSetForegroundWindow(launchMainService: ILaunchMainService, logService: ILogService): Promise<void> {
459
if (isWindows) {
460
const processId = await launchMainService.getMainProcessId();
461
462
logService.trace('Sending some foreground love to the running instance:', processId);
463
464
try {
465
(await import('windows-foreground-love')).allowSetForegroundWindow(processId);
466
} catch (error) {
467
logService.error(error);
468
}
469
}
470
}
471
472
private quit(accessor: ServicesAccessor, reason?: ExpectedError | Error): void {
473
const logService = accessor.get(ILogService);
474
const lifecycleMainService = accessor.get(ILifecycleMainService);
475
476
let exitCode = 0;
477
478
if (reason) {
479
if ((reason as ExpectedError).isExpected) {
480
if (reason.message) {
481
logService.trace(reason.message);
482
}
483
} else {
484
exitCode = 1; // signal error to the outside
485
486
if (reason.stack) {
487
logService.error(reason.stack);
488
} else {
489
logService.error(`Startup error: ${reason.toString()}`);
490
}
491
}
492
}
493
494
lifecycleMainService.kill(exitCode);
495
}
496
497
//#region Command line arguments utilities
498
499
private resolveArgs(): NativeParsedArgs {
500
501
// Parse arguments
502
const args = this.validatePaths(parseMainProcessArgv(process.argv));
503
504
if (args.wait && !args.waitMarkerFilePath) {
505
// If we are started with --wait create a random temporary file
506
// and pass it over to the starting instance. We can use this file
507
// to wait for it to be deleted to monitor that the edited file
508
// is closed and then exit the waiting process.
509
//
510
// Note: we are not doing this if the wait marker has been already
511
// added as argument. This can happen if VS Code was started from CLI.
512
const waitMarkerFilePath = createWaitMarkerFileSync(args.verbose);
513
if (waitMarkerFilePath) {
514
addArg(process.argv, '--waitMarkerFilePath', waitMarkerFilePath);
515
args.waitMarkerFilePath = waitMarkerFilePath;
516
}
517
}
518
519
if (args.chat) {
520
if (args.chat['new-window']) {
521
// Apply `--new-window` flag to the main arguments
522
args['new-window'] = true;
523
} else if (args.chat['reuse-window']) {
524
// Apply `--reuse-window` flag to the main arguments
525
args['reuse-window'] = true;
526
} else if (args.chat['profile']) {
527
// Apply `--profile` flag to the main arguments
528
args['profile'] = args.chat['profile'];
529
} else {
530
// Unless we are started with specific instructions about
531
// new windows or reusing existing ones, always take the
532
// current working directory as workspace to open.
533
args._ = [cwd()];
534
}
535
}
536
537
return args;
538
}
539
540
private validatePaths(args: NativeParsedArgs): NativeParsedArgs {
541
542
// Track URLs if they're going to be used
543
if (args['open-url']) {
544
args._urls = args._;
545
args._ = [];
546
}
547
548
// Normalize paths and watch out for goto line mode
549
if (!args['remote']) {
550
const paths = this.doValidatePaths(args._, args.goto);
551
args._ = paths;
552
}
553
554
return args;
555
}
556
557
private doValidatePaths(args: string[], gotoLineMode?: boolean): string[] {
558
const currentWorkingDir = cwd();
559
const result = args.map(arg => {
560
let pathCandidate = String(arg);
561
562
let parsedPath: IPathWithLineAndColumn | undefined = undefined;
563
if (gotoLineMode) {
564
parsedPath = parseLineAndColumnAware(pathCandidate);
565
pathCandidate = parsedPath.path;
566
}
567
568
if (pathCandidate) {
569
pathCandidate = this.preparePath(currentWorkingDir, pathCandidate);
570
}
571
572
const sanitizedFilePath = sanitizeFilePath(pathCandidate, currentWorkingDir);
573
574
const filePathBasename = basename(sanitizedFilePath);
575
if (filePathBasename /* can be empty if code is opened on root */ && !isValidBasename(filePathBasename)) {
576
return null; // do not allow invalid file names
577
}
578
579
if (gotoLineMode && parsedPath) {
580
parsedPath.path = sanitizedFilePath;
581
582
return this.toPath(parsedPath);
583
}
584
585
return sanitizedFilePath;
586
});
587
588
const caseInsensitive = isWindows || isMacintosh;
589
const distinctPaths = distinct(result, path => path && caseInsensitive ? path.toLowerCase() : (path || ''));
590
591
return coalesce(distinctPaths);
592
}
593
594
private preparePath(cwd: string, path: string): string {
595
596
// Trim trailing quotes
597
if (isWindows) {
598
path = rtrim(path, '"'); // https://github.com/microsoft/vscode/issues/1498
599
}
600
601
// Trim whitespaces
602
path = trim(trim(path, ' '), '\t');
603
604
if (isWindows) {
605
606
// Resolve the path against cwd if it is relative
607
path = resolve(cwd, path);
608
609
// Trim trailing '.' chars on Windows to prevent invalid file names
610
path = rtrim(path, '.');
611
}
612
613
return path;
614
}
615
616
private toPath(pathWithLineAndCol: IPathWithLineAndColumn): string {
617
const segments = [pathWithLineAndCol.path];
618
619
if (typeof pathWithLineAndCol.line === 'number') {
620
segments.push(String(pathWithLineAndCol.line));
621
}
622
623
if (typeof pathWithLineAndCol.column === 'number') {
624
segments.push(String(pathWithLineAndCol.column));
625
}
626
627
return segments.join(':');
628
}
629
630
//#endregion
631
}
632
633
// Main Startup
634
const code = new CodeMain();
635
code.main();
636
637