extensionManagementService.ts 12.7 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, ILocalExtension, IGalleryExtension, IExtensionIdentity, IExtensionManifest, IGalleryVersion, IGalleryMetadata, InstallExtensionEvent, DidInstallExtensionEvent } 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

J
Joao Moreno 已提交
31
function parseManifest(raw: string): TPromise<{ manifest: IExtensionManifest; metadata: IGalleryMetadata; }> {
E
Erich Gamma 已提交
32 33
	return new Promise((c, e) => {
		try {
J
Joao Moreno 已提交
34 35 36 37
			const manifest = JSON.parse(raw);
			const metadata = manifest.__metadata || null;
			delete manifest.__metadata;
			c({ manifest, metadata });
E
Erich Gamma 已提交
38 39 40 41 42 43
		} catch (err) {
			e(new Error(nls.localize('invalidManifest', "Extension invalid: package.json is not a JSON file.")));
		}
	});
}

J
Joao Moreno 已提交
44
function validate(zipPath: string, extension?: IExtensionIdentity, version?: string): TPromise<IExtensionManifest> {
E
Erich Gamma 已提交
45 46
	return buffer(zipPath, 'extension/package.json')
		.then(buffer => parseManifest(buffer.toString('utf8')))
J
Joao Moreno 已提交
47
		.then(({ manifest }) => {
E
Erich Gamma 已提交
48 49 50 51 52 53 54 55 56
			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 已提交
57
				if (version !== manifest.version) {
E
Erich Gamma 已提交
58 59 60 61
					return Promise.wrapError(Error(nls.localize('invalidVersion', "Extension invalid: manifest version mismatch.")));
				}
			}

A
Alex Dima 已提交
62
			return TPromise.as(manifest);
E
Erich Gamma 已提交
63 64 65
		});
}

J
Joao Moreno 已提交
66
function getExtensionId(extension: IExtensionIdentity, version: string): string {
J
Joao Moreno 已提交
67
	return `${ extension.publisher }.${ extension.name }-${ version }`;
68 69
}

J
Joao Moreno 已提交
70
export class ExtensionManagementService implements IExtensionManagementService {
E
Erich Gamma 已提交
71

J
Joao Moreno 已提交
72
	serviceId = IExtensionManagementService;
E
Erich Gamma 已提交
73 74

	private extensionsPath: string;
75 76
	private obsoletePath: string;
	private obsoleteFileLimiter: Limiter<void>;
77
	private disposables: IDisposable[];
E
Erich Gamma 已提交
78

J
Joao Moreno 已提交
79 80
	private _onInstallExtension = new Emitter<InstallExtensionEvent>();
	onInstallExtension: Event<InstallExtensionEvent> = this._onInstallExtension.event;
E
Erich Gamma 已提交
81

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

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

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

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

J
Joao Moreno 已提交
99 100 101 102 103 104 105 106 107 108
		// 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 已提交
109 110
	}

J
Joao Moreno 已提交
111
	install(extension: IGalleryExtension): TPromise<void>;
J
Joao Moreno 已提交
112 113
	install(zipPath: string): TPromise<void>;
	install(arg: any): TPromise<void> {
E
Erich Gamma 已提交
114
		if (types.isString(arg)) {
J
Joao Moreno 已提交
115 116 117 118 119 120 121 122
			const zipPath = arg as string;

			return validate(zipPath).then(manifest => {
				const id = getExtensionId(manifest, manifest.version);
				this._onInstallExtension.fire({ id });

				return this.installValidExtension(zipPath, id);
			});
E
Erich Gamma 已提交
123 124
		}

J
Joao Moreno 已提交
125
		const extension = arg as IGalleryExtension;
J
Joao Moreno 已提交
126
		const id = getExtensionId(extension, extension.versions[0].version);
J
Joao Moreno 已提交
127
		this._onInstallExtension.fire({ id, gallery: extension });
J
Joao Moreno 已提交
128

J
Joao Moreno 已提交
129
		return this.isObsolete(id).then(obsolete => {
130
			if (obsolete) {
J
Joao Moreno 已提交
131
				return TPromise.wrapError<void>(new Error(nls.localize('restartCode', "Please restart Code before reinstalling {0}.", extension.displayName || extension.name)));
132 133 134 135
			}

			return this.installFromGallery(arg);
		});
E
Erich Gamma 已提交
136 137
	}

