cliProcessMain.ts 12.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/node/product';
import pkg from 'vs/platform/node/package';
9
import * as path from 'path';
J
Joao Moreno 已提交
10

J
Joao Moreno 已提交
11
import { TPromise } from 'vs/base/common/winjs.base';
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';
38
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
B
Benjamin Pasero 已提交
39
import { CommandLineDialogService } from 'vs/platform/dialogs/node/dialogService';
40
import { areSameExtensions, getGalleryExtensionIdFromLocal, adoptToGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
41
import Severity from 'vs/base/common/severity';
42
import { URI } from 'vs/base/common/uri';
43
import { getManifest } from 'vs/platform/extensionManagement/node/extensionManagementUtil';
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 59 60 61 62 63 64 65 66 67
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 已提交
68
type Task = { (): TPromise<void> };
69

J
Joao Moreno 已提交
70 71 72
class Main {

	constructor(
73
		@IEnvironmentService private environmentService: IEnvironmentService,
J
Joao Moreno 已提交
74
		@IExtensionManagementService private extensionManagementService: IExtensionManagementService,
75 76
		@IExtensionGalleryService private extensionGalleryService: IExtensionGalleryService,
		@IDialogService private dialogService: IDialogService
J
Johannes Rieken 已提交
77
	) { }
J
Joao Moreno 已提交
78 79

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

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

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

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

109
	private installExtension(extensions: string[], force: boolean): TPromise<any> {
110 111 112 113
		const vsixTasks: Task[] = extensions
			.filter(e => /\.vsix$/i.test(e))
			.map(id => () => {
				const extension = path.isAbsolute(id) ? id : path.join(process.cwd(), id);
114

115
				return this.extensionManagementService.install(URI.file(extension)).then(() => {
B
Benjamin Pasero 已提交
116
					console.log(localize('successVsixInstall', "Extension '{0}' was successfully installed!", getBaseLabel(extension)));
117 118 119 120 121 122 123
				}, error => {
					if (isPromiseCanceledError(error)) {
						console.log(localize('cancelVsixInstall', "Cancelled installing Extension '{0}'.", getBaseLabel(extension)));
						return null;
					} else {
						return TPromise.wrapError(error);
					}
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 137 138
							if (err.responseText) {
								try {
									const response = JSON.parse(err.responseText);
									return TPromise.wrapError(response.message);
								} catch (e) {
J
Joao Moreno 已提交
139
									// noop
140
								}
J
Joao Moreno 已提交
141
							}
J
Joao Moreno 已提交
142
							return TPromise.wrapError(err);
143
						})
144
						.then(extension => {
145
							if (!extension) {
146
								return TPromise.wrapError(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 156 157 158 159 160 161 162 163 164 165
										return this.installFromGallery(id, extension);
									} else {
										const updateMessage = localize('updateConfirmationMessage', "Extension '{0}' v{1} is already installed, but a newer version {2} is available in the marketplace. Would you like to update?", id, installedExtension.manifest.version, extension.version);
										return this.dialogService.show(Severity.Info, updateMessage, [localize('yes', "Yes"), localize('no', "No")])
											.then(option => {
												if (option === 0) {
													return this.installFromGallery(id, extension);
												}
												console.log(localize('cancelInstall', "Cancelled installing Extension '{0}'.", id));
												return TPromise.as(null);
											});
									}
O
oriash93 已提交
166
								} else {
167
									console.log(localize('alreadyInstalled', "Extension '{0}' is already installed.", version ? `${id}@${version}` : id));
O
oriash93 已提交
168 169
									return TPromise.as(null);
								}
170
							} else {
171
								console.log(localize('foundExtension', "Found '{0}' in the marketplace.", id));
172
								return this.installFromGallery(id, extension);
173
							}
J
Joao Moreno 已提交
174

175
						}));
176
			});
177 178

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

181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
	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);
					}
				});
	}

