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

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

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

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

J
Joao Moreno 已提交
61 62 63
class Main {

	constructor(
64
		@IEnvironmentService private environmentService: IEnvironmentService,
J
Joao Moreno 已提交
65
		@IExtensionManagementService private extensionManagementService: IExtensionManagementService,
66 67
		@IExtensionGalleryService private extensionGalleryService: IExtensionGalleryService,
		@IDialogService private dialogService: IDialogService
J
Johannes Rieken 已提交
68
	) { }
J
Joao Moreno 已提交
69 70

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

73
		let returnPromise: TPromise<any>;
74
		if (argv['install-source']) {
75
			returnPromise = this.setInstallSource(argv['install-source']);
76
		} else if (argv['list-extensions']) {
77
			returnPromise = this.listExtensions(argv['show-versions']);
J
Joao Moreno 已提交
78
		} else if (argv['install-extension']) {
79
			const arg = argv['install-extension'];
J
Joao Moreno 已提交
80
			const args: string[] = typeof arg === 'string' ? [arg] : arg;
81
			returnPromise = this.installExtension(args, argv['force']);
J
Joao Moreno 已提交
82
		} else if (argv['uninstall-extension']) {
83 84
			const arg = argv['uninstall-extension'];
			const ids: string[] = typeof arg === 'string' ? [arg] : arg;
85
			returnPromise = this.uninstallExtension(ids);
J
Joao Moreno 已提交
86
		}
87
		return returnPromise || TPromise.as(null);
J
Joao Moreno 已提交
88
	}
J
Joao Moreno 已提交
89

90
	private setInstallSource(installSource: string): TPromise<any> {
91
		return writeFile(this.environmentService.installSourcePath, installSource.slice(0, 30));
92 93
	}

G
greams 已提交
94
	private listExtensions(showVersions: boolean): TPromise<any> {
J
Joao Moreno 已提交
95
		return this.extensionManagementService.getInstalled(LocalExtensionType.User).then(extensions => {
G
greams 已提交
96
			extensions.forEach(e => console.log(getId(e.manifest, showVersions)));
J
Joao Moreno 已提交
97 98 99
		});
	}

100
	private installExtension(extensions: string[], force: boolean): TPromise<any> {
101 102 103 104
		const vsixTasks: Task[] = extensions
			.filter(e => /\.vsix$/i.test(e))
			.map(id => () => {
				const extension = path.isAbsolute(id) ? id : path.join(process.cwd(), id);
105

106
				return this.extensionManagementService.install(URI.file(extension)).then(() => {
B
Benjamin Pasero 已提交
107
					console.log(localize('successVsixInstall', "Extension '{0}' was successfully installed!", getBaseLabel(extension)));
108 109 110 111 112 113 114
				}, error => {
					if (isPromiseCanceledError(error)) {
						console.log(localize('cancelVsixInstall', "Cancelled installing Extension '{0}'.", getBaseLabel(extension)));
						return null;
					} else {
						return TPromise.wrapError(error);
					}
115 116
				});
			});
J
Joao Moreno 已提交
117

118 119 120
		const galleryTasks: Task[] = extensions
			.filter(e => !/\.vsix$/i.test(e))
			.map(id => () => {
121 122
				return this.extensionManagementService.getInstalled(LocalExtensionType.User)
					.then(installed => this.extensionGalleryService.query({ names: [id], source: 'cli' })
123 124 125 126 127 128
						.then<IPager<IGalleryExtension>>(null, err => {
							if (err.responseText) {
								try {
									const response = JSON.parse(err.responseText);
									return TPromise.wrapError(response.message);
								} catch (e) {
J
Joao Moreno 已提交
129
									// noop
130
								}
J
Joao Moreno 已提交
131
							}
J
Joao Moreno 已提交
132
							return TPromise.wrapError(err);
133 134 135
						})
						.then(result => {
							const [extension] = result.firstPage;
J
Joao Moreno 已提交
136

137
							if (!extension) {
138
								return TPromise.wrapError(new Error(`${notFound(id)}\n${useId}`));
139
							}
J
Joao Moreno 已提交
140

141
							const [installedExtension] = installed.filter(e => areSameExtensions({ id: getGalleryExtensionIdFromLocal(e) }, { id }));
142
							if (installedExtension) {
143 144
								const outdated = semver.gt(extension.version, installedExtension.manifest.version);
								if (outdated) {
145
									if (force) {
S
Sandeep Somavarapu 已提交
146
										console.log(localize('updateMessage', "Updating the Extension '{0}' to a newer version {1}", id, extension.version));
147 148 149 150 151 152 153 154 155 156 157 158
										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 已提交
159
								} else {
160
									console.log(localize('alreadyInstalled', "Extension '{0}' is already installed.", id));
O
oriash93 已提交
161 162
									return TPromise.as(null);
								}
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

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
	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);
					}
				});
	}

189
	private uninstallExtension(extensions: string[]): TPromise<any> {
J
Joao Moreno 已提交
190
		async function getExtensionId(extensionDescription: string): Promise<string> {
191 192
			if (!/\.vsix$/i.test(extensionDescription)) {
				return extensionDescription;
193
			}
J
Joao Moreno 已提交
194

195
			const zipPath = path.isAbsolute(extensionDescription) ? extensionDescription : path.join(process.cwd(), extensionDescription);
196
			const manifest = await getManifest(zipPath);
197
			return getId(manifest);
198
		}
J
Joao Moreno 已提交
199

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

205 206 207
					if (!extension) {
						return TPromise.wrapError(new Error(`${notInstalled(id)}\n${useId}`));
					}
J
Joao Moreno 已提交
208

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

211 212 213
					return this.extensionManagementService.uninstall(extension, true)
						.then(() => console.log(localize('successUninstall', "Extension '{0}' was successfully uninstalled!", id)));
				});
J
Joao Moreno 已提交
214
			});
