cliProcessMain.ts 11.5 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
import { IPager } from 'vs/base/common/paging';
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, validateLocalExtension } 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';
39
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
B
Benjamin Pasero 已提交
40
import { CommandLineDialogService } from 'vs/platform/dialogs/node/dialogService';
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
}

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

J
Joao Moreno 已提交
56 57 58
class Main {

	constructor(
59
		@IEnvironmentService private environmentService: IEnvironmentService,
J
Joao Moreno 已提交
60 61
		@IExtensionManagementService private extensionManagementService: IExtensionManagementService,
		@IExtensionGalleryService private extensionGalleryService: IExtensionGalleryService
J
Johannes Rieken 已提交
62
	) { }
J
Joao Moreno 已提交
63 64

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

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

84
	private setInstallSource(installSource: string): TPromise<any> {
85
		return writeFile(this.environmentService.installSourcePath, installSource.slice(0, 30));
86 87
	}

G
greams 已提交
88
	private listExtensions(showVersions: boolean): TPromise<any> {
J
Joao Moreno 已提交
89
		return this.extensionManagementService.getInstalled(LocalExtensionType.User).then(extensions => {
G
greams 已提交
90
			extensions.forEach(e => console.log(getId(e.manifest, showVersions)));
J
Joao Moreno 已提交
91 92 93
		});
	}

94 95 96 97 98
	private installExtension(extensions: string[]): TPromise<any> {
		const vsixTasks: Task[] = extensions
			.filter(e => /\.vsix$/i.test(e))
			.map(id => () => {
				const extension = path.isAbsolute(id) ? id : path.join(process.cwd(), id);
99

100
				return this.extensionManagementService.install(extension).then(() => {
B
Benjamin Pasero 已提交
101
					console.log(localize('successVsixInstall', "Extension '{0}' was successfully installed!", getBaseLabel(extension)));
102 103 104 105 106 107 108
				}, error => {
					if (isPromiseCanceledError(error)) {
						console.log(localize('cancelVsixInstall', "Cancelled installing Extension '{0}'.", getBaseLabel(extension)));
						return null;
					} else {
						return TPromise.wrapError(error);
					}
109 110
				});
			});
J
Joao Moreno 已提交
111

112 113 114
		const galleryTasks: Task[] = extensions
			.filter(e => !/\.vsix$/i.test(e))
			.map(id => () => {
J
Joao Moreno 已提交
115
				return this.extensionManagementService.getInstalled(LocalExtensionType.User).then(installed => {
116 117 118 119 120 121 122
					const isInstalled = installed.some(e => getId(e.manifest) === id);

					if (isInstalled) {
						console.log(localize('alreadyInstalled', "Extension '{0}' is already installed.", id));
						return TPromise.as(null);
					}

123
					return this.extensionGalleryService.query({ names: [id], source: 'cli' })
124 125 126 127 128 129
						.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 已提交
130
									// noop
131
								}
J
Joao Moreno 已提交
132
							}
J
Joao Moreno 已提交
133 134

							return TPromise.wrapError(err);
135 136 137
						})
						.then(result => {
							const [extension] = result.firstPage;
J
Joao Moreno 已提交
138

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

143 144 145 146 147 148 149 150 151 152 153 154
							const installedExtension = installed.filter(e => getId(e.manifest) === id)[0];
							const installedVersion = installedExtension.manifest.version;
							const newestVersion = extension.version;
							const shouldUpdate = installedVersion !== newestVersion;

							if (shouldUpdate) {
								console.log(localize('foundNewerVersion', "Installed version is '{0}', found newer version '{1}' in the marketplace.", installedVersion, newestVersion));
								console.log(localize('updating', "Updating..."));
							} else {
								console.log(localize('foundExtension', "Found '{0}' in the marketplace.", id));
								console.log(localize('installing', "Installing..."));
							}
J
Joao Moreno 已提交
155

S
Sandeep Somavarapu 已提交
156
							return this.extensionManagementService.installFromGallery(extension)
157
								.then(
M
Matt Bierner 已提交
158 159 160 161 162 163 164 165 166
									() => 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);
										}
									});
J
Joao Moreno 已提交
167
						});
168
				});
169
			});
170 171

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

