cliProcessMain.ts 13.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 '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';
J
Joao Moreno 已提交
19
import { IExtensionManagementService, IExtensionGalleryService, IExtensionManifest, IGalleryExtension, LocalExtensionType } 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';
S
Sandeep Somavarapu 已提交
38
import { areSameExtensions, getGalleryExtensionIdFromLocal, 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';
J
Joao Moreno 已提交
41

42 43
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 已提交
44
const useId = localize('useId', "Make sure you use the full extension ID, including the publisher, eg: {0}", 'ms-vscode.csharp');
J
Joao Moreno 已提交
45

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

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

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


J
Johannes Rieken 已提交
65
type Task = { (): Promise<void> };
66

J
Joao Moreno 已提交
67 68 69
class Main {

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

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

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

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

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

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

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

J
Joao Moreno 已提交
103
	private installExtension(extensions: string[], force: boolean): Promise<any> {
104 105 106 107
		const vsixTasks: Task[] = extensions
			.filter(e => /\.vsix$/i.test(e))
			.map(id => () => {
				const extension = path.isAbsolute(id) ? id : path.join(process.cwd(), id);
J
Joao Moreno 已提交
108

S
Sandeep Somavarapu 已提交
109 110 111 112 113 114 115 116 117 118
				return this.validate(extension, force)
					.then(valid => {
						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 {
J
Joao Moreno 已提交
119
									return Promise.reject(error);
S
Sandeep Somavarapu 已提交
120 121 122
								}
							});
						}
123
						return null;
S
Sandeep Somavarapu 已提交
124
					});
125
			});
J
Joao Moreno 已提交
126

127 128
		const galleryTasks: Task[] = extensions
			.filter(e => !/\.vsix$/i.test(e))
129 130
			.map(e => () => {
				const [id, version] = getIdAndVersion(e);
131
				return this.extensionManagementService.getInstalled(LocalExtensionType.User)
132 133
					.then(installed => this.extensionGalleryService.getExtension({ id }, version)
						.then<IGalleryExtension>(null, err => {
134 135 136
							if (err.responseText) {
								try {
									const response = JSON.parse(err.responseText);
J
Joao Moreno 已提交
137
									return Promise.reject(response.message);
138
								} catch (e) {
J
Joao Moreno 已提交
139
									// noop
140
								}
J
Joao Moreno 已提交
141
							}
J
Joao Moreno 已提交
142
							return Promise.reject(err);
143
						})
144
						.then(extension => {
145
							if (!extension) {
J
Joao Moreno 已提交
146
								return Promise.reject(new Error(`${notFound(version ? `${id}@${version}` : id)}\n${useId}`));
147
							}
J
Joao Moreno 已提交
148

149
							const [installedExtension] = installed.filter(e => areSameExtensions({ id: getGalleryExtensionIdFromLocal(e) }, { id }));
150
							if (installedExtension) {
151 152 153
								if (extension.version !== installedExtension.manifest.version) {
									if (version || force) {
										console.log(localize('updateMessage', "Updating the Extension '{0}' to the version {1}", id, extension.version));
154 155
										return this.installFromGallery(id, extension);
									} else {
S
Sandeep Somavarapu 已提交
156 157
										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);
158
									}
O
oriash93 已提交
159
								} else {
160
									console.log(localize('alreadyInstalled', "Extension '{0}' is already installed.", version ? `${id}@${version}` : id));
J
Joao Moreno 已提交
161
									return Promise.resolve(null);
O
oriash93 已提交
162
								}
163
							} else {
164
								console.log(localize('foundExtension', "Found '{0}' in the marketplace.", id));
165
								return this.installFromGallery(id, extension);
166
							}
J
Joao Moreno 已提交
167

168
						}));
169
			});
170 171

		return sequence([...vsixTasks, ...galleryTasks]);
J
Joao Moreno 已提交
172
	}
J
Joao Moreno 已提交
173

J
Joao Moreno 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
	private async validate(vsix: string, force: boolean): Promise<boolean> {
		const manifest = await getManifest(vsix);

		if (!manifest) {
			throw new Error('Invalid vsix');
		}

		const extensionIdentifier = { id: getGalleryExtensionId(manifest.publisher, manifest.name) };
		const installedExtensions = await this.extensionManagementService.getInstalled(LocalExtensionType.User);
		const newer = installedExtensions.filter(local => areSameExtensions(extensionIdentifier, { id: getGalleryExtensionIdFromLocal(local) }) && semver.gt(local.manifest.version, manifest.version))[0];

		if (newer && !force) {
			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.galleryIdentifier.id, newer.manifest.version, manifest.version));
			return false;
		}

		return true;
S
Sandeep Somavarapu 已提交
191 192
	}

