cliProcessMain.ts 15.6 KB
Newer Older
J
Joao Moreno 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

J
Joao Moreno 已提交
6
import { localize } from 'vs/nls';
7 8
import product from 'vs/platform/product/node/product';
import pkg from 'vs/platform/product/node/package';
9
import * as path from 'vs/base/common/path';
S
Sandeep Somavarapu 已提交
10
import * as semver from 'semver';
J
Joao Moreno 已提交
11

J
Joao Moreno 已提交
12 13 14 15
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';
J
Joao Moreno 已提交
16
import { IEnvironmentService, ParsedArgs } from 'vs/platform/environment/common/environment';
17
import { EnvironmentService } from 'vs/platform/environment/node/environmentService';
S
Sandeep Somavarapu 已提交
18
import { IExtensionManagementService, IExtensionGalleryService, IGalleryExtension, ILocalExtension } from 'vs/platform/extensionManagement/common/extensionManagement';
19
import { ExtensionManagementService } from 'vs/platform/extensionManagement/node/extensionManagementService';
J
Joao Moreno 已提交
20
import { ExtensionGalleryService } from 'vs/platform/extensionManagement/node/extensionGalleryService';
21 22
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { combinedAppender, NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
23 24
import { TelemetryService, ITelemetryServiceConfig } from 'vs/platform/telemetry/common/telemetryService';
import { resolveCommonProperties } from 'vs/platform/telemetry/node/commonProperties';
J
Joao Moreno 已提交
25
import { IRequestService } from 'vs/platform/request/node/request';
J
Joao Moreno 已提交
26
import { RequestService } from 'vs/platform/request/node/requestService';
J
Joao Moreno 已提交
27
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
28
import { ConfigurationService } from 'vs/platform/configuration/node/configurationService';
29
import { AppInsightsAppender } from 'vs/platform/telemetry/node/appInsightsAppender';
30
import { mkdirp, writeFile } from 'vs/base/node/pfs';
B
Benjamin Pasero 已提交
31
import { getBaseLabel } from 'vs/base/common/labels';
32 33
import { IStateService } from 'vs/platform/state/common/state';
import { StateService } from 'vs/platform/state/node/stateService';
34
import { createSpdLogService } from 'vs/platform/log/node/spdlogService';
S
Sandeep Somavarapu 已提交
35
import { ILogService, getLogLevel } from 'vs/platform/log/common/log';
36
import { isPromiseCanceledError } from 'vs/base/common/errors';
37
import { areSameExtensions, adoptToGalleryExtensionId, getGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
38
import { URI } from 'vs/base/common/uri';
39
import { getManifest } from 'vs/platform/extensionManagement/node/extensionManagementUtil';
S
Sandeep Somavarapu 已提交
40
import { IExtensionManifest, ExtensionType, isLanguagePackExtension } from 'vs/platform/extensions/common/extensions';
41 42
import { isUIExtension } from 'vs/platform/extensions/node/extensionsUtil';
import { CancellationToken } from 'vs/base/common/cancellation';
S
Sandeep Somavarapu 已提交
43
import { LocalizationsService } from 'vs/platform/localizations/node/localizations';
44
import { Schemas } from 'vs/base/common/network';
J
Joao Moreno 已提交
45

46 47
const notFound = (id: string) => localize('notFound', "Extension '{0}' not found.", id);
const notInstalled = (id: string) => localize('notInstalled', "Extension '{0}' is not installed.", id);
J
Joao Moreno 已提交
48
const useId = localize('useId', "Make sure you use the full extension ID, including the publisher, eg: {0}", 'ms-vscode.csharp');
J
Joao Moreno 已提交
49

G
greams 已提交
50 51
function getId(manifest: IExtensionManifest, withVersion?: boolean): string {
	if (withVersion) {
J
Joao Moreno 已提交
52
		return `${manifest.publisher}.${manifest.name}@${manifest.version}`;
G
greams 已提交
53
	} else {
54
		return `${manifest.publisher}.${manifest.name}`;
G
greams 已提交
55
	}
J
Joao Moreno 已提交
56 57
}

58 59
const EXTENSION_ID_REGEX = /^([^.]+\..+)@(\d+\.\d+\.\d+(-.*)?)$/;

M
Matt Bierner 已提交
60
export function getIdAndVersion(id: string): [string, string | undefined] {
61 62 63 64
	const matches = EXTENSION_ID_REGEX.exec(id);
	if (matches && matches[1]) {
		return [adoptToGalleryExtensionId(matches[1]), matches[2]];
	}
R
Rob Lourens 已提交
65
	return [adoptToGalleryExtensionId(id), undefined];
66 67 68
}


A
Alex Dima 已提交
69
export class Main {
J
Joao Moreno 已提交
70 71

	constructor(
72
		private readonly remote: boolean,
S
Sandeep Somavarapu 已提交
73
		@IInstantiationService private readonly instantiationService: IInstantiationService,
74
		@IEnvironmentService private readonly environmentService: IEnvironmentService,
75
		@IConfigurationService private readonly configurationService: IConfigurationService,
76 77
		@IExtensionManagementService private readonly extensionManagementService: IExtensionManagementService,
		@IExtensionGalleryService private readonly extensionGalleryService: IExtensionGalleryService
J
Johannes Rieken 已提交
78
	) { }
J
Joao Moreno 已提交
79

80
	async run(argv: ParsedArgs): Promise<void> {
81
		if (argv['install-source']) {
J
Joao Moreno 已提交
82 83
			await this.setInstallSource(argv['install-source']);

84
		} else if (argv['list-extensions']) {
M
Matt Bierner 已提交
85
			await this.listExtensions(!!argv['show-versions']);
J
Joao Moreno 已提交
86

J
Joao Moreno 已提交
87
		} else if (argv['install-extension']) {
88
			const arg = argv['install-extension'];
J
Joao Moreno 已提交
89
			const args: string[] = typeof arg === 'string' ? [arg] : arg;
S
Sandeep Somavarapu 已提交
90
			await this.installExtensions(args, argv['force']);
J
Joao Moreno 已提交
91

J
Joao Moreno 已提交
92
		} else if (argv['uninstall-extension']) {
93 94
			const arg = argv['uninstall-extension'];
			const ids: string[] = typeof arg === 'string' ? [arg] : arg;
J
Joao Moreno 已提交
95
			await this.uninstallExtension(ids);
96 97 98 99
		} else if (argv['locate-extension']) {
			const arg = argv['locate-extension'];
			const ids: string[] = typeof arg === 'string' ? [arg] : arg;
			await this.locateExtension(ids);
J
Joao Moreno 已提交
100 101
		}
	}
J
Joao Moreno 已提交
102

103
	private setInstallSource(installSource: string): Promise<void> {
104
		return writeFile(this.environmentService.installSourcePath, installSource.slice(0, 30));
105 106
	}

107
	private async listExtensions(showVersions: boolean): Promise<void> {
108
		const extensions = await this.extensionManagementService.getInstalled(ExtensionType.User);
J
Joao Moreno 已提交
109
		extensions.forEach(e => console.log(getId(e.manifest, showVersions)));
J
Joao Moreno 已提交
110 111
	}

S
Sandeep Somavarapu 已提交
112
	private async installExtensions(extensions: string[], force: boolean): Promise<void> {
113
		const failed: string[] = [];
S
Sandeep Somavarapu 已提交
114
		const installedExtensionsManifests: IExtensionManifest[] = [];
S
Sandeep Somavarapu 已提交
115 116
		for (const extension of extensions) {
			try {
S
Sandeep Somavarapu 已提交
117 118 119 120
				const manifest = await this.installExtension(extension, force);
				if (manifest) {
					installedExtensionsManifests.push(manifest);
				}
S
Sandeep Somavarapu 已提交
121 122 123 124 125
			} catch (err) {
				console.error(err.message || err.stack || err);
				failed.push(extension);
			}
		}
S
Sandeep Somavarapu 已提交
126 127 128
		if (installedExtensionsManifests.some(manifest => isLanguagePackExtension(manifest))) {
			await this.updateLocalizationsCache();
		}
S
Sandeep Somavarapu 已提交
129 130
		return failed.length ? Promise.reject(localize('installation failed', "Failed Installing Extensions: {0}", failed.join(', '))) : Promise.resolve();
	}
J
Joao Moreno 已提交
131

S
Sandeep Somavarapu 已提交
132
	private async installExtension(extension: string, force: boolean): Promise<IExtensionManifest | null> {
S
Sandeep Somavarapu 已提交
133 134 135
		if (/\.vsix$/i.test(extension)) {
			extension = path.isAbsolute(extension) ? extension : path.join(process.cwd(), extension);

136
			const manifest = await getManifest(extension);
137
			if (this.remote && (!isLanguagePackExtension(manifest) && isUIExtension(manifest, [], this.configurationService))) {
138 139 140 141 142 143
				console.log(localize('notSupportedUIExtension', "Can't install extension {0} since UI Extensions are not supported", getBaseLabel(extension)));
				return null;
			}
			const valid = await this.validate(manifest, force);

			if (valid) {
S
Sandeep Somavarapu 已提交
144
				return this.extensionManagementService.install(URI.file(extension)).then(id => {
145
					console.log(localize('successVsixInstall', "Extension '{0}' was successfully installed!", getBaseLabel(extension)));
S
Sandeep Somavarapu 已提交
146
					return manifest;
147 148 149 150 151 152
				}, error => {
					if (isPromiseCanceledError(error)) {
						console.log(localize('cancelVsixInstall', "Cancelled installing Extension '{0}'.", getBaseLabel(extension)));
						return null;
					} else {
						return Promise.reject(error);
S
Sandeep Somavarapu 已提交
153 154
					}
				});
155 156
			}
			return null;
S
Sandeep Somavarapu 已提交
157
		}
J
Joao Moreno 已提交
158

S
Sandeep Somavarapu 已提交
159
		const [id, version] = getIdAndVersion(extension);
160
		return this.extensionManagementService.getInstalled(ExtensionType.User)
S
Sandeep Somavarapu 已提交
161
			.then(installed => this.extensionGalleryService.getCompatibleExtension({ id }, version)
S
Sandeep Somavarapu 已提交
162 163 164 165 166 167 168 169 170 171 172
				.then<IGalleryExtension>(null, err => {
					if (err.responseText) {
						try {
							const response = JSON.parse(err.responseText);
							return Promise.reject(response.message);
						} catch (e) {
							// noop
						}
					}
					return Promise.reject(err);
				})
173
				.then(async extension => {
S
Sandeep Somavarapu 已提交
174 175 176 177
					if (!extension) {
						return Promise.reject(new Error(`${notFound(version ? `${id}@${version}` : id)}\n${useId}`));
					}

178
					const manifest = await this.extensionGalleryService.getManifest(extension, CancellationToken.None);
179
					if (this.remote && manifest && (!isLanguagePackExtension(manifest) && isUIExtension(manifest, [], this.configurationService))) {
180 181 182 183
						console.log(localize('notSupportedUIExtension', "Can't install extension {0} since UI Extensions are not supported", extension.identifier.id));
						return null;
					}

184
					const [installedExtension] = installed.filter(e => areSameExtensions(e.identifier, { id }));
S
Sandeep Somavarapu 已提交
185
					if (installedExtension) {
S
Sandeep Somavarapu 已提交
186
						if (extension.version === installedExtension.manifest.version) {
S
Sandeep Somavarapu 已提交
187 188 189
							console.log(localize('alreadyInstalled', "Extension '{0}' is already installed.", version ? `${id}@${version}` : id));
							return Promise.resolve(null);
						}
S
Sandeep Somavarapu 已提交
190 191 192 193 194
						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, extension.version));
							return Promise.resolve(null);
						}
						console.log(localize('updateMessage', "Updating the Extension '{0}' to the version {1}", id, extension.version));
S
Sandeep Somavarapu 已提交
195 196 197
					} else {
						console.log(localize('foundExtension', "Found '{0}' in the marketplace.", id));
					}
S
Sandeep Somavarapu 已提交
198 199
					await this.installFromGallery(id, extension);
					return manifest;
S
Sandeep Somavarapu 已提交
200
				}));
J
Joao Moreno 已提交
201
	}
