cliProcessMain.ts 14.9 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';
S
Sandeep Somavarapu 已提交
34
import { ILogService, getLogLevel } from 'vs/platform/log/common/log';
35
import { isPromiseCanceledError } from 'vs/base/common/errors';
36
import { areSameExtensions, adoptToGalleryExtensionId, getGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
37
import { URI } from 'vs/base/common/uri';
38
import { getManifest } from 'vs/platform/extensionManagement/node/extensionManagementUtil';
S
Sandeep Somavarapu 已提交
39
import { IExtensionManifest, ExtensionType, isLanguagePackExtension } from 'vs/platform/extensions/common/extensions';
40
import { CancellationToken } from 'vs/base/common/cancellation';
S
Sandeep Somavarapu 已提交
41
import { LocalizationsService } from 'vs/platform/localizations/node/localizations';
42
import { Schemas } from 'vs/base/common/network';
43
import { SpdLogService } from 'vs/platform/log/node/spdlogService';
J
Joao Moreno 已提交
44

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

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

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

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


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

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

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

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

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

J
Joao Moreno 已提交
89
		} else if (argv['uninstall-extension']) {
90 91
			const arg = argv['uninstall-extension'];
			const ids: string[] = typeof arg === 'string' ? [arg] : arg;
J
Joao Moreno 已提交
92
			await this.uninstallExtension(ids);
93 94 95 96
		} 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 已提交
97 98
		}
	}
J
Joao Moreno 已提交
99

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

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

S
Sandeep Somavarapu 已提交
109
	private async installExtensions(extensions: string[], force: boolean): Promise<void> {
110
		const failed: string[] = [];
S
Sandeep Somavarapu 已提交
111
		const installedExtensionsManifests: IExtensionManifest[] = [];
R
RMacfarlane 已提交
112 113 114 115
		if (extensions.length) {
			console.log(localize('installingExtensions', "Installing extensions..."));
		}

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

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

137 138 139 140
			const manifest = await getManifest(extension);
			const valid = await this.validate(manifest, force);

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

S
Sandeep Somavarapu 已提交
156
		const [id, version] = getIdAndVersion(extension);
157
		return this.extensionManagementService.getInstalled(ExtensionType.User)
S
Sandeep Somavarapu 已提交
158
			.then(installed => this.extensionGalleryService.getCompatibleExtension({ id }, version)
S
Sandeep Somavarapu 已提交
159 160 161 162 163 164 165 166 167 168 169
				.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);
				})
170
				.then(async extension => {
S
Sandeep Somavarapu 已提交
171 172 173 174
					if (!extension) {
						return Promise.reject(new Error(`${notFound(version ? `${id}@${version}` : id)}\n${useId}`));
					}

175
					const manifest = await this.extensionGalleryService.getManifest(extension, CancellationToken.None);
176
					const [installedExtension] = installed.filter(e => areSameExtensions(e.identifier, { id }));
S
Sandeep Somavarapu 已提交
177
					if (installedExtension) {
S
Sandeep Somavarapu 已提交
178
						if (extension.version === installedExtension.manifest.version) {
S
Sandeep Somavarapu 已提交
179 180 181
							console.log(localize('alreadyInstalled', "Extension '{0}' is already installed.", version ? `${id}@${version}` : id));
							return Promise.resolve(null);
						}
S
Sandeep Somavarapu 已提交
182 183 184 185
						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);
						}
R
RMacfarlane 已提交
186
						console.log(localize('updateMessage', "Updating the extension '{0}' to the version {1}", id, extension.version));
S
Sandeep Somavarapu 已提交
187
					}
S
Sandeep Somavarapu 已提交
188 189
					await this.installFromGallery(id, extension);
					return manifest;
S
Sandeep Somavarapu 已提交
190
				}));
J
Joao Moreno 已提交
191
	}
J
Joao Moreno 已提交
192

193
	private async validate(manifest: IExtensionManifest, force: boolean): Promise<boolean> {
J
Joao Moreno 已提交
194 195 196 197 198
		if (!manifest) {
			throw new Error('Invalid vsix');
		}

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

		if (newer && !force) {
R
RMacfarlane 已提交
203
			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));
J
Joao Moreno 已提交
204 205 206 207
			return false;
		}

		return true;
S
Sandeep Somavarapu 已提交
208 209
	}

J
Joao Moreno 已提交
210
	private async installFromGallery(id: string, extension: IGalleryExtension): Promise<void> {
R
RMacfarlane 已提交
211
		console.log(localize('installing', "Installing extension '{0}' v{1}...", id, extension.version));
J
Joao Moreno 已提交
212 213 214

		try {
			await this.extensionManagementService.installFromGallery(extension);
R
RMacfarlane 已提交
215
			console.log(localize('successInstall', "Extension '{0}' v{1} was successfully installed.", id, extension.version));
J
Joao Moreno 已提交
216 217
		} catch (error) {
			if (isPromiseCanceledError(error)) {
R
RMacfarlane 已提交
218
				console.log(localize('cancelVsixInstall', "Cancelled installing extension '{0}'.", id));
J
Joao Moreno 已提交
219 220 221 222
			} else {
				throw error;
			}
		}
223 224
	}