J
Joao Moreno 已提交
138 139
	private installFromGallery(extension: IGalleryExtension): TPromise<void> {
		return this.getLastValidExtensionVersion(extension).then(versionInfo => {
J
Joao Moreno 已提交
140 141 142
				const version = versionInfo.version;
				const url = versionInfo.downloadUrl;
				const headers = versionInfo.downloadHeaders;
J
Joao Moreno 已提交
143
				const zipPath = path.join(tmpdir(), extension.id);
J
Joao Moreno 已提交
144
				const id = getExtensionId(extension, version);
145 146 147 148 149
				const metadata = {
					id: extension.id,
					publisherId: extension.publisherId,
					publisherDisplayName: extension.publisherDisplayName
				};
J
Joao Moreno 已提交
150 151 152 153

				return this.request(url)
					.then(opts => assign(opts, { headers }))
					.then(opts => download(zipPath, opts))
J
Joao Moreno 已提交
154
					.then(() => validate(zipPath, extension, version))
155
					.then(() => this.installValidExtension(zipPath, id, metadata));
156
		});
E
Erich Gamma 已提交
157 158
	}

J
Joao Moreno 已提交
159
	private getLastValidExtensionVersion(extension: IGalleryExtension): TPromise<IGalleryVersion> {
J
Joao Moreno 已提交
160
		return this._getLastValidExtensionVersion(extension, extension.versions);
J
Joao Moreno 已提交
161 162 163
	}

	private _getLastValidExtensionVersion(extension: IGalleryExtension, versions: IGalleryVersion[]): TPromise<IGalleryVersion> {
164
		if (!versions.length) {
J
Joao Moreno 已提交
165
			return TPromise.wrapError(new Error(nls.localize('noCompatible', "Couldn't find a compatible version of {0} with this version of Code.", extension.displayName || extension.name)));
166 167 168 169 170 171 172 173
		}

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

178
				if (!isValidExtensionVersion(pkg.version, desc, [])) {
J
Joao Moreno 已提交
179
					return this._getLastValidExtensionVersion(extension, versions.slice(1));
180 181 182 183 184
				}

				return version;
			});
	}
J
Joao Moreno 已提交
185 186 187 188 189 190 191 192

	private installValidExtension(zipPath: string, id: string, metadata: IGalleryMetadata = null): TPromise<void> {
		const extensionPath = path.join(this.extensionsPath, id);
		const manifestPath = path.join(extensionPath, 'package.json');

		return extract(zipPath, extensionPath, { sourcePath: 'extension', overwrite: true })
			.then(() => pfs.readFile(manifestPath, 'utf8'))
			.then(raw => parseManifest(raw))
J
Joao Moreno 已提交
193 194 195 196 197 198 199
			.then(({ manifest }) => {
				const local: ILocalExtension = { id, manifest, metadata, path: extensionPath };
				const rawManifest = assign(manifest, { __metadata: metadata });

				return pfs.writeFile(manifestPath, JSON.stringify(rawManifest, null, '\t'))
					.then(() => this._onDidInstallExtension.fire({ id, local }));
			})
J
Joao Moreno 已提交
200
			.then<void>(null, error => { this._onDidInstallExtension.fire({ id, error }); return TPromise.wrapError(error); });
E
Erich Gamma 已提交
201 202
	}