J
Joao Moreno 已提交
202

203
	private async validate(manifest: IExtensionManifest, force: boolean): Promise<boolean> {
J
Joao Moreno 已提交
204 205 206 207 208
		if (!manifest) {
			throw new Error('Invalid vsix');
		}

		const extensionIdentifier = { id: getGalleryExtensionId(manifest.publisher, manifest.name) };
209
		const installedExtensions = await this.extensionManagementService.getInstalled(ExtensionType.User);
210
		const newer = installedExtensions.filter(local => areSameExtensions(extensionIdentifier, local.identifier) && semver.gt(local.manifest.version, manifest.version))[0];
J
Joao Moreno 已提交
211 212

		if (newer && !force) {
213
			console.log(localize('forceDowngrade', "A newer version of this extension '{0}' v{1} is already installed. Use '--force' option to downgrade to older version.", newer.identifier.id, newer.manifest.version, manifest.version));
J
Joao Moreno 已提交
214 215 216 217
			return false;
		}

		return true;
S
Sandeep Somavarapu 已提交
218 219
	}

J
Joao Moreno 已提交
220
	private async installFromGallery(id: string, extension: IGalleryExtension): Promise<void> {
221
		console.log(localize('installing', "Installing..."));
J
Joao Moreno 已提交
222 223 224 225 226 227 228 229 230 231 232

		try {
			await this.extensionManagementService.installFromGallery(extension);
			console.log(localize('successInstall', "Extension '{0}' v{1} was successfully installed!", id, extension.version));
		} catch (error) {
			if (isPromiseCanceledError(error)) {
				console.log(localize('cancelVsixInstall', "Cancelled installing Extension '{0}'.", id));
			} else {
				throw error;
			}
		}
233 234
	}

