cliProcessMain.ts 17.2 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-umd';
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';
20
import { ExtensionGalleryService } from 'vs/platform/extensionManagement/common/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';
25
import { IRequestService } from 'vs/platform/request/common/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';
L
Logan Ramos 已提交
44
import { buildTelemetryMessage } from 'vs/platform/telemetry/node/telemetry';
S
Sandeep Somavarapu 已提交
45 46 47 48
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';
49 50
import { IProductService } from 'vs/platform/product/common/product';
import { ProductService } from 'vs/platform/product/node/productService';
J
Joao Moreno 已提交
51

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

G
greams 已提交
56 57
function getId(manifest: IExtensionManifest, withVersion?: boolean): string {
	if (withVersion) {
J
Joao Moreno 已提交
58
		return `${manifest.publisher}.${manifest.name}@${manifest.version}`;
G
greams 已提交
59
	} else {
60
		return `${manifest.publisher}.${manifest.name}`;
G
greams 已提交
61
	}
J
Joao Moreno 已提交
62 63
}

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

M
Matt Bierner 已提交
66
export function getIdAndVersion(id: string): [string, string | undefined] {
67 68 69 70
	const matches = EXTENSION_ID_REGEX.exec(id);
	if (matches && matches[1]) {
		return [adoptToGalleryExtensionId(matches[1]), matches[2]];
	}
R
Rob Lourens 已提交
71
	return [adoptToGalleryExtensionId(id), undefined];
72 73 74
}


A
Alex Dima 已提交
75
export class Main {
J
Joao Moreno 已提交
76 77

	constructor(
S
Sandeep Somavarapu 已提交
78
		@IInstantiationService private readonly instantiationService: IInstantiationService,
79 80 81
		@IEnvironmentService private readonly environmentService: IEnvironmentService,
		@IExtensionManagementService private readonly extensionManagementService: IExtensionManagementService,
		@IExtensionGalleryService private readonly extensionGalleryService: IExtensionGalleryService
J
Johannes Rieken 已提交
82
	) { }
J
Joao Moreno 已提交
83

84
	async run(argv: ParsedArgs): Promise<void> {
85
		if (argv['install-source']) {
J
Joao Moreno 已提交
86 87
			await this.setInstallSource(argv['install-source']);

88
		} else if (argv['list-extensions']) {
89
			await this.listExtensions(!!argv['show-versions'], argv['category']);
J
Joao Moreno 已提交
90

J
Joao Moreno 已提交
91
		} else if (argv['install-extension']) {
92
			const arg = argv['install-extension'];
J
Joao Moreno 已提交
93
			const args: string[] = typeof arg === 'string' ? [arg] : arg;
94
			await this.installExtensions(args, !!argv['force']);
J
Joao Moreno 已提交
95

J
Joao Moreno 已提交
96
		} else if (argv['uninstall-extension']) {
97 98
			const arg = argv['uninstall-extension'];
			const ids: string[] = typeof arg === 'string' ? [arg] : arg;
J
Joao Moreno 已提交
99
			await this.uninstallExtension(ids);
100 101 102 103
		} else if (argv['locate-extension']) {
			const arg = argv['locate-extension'];
			const ids: string[] = typeof arg === 'string' ? [arg] : arg;
			await this.locateExtension(ids);
L
Logan Ramos 已提交
104
		} else if (argv['telemetry']) {
105
			console.log(buildTelemetryMessage(this.environmentService.appRoot, this.environmentService.extensionsPath ? this.environmentService.extensionsPath : undefined));
J
Joao Moreno 已提交
106 107
		}
	}
J
Joao Moreno 已提交
108

109
	private setInstallSource(installSource: string): Promise<void> {
110
		return writeFile(this.environmentService.installSourcePath, installSource.slice(0, 30));
111 112
	}

113 114
	private async listExtensions(showVersions: boolean, category?: string): Promise<void> {
		let extensions = await this.extensionManagementService.getInstalled(ExtensionType.User);
L
Logan Ramos 已提交
115 116 117 118 119 120 121
		// TODO: we should save this array in a common place so that the command and extensionQuery can use it that way changing it is easier
		const categories = ['"programming languages"', 'snippets', 'linters', 'themes', 'debuggers', 'formatters', 'keymaps', '"scm providers"', 'other', '"extension packs"', '"language packs"'];
		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;
			}
122 123 124 125 126 127 128
			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;
			});
L
Logan Ramos 已提交
129 130 131 132 133 134
		} else if (category === '') {
			console.log('Possible Categories: ');
			categories.forEach(category => {
				console.log(category);
			});
			return;
135
		}
J
Joao Moreno 已提交
136
		extensions.forEach(e => console.log(getId(e.manifest, showVersions)));
J
Joao Moreno 已提交
137 138
	}

