Change:
<!-- Do Not Delete This! bugreporttemplate --<!-- Please read our Rules of Conduct: --<!-- Read our guide about submitting issues: --<!-- Search existing issues to avoid creating duplicates. --<!-- Test using the latest Insiders build to see if your issue has already been fixed: --<!-- Instead of creating your report here, use 'Report Issue' from the 'Help' menu in VS Code to pre-fill useful information. --<!-- Launch with to check. --Does this issue occur when all extensions are disabled?: Yes/No <!-- If you answered No above, use 'Help: Start Extension Bisect' from Command Palette to try to identify the cause. --<!-- Issues caused by an extension need to be reported directly to the extension publisher. The 'Help Report Issue' dialog can assist with this. --- VS Code Version: Latest Insiders. OS Version: Mac Steps to Reproduce: Run the VS Code-Jupyter tests on CI and it fails. Here are the logs where we use the VS Code test cli to download VS Code and install the Python extension Basically it looks like we cannot install any extension into VS Code I have tried this locally as well and the same code falls over Here is the code used to isntall the extension here are the logs
If i try this manually in the terminal this fails Here is the same CLI with the stable version of VS Code
Thanks, I was not aware that upstream modules depend on the path to our CLI. I will revert that part of the move.

Discussion:
exports.code = [ createModuleDescription('vs/code/electron-main/main'), <del> createModuleDescription('vs/code/node/cli/main'), createModuleDescription('vs/code/node/cli/cliProcessMain', ['vs/code/node/cli/main']), </del> <ins> createModuleDescription('vs/code/node/cli'), createModuleDescription('vs/code/node/cliProcessMain', ['vs/code/node/cli']), </ins> createModuleDescription('vs/code/electron-sandbox/issue/issueReporterMain'), createModuleDescription('vs/code/node/sharedProcess/sharedProcessMain'), createModuleDescription('vs/code/electron-sandbox/processExplorer/processExplorerMain')

process.env['VSCODE_CLI'] = '1'; // Load CLI through AMD loader <del> require('./bootstrap-amd').load('vs/code/node/cli/main'); </del> <ins> require('./bootstrap-amd').load('vs/code/node/cli'); </ins>

<ins> /*--------------------------------------------------------------------------------------------- *  Copyright (c) Microsoft Corporation. All rights reserved. *  Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ChildProcess, ChildProcessWithoutNullStreams, spawn, SpawnOptions } from 'child_process'; import { chmodSync, existsSync, readFileSync, statSync, truncateSync, unlinkSync } from 'fs'; import { homedir, release, tmpdir } from 'os'; import type { ProfilingSession, Target } from 'v8-inspect-profiler'; import { Event } from 'vs/base/common/event'; import { isAbsolute, resolve, join, dirname } from 'vs/base/common/path'; import { IProcessEnvironment, isMacintosh, isWindows } from 'vs/base/common/platform'; import { randomPort } from 'vs/base/common/ports'; import { isString } from 'vs/base/common/types'; import { whenDeleted, writeFileSync } from 'vs/base/node/pfs'; import { findFreePort } from 'vs/base/node/ports'; import { watchFileContents } from 'vs/platform/files/node/watcher/nodejs/nodejsWatcherLib'; import { NativeParsedArgs } from 'vs/platform/environment/common/argv'; import { buildHelpMessage, buildVersionMessage, OPTIONS } from 'vs/platform/environment/node/argv'; import { addArg, parseCLIProcessArgv } from 'vs/platform/environment/node/argvHelper'; import { getStdinFilePath, hasStdinWithoutTty, readFromStdin, stdinDataListener } from 'vs/platform/environment/node/stdin'; import { createWaitMarkerFileSync } from 'vs/platform/environment/node/wait'; import product from 'vs/platform/product/common/product'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { randomPath } from 'vs/base/common/extpath'; import { Utils } from 'vs/platform/profiling/common/profiling'; import { FileAccess } from 'vs/base/common/network'; function shouldSpawnCliProcess(argv: NativeParsedArgs): boolean { return !!argv['install-source'] || !!argv['list-extensions'] || !!argv['install-extension'] || !!argv['uninstall-extension'] || !!argv['locate-extension'] || !!argv['telemetry']; } interface IMainCli { main: (argv: NativeParsedArgs) => Promise<void>; } export async function main(argv: string[]): Promise<any> { let args: NativeParsedArgs; try { args = parseCLIProcessArgv(argv); } catch (err) { console.error(err.message); return; } if (args.tunnel) { if (!product.tunnelApplicationName) { console.error(`'tunnel' command not supported in ${product.applicationName}`); return; } return new Promise((resolve, reject) => { let tunnelProcess: ChildProcessWithoutNullStreams; if (process.env['VSCODE_DEV']) { tunnelProcess = spawn('cargo', ['run', '--', 'tunnel', ...argv.slice(5)], { cwd: join(getAppRoot(), 'cli') }); } else { const appPath = process.platform === 'darwin' // ./Contents/MacOS/Electron => ./Contents/Resources/app/bin/code-tunnel-insiders ? join(dirname(dirname(process.execPath)), 'Resources', 'app') : dirname(process.execPath); const tunnelCommand = join(appPath, 'bin', `${product.tunnelApplicationName}${isWindows ? '.exe' : ''}`); const tunnelArgs = argv.slice(3); tunnelProcess = spawn(tunnelCommand, ['tunnel', ...tunnelArgs]); } tunnelProcess.stdout.pipe(process.stdout); tunnelProcess.stderr.pipe(process.stderr); tunnelProcess.on('exit', resolve); tunnelProcess.on('error', reject); }); } // Help if (args.help) { const executable = `${product.applicationName}${isWindows ? '.exe' : ''}`; console.log(buildHelpMessage(product.nameLong, executable, product.version, OPTIONS)); } // Version Info else if (args.version) { console.log(buildVersionMessage(product.version, product.commit)); } // Shell integration else if (args['locate-shell-integration-path']) { let file: string; switch (args['locate-shell-integration-path']) { // Usage: `[[ "$TERM_PROGRAM" == "vscode" ]] && . "$(code --locate-shell-integration-path bash)"` case 'bash': file = 'shellIntegration-bash.sh'; break; // Usage: `if ($env:TERM_PROGRAM -eq "vscode") { . "$(code --locate-shell-integration-path pwsh)" }` case 'pwsh': file = 'shellIntegration.ps1'; break; // Usage: `[[ "$TERM_PROGRAM" == "vscode" ]] && . "$(code --locate-shell-integration-path zsh)"` case 'zsh': file = 'shellIntegration-rc.zsh'; break; // Usage: `string match -q "$TERM_PROGRAM" "vscode"; and . (code --locate-shell-integration-path fish)` case 'fish': file = 'shellIntegration.fish'; break; default: throw new Error('Error using --locate-shell-integration-path: Invalid shell type'); } console.log(join(getAppRoot(), 'out', 'vs', 'workbench', 'contrib', 'terminal', 'browser', 'media', file)); } // Extensions Management else if (shouldSpawnCliProcess(args)) { const cli = await new Promise<IMainCli>((resolve, reject) => require(['vs/code/node/cliProcessMain'], resolve, reject)); await cli.main(args); return; } // Write File else if (args['file-write']) { const source = args._[0]; const target = args._[1]; // Validate if ( !source || !target || source === target ||				// make sure source and target are provided and are not the same !isAbsolute(source) || !isAbsolute(target) ||			// make sure both source and target are absolute paths !existsSync(source) || !statSync(source).isFile() ||	// make sure source exists as file !existsSync(target) || !statSync(target).isFile()		// make sure target exists as file ) { throw new Error('Using --file-write with invalid arguments.'); } try { // Check for readonly status and chmod if so if we are told so let targetMode: number = 0; let restoreMode = false; if (!!args['file-chmod']) { targetMode = statSync(target).mode; if (!(targetMode & 0o200 /* File mode indicating writable by owner */)) { chmodSync(target, targetMode | 0o200); restoreMode = true; } } // Write source to target const data = readFileSync(source); if (isWindows) { // On Windows we use a different strategy of saving the file // by first truncating the file and then writing with r+ mode. // This helps to save hidden files on Windows // (see https://github.com/microsoft/vscode/issues/931) and // prevent removing alternate data streams // (see https://github.com/microsoft/vscode/issues/6363) truncateSync(target, 0); writeFileSync(target, data, { flag: 'r+' }); } else { writeFileSync(target, data); } // Restore previous mode as needed if (restoreMode) { chmodSync(target, targetMode); } } catch (error) { error.message = `Error using --file-write: ${error.message}`; throw error; } } // Just Code else { const env: IProcessEnvironment = { ...process.env, 'ELECTRON_NO_ATTACH_CONSOLE': '1' }; delete env['ELECTRON_RUN_AS_NODE']; const processCallbacks: ((child: ChildProcess) => Promise<void>)[] = []; const verbose = args.verbose || args.status; if (verbose) { env['ELECTRON_ENABLE_LOGGING'] = '1'; processCallbacks.push(async child => { child.stdout!.on('data', (data: Buffer) => console.log(data.toString('utf8').trim())); child.stderr!.on('data', (data: Buffer) => console.log(data.toString('utf8').trim())); await Event.toPromise(Event.fromNodeEventEmitter(child, 'exit')); }); } const hasReadStdinArg = args._.some(a => a === '-'); if (hasReadStdinArg) { // remove the "-" argument when we read from stdin args._ = args._.filter(a => a !== '-'); argv = argv.filter(a => a !== '-'); } let stdinFilePath: string | undefined; if (hasStdinWithoutTty()) { // Read from stdin: we require a single "-" argument to be passed in order to start reading from // stdin. We do this because there is no reliable way to find out if data is piped to stdin. Just // checking for stdin being connected to a TTY is not enough (https://github.com/microsoft/vscode/issues/40351) if (hasReadStdinArg) { stdinFilePath = getStdinFilePath(); // returns a file path where stdin input is written into (write in progress). try { await readFromStdin(stdinFilePath, !!verbose); // throws error if file can not be written // Make sure to open tmp file addArg(argv, stdinFilePath); // Enable --wait to get all data and ignore adding this to history addArg(argv, '--wait'); addArg(argv, '--skip-add-to-recently-opened'); args.wait = true; console.log(`Reading from stdin via: ${stdinFilePath}`); } catch (e) { console.log(`Failed to create file to read via stdin: ${e.toString()}`); stdinFilePath = undefined; } } else { // If the user pipes data via stdin but forgot to add the "-" argument, help by printing a message // if we detect that data flows into via stdin after a certain timeout. processCallbacks.push(_ => stdinDataListener(1000).then(dataReceived => { if (dataReceived) { if (isWindows) { console.log(`Run with '${product.applicationName} -' to read output from another program (e.g. 'echo Hello World | ${product.applicationName} -').`); } else { console.log(`Run with '${product.applicationName} -' to read from stdin (e.g. 'ps aux | grep code | ${product.applicationName} -').`); } } })); } } const isMacOSBigSurOrNewer = isMacintosh && release() > '20.0.0'; // If we are started with --wait create a random temporary file // and pass it over to the starting instance. We can use this file // to wait for it to be deleted to monitor that the edited file // is closed and then exit the waiting process. let waitMarkerFilePath: string | undefined; if (args.wait) { waitMarkerFilePath = createWaitMarkerFileSync(verbose); if (waitMarkerFilePath) { addArg(argv, '--waitMarkerFilePath', waitMarkerFilePath); } // When running with --wait, we want to continue running CLI process // until either: // - the wait marker file has been deleted (e.g. when closing the editor) // - the launched process terminates (e.g. due to a crash) processCallbacks.push(async child => { let childExitPromise; if (isMacOSBigSurOrNewer) { // On Big Sur, we resolve the following promise only when the child, // i.e. the open command, exited with a signal or error. Otherwise, we // wait for the marker file to be deleted or for the child to error. childExitPromise = new Promise<void>(resolve => { // Only resolve this promise if the child (i.e. open) exited with an error child.on('exit', (code, signal) => { if (code !== 0 || signal) { resolve(); } }); }); } else { // On other platforms, we listen for exit in case the child exits before the // marker file is deleted. childExitPromise = Event.toPromise(Event.fromNodeEventEmitter(child, 'exit')); } try { await Promise.race([ whenDeleted(waitMarkerFilePath!), Event.toPromise(Event.fromNodeEventEmitter(child, 'error')), childExitPromise ]); } finally { if (stdinFilePath) { unlinkSync(stdinFilePath); // Make sure to delete the tmp stdin file if we have any } } }); } // If we have been started with `--prof-startup` we need to find free ports to profile // the main process, the renderer, and the extension host. We also disable v8 cached data // to get better profile traces. Last, we listen on stdout for a signal that tells us to // stop profiling. if (args['prof-startup']) { const portMain = await findFreePort(randomPort(), 10, 3000); const portRenderer = await findFreePort(portMain + 1, 10, 3000); const portExthost = await findFreePort(portRenderer + 1, 10, 3000); // fail the operation when one of the ports couldn't be acquired. if (portMain * portRenderer * portExthost === 0) { throw new Error('Failed to find free ports for profiler. Make sure to shutdown all instances of the editor first.'); } const filenamePrefix = randomPath(homedir(), 'prof'); addArg(argv, `--inspect-brk=${portMain}`); addArg(argv, `--remote-debugging-port=${portRenderer}`); addArg(argv, `--inspect-brk-extensions=${portExthost}`); addArg(argv, `--prof-startup-prefix`, filenamePrefix); addArg(argv, `--no-cached-data`); writeFileSync(filenamePrefix, argv.slice(-6).join('|')); processCallbacks.push(async _child => { class Profiler { static async start(name: string, filenamePrefix: string, opts: { port: number; tries?: number; target?: (targets: Target[]) => Target }) { const profiler = await import('v8-inspect-profiler'); let session: ProfilingSession; try { session = await profiler.startProfiling(opts); } catch (err) { console.error(`FAILED to start profiling for '${name}' on port '${opts.port}'`); } return { async stop() { if (!session) { return; } let suffix = ''; const result = await session.stop(); if (!process.env['VSCODE_DEV']) { // when running from a not-development-build we remove // absolute filenames because we don't want to reveal anything // about users. We also append the `.txt` suffix to make it // easier to attach these files to GH issues result.profile = Utils.rewriteAbsolutePaths(result.profile, 'piiRemoved'); suffix = '.txt'; } writeFileSync(`${filenamePrefix}.${name}.cpuprofile${suffix}`, JSON.stringify(result.profile, undefined, 4)); } }; } } try { // load and start profiler const mainProfileRequest = Profiler.start('main', filenamePrefix, { port: portMain }); const extHostProfileRequest = Profiler.start('extHost', filenamePrefix, { port: portExthost, tries: 300 }); const rendererProfileRequest = Profiler.start('renderer', filenamePrefix, { port: portRenderer, tries: 200, target: function (targets) { return targets.filter(target => { if (!target.webSocketDebuggerUrl) { return false; } if (target.type === 'page') { return target.url.indexOf('workbench/workbench.html') > 0 || target.url.indexOf('workbench/workbench-dev.html') > 0; } else { return true; } })[0]; } }); const main = await mainProfileRequest; const extHost = await extHostProfileRequest; const renderer = await rendererProfileRequest; // wait for the renderer to delete the // marker file await whenDeleted(filenamePrefix); // stop profiling await main.stop(); await renderer.stop(); await extHost.stop(); // re-create the marker file to signal that profiling is done writeFileSync(filenamePrefix, ''); } catch (e) { console.error('Failed to profile startup. Make sure to quit Code first.'); } }); } const jsFlags = args['js-flags']; if (isString(jsFlags)) { const match = /max_old_space_size=(d+)/g.exec(jsFlags); if (match && !args['max-memory']) { addArg(argv, `--max-memory=${match[1]}`); } } const options: SpawnOptions = { detached: true, env }; if (!verbose) { options['stdio'] = 'ignore'; } let child: ChildProcess; if (!isMacOSBigSurOrNewer) { // We spawn process.execPath directly child = spawn(process.execPath, argv.slice(2), options); } else { // On Big Sur, we spawn using the open command to obtain behavior // similar to if the app was launched from the dock // https://github.com/microsoft/vscode/issues/102975 // The following args are for the open command itself, rather than for VS Code: // -n creates a new instance. //    Without -n, the open command re-opens the existing instance as-is. // -g starts the new instance in the background. //    Later, Electron brings the instance to the foreground. //    This way, Mac does not automatically try to foreground the new instance, which causes //    focusing issues when the new instance only sends data to a previous instance and then closes. const spawnArgs = ['-n', '-g']; // -a opens the given application. spawnArgs.push('-a', process.execPath); // -a: opens a specific application if (verbose) { spawnArgs.push('--wait-apps'); // `open --wait-apps`: blocks until the launched app is closed (even if they were already running) // The open command only allows for redirecting stderr and stdout to files, // so we make it redirect those to temp files, and then use a logger to // redirect the file output to the console for (const outputType of ['stdout', 'stderr']) { // Tmp file to target output to const tmpName = randomPath(tmpdir(), `code-${outputType}`); writeFileSync(tmpName, ''); spawnArgs.push(`--${outputType}`, tmpName); // Listener to redirect content to stdout/stderr processCallbacks.push(async child => { try { const stream = outputType === 'stdout' ? process.stdout : process.stderr; const cts = new CancellationTokenSource(); child.on('close', () => { // We must dispose the token to stop watching, // but the watcher might still be reading data. setTimeout(() => cts.dispose(true), 200); }); await watchFileContents(tmpName, chunk => stream.write(chunk), () => { /* ignore */ }, cts.token); } finally { unlinkSync(tmpName); } }); } } for (const e in env) { // Ignore the _ env var, because the open command // ignores it anyway. // Pass the rest of the env vars in to fix // https://github.com/microsoft/vscode/issues/134696. if (e !== '_') { spawnArgs.push('--env'); spawnArgs.push(`${e}=${env[e]}`); } } spawnArgs.push('--args', ...argv.slice(2)); // pass on our arguments if (env['VSCODE_DEV']) { // If we're in development mode, replace the . arg with the // vscode source arg. Because the OSS app isn't bundled, // it needs the full vscode source arg to launch properly. const curdir = '.'; const launchDirIndex = spawnArgs.indexOf(curdir); if (launchDirIndex !== -1) { spawnArgs[launchDirIndex] = resolve(curdir); } } // We already passed over the env variables // using the --env flags, so we can leave them out here. // Also, we don't need to pass env._, which is different from argv._ child = spawn('open', spawnArgs, { ...options, env: {} }); } return Promise.all(processCallbacks.map(callback => callback(child))); } } function getAppRoot() { return dirname(FileAccess.asFileUri('').fsPath); } function eventuallyExit(code: number): void { setTimeout(() => process.exit(code), 0); } main(process.argv) .then(() => eventuallyExit(0)) .then(null, err => { console.error(err.message || err.stack || err); eventuallyExit(1); }); </ins>

