extensionManagementService.ts 12.0 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

import nls = require('vs/nls');
import { tmpdir } from 'os';
import * as path from 'path';
import types = require('vs/base/common/types');
import * as pfs from 'vs/base/node/pfs';
import { assign } from 'vs/base/common/objects';
14
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
J
Joao Moreno 已提交
15
import { flatten } from 'vs/base/common/arrays';
E
Erich Gamma 已提交
16 17
import { extract, buffer } from 'vs/base/node/zip';
import { Promise, TPromise } from 'vs/base/common/winjs.base';
J
Joao Moreno 已提交
18
import { IExtensionManagementService, IExtension, IGalleryExtension, IExtensionManifest, IGalleryVersion } from 'vs/platform/extensionManagement/common/extensionManagement';
19
import { download, json, IRequestOptions } from 'vs/base/node/request';
20
import { getProxyAgent } from 'vs/base/node/proxy';
J
Joao Moreno 已提交
21
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
22
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
E
Erich Gamma 已提交
23
import { Limiter } from 'vs/base/common/async';
J
Joao Moreno 已提交
24
import Event, { Emitter } from 'vs/base/common/event';
25
import { UserSettings } from 'vs/workbench/node/userSettings';
J
Joao Moreno 已提交
26
import * as semver from 'semver';
27
import { groupBy, values } from 'vs/base/common/collections';
28
import { isValidExtensionVersion } from 'vs/platform/extensions/node/extensionValidator';
J
Joao Moreno 已提交
29
import pkg from 'vs/platform/package';
E
Erich Gamma 已提交
30 31 32 33 34 35 36 37 38 39 40

function parseManifest(raw: string): TPromise<IExtensionManifest> {
	return new Promise((c, e) => {
		try {
			c(JSON.parse(raw));
		} catch (err) {
			e(new Error(nls.localize('invalidManifest', "Extension invalid: package.json is not a JSON file.")));
		}
	});
}

J
Joao Moreno 已提交
41
function validate(zipPath: string, extension?: IExtensionManifest, version = extension && extension.version): TPromise<IExtensionManifest> {
E
Erich Gamma 已提交
42 43 44 45 46 47 48 49 50 51 52 53
	return buffer(zipPath, 'extension/package.json')
		.then(buffer => parseManifest(buffer.toString('utf8')))
		.then(manifest => {
			if (extension) {
				if (extension.name !== manifest.name) {
					return Promise.wrapError(Error(nls.localize('invalidName', "Extension invalid: manifest name mismatch.")));
				}

				if (extension.publisher !== manifest.publisher) {
					return Promise.wrapError(Error(nls.localize('invalidPublisher', "Extension invalid: manifest publisher mismatch.")));
				}

J
Joao Moreno 已提交
54
				if (version !== manifest.version) {
E
Erich Gamma 已提交
55 56 57 58
					return Promise.wrapError(Error(nls.localize('invalidVersion', "Extension invalid: manifest version mismatch.")));
				}
			}

A
Alex Dima 已提交
59
			return TPromise.as(manifest);
E
Erich Gamma 已提交
60 61 62
		});
}

63
function getExtensionId(extension: IExtensionManifest, version = extension.version): string {
J
Joao Moreno 已提交
64
	return `${ extension.publisher }.${ extension.name }-${ version }`;
65 66
}

J
Joao Moreno 已提交
67
export class ExtensionManagementService implements IExtensionManagementService {
E
Erich Gamma 已提交
68

J
Joao Moreno 已提交
69
	serviceId = IExtensionManagementService;
E
Erich Gamma 已提交
70 71

	private extensionsPath: string;
72 73
	private obsoletePath: string;
	private obsoleteFileLimiter: Limiter<void>;
74
	private disposables: IDisposable[];
E
Erich Gamma 已提交
75

J
Joao Moreno 已提交
76 77
	private _onInstallExtension = new Emitter<string>();
	onInstallExtension: Event<string> = this._onInstallExtension.event;
E
Erich Gamma 已提交
78

J
Joao Moreno 已提交
79 80
	private _onDidInstallExtension = new Emitter<{ id: string; error?: Error; }>();
	onDidInstallExtension: Event<{ id: string; error?: Error; }> = this._onDidInstallExtension.event;
E
Erich Gamma 已提交
81

J
Joao Moreno 已提交
82 83
	private _onUninstallExtension = new Emitter<string>();
	onUninstallExtension: Event<string> = this._onUninstallExtension.event;
E
Erich Gamma 已提交
84

J
Joao Moreno 已提交
85 86
	private _onDidUninstallExtension = new Emitter<string>();
	onDidUninstallExtension: Event<string> = this._onDidUninstallExtension.event;
E
Erich Gamma 已提交
87 88

