cliProcessMain.ts 14.0 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/node/product';
import pkg from 'vs/platform/node/package';
9
import * as path from 'vs/base/common/path';
S
Sandeep Somavarapu 已提交
10
import * as semver from 'semver';
J
Joao Moreno 已提交
11

12
import { sequence } from 'vs/base/common/async';
J
Joao Moreno 已提交
13 14 15 16
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 已提交
17
import { IEnvironmentService, ParsedArgs } from 'vs/platform/environment/common/environment';
18
import { EnvironmentService } from 'vs/platform/environment/node/environmentService';
19
import { IExtensionManagementService, IExtensionGalleryService, IGalleryExtension } from 'vs/platform/extensionManagement/common/extensionManagement';
20
import { ExtensionManagementService } from 'vs/platform/extensionManagement/node/extensionManagementService';
J
Joao Moreno 已提交
21
import { ExtensionGalleryService } from 'vs/platform/extensionManagement/node/extensionGalleryService';
22 23
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { combinedAppender, NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
24 25
import { TelemetryService, ITelemetryServiceConfig } from 'vs/platform/telemetry/common/telemetryService';
import { resolveCommonProperties } from 'vs/platform/telemetry/node/commonProperties';
J
Joao Moreno 已提交
26
import { IRequestService } from 'vs/platform/request/node/request';
J
Joao Moreno 已提交
27
import { RequestService } from 'vs/platform/request/node/requestService';
J
Joao Moreno 已提交
28
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
29
import { ConfigurationService } from 'vs/platform/configuration/node/configurationService';
30
import { AppInsightsAppender } from 'vs/platform/telemetry/node/appInsightsAppender';
31
import { mkdirp, writeFile } from 'vs/base/node/pfs';
B
Benjamin Pasero 已提交
32
import { getBaseLabel } from 'vs/base/common/labels';
33 34
import { IStateService } from 'vs/platform/state/common/state';
import { StateService } from 'vs/platform/state/node/stateService';
35
import { createSpdLogService } from 'vs/platform/log/node/spdlogService';
S
Sandeep Somavarapu 已提交
36
import { ILogService, getLogLevel } from 'vs/platform/log/common/log';
37
import { isPromiseCanceledError } from 'vs/base/common/errors';
38
import { areSameExtensions, adoptToGalleryExtensionId, getGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
39
import { URI } from 'vs/base/common/uri';
40
import { getManifest } from 'vs/platform/extensionManagement/node/extensionManagementUtil';
41
import { IExtensionManifest, ExtensionType } from 'vs/platform/extensions/common/extensions';
42 43
import { isUIExtension } from 'vs/platform/extensions/node/extensionsUtil';
import { CancellationToken } from 'vs/base/common/cancellation';
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);
J
Joao Moreno 已提交
47
const useId = localize('useId', "Make sure you use the full extension ID, including the publisher, eg: {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(
71
		private readonly remote: boolean,
72
		@IEnvironmentService private readonly environmentService: IEnvironmentService,
73
		@IConfigurationService private readonly configurationService: IConfigurationService,
74 75
		@IExtensionManagementService private readonly extensionManagementService: IExtensionManagementService,
		@IExtensionGalleryService private readonly extensionGalleryService: IExtensionGalleryService
J
Johannes Rieken 已提交
76
	) { }
J
Joao Moreno 已提交
77

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

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

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

J
Joao Moreno 已提交
90
		} else if (argv['uninstall-extension']) {
91 92
			const arg = argv['uninstall-extension'];
			const ids: string[] = typeof arg === 'string' ? [arg] : arg;
J
Joao Moreno 已提交
93
			await this.uninstallExtension(ids);
J
Joao Moreno 已提交
94 95
		}
	}
J
Joao Moreno 已提交
96

J
Joao Moreno 已提交
97
	private setInstallSource(installSource: string): Promise<any> {
98
		return writeFile(this.environmentService.installSourcePath, installSource.slice(0, 30));
99 100
	}

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