S
Sandeep Somavarapu 已提交
139
	private async installExtensions(extensions: string[], force: boolean): Promise<void> {
140
		const failed: string[] = [];
S
Sandeep Somavarapu 已提交
141
		const installedExtensionsManifests: IExtensionManifest[] = [];
R
RMacfarlane 已提交
142 143 144 145
		if (extensions.length) {
			console.log(localize('installingExtensions', "Installing extensions..."));
		}

S
Sandeep Somavarapu 已提交
146 147
		for (const extension of extensions) {
			try {
S
Sandeep Somavarapu 已提交
148 149 150 151
				const manifest = await this.installExtension(extension, force);
				if (manifest) {
					installedExtensionsManifests.push(manifest);
				}
S
Sandeep Somavarapu 已提交
152 153 154 155 156
			} catch (err) {
				console.error(err.message || err.stack || err);
				failed.push(extension);
			}
		}
S
Sandeep Somavarapu 已提交
157 158 159
		if (installedExtensionsManifests.some(manifest => isLanguagePackExtension(manifest))) {
			await this.updateLocalizationsCache();
		}
S
Sandeep Somavarapu 已提交
160 161
		return failed.length ? Promise.reject(localize('installation failed', "Failed Installing Extensions: {0}", failed.join(', '))) : Promise.resolve();
	}
J
Joao Moreno 已提交
162

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

167 168 169 170
			const manifest = await getManifest(extension);
			const valid = await this.validate(manifest, force);

			if (valid) {
S
Sandeep Somavarapu 已提交
171
				return this.extensionManagementService.install(URI.file(extension)).then(id => {
R
RMacfarlane 已提交
172
					console.log(localize('successVsixInstall', "Extension '{0}' was successfully installed.", getBaseLabel(extension)));
S
Sandeep Somavarapu 已提交
173
					return manifest;
174 175
				}, error => {
					if (isPromiseCanceledError(error)) {
R
RMacfarlane 已提交
176
						console.log(localize('cancelVsixInstall', "Cancelled installing extension '{0}'.", getBaseLabel(extension)));
177 178 179
						return null;
					} else {
						return Promise.reject(error);
S
Sandeep Somavarapu 已提交
180 181
					}
				});
182 183
			}
			return null;
S
Sandeep Somavarapu 已提交
184
		}
J
Joao Moreno 已提交
185

S
Sandeep Somavarapu 已提交
186
		const [id, version] = getIdAndVersion(extension);
187
		return this.extensionManagementService.getInstalled(ExtensionType.User)
S
Sandeep Somavarapu 已提交
188
			.then(installed => this.extensionGalleryService.getCompatibleExtension({ id }, version)
S
Sandeep Somavarapu 已提交
189 190 191 192 193 194 195 196 197 198 199
				.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);
				})
200
				.then(async extension => {
S
Sandeep Somavarapu 已提交
201 202 203 204
					if (!extension) {
						return Promise.reject(new Error(`${notFound(version ? `${id}@${version}` : id)}\n${useId}`));
					}

205
					const manifest = await this.extensionGalleryService.getManifest(extension, CancellationToken.None);
206
					const [installedExtension] = installed.filter(e => areSameExtensions(e.identifier, { id }));
S
Sandeep Somavarapu 已提交
207
					if (installedExtension) {
S
Sandeep Somavarapu 已提交
208
						if (extension.version === installedExtension.manifest.version) {
S
Sandeep Somavarapu 已提交
209 210 211
							console.log(localize('alreadyInstalled', "Extension '{0}' is already installed.", version ? `${id}@${version}` : id));
							return Promise.resolve(null);
						}
S
Sandeep Somavarapu 已提交
212 213 214 215
						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 已提交
216
						console.log(localize('updateMessage', "Updating the extension '{0}' to the version {1}", id, extension.version));
S
Sandeep Somavarapu 已提交
217
					}
S
Sandeep Somavarapu 已提交
218 219
					await this.installFromGallery(id, extension);
					return manifest;
S
Sandeep Somavarapu 已提交
220
				}));
J
Joao Moreno 已提交
221
	}
J
Joao Moreno 已提交
222

223
	private async validate(manifest: IExtensionManifest, force: boolean): Promise<boolean> {
J
Joao Moreno 已提交
224 225 226 227 228
		if (!manifest) {
			throw new Error('Invalid vsix');
		}

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

		if (newer && !force) {
R
RMacfarlane 已提交
233
			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 已提交
234 235 236 237
			return false;
		}

		return true;
S
Sandeep Somavarapu 已提交
238 239
	}

J
Joao Moreno 已提交
240
	private async installFromGallery(id: string, extension: IGalleryExtension): Promise<void> {
R
RMacfarlane 已提交
241
		console.log(localize('installing', "Installing extension '{0}' v{1}...", id, extension.version));
J
Joao Moreno 已提交
242 243 244

		try {
			await this.extensionManagementService.installFromGallery(extension);
R
RMacfarlane 已提交
245
			console.log(localize('successInstall', "Extension '{0}' v{1} was successfully installed.", id, extension.version));
J
Joao Moreno 已提交
246 247
		} catch (error) {
			if (isPromiseCanceledError(error)) {
R
RMacfarlane 已提交
248
				console.log(localize('cancelVsixInstall', "Cancelled installing extension '{0}'.", id));
J
Joao Moreno 已提交
249 250 251 252
			} else {
				throw error;
			}
		}
253 254
	}