J
Joao Moreno 已提交
193
	private async installFromGallery(id: string, extension: IGalleryExtension): Promise<void> {
194
		console.log(localize('installing', "Installing..."));
J
Joao Moreno 已提交
195 196 197 198 199 200 201 202 203 204 205

		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;
			}
		}
206 207
	}

J
Johannes Rieken 已提交
208
	private uninstallExtension(extensions: string[]): Promise<any> {
J
Joao Moreno 已提交
209
		async function getExtensionId(extensionDescription: string): Promise<string> {
210 211
			if (!/\.vsix$/i.test(extensionDescription)) {
				return extensionDescription;
212
			}
J
Joao Moreno 已提交
213

214
			const zipPath = path.isAbsolute(extensionDescription) ? extensionDescription : path.join(process.cwd(), extensionDescription);
215
			const manifest = await getManifest(zipPath);
216
			return getId(manifest);
217
		}
J
Joao Moreno 已提交
218

219
		return sequence(extensions.map(extension => () => {
220
			return getExtensionId(extension).then(id => {
221
				return this.extensionManagementService.getInstalled(LocalExtensionType.User).then(installed => {
S
Sandeep Somavarapu 已提交
222
					const [extension] = installed.filter(e => areSameExtensions({ id: getGalleryExtensionIdFromLocal(e) }, { id }));
J
Joao Moreno 已提交
223

224
					if (!extension) {
J
Joao Moreno 已提交
225
						return Promise.reject(new Error(`${notInstalled(id)}\n${useId}`));
226
					}
J
Joao Moreno 已提交
227

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

230 231 232
					return this.extensionManagementService.uninstall(extension, true)
						.then(() => console.log(localize('successUninstall', "Extension '{0}' was successfully uninstalled!", id)));
				});
J
Joao Moreno 已提交
233
			});
234
		}));
J
Joao Moreno 已提交
235
	}
J
Joao Moreno 已提交
236 237
}

238 239
const eventPrefix = 'monacoworkbench';

J
Joao Moreno 已提交
240
export function main(argv: ParsedArgs): Promise<void> {
J
Joao Moreno 已提交
241
	const services = new ServiceCollection();
J
Joao Moreno 已提交
242 243

	const environmentService = new EnvironmentService(argv, process.execPath);
S
Sandeep Somavarapu 已提交
244
	const logService = createSpdLogService('cli', getLogLevel(environmentService), environmentService.logsPath);
245
	process.once('exit', () => logService.dispose());
J
Joao Moreno 已提交
246 247 248 249 250

	logService.info('main', argv);

	services.set(IEnvironmentService, environmentService);
	services.set(ILogService, logService);
251
	services.set(IStateService, new SyncDescriptor(StateService));
J
Joao Moreno 已提交
252 253

	const instantiationService: IInstantiationService = new InstantiationService(services);
254 255

	return instantiationService.invokeFunction(accessor => {
J
Joao Moreno 已提交
256
		const envService = accessor.get(IEnvironmentService);
257
		const stateService = accessor.get(IStateService);
258

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

J
Joao Moreno 已提交
262
			const services = new ServiceCollection();
263
			services.set(IConfigurationService, new SyncDescriptor(ConfigurationService));
J
Joao Moreno 已提交
264
			services.set(IRequestService, new SyncDescriptor(RequestService));
J
Joao Moreno 已提交
265 266
			services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService));
			services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService));
267

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

J
Joao Moreno 已提交
271
				if (product.aiConfig && product.aiConfig.asimovKey) {
272
					appenders.push(new AppInsightsAppender(eventPrefix, null, product.aiConfig.asimovKey, logService));
J
Joao Moreno 已提交
273
				}
274

J
Joao Moreno 已提交
275 276
				const config: ITelemetryServiceConfig = {
					appender: combinedAppender(...appenders),
277
					commonProperties: resolveCommonProperties(product.commit, pkg.version, stateService.getItem('telemetry.machineId'), installSourcePath),
J
Joao Moreno 已提交
278 279
					piiPaths: [appRoot, extensionsPath]
				};
280

281
				services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));
J
Joao Moreno 已提交
282 283 284
			} else {
				services.set(ITelemetryService, NullTelemetryService);
			}
285

J
Joao Moreno 已提交
286 287
			const instantiationService2 = instantiationService.createChild(services);
			const main = instantiationService2.createInstance(Main);
288

289 290 291 292
			return main.run(argv).then(() => {
				// Dispose the AI adapter so that remaining data gets flushed.
				return combinedAppender(...appenders).dispose();
			});
J
Joao Moreno 已提交
293
		});
294
	});
J
Joao Moreno 已提交
295
}