<del> /*--------------------------------------------------------------------------------------------- *  Copyright (c) Microsoft Corporation. All rights reserved. *  Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { hostname, release } from 'os'; import { raceTimeout } from 'vs/base/common/async'; import { VSBuffer } from 'vs/base/common/buffer'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { isSigPipeError, onUnexpectedError, setUnexpectedErrorHandler } from 'vs/base/common/errors'; import { Disposable } from 'vs/base/common/lifecycle'; import { Schemas } from 'vs/base/common/network'; import { isAbsolute, join } from 'vs/base/common/path'; import { isWindows } from 'vs/base/common/platform'; import { cwd } from 'vs/base/common/process'; import { URI } from 'vs/base/common/uri'; import { Promises } from 'vs/base/node/pfs'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ConfigurationService } from 'vs/platform/configuration/common/configurationService'; import { IDownloadService } from 'vs/platform/download/common/download'; import { DownloadService } from 'vs/platform/download/common/downloadService'; import { NativeParsedArgs } from 'vs/platform/environment/common/argv'; import { INativeEnvironmentService } from 'vs/platform/environment/common/environment'; import { NativeEnvironmentService } from 'vs/platform/environment/node/environmentService'; import { ExtensionGalleryServiceWithNoStorageService } from 'vs/platform/extensionManagement/common/extensionGalleryService'; import { IExtensionGalleryService, InstallOptions } from 'vs/platform/extensionManagement/common/extensionManagement'; import { ExtensionSignatureVerificationService, IExtensionSignatureVerificationService } from 'vs/platform/extensionManagement/node/extensionSignatureVerificationService'; import { ExtensionManagementCLI } from 'vs/platform/extensionManagement/common/extensionManagementCLI'; import { IExtensionsProfileScannerService } from 'vs/platform/extensionManagement/common/extensionsProfileScannerService'; import { IExtensionsScannerService } from 'vs/platform/extensionManagement/common/extensionsScannerService'; import { ExtensionManagementService, INativeServerExtensionManagementService } from 'vs/platform/extensionManagement/node/extensionManagementService'; import { ExtensionsScannerService } from 'vs/platform/extensionManagement/node/extensionsScannerService'; import { IFileService } from 'vs/platform/files/common/files'; import { FileService } from 'vs/platform/files/common/fileService'; import { DiskFileSystemProvider } from 'vs/platform/files/node/diskFileSystemProvider'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { ILanguagePackService } from 'vs/platform/languagePacks/common/languagePacks'; import { NativeLanguagePackService } from 'vs/platform/languagePacks/node/languagePacks'; import { ConsoleLogger, getLogLevel, ILogger, ILogService, LogLevel } from 'vs/platform/log/common/log'; import { SpdLogLogger } from 'vs/platform/log/node/spdlogLog'; import { FilePolicyService } from 'vs/platform/policy/common/filePolicyService'; import { IPolicyService, NullPolicyService } from 'vs/platform/policy/common/policy'; import { NativePolicyService } from 'vs/platform/policy/node/nativePolicyService'; import product from 'vs/platform/product/common/product'; import { IProductService } from 'vs/platform/product/common/productService'; import { IRequestService } from 'vs/platform/request/common/request'; import { RequestService } from 'vs/platform/request/node/requestService'; import { SaveStrategy, StateReadonlyService } from 'vs/platform/state/node/stateService'; import { resolveCommonProperties } from 'vs/platform/telemetry/common/commonProperties'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { ITelemetryServiceConfig, TelemetryService } from 'vs/platform/telemetry/common/telemetryService'; import { supportsTelemetry, NullTelemetryService, getPiiPathsFromEnvironment, isInternalTelemetry, ITelemetryAppender } from 'vs/platform/telemetry/common/telemetryUtils'; import { OneDataSystemAppender } from 'vs/platform/telemetry/node/1dsAppender'; import { buildTelemetryMessage } from 'vs/platform/telemetry/node/telemetry'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { UriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentityService'; import { IUserDataProfile, IUserDataProfilesService } from 'vs/platform/userDataProfile/common/userDataProfile'; import { UserDataProfilesReadonlyService } from 'vs/platform/userDataProfile/node/userDataProfile'; import { resolveMachineId } from 'vs/platform/telemetry/node/telemetryUtils'; import { ExtensionsProfileScannerService } from 'vs/platform/extensionManagement/node/extensionsProfileScannerService'; import { LogService } from 'vs/platform/log/common/logService'; class CliMain extends Disposable { constructor( private argv: NativeParsedArgs ) { super(); this.registerListeners(); } private registerListeners(): void { // Dispose on exit process.once('exit', () => this.dispose()); } async run(): Promise<void> { // Services const [instantiationService, appenders] = await this.initServices(); return instantiationService.invokeFunction(async accessor => { const logService = accessor.get(ILogService); const fileService = accessor.get(IFileService); const environmentService = accessor.get(INativeEnvironmentService); const userDataProfilesService = accessor.get(IUserDataProfilesService); // Log info logService.info('CLI main', this.argv); // Error handler this.registerErrorHandler(logService); // Run based on argv await this.doRun(environmentService, fileService, userDataProfilesService, instantiationService); // Flush the remaining data in AI adapter (with 1s timeout) await Promise.all(appenders.map(a => { raceTimeout(a.flush(), 1000); })); return; }); } private async initServices(): Promise<[IInstantiationService, ITelemetryAppender[]]> { const services = new ServiceCollection(); // Product const productService = { _serviceBrand: undefined, ...product }; services.set(IProductService, productService); // Environment const environmentService = new NativeEnvironmentService(this.argv, productService); services.set(INativeEnvironmentService, environmentService); // Init folders await Promise.all([ environmentService.appSettingsHome.fsPath, environmentService.extensionsPath ].map(path => path ? Promises.mkdir(path, { recursive: true }) : undefined)); // Log const logLevel = getLogLevel(environmentService); const spdLogLogger = new SpdLogLogger('cli', join(environmentService.logsPath, 'cli.log'), true, false, logLevel); const otherLoggers: ILogger[] = []; if (logLevel === LogLevel.Trace) { otherLoggers.push(new ConsoleLogger(logLevel)); } const logService = this._register(new LogService(spdLogLogger, otherLoggers)); services.set(ILogService, logService); // Files const fileService = this._register(new FileService(logService)); services.set(IFileService, fileService); const diskFileSystemProvider = this._register(new DiskFileSystemProvider(logService)); fileService.registerProvider(Schemas.file, diskFileSystemProvider); // State // Uri Identity const uriIdentityService = new UriIdentityService(fileService); services.set(IUriIdentityService, uriIdentityService); // User Data Profiles const stateService = new StateReadonlyService(SaveStrategy.DELAYED, environmentService, logService, fileService); const userDataProfilesService = new UserDataProfilesReadonlyService(stateService, uriIdentityService, environmentService, fileService, logService); services.set(IUserDataProfilesService, userDataProfilesService); // Policy const policyService = isWindows && productService.win32RegValueName ? this._register(new NativePolicyService(logService, productService.win32RegValueName)) : environmentService.policyFile ? this._register(new FilePolicyService(environmentService.policyFile, fileService, logService)) : new NullPolicyService(); services.set(IPolicyService, policyService); // Configuration const configurationService = this._register(new ConfigurationService(userDataProfilesService.defaultProfile.settingsResource, fileService, policyService, logService)); services.set(IConfigurationService, configurationService); // Initialize await Promise.all([ stateService.init(), configurationService.initialize() ]); // Initialize user data profiles after initializing the state userDataProfilesService.init(); // URI Identity services.set(IUriIdentityService, new UriIdentityService(fileService)); // Request services.set(IRequestService, new SyncDescriptor(RequestService, undefined, true)); // Download Service services.set(IDownloadService, new SyncDescriptor(DownloadService, undefined, true)); // Extensions services.set(IExtensionsProfileScannerService, new SyncDescriptor(ExtensionsProfileScannerService, undefined, true)); services.set(IExtensionsScannerService, new SyncDescriptor(ExtensionsScannerService, undefined, true)); services.set(IExtensionSignatureVerificationService, new SyncDescriptor(ExtensionSignatureVerificationService, undefined, true)); services.set(INativeServerExtensionManagementService, new SyncDescriptor(ExtensionManagementService, undefined, true)); services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryServiceWithNoStorageService, undefined, true)); // Localizations services.set(ILanguagePackService, new SyncDescriptor(NativeLanguagePackService, undefined, false)); // Telemetry const appenders: ITelemetryAppender[] = []; const isInternal = isInternalTelemetry(productService, configurationService); if (supportsTelemetry(productService, environmentService)) { if (productService.aiConfig && productService.aiConfig.ariaKey) { appenders.push(new OneDataSystemAppender(isInternal, 'monacoworkbench', null, productService.aiConfig.ariaKey)); } const { installSourcePath } = environmentService; const config: ITelemetryServiceConfig = { appenders, sendErrorTelemetry: false, commonProperties: (async () => { let machineId: string | undefined = undefined; try { machineId = await resolveMachineId(stateService); } catch (error) { if (error.code !== 'ENOENT') { logService.error(error); } } return resolveCommonProperties(fileService, release(), hostname(), process.arch, productService.commit, productService.version, machineId, isInternal, installSourcePath); })(), piiPaths: getPiiPathsFromEnvironment(environmentService) }; services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config], false)); } else { services.set(ITelemetryService, NullTelemetryService); } return [new InstantiationService(services), appenders]; } private registerErrorHandler(logService: ILogService): void { // Install handler for unexpected errors setUnexpectedErrorHandler(error => { const message = toErrorMessage(error, true); if (!message) { return; } logService.error(`[uncaught exception in CLI]: ${message}`); }); // Handle unhandled errors that can occur process.on('uncaughtException', err => { if (!isSigPipeError(err)) { onUnexpectedError(err); } }); process.on('unhandledRejection', (reason: unknown) => onUnexpectedError(reason)); } private async doRun(environmentService: INativeEnvironmentService, fileService: IFileService, userDataProfilesService: IUserDataProfilesService, instantiationService: IInstantiationService): Promise<void> { let profile: IUserDataProfile | undefined = undefined; if (environmentService.args.profile) { profile = userDataProfilesService.profiles.find(p => p.name === environmentService.args.profile); if (!profile) { throw new Error(`Profile '${environmentService.args.profile}' not found.`); } } const profileLocation = (profile ?? userDataProfilesService.defaultProfile).extensionsResource; // Install Source if (this.argv['install-source']) { return this.setInstallSource(environmentService, fileService, this.argv['install-source']); } // List Extensions if (this.argv['list-extensions']) { return instantiationService.createInstance(ExtensionManagementCLI).listExtensions(!!this.argv['show-versions'], this.argv['category'], profileLocation); } // Install Extension else if (this.argv['install-extension'] || this.argv['install-builtin-extension']) { const installOptions: InstallOptions = { isMachineScoped: !!this.argv['do-not-sync'], installPreReleaseVersion: !!this.argv['pre-release'], profileLocation }; return instantiationService.createInstance(ExtensionManagementCLI).installExtensions(this.asExtensionIdOrVSIX(this.argv['install-extension'] || []), this.argv['install-builtin-extension'] || [], installOptions, !!this.argv['force']); } // Uninstall Extension else if (this.argv['uninstall-extension']) { return instantiationService.createInstance(ExtensionManagementCLI).uninstallExtensions(this.asExtensionIdOrVSIX(this.argv['uninstall-extension']), !!this.argv['force'], profileLocation); } // Locate Extension else if (this.argv['locate-extension']) { return instantiationService.createInstance(ExtensionManagementCLI).locateExtension(this.argv['locate-extension']); } // Telemetry else if (this.argv['telemetry']) { console.log(await buildTelemetryMessage(environmentService.appRoot, environmentService.extensionsPath)); } } private asExtensionIdOrVSIX(inputs: string[]): (string | URI)[] { return inputs.map(input => /.vsix$/i.test(input) ? URI.file(isAbsolute(input) ? input : join(cwd(), input)) : input); } private async setInstallSource(environmentService: INativeEnvironmentService, fileService: IFileService, installSource: string): Promise<void> { await fileService.writeFile(URI.file(environmentService.installSourcePath), VSBuffer.fromString(installSource.slice(0, 30))); } } export async function main(argv: NativeParsedArgs): Promise<void> { const cliMain = new CliMain(argv); try { await cliMain.run(); } finally { cliMain.dispose(); } } </del>

<del> /*--------------------------------------------------------------------------------------------- *  Copyright (c) Microsoft Corporation. All rights reserved. *  Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { ChildProcess, ChildProcessWithoutNullStreams, spawn, SpawnOptions } from 'child_process'; import { chmodSync, existsSync, readFileSync, statSync, truncateSync, unlinkSync } from 'fs'; import { homedir, release, tmpdir } from 'os'; import type { ProfilingSession, Target } from 'v8-inspect-profiler'; import { Event } from 'vs/base/common/event'; import { isAbsolute, resolve, join, dirname } from 'vs/base/common/path'; import { IProcessEnvironment, isMacintosh, isWindows } from 'vs/base/common/platform'; import { randomPort } from 'vs/base/common/ports'; import { isString } from 'vs/base/common/types'; import { whenDeleted, writeFileSync } from 'vs/base/node/pfs'; import { findFreePort } from 'vs/base/node/ports'; import { watchFileContents } from 'vs/platform/files/node/watcher/nodejs/nodejsWatcherLib'; import { NativeParsedArgs } from 'vs/platform/environment/common/argv'; import { buildHelpMessage, buildVersionMessage, OPTIONS } from 'vs/platform/environment/node/argv'; import { addArg, parseCLIProcessArgv } from 'vs/platform/environment/node/argvHelper'; import { getStdinFilePath, hasStdinWithoutTty, readFromStdin, stdinDataListener } from 'vs/platform/environment/node/stdin'; import { createWaitMarkerFileSync } from 'vs/platform/environment/node/wait'; import product from 'vs/platform/product/common/product'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { randomPath } from 'vs/base/common/extpath'; import { Utils } from 'vs/platform/profiling/common/profiling'; import { FileAccess } from 'vs/base/common/network'; function shouldSpawnCliProcess(argv: NativeParsedArgs): boolean { return !!argv['install-source'] || !!argv['list-extensions'] || !!argv['install-extension'] || !!argv['uninstall-extension'] || !!argv['locate-extension'] || !!argv['telemetry']; } interface IMainCli { main: (argv: NativeParsedArgs) => Promise<void>; } export async function main(argv: string[]): Promise<any> { let args: NativeParsedArgs; try { args = parseCLIProcessArgv(argv); } catch (err) { console.error(err.message); return; } if (args.tunnel) { if (!product.tunnelApplicationName) { console.error(`'tunnel' command not supported in ${product.applicationName}`); return; } return new Promise((resolve, reject) => { let tunnelProcess: ChildProcessWithoutNullStreams; if (process.env['VSCODE_DEV']) { tunnelProcess = spawn('cargo', ['run', '--', 'tunnel', ...argv.slice(5)], { cwd: join(getAppRoot(), 'cli') }); } else { const appPath = process.platform === 'darwin' // ./Contents/MacOS/Electron => ./Contents/Resources/app/bin/code-tunnel-insiders ? join(dirname(dirname(process.execPath)), 'Resources', 'app') : dirname(process.execPath); const tunnelCommand = join(appPath, 'bin', `${product.tunnelApplicationName}${isWindows ? '.exe' : ''}`); const tunnelArgs = argv.slice(3); tunnelProcess = spawn(tunnelCommand, ['tunnel', ...tunnelArgs]); } tunnelProcess.stdout.pipe(process.stdout); tunnelProcess.stderr.pipe(process.stderr); tunnelProcess.on('exit', resolve); tunnelProcess.on('error', reject); }); } // Help if (args.help) { const executable = `${product.applicationName}${isWindows ? '.exe' : ''}`; console.log(buildHelpMessage(product.nameLong, executable, product.version, OPTIONS)); } // Version Info else if (args.version) { console.log(buildVersionMessage(product.version, product.commit)); } // Shell integration else if (args['locate-shell-integration-path']) { let file: string; switch (args['locate-shell-integration-path']) { // Usage: `[[ "$TERM_PROGRAM" == "vscode" ]] && . "$(code --locate-shell-integration-path bash)"` case 'bash': file = 'shellIntegration-bash.sh'; break; // Usage: `if ($env:TERM_PROGRAM -eq "vscode") { . "$(code --locate-shell-integration-path pwsh)" }` case 'pwsh': file = 'shellIntegration.ps1'; break; // Usage: `[[ "$TERM_PROGRAM" == "vscode" ]] && . "$(code --locate-shell-integration-path zsh)"` case 'zsh': file = 'shellIntegration-rc.zsh'; break; // Usage: `string match -q "$TERM_PROGRAM" "vscode"; and . (code --locate-shell-integration-path fish)` case 'fish': file = 'shellIntegration.fish'; break; default: throw new Error('Error using --locate-shell-integration-path: Invalid shell type'); } console.log(join(getAppRoot(), 'out', 'vs', 'workbench', 'contrib', 'terminal', 'browser', 'media', file)); } // Extensions Management else if (shouldSpawnCliProcess(args)) { const cli = await new Promise<IMainCli>((resolve, reject) => require(['vs/code/node/cliProcessMain'], resolve, reject)); await cli.main(args); return; } // Write File else if (args['file-write']) { const source = args._[0]; const target = args._[1]; // Validate if ( !source || !target || source === target ||				// make sure source and target are provided and are not the same !isAbsolute(source) || !isAbsolute(target) ||			// make sure both source and target are absolute paths !existsSync(source) || !statSync(source).isFile() ||	// make sure source exists as file !existsSync(target) || !statSync(target).isFile()		// make sure target exists as file ) { throw new Error('Using --file-write with invalid arguments.'); } try { // Check for readonly status and chmod if so if we are told so let targetMode: number = 0; let restoreMode = false; if (!!args['file-chmod']) { targetMode = statSync(target).mode; if (!(targetMode & 0o200 /* File mode indicating writable by owner */)) { chmodSync(target, targetMode | 0o200); restoreMode = true; } } // Write source to target const data = readFileSync(source); if (isWindows) { // On Windows we use a different strategy of saving the file // by first truncating the file and then writing with r+ mode. // This helps to save hidden files on Windows // (see https://github.com/microsoft/vscode/issues/931) and // prevent removing alternate data streams // (see https://github.com/microsoft/vscode/issues/6363) truncateSync(target, 0); writeFileSync(target, data, { flag: 'r+' }); } else { writeFileSync(target, data); } // Restore previous mode as needed if (restoreMode) { chmodSync(target, targetMode); } } catch (error) { error.message = `Error using --file-write: ${error.message}`; throw error; } } // Just Code else { const env: IProcessEnvironment = { ...process.env, 'ELECTRON_NO_ATTACH_CONSOLE': '1' }; delete env['ELECTRON_RUN_AS_NODE']; const processCallbacks: ((child: ChildProcess) => Promise<void>)[] = []; const verbose = args.verbose || args.status; if (verbose) { env['ELECTRON_ENABLE_LOGGING'] = '1'; processCallbacks.push(async child => { child.stdout!.on('data', (data: Buffer) => console.log(data.toString('utf8').trim())); child.stderr!.on('data', (data: Buffer) => console.log(data.toString('utf8').trim())); await Event.toPromise(Event.fromNodeEventEmitter(child, 'exit')); }); } const hasReadStdinArg = args._.some(a => a === '-'); if (hasReadStdinArg) { // remove the "-" argument when we read from stdin args._ = args._.filter(a => a !== '-'); argv = argv.filter(a => a !== '-'); } let stdinFilePath: string | undefined; if (hasStdinWithoutTty()) { // Read from stdin: we require a single "-" argument to be passed in order to start reading from // stdin. We do this because there is no reliable way to find out if data is piped to stdin. Just // checking for stdin being connected to a TTY is not enough (https://github.com/microsoft/vscode/issues/40351) if (hasReadStdinArg) { stdinFilePath = getStdinFilePath(); // returns a file path where stdin input is written into (write in progress). try { await readFromStdin(stdinFilePath, !!verbose); // throws error if file can not be written // Make sure to open tmp file addArg(argv, stdinFilePath); // Enable --wait to get all data and ignore adding this to history addArg(argv, '--wait'); addArg(argv, '--skip-add-to-recently-opened'); args.wait = true; console.log(`Reading from stdin via: ${stdinFilePath}`); } catch (e) { console.log(`Failed to create file to read via stdin: ${e.toString()}`); stdinFilePath = undefined; } } else { // If the user pipes data via stdin but forgot to add the "-" argument, help by printing a message // if we detect that data flows into via stdin after a certain timeout. processCallbacks.push(_ => stdinDataListener(1000).then(dataReceived => { if (dataReceived) { if (isWindows) { console.log(`Run with '${product.applicationName} -' to read output from another program (e.g. 'echo Hello World | ${product.applicationName} -').`); } else { console.log(`Run with '${product.applicationName} -' to read from stdin (e.g. 'ps aux | grep code | ${product.applicationName} -').`); } } })); } } const isMacOSBigSurOrNewer = isMacintosh && release() > '20.0.0'; // If we are started with --wait create a random temporary file // and pass it over to the starting instance. We can use this file // to wait for it to be deleted to monitor that the edited file // is closed and then exit the waiting process. let waitMarkerFilePath: string | undefined; if (args.wait) { waitMarkerFilePath = createWaitMarkerFileSync(verbose); if (waitMarkerFilePath) { addArg(argv, '--waitMarkerFilePath', waitMarkerFilePath); } // When running with --wait, we want to continue running CLI process // until either: // - the wait marker file has been deleted (e.g. when closing the editor) // - the launched process terminates (e.g. due to a crash) processCallbacks.push(async child => { let childExitPromise; if (isMacOSBigSurOrNewer) { // On Big Sur, we resolve the following promise only when the child, // i.e. the open command, exited with a signal or error. Otherwise, we // wait for the marker file to be deleted or for the child to error. childExitPromise = new Promise<void>(resolve => { // Only resolve this promise if the child (i.e. open) exited with an error child.on('exit', (code, signal) => { if (code !== 0 || signal) { resolve(); } }); }); } else { // On other platforms, we listen for exit in case the child exits before the // marker file is deleted. childExitPromise = Event.toPromise(Event.fromNodeEventEmitter(child, 'exit')); } try { await Promise.race([ whenDeleted(waitMarkerFilePath!), Event.toPromise(Event.fromNodeEventEmitter(child, 'error')), childExitPromise ]); } finally { if (stdinFilePath) { unlinkSync(stdinFilePath); // Make sure to delete the tmp stdin file if we have any } } }); } // If we have been started with `--prof-startup` we need to find free ports to profile // the main process, the renderer, and the extension host. We also disable v8 cached data // to get better profile traces. Last, we listen on stdout for a signal that tells us to // stop profiling. if (args['prof-startup']) { const portMain = await findFreePort(randomPort(), 10, 3000); const portRenderer = await findFreePort(portMain + 1, 10, 3000); const portExthost = await findFreePort(portRenderer + 1, 10, 3000); // fail the operation when one of the ports couldn't be acquired. if (portMain * portRenderer * portExthost === 0) { throw new Error('Failed to find free ports for profiler. Make sure to shutdown all instances of the editor first.'); } const filenamePrefix = randomPath(homedir(), 'prof'); addArg(argv, `--inspect-brk=${portMain}`); addArg(argv, `--remote-debugging-port=${portRenderer}`); addArg(argv, `--inspect-brk-extensions=${portExthost}`); addArg(argv, `--prof-startup-prefix`, filenamePrefix); addArg(argv, `--no-cached-data`); writeFileSync(filenamePrefix, argv.slice(-6).join('|')); processCallbacks.push(async _child => { class Profiler { static async start(name: string, filenamePrefix: string, opts: { port: number; tries?: number; target?: (targets: Target[]) => Target }) { const profiler = await import('v8-inspect-profiler'); let session: ProfilingSession; try { session = await profiler.startProfiling(opts); } catch (err) { console.error(`FAILED to start profiling for '${name}' on port '${opts.port}'`); } return { async stop() { if (!session) { return; } let suffix = ''; const result = await session.stop(); if (!process.env['VSCODE_DEV']) { // when running from a not-development-build we remove // absolute filenames because we don't want to reveal anything // about users. We also append the `.txt` suffix to make it // easier to attach these files to GH issues result.profile = Utils.rewriteAbsolutePaths(result.profile, 'piiRemoved'); suffix = '.txt'; } writeFileSync(`${filenamePrefix}.${name}.cpuprofile${suffix}`, JSON.stringify(result.profile, undefined, 4)); } }; } } try { // load and start profiler const mainProfileRequest = Profiler.start('main', filenamePrefix, { port: portMain }); const extHostProfileRequest = Profiler.start('extHost', filenamePrefix, { port: portExthost, tries: 300 }); const rendererProfileRequest = Profiler.start('renderer', filenamePrefix, { port: portRenderer, tries: 200, target: function (targets) { return targets.filter(target => { if (!target.webSocketDebuggerUrl) { return false; } if (target.type === 'page') { return target.url.indexOf('workbench/workbench.html') > 0 || target.url.indexOf('workbench/workbench-dev.html') > 0; } else { return true; } })[0]; } }); const main = await mainProfileRequest; const extHost = await extHostProfileRequest; const renderer = await rendererProfileRequest; // wait for the renderer to delete the // marker file await whenDeleted(filenamePrefix); // stop profiling await main.stop(); await renderer.stop(); await extHost.stop(); // re-create the marker file to signal that profiling is done writeFileSync(filenamePrefix, ''); } catch (e) { console.error('Failed to profile startup. Make sure to quit Code first.'); } }); } const jsFlags = args['js-flags']; if (isString(jsFlags)) { const match = /max_old_space_size=(d+)/g.exec(jsFlags); if (match && !args['max-memory']) { addArg(argv, `--max-memory=${match[1]}`); } } const options: SpawnOptions = { detached: true, env }; if (!verbose) { options['stdio'] = 'ignore'; } let child: ChildProcess; if (!isMacOSBigSurOrNewer) { // We spawn process.execPath directly child = spawn(process.execPath, argv.slice(2), options); } else { // On Big Sur, we spawn using the open command to obtain behavior // similar to if the app was launched from the dock // https://github.com/microsoft/vscode/issues/102975 // The following args are for the open command itself, rather than for VS Code: // -n creates a new instance. //    Without -n, the open command re-opens the existing instance as-is. // -g starts the new instance in the background. //    Later, Electron brings the instance to the foreground. //    This way, Mac does not automatically try to foreground the new instance, which causes //    focusing issues when the new instance only sends data to a previous instance and then closes. const spawnArgs = ['-n', '-g']; // -a opens the given application. spawnArgs.push('-a', process.execPath); // -a: opens a specific application if (verbose) { spawnArgs.push('--wait-apps'); // `open --wait-apps`: blocks until the launched app is closed (even if they were already running) // The open command only allows for redirecting stderr and stdout to files, // so we make it redirect those to temp files, and then use a logger to // redirect the file output to the console for (const outputType of ['stdout', 'stderr']) { // Tmp file to target output to const tmpName = randomPath(tmpdir(), `code-${outputType}`); writeFileSync(tmpName, ''); spawnArgs.push(`--${outputType}`, tmpName); // Listener to redirect content to stdout/stderr processCallbacks.push(async child => { try { const stream = outputType === 'stdout' ? process.stdout : process.stderr; const cts = new CancellationTokenSource(); child.on('close', () => { // We must dispose the token to stop watching, // but the watcher might still be reading data. setTimeout(() => cts.dispose(true), 200); }); await watchFileContents(tmpName, chunk => stream.write(chunk), () => { /* ignore */ }, cts.token); } finally { unlinkSync(tmpName); } }); } } for (const e in env) { // Ignore the _ env var, because the open command // ignores it anyway. // Pass the rest of the env vars in to fix // https://github.com/microsoft/vscode/issues/134696. if (e !== '_') { spawnArgs.push('--env'); spawnArgs.push(`${e}=${env[e]}`); } } spawnArgs.push('--args', ...argv.slice(2)); // pass on our arguments if (env['VSCODE_DEV']) { // If we're in development mode, replace the . arg with the // vscode source arg. Because the OSS app isn't bundled, // it needs the full vscode source arg to launch properly. const curdir = '.'; const launchDirIndex = spawnArgs.indexOf(curdir); if (launchDirIndex !== -1) { spawnArgs[launchDirIndex] = resolve(curdir); } } // We already passed over the env variables // using the --env flags, so we can leave them out here. // Also, we don't need to pass env._, which is different from argv._ child = spawn('open', spawnArgs, { ...options, env: {} }); } return Promise.all(processCallbacks.map(callback => callback(child))); } } function getAppRoot() { return dirname(FileAccess.asFileUri('').fsPath); } function eventuallyExit(code: number): void { setTimeout(() => process.exit(code), 0); } main(process.argv) .then(() => eventuallyExit(0)) .then(null, err => { console.error(err.message || err.stack || err); eventuallyExit(1); }); </del>