255
	private async uninstallExtension(extensions: string[]): Promise<void> {
J
Joao Moreno 已提交
256
		async function getExtensionId(extensionDescription: string): Promise<string> {
257 258
			if (!/\.vsix$/i.test(extensionDescription)) {
				return extensionDescription;
259
			}
J
Joao Moreno 已提交
260

261
			const zipPath = path.isAbsolute(extensionDescription) ? extensionDescription : path.join(process.cwd(), extensionDescription);
262
			const manifest = await getManifest(zipPath);
263
			return getId(manifest);
264
		}
J
Joao Moreno 已提交
265

S
Sandeep Somavarapu 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278
		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 已提交
279

S
Sandeep Somavarapu 已提交
280 281 282 283
		if (uninstalledExtensions.some(e => isLanguagePackExtension(e.manifest))) {
			await this.updateLocalizationsCache();
		}
	}
J
Joao Moreno 已提交
284

285 286 287 288 289 290 291 292 293 294 295 296 297 298
	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 已提交
299 300 301 302
	private async updateLocalizationsCache(): Promise<void> {
		const localizationService = this.instantiationService.createInstance(LocalizationsService);
		await localizationService.update();
		localizationService.dispose();
J
Joao Moreno 已提交
303
	}
J
Joao Moreno 已提交
304 305
}

306 307
const eventPrefix = 'monacoworkbench';

S
Sandeep Somavarapu 已提交
308
export async function main(argv: ParsedArgs): Promise<void> {
J
Joao Moreno 已提交
309
	const services = new ServiceCollection();
S
Sandeep Somavarapu 已提交
310
	const disposables = new DisposableStore();
J
Joao Moreno 已提交
311 312

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

317 318
	await Promise.all<void | undefined>([environmentService.appSettingsHome.fsPath, environmentService.extensionsPath]
		.map((path): undefined | Promise<void> => path ? mkdirp(path) : undefined));
S
Sandeep Somavarapu 已提交
319

S
Sandeep Somavarapu 已提交
320
	const configurationService = new ConfigurationService(environmentService.settingsResource);
S
Sandeep Somavarapu 已提交
321
	disposables.add(configurationService);
S
Sandeep Somavarapu 已提交
322 323
	await configurationService.initialize();

J
Joao Moreno 已提交
324 325
	services.set(IEnvironmentService, environmentService);
	services.set(ILogService, logService);
S
Sandeep Somavarapu 已提交
326
	services.set(IConfigurationService, configurationService);
327
	services.set(IStateService, new SyncDescriptor(StateService));
328
	services.set(IProductService, new SyncDescriptor(ProductService));
J
Joao Moreno 已提交
329

S
Sandeep Somavarapu 已提交
330 331 332 333 334 335 336 337 338
	// 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);

J
Joao Moreno 已提交
339
	const instantiationService: IInstantiationService = new InstantiationService(services);
340

S
Sandeep Somavarapu 已提交
341
	return instantiationService.invokeFunction(async accessor => {
J
Joao Moreno 已提交
342
		const envService = accessor.get(IEnvironmentService);
343
		const stateService = accessor.get(IStateService);
344

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

S
Sandeep Somavarapu 已提交
347
		const services = new ServiceCollection();
S
Sandeep Somavarapu 已提交
348 349


S
Sandeep Somavarapu 已提交
350 351 352
		services.set(IRequestService, new SyncDescriptor(RequestService));
		services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService));
		services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService));
353

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

S
Sandeep Somavarapu 已提交
357 358 359
			if (product.aiConfig && product.aiConfig.asimovKey) {
				appenders.push(new AppInsightsAppender(eventPrefix, null, product.aiConfig.asimovKey, logService));
			}
360

S
Sandeep Somavarapu 已提交
361 362 363
			const config: ITelemetryServiceConfig = {
				appender: combinedAppender(...appenders),
				commonProperties: resolveCommonProperties(product.commit, pkg.version, stateService.getItem('telemetry.machineId'), installSourcePath),
364
				piiPaths: extensionsPath ? [appRoot, extensionsPath] : [appRoot]
S
Sandeep Somavarapu 已提交
365
			};
366

S
Sandeep Somavarapu 已提交
367
			services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));
S
Sandeep Somavarapu 已提交
368

S
Sandeep Somavarapu 已提交
369 370 371
		} else {
			services.set(ITelemetryService, NullTelemetryService);
		}
372

S
Sandeep Somavarapu 已提交
373 374
		const instantiationService2 = instantiationService.createChild(services);
		const main = instantiationService2.createInstance(Main);
375

S
Sandeep Somavarapu 已提交
376 377
		try {
			await main.run(argv);
378 379
			// Flush the remaining data in AI adapter.
			await combinedAppender(...appenders).flush();
S
Sandeep Somavarapu 已提交
380
		} finally {
S
Sandeep Somavarapu 已提交
381
			disposables.dispose();
S
Sandeep Somavarapu 已提交
382
		}
383
	});
L
Logan Ramos 已提交
384
}