235
	private async uninstallExtension(extensions: string[]): Promise<void> {
J
Joao Moreno 已提交
236
		async function getExtensionId(extensionDescription: string): Promise<string> {
237 238
			if (!/\.vsix$/i.test(extensionDescription)) {
				return extensionDescription;
239
			}
J
Joao Moreno 已提交
240

241
			const zipPath = path.isAbsolute(extensionDescription) ? extensionDescription : path.join(process.cwd(), extensionDescription);
242
			const manifest = await getManifest(zipPath);
243
			return getId(manifest);
244
		}
J
Joao Moreno 已提交
245

S
Sandeep Somavarapu 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258
		const uninstalledExtensions: ILocalExtension[] = [];
		for (const extension of extensions) {
			const id = await getExtensionId(extension);
			const installed = await this.extensionManagementService.getInstalled(ExtensionType.User);
			const [extensionToUninstall] = installed.filter(e => areSameExtensions(e.identifier, { id }));
			if (!extensionToUninstall) {
				return Promise.reject(new Error(`${notInstalled(id)}\n${useId}`));
			}
			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));
		}
J
Joao Moreno 已提交
259

S
Sandeep Somavarapu 已提交
260 261 262 263
		if (uninstalledExtensions.some(e => isLanguagePackExtension(e.manifest))) {
			await this.updateLocalizationsCache();
		}
	}
