cliProcessMain.ts 13.4 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

J
Joao Moreno 已提交
12
import { TPromise } from 'vs/base/common/winjs.base';
13
import { sequence } from 'vs/base/common/async';
J
Joao Moreno 已提交
14 15 16 17
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 已提交
18
import { IEnvironmentService, ParsedArgs } from 'vs/platform/environment/common/environment';
19
import { EnvironmentService } from 'vs/platform/environment/node/environmentService';
J
Joao Moreno 已提交
20
import { IExtensionManagementService, IExtensionGalleryService, IExtensionManifest, IGalleryExtension, LocalExtensionType } from 'vs/platform/extensionManagement/common/extensionManagement';
21
import { ExtensionManagementService } from 'vs/platform/extensionManagement/node/extensionManagementService';
J
Joao Moreno 已提交
22
import { ExtensionGalleryService } from 'vs/platform/extensionManagement/node/extensionGalleryService';
23 24
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { combinedAppender, NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
25 26
import { TelemetryService, ITelemetryServiceConfig } from 'vs/platform/telemetry/common/telemetryService';
import { resolveCommonProperties } from 'vs/platform/telemetry/node/commonProperties';
J
Joao Moreno 已提交
27
import { IRequestService } from 'vs/platform/request/node/request';
J
Joao Moreno 已提交
28
import { RequestService } from 'vs/platform/request/node/requestService';
J
Joao Moreno 已提交
29
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
30
import { ConfigurationService } from 'vs/platform/configuration/node/configurationService';
31
import { AppInsightsAppender } from 'vs/platform/telemetry/node/appInsightsAppender';
32
import { mkdirp, writeFile } from 'vs/base/node/pfs';
B
Benjamin Pasero 已提交
33
import { getBaseLabel } from 'vs/base/common/labels';
34 35
import { IStateService } from 'vs/platform/state/common/state';
import { StateService } from 'vs/platform/state/node/stateService';
36
import { createSpdLogService } from 'vs/platform/log/node/spdlogService';
S
Sandeep Somavarapu 已提交
37
import { ILogService, getLogLevel } from 'vs/platform/log/common/log';
38
import { isPromiseCanceledError } from 'vs/base/common/errors';
S
Sandeep Somavarapu 已提交
39
import { areSameExtensions, getGalleryExtensionIdFromLocal, adoptToGalleryExtensionId, getGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
40
import { URI } from 'vs/base/common/uri';
41
import { getManifest } from 'vs/platform/extensionManagement/node/extensionManagementUtil';
J
Joao Moreno 已提交
42

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

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

55 56 57 58 59 60 61 62 63 64 65
const EXTENSION_ID_REGEX = /^([^.]+\..+)@(\d+\.\d+\.\d+(-.*)?)$/;

export function getIdAndVersion(id: string): [string, string] {
	const matches = EXTENSION_ID_REGEX.exec(id);
	if (matches && matches[1]) {
		return [adoptToGalleryExtensionId(matches[1]), matches[2]];
	}
	return [adoptToGalleryExtensionId(id), void 0];
}


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

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

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

	run(argv: ParsedArgs): TPromise<any> {
J
Joao Moreno 已提交
77 78
		// TODO@joao - make this contributable

79
		let returnPromise: TPromise<any>;
80
		if (argv['install-source']) {
81
			returnPromise = this.setInstallSource(argv['install-source']);
82
		} else if (argv['list-extensions']) {
83
			returnPromise = this.listExtensions(argv['show-versions']);
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;
87
			returnPromise = this.installExtension(args, argv['force']);
J
Joao Moreno 已提交
88
		} else if (argv['uninstall-extension']) {
89 90
			const arg = argv['uninstall-extension'];
			const ids: string[] = typeof arg === 'string' ? [arg] : arg;
91
			returnPromise = this.uninstallExtension(ids);
J
Joao Moreno 已提交
92
		}
93
		return returnPromise || TPromise.as(null);
J
Joao Moreno 已提交
94
	}
J
Joao Moreno 已提交
95

96
	private setInstallSource(installSource: string): TPromise<any> {
97
		return writeFile(this.environmentService.installSourcePath, installSource.slice(0, 30));
98 99
	}

G
greams 已提交
100
	private listExtensions(showVersions: boolean): TPromise<any> {
J
Joao Moreno 已提交
101
		return this.extensionManagementService.getInstalled(LocalExtensionType.User).then(extensions => {
G
greams 已提交
102
			extensions.forEach(e => console.log(getId(e.manifest, showVersions)));
J
Joao Moreno 已提交
103 104 105
		});
	}

106
	private installExtension(extensions: string[], force: boolean): TPromise<any> {
107 108 109 110
		const vsixTasks: Task[] = extensions
			.filter(e => /\.vsix$/i.test(e))
			.map(id => () => {
				const extension = path.isAbsolute(id) ? id : path.join(process.cwd(), id);
S
Sandeep Somavarapu 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124
				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 {
									return TPromise.wrapError(error);
								}
							});
						}
125
						return null;
S
Sandeep Somavarapu 已提交
126
					});
127
			});
J
Joao Moreno 已提交
128

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

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

170
						}));
171
			});
172 173

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

S
Sandeep Somavarapu 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
	private validate(vsix: string, force: boolean): Thenable<boolean> {
		return getManifest(vsix)
			.then(manifest => {
				if (manifest) {
					const extensionIdentifier = { id: getGalleryExtensionId(manifest.publisher, manifest.name) };
					return this.extensionManagementService.getInstalled(LocalExtensionType.User)
						.then(installedExtensions => {
							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;
						});
				} else {
					return Promise.reject(new Error('Invalid vsix'));
				}
			});
	}

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
	private installFromGallery(id: string, extension: IGalleryExtension): TPromise<void> {
		console.log(localize('installing', "Installing..."));
		return this.extensionManagementService.installFromGallery(extension)
			.then(
				() => console.log(localize('successInstall', "Extension '{0}' v{1} was successfully installed!", id, extension.version)),
				error => {
					if (isPromiseCanceledError(error)) {
						console.log(localize('cancelVsixInstall', "Cancelled installing Extension '{0}'.", id));
						return null;
					} else {
						return TPromise.wrapError(error);
					}
				});
	}

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

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

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

227 228 229
					if (!extension) {
						return TPromise.wrapError(new Error(`${notInstalled(id)}\n${useId}`));
					}
J
Joao Moreno 已提交
230

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

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

241 242
const eventPrefix = 'monacoworkbench';

J
Joao Moreno 已提交
243 244
export function main(argv: ParsedArgs): TPromise<void> {
	const services = new ServiceCollection();
J
Joao Moreno 已提交
245 246

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

	logService.info('main', argv);

	services.set(IEnvironmentService, environmentService);
	services.set(ILogService, logService);
254
	services.set(IStateService, new SyncDescriptor(StateService));
J
Joao Moreno 已提交
255 256

	const instantiationService: IInstantiationService = new InstantiationService(services);
257 258

	return instantiationService.invokeFunction(accessor => {
J
Joao Moreno 已提交
259
		const envService = accessor.get(IEnvironmentService);
260
		const stateService = accessor.get(IStateService);
261

D
Daniel Imms 已提交
262
		return TPromise.join([envService.appSettingsHome, envService.extensionsPath].map(p => mkdirp(p))).then(() => {
263
			const { appRoot, extensionsPath, extensionDevelopmentLocationURI, isBuilt, installSourcePath } = envService;
264

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

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

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

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

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

J
Joao Moreno 已提交
289 290
			const instantiationService2 = instantiationService.createChild(services);
			const main = instantiationService2.createInstance(Main);
291

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