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';
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';
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,
S
Sandeep Somavarapu 已提交
72
		@IInstantiationService private readonly instantiationService: IInstantiationService,
73
		@IEnvironmentService private readonly environmentService: IEnvironmentService,
74
		@IConfigurationService private readonly configurationService: IConfigurationService,
75 76
		@IExtensionManagementService private readonly extensionManagementService: IExtensionManagementService,
		@IExtensionGalleryService private readonly extensionGalleryService: IExtensionGalleryService
J
Johannes Rieken 已提交
77
	) { }
J
Joao Moreno 已提交
78

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

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

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

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

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

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

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

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

131
			const manifest = await getManifest(extension);
132
			if (this.remote && (!isLanguagePackExtension(manifest) && isUIExtension(manifest, [], this.configurationService))) {
133 134 135 136 137 138
				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 已提交
139
				return this.extensionManagementService.install(URI.file(extension)).then(id => {
140
					console.log(localize('successVsixInstall', "Extension '{0}' was successfully installed!", getBaseLabel(extension)));
S
Sandeep Somavarapu 已提交
141
					return manifest;
142 143 144 145 146 147
				}, error => {
					if (isPromiseCanceledError(error)) {
						console.log(localize('cancelVsixInstall', "Cancelled installing Extension '{0}'.", getBaseLabel(extension)));
						return null;
					} else {
						return Promise.reject(error);
S
Sandeep Somavarapu 已提交
148 149
					}
				});
150 151
			}
			return null;
S
Sandeep Somavarapu 已提交
152
		}
J
Joao Moreno 已提交
153

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

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

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

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

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

		if (newer && !force) {
208
			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 已提交
209 210 211 212
			return false;
		}

		return true;
S
Sandeep Somavarapu 已提交
213 214
	}

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

		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;
			}
		}
228 229
	}

230
	private async uninstallExtension(extensions: string[]): Promise<void> {
J
Joao Moreno 已提交
231
		async function getExtensionId(extensionDescription: string): Promise<string> {
232 233
			if (!/\.vsix$/i.test(extensionDescription)) {
				return extensionDescription;
234
			}
J
Joao Moreno 已提交
235

236
			const zipPath = path.isAbsolute(extensionDescription) ? extensionDescription : path.join(process.cwd(), extensionDescription);
237
			const manifest = await getManifest(zipPath);
238
			return getId(manifest);
239
		}
J
Joao Moreno 已提交
240

S
Sandeep Somavarapu 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253
		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 已提交
254

S
Sandeep Somavarapu 已提交
255 256 257 258
		if (uninstalledExtensions.some(e => isLanguagePackExtension(e.manifest))) {
			await this.updateLocalizationsCache();
		}
	}
J
Joao Moreno 已提交
259

S
Sandeep Somavarapu 已提交
260 261 262 263
	private async updateLocalizationsCache(): Promise<void> {
		const localizationService = this.instantiationService.createInstance(LocalizationsService);
		await localizationService.update();
		localizationService.dispose();
J
Joao Moreno 已提交
264
	}
J
Joao Moreno 已提交
265 266
}

267 268
const eventPrefix = 'monacoworkbench';

J
Joao Moreno 已提交
269
export function main(argv: ParsedArgs): Promise<void> {
J
Joao Moreno 已提交
270
	const services = new ServiceCollection();
J
Joao Moreno 已提交
271 272

	const environmentService = new EnvironmentService(argv, process.execPath);
S
Sandeep Somavarapu 已提交
273
	const logService = createSpdLogService('cli', getLogLevel(environmentService), environmentService.logsPath);
274
	process.once('exit', () => logService.dispose());
J
Joao Moreno 已提交
275 276 277 278 279

	logService.info('main', argv);

	services.set(IEnvironmentService, environmentService);
	services.set(ILogService, logService);
280
	services.set(IStateService, new SyncDescriptor(StateService));
J
Joao Moreno 已提交
281 282

	const instantiationService: IInstantiationService = new InstantiationService(services);
283 284

	return instantiationService.invokeFunction(accessor => {
J
Joao Moreno 已提交
285
		const envService = accessor.get(IEnvironmentService);
286
		const stateService = accessor.get(IStateService);
287

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

J
Joao Moreno 已提交
291
			const services = new ServiceCollection();
292
			services.set(IConfigurationService, new SyncDescriptor(ConfigurationService));
J
Joao Moreno 已提交
293
			services.set(IRequestService, new SyncDescriptor(RequestService));
294
			services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService, [false]));
J
Joao Moreno 已提交
295
			services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService));
296

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

J
Joao Moreno 已提交
300
				if (product.aiConfig && product.aiConfig.asimovKey) {
301
					appenders.push(new AppInsightsAppender(eventPrefix, null, product.aiConfig.asimovKey, logService));
J
Joao Moreno 已提交
302
				}
303

J
Joao Moreno 已提交
304 305
				const config: ITelemetryServiceConfig = {
					appender: combinedAppender(...appenders),
306
					commonProperties: resolveCommonProperties(product.commit, pkg.version, stateService.getItem('telemetry.machineId'), installSourcePath),
J
Joao Moreno 已提交
307 308
					piiPaths: [appRoot, extensionsPath]
				};
309

310
				services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));
J
Joao Moreno 已提交
311 312 313
			} else {
				services.set(ITelemetryService, NullTelemetryService);
			}
314

J
Joao Moreno 已提交
315
			const instantiationService2 = instantiationService.createChild(services);
316
			const main = instantiationService2.createInstance(Main, false);
317

318 319 320 321
			return main.run(argv).then(() => {
				// Dispose the AI adapter so that remaining data gets flushed.
				return combinedAppender(...appenders).dispose();
			});
J
Joao Moreno 已提交
322
		});
323
	});
J
Joao Moreno 已提交
324
}