S
Sandeep Somavarapu 已提交
106 107 108 109 110 111 112 113 114 115 116 117
	private async installExtensions(extensions: string[], force: boolean): Promise<void> {
		let failed: string[] = [];
		for (const extension of extensions) {
			try {
				await this.installExtension(extension, force);
			} catch (err) {
				console.error(err.message || err.stack || err);
				failed.push(extension);
			}
		}
		return failed.length ? Promise.reject(localize('installation failed', "Failed Installing Extensions: {0}", failed.join(', '))) : Promise.resolve();
	}
J
Joao Moreno 已提交
118

119
	private async installExtension(extension: string, force: boolean): Promise<any> {
S
Sandeep Somavarapu 已提交
120 121 122
		if (/\.vsix$/i.test(extension)) {
			extension = path.isAbsolute(extension) ? extension : path.join(process.cwd(), extension);

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
			const manifest = await getManifest(extension);
			if (this.remote && isUIExtension(manifest, this.configurationService)) {
				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) {
				return this.extensionManagementService.install(URI.file(extension)).then(() => {
					console.log(localize('successVsixInstall', "Extension '{0}' was successfully installed!", getBaseLabel(extension)));
				}, error => {
					if (isPromiseCanceledError(error)) {
						console.log(localize('cancelVsixInstall', "Cancelled installing Extension '{0}'.", getBaseLabel(extension)));
						return null;
					} else {
						return Promise.reject(error);
S
Sandeep Somavarapu 已提交
139 140
					}
				});
141 142
			}
			return null;
S
Sandeep Somavarapu 已提交
143
		}
J
Joao Moreno 已提交
144

S
Sandeep Somavarapu 已提交
145
		const [id, version] = getIdAndVersion(extension);
146
		return this.extensionManagementService.getInstalled(ExtensionType.User)
S
Sandeep Somavarapu 已提交
147
			.then(installed => this.extensionGalleryService.getCompatibleExtension({ id }, version)
S
Sandeep Somavarapu 已提交
148 149 150 151 152 153 154 155 156 157 158
				.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);
				})
159
				.then(async extension => {
S
Sandeep Somavarapu 已提交
160 161 162 163
					if (!extension) {
						return Promise.reject(new Error(`${notFound(version ? `${id}@${version}` : id)}\n${useId}`));
					}

164
					const manifest = await this.extensionGalleryService.getManifest(extension, CancellationToken.None);
S
Sandeep Somavarapu 已提交
165
					if (this.remote && manifest && isUIExtension(manifest, this.configurationService)) {
166 167 168 169
						console.log(localize('notSupportedUIExtension', "Can't install extension {0} since UI Extensions are not supported", extension.identifier.id));
						return null;
					}

170
					const [installedExtension] = installed.filter(e => areSameExtensions(e.identifier, { id }));
S
Sandeep Somavarapu 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
					if (installedExtension) {
						if (extension.version !== installedExtension.manifest.version) {
							if (version || force) {
								console.log(localize('updateMessage', "Updating the Extension '{0}' to the version {1}", id, extension.version));
								return this.installFromGallery(id, extension);
							} else {
								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);
							}
						} else {
							console.log(localize('alreadyInstalled', "Extension '{0}' is already installed.", version ? `${id}@${version}` : id));
							return Promise.resolve(null);
						}
					} else {
						console.log(localize('foundExtension', "Found '{0}' in the marketplace.", id));
						return this.installFromGallery(id, extension);
					}
188

S
Sandeep Somavarapu 已提交
189
				}));
J
Joao Moreno 已提交
190
	}
J
Joao Moreno 已提交
191

S
Sandeep Somavarapu 已提交
192 193


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

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

		if (newer && !force) {
204
			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 已提交
205 206 207 208
			return false;
		}

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

