mirror of
https://github.com/coder/code-server.git
synced 2026-05-07 12:57:26 +02:00
Merge commit 'be3e8236086165e5e45a5a10783823874b3f3ebd' as 'lib/vscode'
This commit is contained in:
365
lib/vscode/src/vs/code/node/cli.ts
Normal file
365
lib/vscode/src/vs/code/node/cli.ts
Normal file
@@ -0,0 +1,365 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import * as os from 'os';
|
||||
import * as fs from 'fs';
|
||||
import { spawn, ChildProcess, SpawnOptions } from 'child_process';
|
||||
import { buildHelpMessage, buildVersionMessage, OPTIONS } from 'vs/platform/environment/node/argv';
|
||||
import { NativeParsedArgs } from 'vs/platform/environment/common/argv';
|
||||
import { parseCLIProcessArgv, addArg } from 'vs/platform/environment/node/argvHelper';
|
||||
import { createWaitMarkerFile } from 'vs/platform/environment/node/waitMarkerFile';
|
||||
import product from 'vs/platform/product/common/product';
|
||||
import * as paths from 'vs/base/common/path';
|
||||
import { whenDeleted, writeFileSync } from 'vs/base/node/pfs';
|
||||
import { findFreePort, randomPort } from 'vs/base/node/ports';
|
||||
import { isWindows, isLinux } from 'vs/base/common/platform';
|
||||
import type { ProfilingSession, Target } from 'v8-inspect-profiler';
|
||||
import { isString } from 'vs/base/common/types';
|
||||
import { hasStdinWithoutTty, stdinDataListener, getStdinFilePath, readFromStdin } from 'vs/platform/environment/node/stdin';
|
||||
|
||||
function shouldSpawnCliProcess(argv: NativeParsedArgs): boolean {
|
||||
return !!argv['install-source']
|
||||
|| !!argv['list-extensions']
|
||||
|| !!argv['install-extension']
|
||||
|| !!argv['install-builtin-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;
|
||||
}
|
||||
|
||||
// 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));
|
||||
}
|
||||
|
||||
// Extensions Management
|
||||
else if (shouldSpawnCliProcess(args)) {
|
||||
const cli = await new Promise<IMainCli>((c, e) => require(['vs/code/node/cliProcessMain'], c, e));
|
||||
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
|
||||
!paths.isAbsolute(source) || !paths.isAbsolute(target) || // make sure both source and target are absolute paths
|
||||
!fs.existsSync(source) || !fs.statSync(source).isFile() || // make sure source exists as file
|
||||
!fs.existsSync(target) || !fs.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 = fs.statSync(target).mode;
|
||||
if (!(targetMode & 128) /* readonly */) {
|
||||
fs.chmodSync(target, targetMode | 128);
|
||||
restoreMode = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Write source to target
|
||||
const data = fs.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)
|
||||
fs.truncateSync(target, 0);
|
||||
writeFileSync(target, data, { flag: 'r+' });
|
||||
} else {
|
||||
writeFileSync(target, data);
|
||||
}
|
||||
|
||||
// Restore previous mode as needed
|
||||
if (restoreMode) {
|
||||
fs.chmodSync(target, targetMode);
|
||||
}
|
||||
} catch (error) {
|
||||
error.message = `Error using --file-write: ${error.message}`;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Just Code
|
||||
else {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
'VSCODE_CLI': '1', // this will signal Code that it was spawned from this module
|
||||
'ELECTRON_NO_ATTACH_CONSOLE': '1'
|
||||
};
|
||||
|
||||
if (args['force-user-env']) {
|
||||
env['VSCODE_FORCE_USER_ENV'] = '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 new Promise<void>(resolve => child.once('exit', () => resolve()));
|
||||
});
|
||||
}
|
||||
|
||||
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 (args._.length === 0) {
|
||||
if (hasReadStdinArg) {
|
||||
stdinFilePath = getStdinFilePath();
|
||||
|
||||
// returns a file path where stdin input is written into (write in progress).
|
||||
try {
|
||||
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} -').`);
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 = createWaitMarkerFile(verbose);
|
||||
if (waitMarkerFilePath) {
|
||||
addArg(argv, '--waitMarkerFilePath', waitMarkerFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
// 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 accquired.
|
||||
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 = paths.join(os.homedir(), 'prof-' + Math.random().toString(16).slice(-4));
|
||||
|
||||
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 = '';
|
||||
let profile = 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
|
||||
profile = profiler.rewriteAbsolutePaths(profile, 'piiRemoved');
|
||||
suffix = '.txt';
|
||||
}
|
||||
|
||||
await profiler.writeProfile(profile, `${filenamePrefix}.${name}.cpuprofile${suffix}`);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
} 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';
|
||||
}
|
||||
|
||||
if (isLinux) {
|
||||
addArg(argv, '--no-sandbox'); // Electron 6 introduces a chrome-sandbox that requires root to run. This can fail. Disable sandbox via --no-sandbox
|
||||
}
|
||||
|
||||
const child = spawn(process.execPath, argv.slice(2), options);
|
||||
|
||||
if (args.wait && waitMarkerFilePath) {
|
||||
return new Promise<void>(resolve => {
|
||||
|
||||
// Complete when process exits
|
||||
child.once('exit', () => resolve(undefined));
|
||||
|
||||
// Complete when wait marker file is deleted
|
||||
whenDeleted(waitMarkerFilePath!).then(resolve, resolve);
|
||||
}).then(() => {
|
||||
|
||||
// Make sure to delete the tmp stdin file if we have any
|
||||
if (stdinFilePath) {
|
||||
fs.unlinkSync(stdinFilePath);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return Promise.all(processCallbacks.map(callback => callback(child)));
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
428
lib/vscode/src/vs/code/node/cliProcessMain.ts
Normal file
428
lib/vscode/src/vs/code/node/cliProcessMain.ts
Normal file
@@ -0,0 +1,428 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import { localize } from 'vs/nls';
|
||||
import { raceTimeout } from 'vs/base/common/async';
|
||||
import * as semver from 'vs/base/common/semver/semver';
|
||||
import product from 'vs/platform/product/common/product';
|
||||
import * as path from 'vs/base/common/path';
|
||||
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
|
||||
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 { IEnvironmentService, INativeEnvironmentService } from 'vs/platform/environment/common/environment';
|
||||
import { NativeParsedArgs } from 'vs/platform/environment/common/argv';
|
||||
import { NativeEnvironmentService } from 'vs/platform/environment/node/environmentService';
|
||||
import { IExtensionManagementService, IExtensionGalleryService, IGalleryExtension, ILocalExtension, InstallOptions } from 'vs/platform/extensionManagement/common/extensionManagement';
|
||||
import { ExtensionManagementService } from 'vs/platform/extensionManagement/node/extensionManagementService';
|
||||
import { ExtensionGalleryService } from 'vs/platform/extensionManagement/common/extensionGalleryService';
|
||||
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
|
||||
import { combinedAppender, NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
|
||||
import { TelemetryService, ITelemetryServiceConfig } from 'vs/platform/telemetry/common/telemetryService';
|
||||
import { resolveCommonProperties } from 'vs/platform/telemetry/node/commonProperties';
|
||||
import { IRequestService } from 'vs/platform/request/common/request';
|
||||
import { RequestService } from 'vs/platform/request/node/requestService';
|
||||
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
|
||||
import { ConfigurationService } from 'vs/platform/configuration/common/configurationService';
|
||||
import { AppInsightsAppender } from 'vs/platform/telemetry/node/appInsightsAppender';
|
||||
import { mkdirp, writeFile } from 'vs/base/node/pfs';
|
||||
import { getBaseLabel } from 'vs/base/common/labels';
|
||||
import { IStateService } from 'vs/platform/state/node/state';
|
||||
import { StateService } from 'vs/platform/state/node/stateService';
|
||||
import { ILogService, getLogLevel } from 'vs/platform/log/common/log';
|
||||
import { isPromiseCanceledError } from 'vs/base/common/errors';
|
||||
import { areSameExtensions, adoptToGalleryExtensionId, getGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
|
||||
import { URI } from 'vs/base/common/uri';
|
||||
import { getManifest } from 'vs/platform/extensionManagement/node/extensionManagementUtil';
|
||||
import { IExtensionManifest, ExtensionType, isLanguagePackExtension, EXTENSION_CATEGORIES } from 'vs/platform/extensions/common/extensions';
|
||||
import { CancellationToken } from 'vs/base/common/cancellation';
|
||||
import { LocalizationsService } from 'vs/platform/localizations/node/localizations';
|
||||
import { Schemas } from 'vs/base/common/network';
|
||||
import { SpdLogService } from 'vs/platform/log/node/spdlogService';
|
||||
import { buildTelemetryMessage } from 'vs/platform/telemetry/node/telemetry';
|
||||
import { FileService } from 'vs/platform/files/common/fileService';
|
||||
import { IFileService } from 'vs/platform/files/common/files';
|
||||
import { DiskFileSystemProvider } from 'vs/platform/files/node/diskFileSystemProvider';
|
||||
import { DisposableStore } from 'vs/base/common/lifecycle';
|
||||
import { IProductService } from 'vs/platform/product/common/productService';
|
||||
|
||||
const notFound = (id: string) => localize('notFound', "Extension '{0}' not found.", id);
|
||||
const notInstalled = (id: string) => localize('notInstalled', "Extension '{0}' is not installed.", id);
|
||||
const useId = localize('useId', "Make sure you use the full extension ID, including the publisher, e.g.: {0}", 'ms-dotnettools.csharp');
|
||||
|
||||
function getId(manifest: IExtensionManifest, withVersion?: boolean): string {
|
||||
if (withVersion) {
|
||||
return `${manifest.publisher}.${manifest.name}@${manifest.version}`;
|
||||
} else {
|
||||
return `${manifest.publisher}.${manifest.name}`;
|
||||
}
|
||||
}
|
||||
|
||||
const EXTENSION_ID_REGEX = /^([^.]+\..+)@(\d+\.\d+\.\d+(-.*)?)$/;
|
||||
|
||||
export function getIdAndVersion(id: string): [string, string | undefined] {
|
||||
const matches = EXTENSION_ID_REGEX.exec(id);
|
||||
if (matches && matches[1]) {
|
||||
return [adoptToGalleryExtensionId(matches[1]), matches[2]];
|
||||
}
|
||||
return [adoptToGalleryExtensionId(id), undefined];
|
||||
}
|
||||
|
||||
type InstallExtensionInfo = { id: string, version?: string, installOptions: InstallOptions };
|
||||
|
||||
export class Main {
|
||||
|
||||
constructor(
|
||||
@IInstantiationService private readonly instantiationService: IInstantiationService,
|
||||
@INativeEnvironmentService private readonly environmentService: INativeEnvironmentService,
|
||||
@IExtensionManagementService private readonly extensionManagementService: IExtensionManagementService,
|
||||
@IExtensionGalleryService private readonly extensionGalleryService: IExtensionGalleryService
|
||||
) { }
|
||||
|
||||
async run(argv: NativeParsedArgs): Promise<void> {
|
||||
if (argv['install-source']) {
|
||||
await this.setInstallSource(argv['install-source']);
|
||||
} else if (argv['list-extensions']) {
|
||||
await this.listExtensions(!!argv['show-versions'], argv['category']);
|
||||
} else if (argv['install-extension'] || argv['install-builtin-extension']) {
|
||||
await this.installExtensions(argv['install-extension'] || [], argv['install-builtin-extension'] || [], !!argv['do-not-sync'], !!argv['force']);
|
||||
} else if (argv['uninstall-extension']) {
|
||||
await this.uninstallExtension(argv['uninstall-extension'], !!argv['force']);
|
||||
} else if (argv['locate-extension']) {
|
||||
await this.locateExtension(argv['locate-extension']);
|
||||
} else if (argv['telemetry']) {
|
||||
console.log(buildTelemetryMessage(this.environmentService.appRoot, this.environmentService.extensionsPath ? this.environmentService.extensionsPath : undefined));
|
||||
}
|
||||
}
|
||||
|
||||
private setInstallSource(installSource: string): Promise<void> {
|
||||
return writeFile(this.environmentService.installSourcePath, installSource.slice(0, 30));
|
||||
}
|
||||
|
||||
private async listExtensions(showVersions: boolean, category?: string): Promise<void> {
|
||||
let extensions = await this.extensionManagementService.getInstalled(ExtensionType.User);
|
||||
const categories = EXTENSION_CATEGORIES.map(c => c.toLowerCase());
|
||||
if (category && category !== '') {
|
||||
if (categories.indexOf(category.toLowerCase()) < 0) {
|
||||
console.log('Invalid category please enter a valid category. To list valid categories run --category without a category specified');
|
||||
return;
|
||||
}
|
||||
extensions = extensions.filter(e => {
|
||||
if (e.manifest.categories) {
|
||||
const lowerCaseCategories: string[] = e.manifest.categories.map(c => c.toLowerCase());
|
||||
return lowerCaseCategories.indexOf(category.toLowerCase()) > -1;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
} else if (category === '') {
|
||||
console.log('Possible Categories: ');
|
||||
categories.forEach(category => {
|
||||
console.log(category);
|
||||
});
|
||||
return;
|
||||
}
|
||||
extensions.forEach(e => console.log(getId(e.manifest, showVersions)));
|
||||
}
|
||||
|
||||
private async installExtensions(extensions: string[], builtinExtensionIds: string[], isMachineScoped: boolean, force: boolean): Promise<void> {
|
||||
const failed: string[] = [];
|
||||
const installedExtensionsManifests: IExtensionManifest[] = [];
|
||||
if (extensions.length) {
|
||||
console.log(localize('installingExtensions', "Installing extensions..."));
|
||||
}
|
||||
|
||||
const vsixs: string[] = [];
|
||||
const installExtensionInfos: InstallExtensionInfo[] = [];
|
||||
for (const extension of extensions) {
|
||||
if (/\.vsix$/i.test(extension)) {
|
||||
vsixs.push(extension);
|
||||
} else {
|
||||
const [id, version] = getIdAndVersion(extension);
|
||||
installExtensionInfos.push({ id, version, installOptions: { isBuiltin: false, isMachineScoped } });
|
||||
}
|
||||
}
|
||||
for (const extension of builtinExtensionIds) {
|
||||
const [id, version] = getIdAndVersion(extension);
|
||||
installExtensionInfos.push({ id, version, installOptions: { isBuiltin: true, isMachineScoped: false } });
|
||||
}
|
||||
|
||||
if (vsixs.length) {
|
||||
await Promise.all(vsixs.map(async vsix => {
|
||||
try {
|
||||
const manifest = await this.installVSIX(vsix, force);
|
||||
if (manifest) {
|
||||
installedExtensionsManifests.push(manifest);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err.message || err.stack || err);
|
||||
failed.push(vsix);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
const [galleryExtensions, installed] = await Promise.all([
|
||||
this.getGalleryExtensions(installExtensionInfos),
|
||||
this.extensionManagementService.getInstalled(ExtensionType.User)
|
||||
]);
|
||||
|
||||
await Promise.all(installExtensionInfos.map(async extensionInfo => {
|
||||
const gallery = galleryExtensions.get(extensionInfo.id.toLowerCase());
|
||||
if (gallery) {
|
||||
try {
|
||||
const manifest = await this.installFromGallery(extensionInfo, gallery, installed, force);
|
||||
if (manifest) {
|
||||
installedExtensionsManifests.push(manifest);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err.message || err.stack || err);
|
||||
failed.push(extensionInfo.id);
|
||||
}
|
||||
} else {
|
||||
console.error(`${notFound(extensionInfo.version ? `${extensionInfo.id}@${extensionInfo.version}` : extensionInfo.id)}\n${useId}`);
|
||||
failed.push(extensionInfo.id);
|
||||
}
|
||||
}));
|
||||
|
||||
if (installedExtensionsManifests.some(manifest => isLanguagePackExtension(manifest))) {
|
||||
await this.updateLocalizationsCache();
|
||||
}
|
||||
|
||||
if (failed.length) {
|
||||
throw new Error(localize('installation failed', "Failed Installing Extensions: {0}", failed.join(', ')));
|
||||
}
|
||||
}
|
||||
|
||||
private async installVSIX(vsix: string, force: boolean): Promise<IExtensionManifest | null> {
|
||||
vsix = path.isAbsolute(vsix) ? vsix : path.join(process.cwd(), vsix);
|
||||
const manifest = await getManifest(vsix);
|
||||
const valid = await this.validate(manifest, force);
|
||||
if (valid) {
|
||||
try {
|
||||
await this.extensionManagementService.install(URI.file(vsix));
|
||||
console.log(localize('successVsixInstall', "Extension '{0}' was successfully installed.", getBaseLabel(vsix)));
|
||||
return manifest;
|
||||
} catch (error) {
|
||||
if (isPromiseCanceledError(error)) {
|
||||
console.log(localize('cancelVsixInstall', "Cancelled installing extension '{0}'.", getBaseLabel(vsix)));
|
||||
return null;
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async getGalleryExtensions(extensions: InstallExtensionInfo[]): Promise<Map<string, IGalleryExtension>> {
|
||||
const extensionIds = extensions.filter(({ version }) => version === undefined).map(({ id }) => id);
|
||||
const extensionsWithIdAndVersion = extensions.filter(({ version }) => version !== undefined);
|
||||
|
||||
const galleryExtensions = new Map<string, IGalleryExtension>();
|
||||
await Promise.all([
|
||||
(async () => {
|
||||
const result = await this.extensionGalleryService.getExtensions(extensionIds, CancellationToken.None);
|
||||
result.forEach(extension => galleryExtensions.set(extension.identifier.id.toLowerCase(), extension));
|
||||
})(),
|
||||
Promise.all(extensionsWithIdAndVersion.map(async ({ id, version }) => {
|
||||
const extension = await this.extensionGalleryService.getCompatibleExtension({ id }, version);
|
||||
if (extension) {
|
||||
galleryExtensions.set(extension.identifier.id.toLowerCase(), extension);
|
||||
}
|
||||
}))
|
||||
]);
|
||||
|
||||
return galleryExtensions;
|
||||
}
|
||||
|
||||
private async installFromGallery({ id, version, installOptions }: InstallExtensionInfo, galleryExtension: IGalleryExtension, installed: ILocalExtension[], force: boolean): Promise<IExtensionManifest | null> {
|
||||
const manifest = await this.extensionGalleryService.getManifest(galleryExtension, CancellationToken.None);
|
||||
const installedExtension = installed.find(e => areSameExtensions(e.identifier, galleryExtension.identifier));
|
||||
if (installedExtension) {
|
||||
if (galleryExtension.version === installedExtension.manifest.version) {
|
||||
console.log(localize('alreadyInstalled', "Extension '{0}' is already installed.", version ? `${id}@${version}` : id));
|
||||
return null;
|
||||
}
|
||||
if (!version && !force) {
|
||||
console.log(localize('forceUpdate', "Extension '{0}' v{1} is already installed, but a newer version {2} is available in the marketplace. Use '--force' option to update to newer version.", id, installedExtension.manifest.version, galleryExtension.version));
|
||||
return null;
|
||||
}
|
||||
console.log(localize('updateMessage', "Updating the extension '{0}' to the version {1}", id, galleryExtension.version));
|
||||
}
|
||||
|
||||
try {
|
||||
if (installOptions.isBuiltin) {
|
||||
console.log(localize('installing builtin ', "Installing builtin extension '{0}' v{1}...", id, galleryExtension.version));
|
||||
} else {
|
||||
console.log(localize('installing', "Installing extension '{0}' v{1}...", id, galleryExtension.version));
|
||||
}
|
||||
await this.extensionManagementService.installFromGallery(galleryExtension, installOptions);
|
||||
console.log(localize('successInstall', "Extension '{0}' v{1} was successfully installed.", id, galleryExtension.version));
|
||||
return manifest;
|
||||
} catch (error) {
|
||||
if (isPromiseCanceledError(error)) {
|
||||
console.log(localize('cancelInstall', "Cancelled installing extension '{0}'.", id));
|
||||
return null;
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async validate(manifest: IExtensionManifest, force: boolean): Promise<boolean> {
|
||||
if (!manifest) {
|
||||
throw new Error('Invalid vsix');
|
||||
}
|
||||
|
||||
const extensionIdentifier = { id: getGalleryExtensionId(manifest.publisher, manifest.name) };
|
||||
const installedExtensions = await this.extensionManagementService.getInstalled(ExtensionType.User);
|
||||
const newer = installedExtensions.find(local => areSameExtensions(extensionIdentifier, local.identifier) && semver.gt(local.manifest.version, manifest.version));
|
||||
|
||||
if (newer && !force) {
|
||||
console.log(localize('forceDowngrade', "A newer version of extension '{0}' v{1} is already installed. Use '--force' option to downgrade to older version.", newer.identifier.id, newer.manifest.version, manifest.version));
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private async uninstallExtension(extensions: string[], force: boolean): Promise<void> {
|
||||
async function getExtensionId(extensionDescription: string): Promise<string> {
|
||||
if (!/\.vsix$/i.test(extensionDescription)) {
|
||||
return extensionDescription;
|
||||
}
|
||||
|
||||
const zipPath = path.isAbsolute(extensionDescription) ? extensionDescription : path.join(process.cwd(), extensionDescription);
|
||||
const manifest = await getManifest(zipPath);
|
||||
return getId(manifest);
|
||||
}
|
||||
|
||||
const uninstalledExtensions: ILocalExtension[] = [];
|
||||
for (const extension of extensions) {
|
||||
const id = await getExtensionId(extension);
|
||||
const installed = await this.extensionManagementService.getInstalled();
|
||||
const extensionToUninstall = installed.find(e => areSameExtensions(e.identifier, { id }));
|
||||
if (!extensionToUninstall) {
|
||||
throw new Error(`${notInstalled(id)}\n${useId}`);
|
||||
}
|
||||
if (extensionToUninstall.type === ExtensionType.System) {
|
||||
console.log(localize('builtin', "Extension '{0}' is a Built-in extension and cannot be installed", id));
|
||||
return;
|
||||
}
|
||||
if (extensionToUninstall.isBuiltin && !force) {
|
||||
console.log(localize('forceUninstall', "Extension '{0}' is marked as a Built-in extension by user. Please use '--force' option to uninstall it.", id));
|
||||
return;
|
||||
}
|
||||
console.log(localize('uninstalling', "Uninstalling {0}...", id));
|
||||
await this.extensionManagementService.uninstall(extensionToUninstall, true);
|
||||
uninstalledExtensions.push(extensionToUninstall);
|
||||
console.log(localize('successUninstall', "Extension '{0}' was successfully uninstalled!", id));
|
||||
}
|
||||
|
||||
if (uninstalledExtensions.some(e => isLanguagePackExtension(e.manifest))) {
|
||||
await this.updateLocalizationsCache();
|
||||
}
|
||||
}
|
||||
|
||||
private async locateExtension(extensions: string[]): Promise<void> {
|
||||
const installed = await this.extensionManagementService.getInstalled();
|
||||
extensions.forEach(e => {
|
||||
installed.forEach(i => {
|
||||
if (i.identifier.id === e) {
|
||||
if (i.location.scheme === Schemas.file) {
|
||||
console.log(i.location.fsPath);
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private async updateLocalizationsCache(): Promise<void> {
|
||||
const localizationService = this.instantiationService.createInstance(LocalizationsService);
|
||||
await localizationService.update();
|
||||
localizationService.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
const eventPrefix = 'monacoworkbench';
|
||||
|
||||
export async function main(argv: NativeParsedArgs): Promise<void> {
|
||||
const services = new ServiceCollection();
|
||||
const disposables = new DisposableStore();
|
||||
|
||||
const environmentService = new NativeEnvironmentService(argv);
|
||||
const logService: ILogService = new SpdLogService('cli', environmentService.logsPath, getLogLevel(environmentService));
|
||||
process.once('exit', () => logService.dispose());
|
||||
logService.info('main', argv);
|
||||
|
||||
await Promise.all<void | undefined>([environmentService.appSettingsHome.fsPath, environmentService.extensionsPath]
|
||||
.map((path): undefined | Promise<void> => path ? mkdirp(path) : undefined));
|
||||
|
||||
// Files
|
||||
const fileService = new FileService(logService);
|
||||
disposables.add(fileService);
|
||||
services.set(IFileService, fileService);
|
||||
|
||||
const diskFileSystemProvider = new DiskFileSystemProvider(logService);
|
||||
disposables.add(diskFileSystemProvider);
|
||||
fileService.registerProvider(Schemas.file, diskFileSystemProvider);
|
||||
|
||||
const configurationService = new ConfigurationService(environmentService.settingsResource, fileService);
|
||||
disposables.add(configurationService);
|
||||
await configurationService.initialize();
|
||||
|
||||
services.set(IEnvironmentService, environmentService);
|
||||
services.set(INativeEnvironmentService, environmentService);
|
||||
|
||||
services.set(ILogService, logService);
|
||||
services.set(IConfigurationService, configurationService);
|
||||
services.set(IStateService, new SyncDescriptor(StateService));
|
||||
services.set(IProductService, { _serviceBrand: undefined, ...product });
|
||||
|
||||
const instantiationService: IInstantiationService = new InstantiationService(services);
|
||||
|
||||
return instantiationService.invokeFunction(async accessor => {
|
||||
const stateService = accessor.get(IStateService);
|
||||
|
||||
const { appRoot, extensionsPath, extensionDevelopmentLocationURI, isBuilt, installSourcePath } = environmentService;
|
||||
|
||||
const services = new ServiceCollection();
|
||||
services.set(IRequestService, new SyncDescriptor(RequestService));
|
||||
services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService));
|
||||
services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService));
|
||||
|
||||
const appenders: AppInsightsAppender[] = [];
|
||||
if (isBuilt && !extensionDevelopmentLocationURI && !environmentService.disableTelemetry && product.enableTelemetry) {
|
||||
if (product.aiConfig && product.aiConfig.asimovKey) {
|
||||
appenders.push(new AppInsightsAppender(eventPrefix, null, product.aiConfig.asimovKey));
|
||||
}
|
||||
|
||||
const config: ITelemetryServiceConfig = {
|
||||
appender: combinedAppender(...appenders),
|
||||
sendErrorTelemetry: false,
|
||||
commonProperties: resolveCommonProperties(product.commit, product.version, stateService.getItem('telemetry.machineId'), product.msftInternalDomains, installSourcePath),
|
||||
piiPaths: extensionsPath ? [appRoot, extensionsPath] : [appRoot]
|
||||
};
|
||||
|
||||
services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));
|
||||
|
||||
} else {
|
||||
services.set(ITelemetryService, NullTelemetryService);
|
||||
}
|
||||
|
||||
const instantiationService2 = instantiationService.createChild(services);
|
||||
const main = instantiationService2.createInstance(Main);
|
||||
|
||||
try {
|
||||
await main.run(argv);
|
||||
|
||||
// Flush the remaining data in AI adapter.
|
||||
// If it does not complete in 1 second, exit the process.
|
||||
await raceTimeout(combinedAppender(...appenders).flush(), 1000);
|
||||
} finally {
|
||||
disposables.dispose();
|
||||
}
|
||||
});
|
||||
}
|
||||
110
lib/vscode/src/vs/code/node/shellEnv.ts
Normal file
110
lib/vscode/src/vs/code/node/shellEnv.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import { spawn } from 'child_process';
|
||||
import { generateUuid } from 'vs/base/common/uuid';
|
||||
import { isWindows } from 'vs/base/common/platform';
|
||||
import { ILogService } from 'vs/platform/log/common/log';
|
||||
import { INativeEnvironmentService } from 'vs/platform/environment/common/environment';
|
||||
|
||||
function getUnixShellEnvironment(logService: ILogService): Promise<typeof process.env> {
|
||||
const promise = new Promise<typeof process.env>((resolve, reject) => {
|
||||
const runAsNode = process.env['ELECTRON_RUN_AS_NODE'];
|
||||
logService.trace('getUnixShellEnvironment#runAsNode', runAsNode);
|
||||
|
||||
const noAttach = process.env['ELECTRON_NO_ATTACH_CONSOLE'];
|
||||
logService.trace('getUnixShellEnvironment#noAttach', noAttach);
|
||||
|
||||
const mark = generateUuid().replace(/-/g, '').substr(0, 12);
|
||||
const regex = new RegExp(mark + '(.*)' + mark);
|
||||
|
||||
const env = {
|
||||
...process.env,
|
||||
ELECTRON_RUN_AS_NODE: '1',
|
||||
ELECTRON_NO_ATTACH_CONSOLE: '1'
|
||||
};
|
||||
|
||||
const command = `'${process.execPath}' -p '"${mark}" + JSON.stringify(process.env) + "${mark}"'`;
|
||||
logService.trace('getUnixShellEnvironment#env', env);
|
||||
logService.trace('getUnixShellEnvironment#spawn', command);
|
||||
|
||||
const child = spawn(process.env.SHELL!, ['-ilc', command], {
|
||||
detached: true,
|
||||
stdio: ['ignore', 'pipe', process.stderr],
|
||||
env
|
||||
});
|
||||
|
||||
const buffers: Buffer[] = [];
|
||||
child.on('error', () => resolve({}));
|
||||
child.stdout.on('data', b => buffers.push(b));
|
||||
|
||||
child.on('close', code => {
|
||||
if (code !== 0) {
|
||||
return reject(new Error('Failed to get environment'));
|
||||
}
|
||||
|
||||
const raw = Buffer.concat(buffers).toString('utf8');
|
||||
logService.trace('getUnixShellEnvironment#raw', raw);
|
||||
|
||||
const match = regex.exec(raw);
|
||||
const rawStripped = match ? match[1] : '{}';
|
||||
|
||||
try {
|
||||
const env = JSON.parse(rawStripped);
|
||||
|
||||
if (runAsNode) {
|
||||
env['ELECTRON_RUN_AS_NODE'] = runAsNode;
|
||||
} else {
|
||||
delete env['ELECTRON_RUN_AS_NODE'];
|
||||
}
|
||||
|
||||
if (noAttach) {
|
||||
env['ELECTRON_NO_ATTACH_CONSOLE'] = noAttach;
|
||||
} else {
|
||||
delete env['ELECTRON_NO_ATTACH_CONSOLE'];
|
||||
}
|
||||
|
||||
// https://github.com/microsoft/vscode/issues/22593#issuecomment-336050758
|
||||
delete env['XDG_RUNTIME_DIR'];
|
||||
|
||||
logService.trace('getUnixShellEnvironment#result', env);
|
||||
resolve(env);
|
||||
} catch (err) {
|
||||
logService.error('getUnixShellEnvironment#error', err);
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// swallow errors
|
||||
return promise.catch(() => ({}));
|
||||
}
|
||||
|
||||
let shellEnvPromise: Promise<typeof process.env> | undefined = undefined;
|
||||
|
||||
/**
|
||||
* We need to get the environment from a user's shell.
|
||||
* This should only be done when Code itself is not launched
|
||||
* from within a shell.
|
||||
*/
|
||||
export function getShellEnvironment(logService: ILogService, environmentService: INativeEnvironmentService): Promise<typeof process.env> {
|
||||
if (!shellEnvPromise) {
|
||||
if (environmentService.args['disable-user-env-probe']) {
|
||||
logService.trace('getShellEnvironment: disable-user-env-probe set, skipping');
|
||||
shellEnvPromise = Promise.resolve({});
|
||||
} else if (isWindows) {
|
||||
logService.trace('getShellEnvironment: running on Windows, skipping');
|
||||
shellEnvPromise = Promise.resolve({});
|
||||
} else if (process.env['VSCODE_CLI'] === '1' && process.env['VSCODE_FORCE_USER_ENV'] !== '1') {
|
||||
logService.trace('getShellEnvironment: running on CLI, skipping');
|
||||
shellEnvPromise = Promise.resolve({});
|
||||
} else {
|
||||
logService.trace('getShellEnvironment: running on Unix');
|
||||
shellEnvPromise = getUnixShellEnvironment(logService);
|
||||
}
|
||||
}
|
||||
|
||||
return shellEnvPromise;
|
||||
}
|
||||
Reference in New Issue
Block a user