225
	private async uninstallExtension(extensions: string[]): Promise<void> {
J
Joao Moreno 已提交
226
		async function getExtensionId(extensionDescription: string): Promise<string> {
227 228
			if (!/\.vsix$/i.test(extensionDescription)) {
				return extensionDescription;
229
			}
J
Joao Moreno 已提交
230

231
			const zipPath = path.isAbsolute(extensionDescription) ? extensionDescription : path.join(process.cwd(), extensionDescription);
232
			const manifest = await getManifest(zipPath);
233
			return getId(manifest);
234
		}
J
Joao Moreno 已提交
235

S
Sandeep Somavarapu 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248
		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 已提交
249

S
Sandeep Somavarapu 已提交
250 251 252 253
		if (uninstalledExtensions.some(e => isLanguagePackExtension(e.manifest))) {
			await this.updateLocalizationsCache();
		}
	}
J
Joao Moreno 已提交
254

255 256 257 258 259 260 261 262 263 264 265 266 267 268
	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 已提交
269 270 271 272
	private async updateLocalizationsCache(): Promise<void> {
		const localizationService = this.instantiationService.createInstance(LocalizationsService);
		await localizationService.update();
		localizationService.dispose();
J
Joao Moreno 已提交
273
	}
J
Joao Moreno 已提交
274 275
}

276 277
const eventPrefix = 'monacoworkbench';

S
Sandeep Somavarapu 已提交
278
export async function main(argv: ParsedArgs): Promise<void> {
J
Joao Moreno 已提交
279
	const services = new ServiceCollection();
J
Joao Moreno 已提交
280 281

	const environmentService = new EnvironmentService(argv, process.execPath);
282
	const logService: ILogService = new SpdLogService('cli', environmentService.logsPath, getLogLevel(environmentService));
283
	process.once('exit', () => logService.dispose());
J
Joao Moreno 已提交
284 285
	logService.info('main', argv);

S
Sandeep Somavarapu 已提交
286
	await Promise.all([environmentService.appSettingsHome.fsPath, environmentService.extensionsPath].map(p => mkdirp(p)));
S
Sandeep Somavarapu 已提交
287

S
Sandeep Somavarapu 已提交
288
	const configurationService = new ConfigurationService(environmentService.settingsResource);
S
Sandeep Somavarapu 已提交
289 290
	await configurationService.initialize();

J
Joao Moreno 已提交
291 292
	services.set(IEnvironmentService, environmentService);
	services.set(ILogService, logService);
S
Sandeep Somavarapu 已提交
293
	services.set(IConfigurationService, configurationService);
294
	services.set(IStateService, new SyncDescriptor(StateService));
J
Joao Moreno 已提交
295 296

	const instantiationService: IInstantiationService = new InstantiationService(services);
297 298

	return instantiationService.invokeFunction(accessor => {
J
Joao Moreno 已提交
299
		const envService = accessor.get(IEnvironmentService);
300
		const stateService = accessor.get(IStateService);
301

S
Sandeep Somavarapu 已提交
302
		const { appRoot, extensionsPath, extensionDevelopmentLocationURI: extensionDevelopmentLocationURI, isBuilt, installSourcePath } = envService;
303

S
Sandeep Somavarapu 已提交
304 305 306 307
		const services = new ServiceCollection();
		services.set(IRequestService, new SyncDescriptor(RequestService));
		services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService));
		services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService));
308

S
Sandeep Somavarapu 已提交
309 310
		const appenders: AppInsightsAppender[] = [];
		if (isBuilt && !extensionDevelopmentLocationURI && !envService.args['disable-telemetry'] && product.enableTelemetry) {
311

S
Sandeep Somavarapu 已提交
312 313 314
			if (product.aiConfig && product.aiConfig.asimovKey) {
				appenders.push(new AppInsightsAppender(eventPrefix, null, product.aiConfig.asimovKey, logService));
			}
315

S
Sandeep Somavarapu 已提交
316 317 318 319 320
			const config: ITelemetryServiceConfig = {
				appender: combinedAppender(...appenders),
				commonProperties: resolveCommonProperties(product.commit, pkg.version, stateService.getItem('telemetry.machineId'), installSourcePath),
				piiPaths: [appRoot, extensionsPath]
			};
321

S
Sandeep Somavarapu 已提交
322 323 324 325
			services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));
		} else {
			services.set(ITelemetryService, NullTelemetryService);
		}
326

S
Sandeep Somavarapu 已提交
327 328
		const instantiationService2 = instantiationService.createChild(services);
		const main = instantiationService2.createInstance(Main);
329

S
Sandeep Somavarapu 已提交
330 331 332
		return main.run(argv).then(() => {
			// Dispose the AI adapter so that remaining data gets flushed.
			return combinedAppender(...appenders).dispose();
J
Joao Moreno 已提交
333
		});
334
	});
335
}