J
Joao Moreno 已提交
211
	private async installFromGallery(id: string, extension: IGalleryExtension): Promise<void> {
212
		console.log(localize('installing', "Installing..."));
J
Joao Moreno 已提交
213 214 215 216 217 218 219 220 221 222 223

		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;
			}
		}
224 225
	}

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

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

237
		return sequence(extensions.map(extension => () => {
238
			return getExtensionId(extension).then(id => {
239
				return this.extensionManagementService.getInstalled(ExtensionType.User).then(installed => {
240
					const [extension] = installed.filter(e => areSameExtensions(e.identifier, { id }));
J
Joao Moreno 已提交
241

242
					if (!extension) {
J
Joao Moreno 已提交
243
						return Promise.reject(new Error(`${notInstalled(id)}\n${useId}`));
244
					}
J
Joao Moreno 已提交
245

246
					console.log(localize('uninstalling', "Uninstalling {0}...", id));
J
Joao Moreno 已提交
247

248 249 250
					return this.extensionManagementService.uninstall(extension, true)
						.then(() => console.log(localize('successUninstall', "Extension '{0}' was successfully uninstalled!", id)));
				});
J
Joao Moreno 已提交
251
			});
252
		}));
J
Joao Moreno 已提交
253
	}
J
Joao Moreno 已提交
254 255
}

256 257
const eventPrefix = 'monacoworkbench';

J
Joao Moreno 已提交
258
export function main(argv: ParsedArgs): Promise<void> {
J
Joao Moreno 已提交
259
	const services = new ServiceCollection();
J
Joao Moreno 已提交
260 261

	const environmentService = new EnvironmentService(argv, process.execPath);
S
Sandeep Somavarapu 已提交
262
	const logService = createSpdLogService('cli', getLogLevel(environmentService), environmentService.logsPath);
263
	process.once('exit', () => logService.dispose());
J
Joao Moreno 已提交
264 265 266 267 268

	logService.info('main', argv);

	services.set(IEnvironmentService, environmentService);
	services.set(ILogService, logService);
269
	services.set(IStateService, new SyncDescriptor(StateService));
J
Joao Moreno 已提交
270 271

	const instantiationService: IInstantiationService = new InstantiationService(services);
272 273

	return instantiationService.invokeFunction(accessor => {
J
Joao Moreno 已提交
274
		const envService = accessor.get(IEnvironmentService);
275
		const stateService = accessor.get(IStateService);
276

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

J
Joao Moreno 已提交
280
			const services = new ServiceCollection();
281
			services.set(IConfigurationService, new SyncDescriptor(ConfigurationService));
J
Joao Moreno 已提交
282
			services.set(IRequestService, new SyncDescriptor(RequestService));
283
			services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService, [false]));
J
Joao Moreno 已提交
284
			services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService));
285

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

J
Joao Moreno 已提交
289
				if (product.aiConfig && product.aiConfig.asimovKey) {
290
					appenders.push(new AppInsightsAppender(eventPrefix, null, product.aiConfig.asimovKey, logService));
J
Joao Moreno 已提交
291
				}
292

J
Joao Moreno 已提交
293 294
				const config: ITelemetryServiceConfig = {
					appender: combinedAppender(...appenders),
295
					commonProperties: resolveCommonProperties(product.commit, pkg.version, stateService.getItem('telemetry.machineId'), installSourcePath),
J
Joao Moreno 已提交
296 297
					piiPaths: [appRoot, extensionsPath]
				};
298

299
				services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));
J
Joao Moreno 已提交
300 301 302
			} else {
				services.set(ITelemetryService, NullTelemetryService);
			}
303

J
Joao Moreno 已提交
304
			const instantiationService2 = instantiationService.createChild(services);
305
			const main = instantiationService2.createInstance(Main, false);
306

307 308 309 310
			return main.run(argv).then(() => {
				// Dispose the AI adapter so that remaining data gets flushed.
				return combinedAppender(...appenders).dispose();
			});
J
Joao Moreno 已提交
311
		});
312
	});
J
Joao Moreno 已提交
313
}