	constructor(
89 90
		@IEnvironmentService private environmentService: IEnvironmentService,
		@ITelemetryService telemetryService: ITelemetryService
E
Erich Gamma 已提交
91
	) {
J
Joao Moreno 已提交
92
		this.extensionsPath = environmentService.extensionsPath;
93 94
		this.obsoletePath = path.join(this.extensionsPath, '.obsolete');
		this.obsoleteFileLimiter = new Limiter(1);
95

J
Joao Moreno 已提交
96 97 98 99 100 101 102 103 104 105
		// this.disposables = [
		// 	this.onDidInstallExtension(({ extension, isUpdate, error }) => telemetryService.publicLog(
		// 		isUpdate ? 'extensionGallery2:update' : 'extensionGallery2:install',
		// 		assign(getTelemetryData(extension), { success: !error })
		// 	)),
		// 	this.onDidUninstallExtension(extension => telemetryService.publicLog(
		// 		'extensionGallery2:uninstall',
		// 		assign(getTelemetryData(extension), { success: true })
		// 	))
		// ];
E
Erich Gamma 已提交
106 107
	}

J
Joao Moreno 已提交
108
	install(extension: IGalleryExtension): TPromise<void>;
J
Joao Moreno 已提交
109 110
	install(zipPath: string): TPromise<void>;
	install(arg: any): TPromise<void> {
E
Erich Gamma 已提交
111 112 113 114
		if (types.isString(arg)) {
			return this.installFromZip(arg);
		}

J
Joao Moreno 已提交
115 116
		const extension = arg as IGalleryExtension;
		const { manifest } = extension;
J
Joao Moreno 已提交
117
		const id = getExtensionId(manifest);
J
Joao Moreno 已提交
118

J
Joao Moreno 已提交
119
		return this.isObsolete(id).then(obsolete => {
120
			if (obsolete) {
J
Joao Moreno 已提交
121
				return TPromise.wrapError<void>(new Error(nls.localize('restartCode', "Please restart Code before reinstalling {0}.", manifest.name)));
122 123 124 125
			}

			return this.installFromGallery(arg);
		});
E
Erich Gamma 已提交
126 127
	}

J
Joao Moreno 已提交
128 129
	private installFromGallery(extension: IGalleryExtension): TPromise<void> {
		const id = getExtensionId(extension.manifest);
E
Erich Gamma 已提交
130

J
Joao Moreno 已提交
131
		this._onInstallExtension.fire(id);
J
Joao Moreno 已提交
132

J
Joao Moreno 已提交
133
		return this.getLastValidExtensionVersion(extension).then(versionInfo => {
J
Joao Moreno 已提交
134 135 136
				const version = versionInfo.version;
				const url = versionInfo.downloadUrl;
				const headers = versionInfo.downloadHeaders;
J
Joao Moreno 已提交
137 138
				const zipPath = path.join(tmpdir(), extension.id);
				const extensionPath = path.join(this.extensionsPath, getExtensionId(extension.manifest, version));
J
Joao Moreno 已提交
139 140 141 142

				return this.request(url)
					.then(opts => assign(opts, { headers }))
					.then(opts => download(zipPath, opts))
J
Joao Moreno 已提交
143 144
					.then(() => validate(zipPath, extension.manifest, version))
					.then(manifest => extract(zipPath, extensionPath, { sourcePath: 'extension', overwrite: true }))
J
Joao Moreno 已提交
145 146
					.then(() => this._onDidInstallExtension.fire({ id }))
					.then<void>(null, error => { this._onDidInstallExtension.fire({ id, error }); return TPromise.wrapError(error); });
147
		});
E
Erich Gamma 已提交
148 149
	}

J
Joao Moreno 已提交
150
	private getLastValidExtensionVersion(extension: IGalleryExtension): TPromise<IGalleryVersion> {
J
Joao Moreno 已提交
151
		return this._getLastValidExtensionVersion(extension, extension.metadata.versions);
J
Joao Moreno 已提交
152 153 154
	}