J
Joao Moreno 已提交
264

265 266 267 268 269 270 271 272 273 274 275 276 277 278
	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;
					}
				}
			});
		});
	}

S
Sandeep Somavarapu 已提交
279 280 281 282
	private async updateLocalizationsCache(): Promise<void> {
		const localizationService = this.instantiationService.createInstance(LocalizationsService);
		await localizationService.update();
		localizationService.dispose();
J
Joao Moreno 已提交
283
	}
J
Joao Moreno 已提交
284 285
}

286 287
const eventPrefix = 'monacoworkbench';

J
Joao Moreno 已提交
288
export function main(argv: ParsedArgs): Promise<void> {
J
Joao Moreno 已提交
289
	const services = new ServiceCollection();
J
Joao Moreno 已提交
290 291

	const environmentService = new EnvironmentService(argv, process.execPath);
S
Sandeep Somavarapu 已提交
292
	const logService = createSpdLogService('cli', getLogLevel(environmentService), environmentService.logsPath);
293
	process.once('exit', () => logService.dispose());
J
Joao Moreno 已提交
294 295 296 297 298

	logService.info('main', argv);

	services.set(IEnvironmentService, environmentService);
	services.set(ILogService, logService);
299
	services.set(IStateService, new SyncDescriptor(StateService));
J
Joao Moreno 已提交
300 301

	const instantiationService: IInstantiationService = new InstantiationService(services);
302 303

	return instantiationService.invokeFunction(accessor => {
J
Joao Moreno 已提交
304
		const envService = accessor.get(IEnvironmentService);
305
		const stateService = accessor.get(IStateService);
306

J
Joao Moreno 已提交
307
		return Promise.all([envService.appSettingsHome, envService.extensionsPath].map(p => mkdirp(p))).then(() => {
308
			const { appRoot, extensionsPath, extensionDevelopmentLocationURI: extensionDevelopmentLocationURI, isBuilt, installSourcePath } = envService;
309

J
Joao Moreno 已提交
310
			const services = new ServiceCollection();
311
			services.set(IConfigurationService, new SyncDescriptor(ConfigurationService, [environmentService.appSettingsPath]));
J
Joao Moreno 已提交
312
			services.set(IRequestService, new SyncDescriptor(RequestService));
313
			services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService, [false]));
J
Joao Moreno 已提交
314
			services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService));
315

316
			const appenders: AppInsightsAppender[] = [];
317
			if (isBuilt && !extensionDevelopmentLocationURI && !envService.args['disable-telemetry'] && product.enableTelemetry) {
318

J
Joao Moreno 已提交
319
				if (product.aiConfig && product.aiConfig.asimovKey) {
320
					appenders.push(new AppInsightsAppender(eventPrefix, null, product.aiConfig.asimovKey, logService));
J
Joao Moreno 已提交
321
				}
322

J
Joao Moreno 已提交
323 324
				const config: ITelemetryServiceConfig = {
					appender: combinedAppender(...appenders),
325
					commonProperties: resolveCommonProperties(product.commit, pkg.version, stateService.getItem('telemetry.machineId'), installSourcePath),
J
Joao Moreno 已提交
326 327
					piiPaths: [appRoot, extensionsPath]
				};
328

329
				services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));
J
Joao Moreno 已提交
330 331 332
			} else {
				services.set(ITelemetryService, NullTelemetryService);
			}
333

J
Joao Moreno 已提交
334
			const instantiationService2 = instantiationService.createChild(services);
335
			const main = instantiationService2.createInstance(Main, false);
336

337 338 339 340
			return main.run(argv).then(() => {
				// Dispose the AI adapter so that remaining data gets flushed.
				return combinedAppender(...appenders).dispose();
			});
J
Joao Moreno 已提交
341
		});
342
	});
343
}