174
	private uninstallExtension(extensions: string[]): TPromise<any> {
175 176 177
		async function getExtensionId(extensionDescription: string): TPromise<string> {
			if (!/\.vsix$/i.test(extensionDescription)) {
				return extensionDescription;
178
			}
J
Joao Moreno 已提交
179

180 181 182
			const zipPath = path.isAbsolute(extensionDescription) ? extensionDescription : path.join(process.cwd(), extensionDescription);
			const manifest = await validateLocalExtension(zipPath);
			return getId(manifest);
183
		}
J
Joao Moreno 已提交
184

185
		return sequence(extensions.map(extension => () => {
186
			return getExtensionId(extension).then(id => {
187 188
				return this.extensionManagementService.getInstalled(LocalExtensionType.User).then(installed => {
					const [extension] = installed.filter(e => getId(e.manifest) === id);
J
Joao Moreno 已提交
189

190 191 192
					if (!extension) {
						return TPromise.wrapError(new Error(`${notInstalled(id)}\n${useId}`));
					}
J
Joao Moreno 已提交
193

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

196 197 198
					return this.extensionManagementService.uninstall(extension, true)
						.then(() => console.log(localize('successUninstall', "Extension '{0}' was successfully uninstalled!", id)));
				});
J
Joao Moreno 已提交
199
			});
200
		}));
J
Joao Moreno 已提交
201
	}
J
Joao Moreno 已提交
202 203
}

204 205
const eventPrefix = 'monacoworkbench';

J
Joao Moreno 已提交
206 207
export function main(argv: ParsedArgs): TPromise<void> {
	const services = new ServiceCollection();
J
Joao Moreno 已提交
208 209

	const environmentService = new EnvironmentService(argv, process.execPath);
S
Sandeep Somavarapu 已提交
210
	const logService = createSpdLogService('cli', getLogLevel(environmentService), environmentService.logsPath);
211
	process.once('exit', () => logService.dispose());
J
Joao Moreno 已提交
212 213 214 215 216

	logService.info('main', argv);

	services.set(IEnvironmentService, environmentService);
	services.set(ILogService, logService);
217
	services.set(IStateService, new SyncDescriptor(StateService));
J
Joao Moreno 已提交
218 219

	const instantiationService: IInstantiationService = new InstantiationService(services);
220 221

	return instantiationService.invokeFunction(accessor => {
J
Joao Moreno 已提交
222
		const envService = accessor.get(IEnvironmentService);
223
		const stateService = accessor.get(IStateService);
224

D
Daniel Imms 已提交
225
		return TPromise.join([envService.appSettingsHome, envService.extensionsPath].map(p => mkdirp(p))).then(() => {
226
			const { appRoot, extensionsPath, extensionDevelopmentPath, isBuilt, installSourcePath } = envService;
227

J
Joao Moreno 已提交
228
			const services = new ServiceCollection();
229
			services.set(IConfigurationService, new SyncDescriptor(ConfigurationService));
J
Joao Moreno 已提交
230
			services.set(IRequestService, new SyncDescriptor(RequestService));
J
Joao Moreno 已提交
231 232
			services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService));
			services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService));
B
Benjamin Pasero 已提交
233
			services.set(IDialogService, new SyncDescriptor(CommandLineDialogService));
234

235
			const appenders: AppInsightsAppender[] = [];
236
			if (isBuilt && !extensionDevelopmentPath && !envService.args['disable-telemetry'] && product.enableTelemetry) {
237

J
Joao Moreno 已提交
238 239 240
				if (product.aiConfig && product.aiConfig.asimovKey) {
					appenders.push(new AppInsightsAppender(eventPrefix, null, product.aiConfig.asimovKey));
				}
241

J
Joao Moreno 已提交
242 243
				const config: ITelemetryServiceConfig = {
					appender: combinedAppender(...appenders),
244
					commonProperties: resolveCommonProperties(product.commit, pkg.version, stateService.getItem('telemetry.machineId'), installSourcePath),
J
Joao Moreno 已提交
245 246
					piiPaths: [appRoot, extensionsPath]
				};
247

J
Joao Moreno 已提交
248 249 250 251
				services.set(ITelemetryService, new SyncDescriptor(TelemetryService, config));
			} else {
				services.set(ITelemetryService, NullTelemetryService);
			}
252

J
Joao Moreno 已提交
253 254
			const instantiationService2 = instantiationService.createChild(services);
			const main = instantiationService2.createInstance(Main);
255

256 257 258 259
			return main.run(argv).then(() => {
				// Dispose the AI adapter so that remaining data gets flushed.
				return combinedAppender(...appenders).dispose();
			});
J
Joao Moreno 已提交
260
		});
261
	});
J
Joao Moreno 已提交
262
}