	private _getLastValidExtensionVersion(extension: IGalleryExtension, versions: IGalleryVersion[]): TPromise<IGalleryVersion> {
155
		if (!versions.length) {
J
Joao Moreno 已提交
156
			return TPromise.wrapError(new Error(nls.localize('noCompatible', "Couldn't find a compatible version of {0} with this version of Code.", extension.manifest.displayName)));
157 158 159 160 161 162 163 164
		}

		const version = versions[0];
		return this.request(version.manifestUrl)
			.then(opts => json<IExtensionManifest>(opts))
			.then(manifest => {
				const desc = {
					isBuiltin: false,
J
Joao Moreno 已提交
165 166
					engines: { vscode: manifest.engines.vscode },
					main: manifest.main
167 168
				};

169
				if (!isValidExtensionVersion(pkg.version, desc, [])) {
J
Joao Moreno 已提交
170
					return this._getLastValidExtensionVersion(extension, versions.slice(1));
171 172 173 174 175 176
				}

				return version;
			});
	}

J
Joao Moreno 已提交
177
	private installFromZip(zipPath: string): TPromise<void> {
E
Erich Gamma 已提交
178
		return validate(zipPath).then(manifest => {
J
Joao Moreno 已提交
179
			const id = getExtensionId(manifest);
J
Joao Moreno 已提交
180
			const extensionPath = path.join(this.extensionsPath, id);
J
Joao Moreno 已提交
181
			this._onInstallExtension.fire(id);
E
Erich Gamma 已提交
182

J
Joao Moreno 已提交
183
			return extract(zipPath, extensionPath, { sourcePath: 'extension', overwrite: true })
J
Joao Moreno 已提交
184
				.then(() => this._onDidInstallExtension.fire({ id }))
J
Joao Moreno 已提交
185
				.then<void>(null, error => { this._onDidInstallExtension.fire({ id, error }); return TPromise.wrapError(error); });
E
Erich Gamma 已提交
186 187 188
		});
	}

J
Joao Moreno 已提交
189
	uninstall(extension: IExtension): TPromise<void> {
J
Joao Moreno 已提交
190 191
		const id = extension.id;
		const extensionPath = path.join(this.extensionsPath, id);
E
Erich Gamma 已提交
192 193 194

		return pfs.exists(extensionPath)
			.then(exists => exists ? null : Promise.wrapError(new Error(nls.localize('notExists', "Could not find extension"))))
J
Joao Moreno 已提交
195
			.then(() => this._onUninstallExtension.fire(id))
J
Joao Moreno 已提交
196
			.then(() => this.setObsolete(id))
E
Erich Gamma 已提交
197
			.then(() => pfs.rimraf(extensionPath))
J
Joao Moreno 已提交
198
			.then(() => this.unsetObsolete(id))
J
Joao Moreno 已提交
199
			.then(() => this._onDidUninstallExtension.fire(id));
E
Erich Gamma 已提交
200 201
	}

J
Joao Moreno 已提交
202
	getInstalled(includeDuplicateVersions: boolean = false): TPromise<IExtension[]> {
J
Joao Moreno 已提交
203 204 205 206 207 208
		const all = this.getAllInstalled();

		if (includeDuplicateVersions) {
			return all;
		}

A
Alex Dima 已提交
209
		return all.then(extensions => {
J
Joao Moreno 已提交
210 211
			const byId = values(groupBy(extensions, p => `${ p.manifest.publisher }.${ p.manifest.name }`));
			return byId.map(p => p.sort((a, b) => semver.rcompare(a.manifest.version, b.manifest.version))[0]);
J
Joao Moreno 已提交
212 213 214 215
		});
	}