J
Joao Moreno 已提交
203
	uninstall(extension: ILocalExtension): TPromise<void> {
J
Joao Moreno 已提交
204 205
		const id = extension.id;
		const extensionPath = path.join(this.extensionsPath, id);
E
Erich Gamma 已提交
206 207 208

		return pfs.exists(extensionPath)
			.then(exists => exists ? null : Promise.wrapError(new Error(nls.localize('notExists', "Could not find extension"))))
J
Joao Moreno 已提交
209
			.then(() => this._onUninstallExtension.fire(id))
J
Joao Moreno 已提交
210
			.then(() => this.setObsolete(id))
E
Erich Gamma 已提交
211
			.then(() => pfs.rimraf(extensionPath))
J
Joao Moreno 已提交
212
			.then(() => this.unsetObsolete(id))
J
Joao Moreno 已提交
213
			.then(() => this._onDidUninstallExtension.fire(id));
E
Erich Gamma 已提交
214 215
	}

J
Joao Moreno 已提交
216
	getInstalled(includeDuplicateVersions: boolean = false): TPromise<ILocalExtension[]> {
J
Joao Moreno 已提交
217 218 219 220 221 222
		const all = this.getAllInstalled();

		if (includeDuplicateVersions) {
			return all;
		}

A
Alex Dima 已提交
223
		return all.then(extensions => {
J
Joao Moreno 已提交
224 225
			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 已提交
226 227 228
		});
	}

J
Joao Moreno 已提交
229
	private getAllInstalled(): TPromise<ILocalExtension[]> {
E
Erich Gamma 已提交
230 231
		const limiter = new Limiter(10);

232 233 234
		return this.getObsoleteExtensions()
			.then(obsolete => {
				return pfs.readdir(this.extensionsPath)
J
Joao Moreno 已提交
235
					.then(extensions => extensions.filter(id => !obsolete[id]))
J
Joao Moreno 已提交
236
					.then<ILocalExtension[]>(extensionIds => Promise.join(extensionIds.map(id => {
J
Joao Moreno 已提交
237
						const extensionPath = path.join(this.extensionsPath, id);
238 239 240 241

						return limiter.queue(
							() => pfs.readFile(path.join(extensionPath, 'package.json'), 'utf8')
								.then(raw => parseManifest(raw))
J
Joao Moreno 已提交
242
								.then(({ manifest, metadata }) => ({ id, manifest, metadata, path: extensionPath }))
243 244 245 246 247
								.then(null, () => null)
						);
					})))
					.then(result => result.filter(a => !!a));
			});
E
Erich Gamma 已提交
248 249
	}

J
Joao Moreno 已提交
250
	removeDeprecatedExtensions(): TPromise<void> {
J
Joao Moreno 已提交
251
		const outdated = this.getOutdatedExtensionIds()
J
Joao Moreno 已提交
252
			.then(extensions => extensions.map(e => getExtensionId(e.manifest, e.manifest.version)));
253 254 255 256 257 258 259 260 261

		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 已提交
262
						.then(() => this.withObsoleteExtensions(obsolete => delete obsolete[id]));
263 264 265 266
				}));
			});
	}

J
Joao Moreno 已提交
267
	private getOutdatedExtensionIds(): TPromise<ILocalExtension[]> {
J
Joao Moreno 已提交
268 269 270
		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 已提交
271 272
	}

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

J
Joao Moreno 已提交
277
	private setObsolete(id: string): TPromise<void> {
J
Joao Moreno 已提交
278
		return this.withObsoleteExtensions(obsolete => assign(obsolete, { [id]: true }));
279 280
	}

J
Joao Moreno 已提交
281
	private unsetObsolete(id: string): TPromise<void> {
J
Joao Moreno 已提交
282
		return this.withObsoleteExtensions<void>(obsolete => delete obsolete[id]);
283 284 285
	}

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

J
Joao Moreno 已提交
289
	private withObsoleteExtensions<T>(fn: (obsolete: { [id:string]: boolean; }) => T): TPromise<T> {
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
		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);
		});
	}
307 308 309 310 311

	// 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 已提交
312 313 314
			// TODO@Joao we need a nice configuration service here!
			UserSettings.getValue(this.environmentService.userDataPath, 'http.proxy'),
			UserSettings.getValue(this.environmentService.userDataPath, 'http.proxyStrictSSL')
315 316 317 318 319 320 321 322 323 324
		]);

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

			return { url, agent, strictSSL };
		});
	}
325 326 327 328

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