<ins> /*--------------------------------------------------------------------------------------------- *  Copyright (c) Microsoft Corporation. All rights reserved. *  Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { hostname, release } from 'os'; import { raceTimeout } from 'vs/base/common/async'; import { VSBuffer } from 'vs/base/common/buffer'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { isSigPipeError, onUnexpectedError, setUnexpectedErrorHandler } from 'vs/base/common/errors'; import { Disposable } from 'vs/base/common/lifecycle'; import { Schemas } from 'vs/base/common/network'; import { isAbsolute, join } from 'vs/base/common/path'; import { isWindows } from 'vs/base/common/platform'; import { cwd } from 'vs/base/common/process'; import { URI } from 'vs/base/common/uri'; import { Promises } from 'vs/base/node/pfs'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ConfigurationService } from 'vs/platform/configuration/common/configurationService'; import { IDownloadService } from 'vs/platform/download/common/download'; import { DownloadService } from 'vs/platform/download/common/downloadService'; import { NativeParsedArgs } from 'vs/platform/environment/common/argv'; import { INativeEnvironmentService } from 'vs/platform/environment/common/environment'; import { NativeEnvironmentService } from 'vs/platform/environment/node/environmentService'; import { ExtensionGalleryServiceWithNoStorageService } from 'vs/platform/extensionManagement/common/extensionGalleryService'; import { IExtensionGalleryService, InstallOptions } from 'vs/platform/extensionManagement/common/extensionManagement'; import { ExtensionSignatureVerificationService, IExtensionSignatureVerificationService } from 'vs/platform/extensionManagement/node/extensionSignatureVerificationService'; import { ExtensionManagementCLI } from 'vs/platform/extensionManagement/common/extensionManagementCLI'; import { IExtensionsProfileScannerService } from 'vs/platform/extensionManagement/common/extensionsProfileScannerService'; import { IExtensionsScannerService } from 'vs/platform/extensionManagement/common/extensionsScannerService'; import { ExtensionManagementService, INativeServerExtensionManagementService } from 'vs/platform/extensionManagement/node/extensionManagementService'; import { ExtensionsScannerService } from 'vs/platform/extensionManagement/node/extensionsScannerService'; import { IFileService } from 'vs/platform/files/common/files'; import { FileService } from 'vs/platform/files/common/fileService'; import { DiskFileSystemProvider } from 'vs/platform/files/node/diskFileSystemProvider'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { InstantiationService } from 'vs/platform/instantiation/common/instantiationService'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { ILanguagePackService } from 'vs/platform/languagePacks/common/languagePacks'; import { NativeLanguagePackService } from 'vs/platform/languagePacks/node/languagePacks'; import { ConsoleLogger, getLogLevel, ILogger, ILogService, LogLevel } from 'vs/platform/log/common/log'; import { SpdLogLogger } from 'vs/platform/log/node/spdlogLog'; import { FilePolicyService } from 'vs/platform/policy/common/filePolicyService'; import { IPolicyService, NullPolicyService } from 'vs/platform/policy/common/policy'; import { NativePolicyService } from 'vs/platform/policy/node/nativePolicyService'; import product from 'vs/platform/product/common/product'; import { IProductService } from 'vs/platform/product/common/productService'; import { IRequestService } from 'vs/platform/request/common/request'; import { RequestService } from 'vs/platform/request/node/requestService'; import { SaveStrategy, StateReadonlyService } from 'vs/platform/state/node/stateService'; import { resolveCommonProperties } from 'vs/platform/telemetry/common/commonProperties'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { ITelemetryServiceConfig, TelemetryService } from 'vs/platform/telemetry/common/telemetryService'; import { supportsTelemetry, NullTelemetryService, getPiiPathsFromEnvironment, isInternalTelemetry, ITelemetryAppender } from 'vs/platform/telemetry/common/telemetryUtils'; import { OneDataSystemAppender } from 'vs/platform/telemetry/node/1dsAppender'; import { buildTelemetryMessage } from 'vs/platform/telemetry/node/telemetry'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { UriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentityService'; import { IUserDataProfile, IUserDataProfilesService } from 'vs/platform/userDataProfile/common/userDataProfile'; import { UserDataProfilesReadonlyService } from 'vs/platform/userDataProfile/node/userDataProfile'; import { resolveMachineId } from 'vs/platform/telemetry/node/telemetryUtils'; import { ExtensionsProfileScannerService } from 'vs/platform/extensionManagement/node/extensionsProfileScannerService'; import { LogService } from 'vs/platform/log/common/logService'; class CliMain extends Disposable { constructor( private argv: NativeParsedArgs ) { super(); this.registerListeners(); } private registerListeners(): void { // Dispose on exit process.once('exit', () => this.dispose()); } async run(): Promise<void> { // Services const [instantiationService, appenders] = await this.initServices(); return instantiationService.invokeFunction(async accessor => { const logService = accessor.get(ILogService); const fileService = accessor.get(IFileService); const environmentService = accessor.get(INativeEnvironmentService); const userDataProfilesService = accessor.get(IUserDataProfilesService); // Log info logService.info('CLI main', this.argv); // Error handler this.registerErrorHandler(logService); // Run based on argv await this.doRun(environmentService, fileService, userDataProfilesService, instantiationService); // Flush the remaining data in AI adapter (with 1s timeout) await Promise.all(appenders.map(a => { raceTimeout(a.flush(), 1000); })); return; }); } private async initServices(): Promise<[IInstantiationService, ITelemetryAppender[]]> { const services = new ServiceCollection(); // Product const productService = { _serviceBrand: undefined, ...product }; services.set(IProductService, productService); // Environment const environmentService = new NativeEnvironmentService(this.argv, productService); services.set(INativeEnvironmentService, environmentService); // Init folders await Promise.all([ environmentService.appSettingsHome.fsPath, environmentService.extensionsPath ].map(path => path ? Promises.mkdir(path, { recursive: true }) : undefined)); // Log const logLevel = getLogLevel(environmentService); const spdLogLogger = new SpdLogLogger('cli', join(environmentService.logsPath, 'cli.log'), true, false, logLevel); const otherLoggers: ILogger[] = []; if (logLevel === LogLevel.Trace) { otherLoggers.push(new ConsoleLogger(logLevel)); } const logService = this._register(new LogService(spdLogLogger, otherLoggers)); services.set(ILogService, logService); // Files const fileService = this._register(new FileService(logService)); services.set(IFileService, fileService); const diskFileSystemProvider = this._register(new DiskFileSystemProvider(logService)); fileService.registerProvider(Schemas.file, diskFileSystemProvider); // State // Uri Identity const uriIdentityService = new UriIdentityService(fileService); services.set(IUriIdentityService, uriIdentityService); // User Data Profiles const stateService = new StateReadonlyService(SaveStrategy.DELAYED, environmentService, logService, fileService); const userDataProfilesService = new UserDataProfilesReadonlyService(stateService, uriIdentityService, environmentService, fileService, logService); services.set(IUserDataProfilesService, userDataProfilesService); // Policy const policyService = isWindows && productService.win32RegValueName ? this._register(new NativePolicyService(logService, productService.win32RegValueName)) : environmentService.policyFile ? this._register(new FilePolicyService(environmentService.policyFile, fileService, logService)) : new NullPolicyService(); services.set(IPolicyService, policyService); // Configuration const configurationService = this._register(new ConfigurationService(userDataProfilesService.defaultProfile.settingsResource, fileService, policyService, logService)); services.set(IConfigurationService, configurationService); // Initialize await Promise.all([ stateService.init(), configurationService.initialize() ]); // Initialize user data profiles after initializing the state userDataProfilesService.init(); // URI Identity services.set(IUriIdentityService, new UriIdentityService(fileService)); // Request services.set(IRequestService, new SyncDescriptor(RequestService, undefined, true)); // Download Service services.set(IDownloadService, new SyncDescriptor(DownloadService, undefined, true)); // Extensions services.set(IExtensionsProfileScannerService, new SyncDescriptor(ExtensionsProfileScannerService, undefined, true)); services.set(IExtensionsScannerService, new SyncDescriptor(ExtensionsScannerService, undefined, true)); services.set(IExtensionSignatureVerificationService, new SyncDescriptor(ExtensionSignatureVerificationService, undefined, true)); services.set(INativeServerExtensionManagementService, new SyncDescriptor(ExtensionManagementService, undefined, true)); services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryServiceWithNoStorageService, undefined, true)); // Localizations services.set(ILanguagePackService, new SyncDescriptor(NativeLanguagePackService, undefined, false)); // Telemetry const appenders: ITelemetryAppender[] = []; const isInternal = isInternalTelemetry(productService, configurationService); if (supportsTelemetry(productService, environmentService)) { if (productService.aiConfig && productService.aiConfig.ariaKey) { appenders.push(new OneDataSystemAppender(isInternal, 'monacoworkbench', null, productService.aiConfig.ariaKey)); } const { installSourcePath } = environmentService; const config: ITelemetryServiceConfig = { appenders, sendErrorTelemetry: false, commonProperties: (async () => { let machineId: string | undefined = undefined; try { machineId = await resolveMachineId(stateService); } catch (error) { if (error.code !== 'ENOENT') { logService.error(error); } } return resolveCommonProperties(fileService, release(), hostname(), process.arch, productService.commit, productService.version, machineId, isInternal, installSourcePath); })(), piiPaths: getPiiPathsFromEnvironment(environmentService) }; services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config], false)); } else { services.set(ITelemetryService, NullTelemetryService); } return [new InstantiationService(services), appenders]; } private registerErrorHandler(logService: ILogService): void { // Install handler for unexpected errors setUnexpectedErrorHandler(error => { const message = toErrorMessage(error, true); if (!message) { return; } logService.error(`[uncaught exception in CLI]: ${message}`); }); // Handle unhandled errors that can occur process.on('uncaughtException', err => { if (!isSigPipeError(err)) { onUnexpectedError(err); } }); process.on('unhandledRejection', (reason: unknown) => onUnexpectedError(reason)); } private async doRun(environmentService: INativeEnvironmentService, fileService: IFileService, userDataProfilesService: IUserDataProfilesService, instantiationService: IInstantiationService): Promise<void> { let profile: IUserDataProfile | undefined = undefined; if (environmentService.args.profile) { profile = userDataProfilesService.profiles.find(p => p.name === environmentService.args.profile); if (!profile) { throw new Error(`Profile '${environmentService.args.profile}' not found.`); } } const profileLocation = (profile ?? userDataProfilesService.defaultProfile).extensionsResource; // Install Source if (this.argv['install-source']) { return this.setInstallSource(environmentService, fileService, this.argv['install-source']); } // List Extensions if (this.argv['list-extensions']) { return instantiationService.createInstance(ExtensionManagementCLI).listExtensions(!!this.argv['show-versions'], this.argv['category'], profileLocation); } // Install Extension else if (this.argv['install-extension'] || this.argv['install-builtin-extension']) { const installOptions: InstallOptions = { isMachineScoped: !!this.argv['do-not-sync'], installPreReleaseVersion: !!this.argv['pre-release'], profileLocation }; return instantiationService.createInstance(ExtensionManagementCLI).installExtensions(this.asExtensionIdOrVSIX(this.argv['install-extension'] || []), this.argv['install-builtin-extension'] || [], installOptions, !!this.argv['force']); } // Uninstall Extension else if (this.argv['uninstall-extension']) { return instantiationService.createInstance(ExtensionManagementCLI).uninstallExtensions(this.asExtensionIdOrVSIX(this.argv['uninstall-extension']), !!this.argv['force'], profileLocation); } // Locate Extension else if (this.argv['locate-extension']) { return instantiationService.createInstance(ExtensionManagementCLI).locateExtension(this.argv['locate-extension']); } // Telemetry else if (this.argv['telemetry']) { console.log(await buildTelemetryMessage(environmentService.appRoot, environmentService.extensionsPath)); } } private asExtensionIdOrVSIX(inputs: string[]): (string | URI)[] { return inputs.map(input => /.vsix$/i.test(input) ? URI.file(isAbsolute(input) ? input : join(cwd(), input)) : input); } private async setInstallSource(environmentService: INativeEnvironmentService, fileService: IFileService, installSource: string): Promise<void> { await fileService.writeFile(URI.file(environmentService.installSourcePath), VSBuffer.fromString(installSource.slice(0, 30))); } } export async function main(argv: NativeParsedArgs): Promise<void> { const cliMain = new CliMain(argv); try { await cliMain.run(); } finally { cliMain.dispose(); } } </ins>