	private getAllInstalled(): TPromise<IExtension[]> {
E
Erich Gamma 已提交
216 217
		const limiter = new Limiter(10);

218 219 220
		return this.getObsoleteExtensions()
			.then(obsolete => {
				return pfs.readdir(this.extensionsPath)
J
Joao Moreno 已提交
221 222 223
					.then(extensions => extensions.filter(id => !obsolete[id]))
					.then<IExtension[]>(extensionIds => Promise.join(extensionIds.map(id => {
						const extensionPath = path.join(this.extensionsPath, id);
224 225 226 227

						return limiter.queue(
							() => pfs.readFile(path.join(extensionPath, 'package.json'), 'utf8')
								.then(raw => parseManifest(raw))
J
Joao Moreno 已提交
228
								.then<IExtension>(manifest => ({ id, manifest }))
229 230 231 232 233
								.then(null, () => null)
						);
					})))
					.then(result => result.filter(a => !!a));
			});
E
Erich Gamma 已提交
234 235
	}

J
Joao Moreno 已提交
236
	removeDeprecatedExtensions(): TPromise<void> {
J
Joao Moreno 已提交
237 238
		const outdated = this.getOutdatedExtensionIds()
			.then(extensions => extensions.map(e => getExtensionId(e.manifest)));
239 240 241 242 243 244 245 246 247

		const obsolete = this.getObsoleteExtensions()
			.then(obsolete => Object.keys(obsolete));

		return TPromise.join([outdated, obsolete])
			.then(result => flatten(result))
			.then<void>(extensionsIds => {
				return TPromise.join(extensionsIds.map(id => {
					return pfs.rimraf(path.join(this.extensionsPath, id))
J
Joao Moreno 已提交
248
						.then(() => this.withObsoleteExtensions(obsolete => delete obsolete[id]));
249 250 251 252
				}));
			});
	}

J
Joao Moreno 已提交
253 254 255 256
	private getOutdatedExtensionIds(): TPromise<IExtension[]> {
		return this.getAllInstalled()
			.then(extensions => values(groupBy(extensions, p => `${ p.manifest.publisher }.${ p.manifest.name }`)))
			.then(versions => flatten(versions.map(p => p.sort((a, b) => semver.rcompare(a.manifest.version, b.manifest.version)).slice(1))));
J
Joao Moreno 已提交
257 258
	}

J
Joao Moreno 已提交
259
	private isObsolete(id: string): TPromise<boolean> {
260 261 262
		return this.withObsoleteExtensions(obsolete => !!obsolete[id]);
	}

J
Joao Moreno 已提交
263
	private setObsolete(id: string): TPromise<void> {
J
Joao Moreno 已提交
264
		return this.withObsoleteExtensions(obsolete => assign(obsolete, { [id]: true }));
265 266
	}

J
Joao Moreno 已提交
267
	private unsetObsolete(id: string): TPromise<void> {
J
Joao Moreno 已提交
268
		return this.withObsoleteExtensions<void>(obsolete => delete obsolete[id]);
269 270 271
	}

	private getObsoleteExtensions(): TPromise<{ [id:string]: boolean; }> {
J
Joao Moreno 已提交
272
		return this.withObsoleteExtensions(obsolete => obsolete);
273 274
	}

J
Joao Moreno 已提交
275
	private withObsoleteExtensions<T>(fn: (obsolete: { [id:string]: boolean; }) => T): TPromise<T> {
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
		return this.obsoleteFileLimiter.queue(() => {
			let result: T = null;
			return pfs.readFile(this.obsoletePath, 'utf8')
				.then(null, err => err.code === 'ENOENT' ? TPromise.as('{}') : TPromise.wrapError(err))
				.then<{ [id: string]: boolean }>(raw => JSON.parse(raw))
				.then(obsolete => { result = fn(obsolete); return obsolete; })
				.then(obsolete => {
					if (Object.keys(obsolete).length === 0) {
						return pfs.rimraf(this.obsoletePath);
					} else {
						const raw = JSON.stringify(obsolete);
						return pfs.writeFile(this.obsoletePath, raw);
					}
				})
				.then(() => result);
		});
	}
293 294 295 296 297

	// Helper for proxy business... shameful.
	// This should be pushed down and not rely on the context service
	private request(url: string): TPromise<IRequestOptions> {
		const settings = TPromise.join([
J
Joao Moreno 已提交
298 299 300
			// TODO@Joao we need a nice configuration service here!
			UserSettings.getValue(this.environmentService.userDataPath, 'http.proxy'),
			UserSettings.getValue(this.environmentService.userDataPath, 'http.proxyStrictSSL')
301 302 303 304 305 306 307 308 309 310
		]);

		return settings.then(settings => {
			const proxyUrl: string = settings[0];
			const strictSSL: boolean = settings[1];
			const agent = getProxyAgent(url, { proxyUrl, strictSSL });

			return { url, agent, strictSSL };
		});
	}
311 312 313 314

	dispose() {
		this.disposables = dispose(this.disposables);
	}
E
Erich Gamma 已提交
315
}