215
		}));
J
Joao Moreno 已提交
216
	}
J
Joao Moreno 已提交
217 218
}

219 220
const eventPrefix = 'monacoworkbench';

J
Joao Moreno 已提交
221 222
export function main(argv: ParsedArgs): TPromise<void> {
	const services = new ServiceCollection();
J
Joao Moreno 已提交
223 224

	const environmentService = new EnvironmentService(argv, process.execPath);
S
Sandeep Somavarapu 已提交
225
	const logService = createSpdLogService('cli', getLogLevel(environmentService), environmentService.logsPath);
226
	process.once('exit', () => logService.dispose());
J
Joao Moreno 已提交
227 228 229 230 231

	logService.info('main', argv);

	services.set(IEnvironmentService, environmentService);
	services.set(ILogService, logService);
232
	services.set(IStateService, new SyncDescriptor(StateService));
J
Joao Moreno 已提交
233 234

	const instantiationService: IInstantiationService = new InstantiationService(services);
235 236

	return instantiationService.invokeFunction(accessor => {
J
Joao Moreno 已提交
237
		const envService = accessor.get(IEnvironmentService);
238
		const stateService = accessor.get(IStateService);
239

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

J
Joao Moreno 已提交
243
			const services = new ServiceCollection();
244
			services.set(IConfigurationService, new SyncDescriptor(ConfigurationService));
J
Joao Moreno 已提交
245
			services.set(IRequestService, new SyncDescriptor(RequestService));
J
Joao Moreno 已提交
246 247
			services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService));
			services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService));
B
Benjamin Pasero 已提交
248
			services.set(IDialogService, new SyncDescriptor(CommandLineDialogService));
249

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

J
Joao Moreno 已提交
253
				if (product.aiConfig && product.aiConfig.asimovKey) {
254
					appenders.push(new AppInsightsAppender(eventPrefix, null, product.aiConfig.asimovKey, logService));
J
Joao Moreno 已提交
255
				}
256

J
Joao Moreno 已提交
257 258
				const config: ITelemetryServiceConfig = {
					appender: combinedAppender(...appenders),
259
					commonProperties: resolveCommonProperties(product.commit, pkg.version, stateService.getItem('telemetry.machineId'), installSourcePath),
J
Joao Moreno 已提交
260 261
					piiPaths: [appRoot, extensionsPath]
				};
262

263
				services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));
J
Joao Moreno 已提交
264 265 266
			} else {
				services.set(ITelemetryService, NullTelemetryService);
			}
267

J
Joao Moreno 已提交
268 269
			const instantiationService2 = instantiationService.createChild(services);
			const main = instantiationService2.createInstance(Main);
270

271 272 273 274
			return main.run(argv).then(() => {
				// Dispose the AI adapter so that remaining data gets flushed.
				return combinedAppender(...appenders).dispose();
			});
J
Joao Moreno 已提交
275
		});
276
	});
J
Joao Moreno 已提交
277
}