196
	private uninstallExtension(extensions: string[]): TPromise<any> {
J
Joao Moreno 已提交
197
		async function getExtensionId(extensionDescription: string): Promise<string> {
198 199
			if (!/\.vsix$/i.test(extensionDescription)) {
				return extensionDescription;
200
			}
J
Joao Moreno 已提交
201

202
			const zipPath = path.isAbsolute(extensionDescription) ? extensionDescription : path.join(process.cwd(), extensionDescription);
203
			const manifest = await getManifest(zipPath);
204
			return getId(manifest);
205
		}
J
Joao Moreno 已提交
206

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

212 213 214
					if (!extension) {
						return TPromise.wrapError(new Error(`${notInstalled(id)}\n${useId}`));
					}
J
Joao Moreno 已提交
215

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

218 219 220
					return this.extensionManagementService.uninstall(extension, true)
						.then(() => console.log(localize('successUninstall', "Extension '{0}' was successfully uninstalled!", id)));
				});
J
Joao Moreno 已提交
221
			});
222
		}));
J
Joao Moreno 已提交
223
	}
J
Joao Moreno 已提交
224 225
}

226 227
const eventPrefix = 'monacoworkbench';

J
Joao Moreno 已提交
228 229
export function main(argv: ParsedArgs): TPromise<void> {
	const services = new ServiceCollection();
J
Joao Moreno 已提交
230 231

	const environmentService = new EnvironmentService(argv, process.execPath);
S
Sandeep Somavarapu 已提交
232
	const logService = createSpdLogService('cli', getLogLevel(environmentService), environmentService.logsPath);
233
	process.once('exit', () => logService.dispose());
J
Joao Moreno 已提交
234 235 236 237 238

	logService.info('main', argv);

	services.set(IEnvironmentService, environmentService);
	services.set(ILogService, logService);
239
	services.set(IStateService, new SyncDescriptor(StateService));
J
Joao Moreno 已提交
240 241

	const instantiationService: IInstantiationService = new InstantiationService(services);
242 243

	return instantiationService.invokeFunction(accessor => {
J
Joao Moreno 已提交
244
		const envService = accessor.get(IEnvironmentService);
245
		const stateService = accessor.get(IStateService);
246

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

J
Joao Moreno 已提交
250
			const services = new ServiceCollection();
251
			services.set(IConfigurationService, new SyncDescriptor(ConfigurationService));
J
Joao Moreno 已提交
252
			services.set(IRequestService, new SyncDescriptor(RequestService));
J
Joao Moreno 已提交
253 254
			services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService));
			services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService));
B
Benjamin Pasero 已提交
255
			services.set(IDialogService, new SyncDescriptor(CommandLineDialogService));
256

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

J
Joao Moreno 已提交
260
				if (product.aiConfig && product.aiConfig.asimovKey) {
261
					appenders.push(new AppInsightsAppender(eventPrefix, null, product.aiConfig.asimovKey, logService));
J
Joao Moreno 已提交
262
				}
263

J
Joao Moreno 已提交
264 265
				const config: ITelemetryServiceConfig = {
					appender: combinedAppender(...appenders),
266
					commonProperties: resolveCommonProperties(product.commit, pkg.version, stateService.getItem('telemetry.machineId'), installSourcePath),
J
Joao Moreno 已提交
267 268
					piiPaths: [appRoot, extensionsPath]
				};
269

270
				services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));
J
Joao Moreno 已提交
271 272 273
			} else {
				services.set(ITelemetryService, NullTelemetryService);
			}
274

J
Joao Moreno 已提交
275 276
			const instantiationService2 = instantiationService.createChild(services);
			const main = instantiationService2.createInstance(Main);
277

278 279 280 281
			return main.run(argv).then(() => {
				// Dispose the AI adapter so that remaining data gets flushed.
				return combinedAppender(...appenders).dispose();
			});
J
Joao Moreno 已提交
282
		});
283
	});
J
Joao Moreno 已提交
284
}