extensionManagementService.ts 41.1 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10
/*---------------------------------------------------------------------------------------------
 *  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 * as path from 'path';
import * as pfs from 'vs/base/node/pfs';
11
import * as errors from 'vs/base/common/errors';
E
Erich Gamma 已提交
12
import { assign } from 'vs/base/common/objects';
13
import { toDisposable, Disposable } from 'vs/base/common/lifecycle';
S
Sandeep Somavarapu 已提交
14
import { flatten, distinct, coalesce } from 'vs/base/common/arrays';
E
Erich Gamma 已提交
15
import { extract, buffer } from 'vs/base/node/zip';
16
import { TPromise } from 'vs/base/common/winjs.base';
J
Johannes Rieken 已提交
17 18
import {
	IExtensionManagementService, IExtensionGalleryService, ILocalExtension,
19
	IGalleryExtension, IExtensionManifest, IGalleryMetadata,
J
Joao Moreno 已提交
20
	InstallExtensionEvent, DidInstallExtensionEvent, DidUninstallExtensionEvent, LocalExtensionType,
S
Sandeep Somavarapu 已提交
21
	StatisticType,
J
Joao Moreno 已提交
22 23
	IExtensionIdentifier,
	IReportedExtension
J
Joao Moreno 已提交
24
} from 'vs/platform/extensionManagement/common/extensionManagement';
S
Sandeep Somavarapu 已提交
25
import { getGalleryExtensionIdFromLocal, adoptToGalleryExtensionId, areSameExtensions, getGalleryExtensionId, groupByExtension, getMaliciousExtensionsSet, getLocalExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
26
import { localizeManifest } from '../common/extensionNls';
J
Joao Moreno 已提交
27
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
28
import { Limiter, always } from 'vs/base/common/async';
J
Joao Moreno 已提交
29
import Event, { Emitter } from 'vs/base/common/event';
J
Joao Moreno 已提交
30
import * as semver from 'semver';
J
João Moreno 已提交
31
import URI from 'vs/base/common/uri';
S
Sandeep Somavarapu 已提交
32
import pkg from 'vs/platform/node/package';
33
import { isMacintosh, isWindows } from 'vs/base/common/platform';
34
import { ILogService } from 'vs/platform/log/common/log';
35
import { ExtensionsManifestCache } from 'vs/platform/extensionManagement/node/extensionsManifestCache';
36
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
37
import Severity from 'vs/base/common/severity';
S
Sandeep Somavarapu 已提交
38
import { ExtensionsLifecycle } from 'vs/platform/extensionManagement/node/extensionLifecycle';
39
import { toErrorMessage } from 'vs/base/common/errorMessage';
E
Erich Gamma 已提交
40

J
Joao Moreno 已提交
41
const SystemExtensionsRoot = path.normalize(path.join(URI.parse(require.toUrl('')).fsPath, '..', 'extensions'));
42 43
const ERROR_SCANNING_SYS_EXTENSIONS = 'scanningSystem';
const ERROR_SCANNING_USER_EXTENSIONS = 'scanningUser';
44
const INSTALL_ERROR_UNSET_UNINSTALLED = 'unsetUninstalled';
S
Sandeep Somavarapu 已提交
45 46 47
const INSTALL_ERROR_INCOMPATIBLE = 'incompatible';
const INSTALL_ERROR_DOWNLOADING = 'downloading';
const INSTALL_ERROR_VALIDATING = 'validating';
48 49
const INSTALL_ERROR_GALLERY = 'gallery';
const INSTALL_ERROR_LOCAL = 'local';
50
const INSTALL_ERROR_EXTRACTING = 'extracting';
51
const INSTALL_ERROR_DELETING = 'deleting';
S
Sandeep Somavarapu 已提交
52 53
const INSTALL_ERROR_UNKNOWN = 'unknown';

54
export class ExtensionManagementError extends Error {
S
Sandeep Somavarapu 已提交
55 56 57 58
	constructor(message: string, readonly code: string) {
		super(message);
	}
}
J
Joao Moreno 已提交
59

J
Joao Moreno 已提交
60
function parseManifest(raw: string): TPromise<{ manifest: IExtensionManifest; metadata: IGalleryMetadata; }> {
61
	return new TPromise((c, e) => {
E
Erich Gamma 已提交
62
		try {
J
Joao Moreno 已提交
63 64 65 66
			const manifest = JSON.parse(raw);
			const metadata = manifest.__metadata || null;
			delete manifest.__metadata;
			c({ manifest, metadata });
E
Erich Gamma 已提交
67 68 69 70 71 72
		} catch (err) {
			e(new Error(nls.localize('invalidManifest', "Extension invalid: package.json is not a JSON file.")));
		}
	});
}

73
export function validateLocalExtension(zipPath: string): TPromise<IExtensionManifest> {
E
Erich Gamma 已提交
74 75
	return buffer(zipPath, 'extension/package.json')
		.then(buffer => parseManifest(buffer.toString('utf8')))
76
		.then(({ manifest }) => TPromise.as(manifest));
E
Erich Gamma 已提交
77 78
}

79 80 81 82 83
function readManifest(extensionPath: string): TPromise<{ manifest: IExtensionManifest; metadata: IGalleryMetadata; }> {
	const promises = [
		pfs.readFile(path.join(extensionPath, 'package.json'), 'utf8')
			.then(raw => parseManifest(raw)),
		pfs.readFile(path.join(extensionPath, 'package.nls.json'), 'utf8')
R
Ron Buckton 已提交
84
			.then(null, err => err.code !== 'ENOENT' ? TPromise.wrapError<string>(err) : '{}')
85 86 87 88 89 90 91 92 93 94 95
			.then(raw => JSON.parse(raw))
	];

	return TPromise.join<any>(promises).then(([{ manifest, metadata }, translations]) => {
		return {
			manifest: localizeManifest(manifest, translations),
			metadata
		};
	});
}

S
Sandeep Somavarapu 已提交
96 97 98
interface InstallableExtension {
	zipPath: string;
	id: string;
S
Sandeep Somavarapu 已提交
99
	metadata?: IGalleryMetadata;
S
Sandeep Somavarapu 已提交
100 101
}

102
export class ExtensionManagementService extends Disposable implements IExtensionManagementService {
E
Erich Gamma 已提交
103

104 105
	private static readonly RENAME_RETRY_TIME = 5 * 1000;

106
	_serviceBrand: any;
E
Erich Gamma 已提交
107 108

	private extensionsPath: string;
109 110
	private uninstalledPath: string;
	private uninstalledFileLimiter: Limiter<void>;
111
	private reportedExtensions: TPromise<IReportedExtension[]> | undefined;
J
Joao Moreno 已提交
112
	private lastReportTimestamp = 0;
113 114
	private readonly installingExtensions: Map<string, TPromise<ILocalExtension>> = new Map<string, TPromise<ILocalExtension>>();
	private readonly manifestCache: ExtensionsManifestCache;
S
Sandeep Somavarapu 已提交
115
	private readonly extensionLifecycle: ExtensionsLifecycle;
E
Erich Gamma 已提交
116

S
Sandeep Somavarapu 已提交
117 118
	private readonly _onInstallExtension = new Emitter<InstallExtensionEvent>();
	readonly onInstallExtension: Event<InstallExtensionEvent> = this._onInstallExtension.event;
E
Erich Gamma 已提交
119

S
Sandeep Somavarapu 已提交
120 121
	private readonly _onDidInstallExtension = new Emitter<DidInstallExtensionEvent>();
	readonly onDidInstallExtension: Event<DidInstallExtensionEvent> = this._onDidInstallExtension.event;
E
Erich Gamma 已提交
122

S
Sandeep Somavarapu 已提交
123 124 125
	private readonly _onUninstallExtension = new Emitter<IExtensionIdentifier>();
	readonly onUninstallExtension: Event<IExtensionIdentifier> = this._onUninstallExtension.event;

S
Sandeep Somavarapu 已提交
126 127
	private _onDidUninstallExtension = new Emitter<DidUninstallExtensionEvent>();
	onDidUninstallExtension: Event<DidUninstallExtensionEvent> = this._onDidUninstallExtension.event;
E
Erich Gamma 已提交
128 129

	constructor(
130
		@IEnvironmentService environmentService: IEnvironmentService,
131
		@IDialogService private dialogService: IDialogService,
132
		@IExtensionGalleryService private galleryService: IExtensionGalleryService,
J
Joao Moreno 已提交
133
		@ILogService private logService: ILogService
E
Erich Gamma 已提交
134
	) {
135
		super();
J
Joao Moreno 已提交
136
		this.extensionsPath = environmentService.extensionsPath;
137 138
		this.uninstalledPath = path.join(this.extensionsPath, '.obsolete');
		this.uninstalledFileLimiter = new Limiter(1);
139 140
		this._register(toDisposable(() => this.installingExtensions.clear()));
		this.manifestCache = this._register(new ExtensionsManifestCache(environmentService, this));
S
Sandeep Somavarapu 已提交
141
		this.extensionLifecycle = this._register(new ExtensionsLifecycle(this.logService));
A
Alex Dima 已提交
142 143
	}

S
Sandeep Somavarapu 已提交
144
	install(zipPath: string): TPromise<ILocalExtension> {
145 146
		zipPath = path.resolve(zipPath);

S
Sandeep Somavarapu 已提交
147
		return validateLocalExtension(zipPath)
S
Sandeep Somavarapu 已提交
148
			.then(manifest => {
S
Sandeep Somavarapu 已提交
149
				const identifier = { id: getLocalExtensionIdFromManifest(manifest) };
150 151
				return this.unsetUninstalledAndRemove(identifier.id)
					.then(
M
Matt Bierner 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
						() => this.checkOutdated(manifest)
							.then(validated => {
								if (validated) {
									this.logService.info('Installing the extension:', identifier.id);
									this._onInstallExtension.fire({ identifier, zipPath });
									return this.getMetadata(getGalleryExtensionId(manifest.publisher, manifest.name))
										.then(
											metadata => this.installFromZipPath(identifier, zipPath, metadata, manifest),
											error => this.installFromZipPath(identifier, zipPath, null, manifest))
										.then(
											local => { this.logService.info('Successfully installed the extension:', identifier.id); return local; },
											e => {
												this.logService.error('Failed to install the extension:', identifier.id, e.message);
												return TPromise.wrapError(e);
											});
								}
								return null;
							}),
						e => TPromise.wrapError(new Error(nls.localize('restartCode', "Please restart Code before reinstalling {0}.", manifest.displayName || manifest.name))));
171 172 173 174 175 176 177
			});
	}

	private unsetUninstalledAndRemove(id: string): TPromise<void> {
		return this.isUninstalled(id)
			.then(isUninstalled => {
				if (isUninstalled) {
178
					this.logService.trace('Removing the extension:', id);
179 180
					const extensionPath = path.join(this.extensionsPath, id);
					return pfs.rimraf(extensionPath)
181
						.then(() => this.unsetUninstalled(id))
182
						.then(() => this.logService.info('Removed the extension:', id));
183 184
				}
				return null;
S
Sandeep Somavarapu 已提交
185 186
			});
	}
187

S
Sandeep Somavarapu 已提交
188 189
	private checkOutdated(manifest: IExtensionManifest): TPromise<boolean> {
		const extensionIdentifier = { id: getGalleryExtensionId(manifest.publisher, manifest.name) };
190
		return this.getInstalled(LocalExtensionType.User)
S
Sandeep Somavarapu 已提交
191 192 193 194
			.then(installedExtensions => {
				const newer = installedExtensions.filter(local => areSameExtensions(extensionIdentifier, { id: getGalleryExtensionIdFromLocal(local) }) && semver.gt(local.manifest.version, manifest.version))[0];
				if (newer) {
					const message = nls.localize('installingOutdatedExtension', "A newer version of this extension is already installed. Would you like to override this with the older version?");
195
					const buttons = [
S
Sandeep Somavarapu 已提交
196 197 198
						nls.localize('override', "Override"),
						nls.localize('cancel', "Cancel")
					];
199
					return this.dialogService.show(Severity.Info, message, buttons, { cancelId: 1 })
S
Sandeep Somavarapu 已提交
200 201 202 203 204 205 206 207
						.then<boolean>(value => {
							if (value === 0) {
								return this.uninstall(newer, true).then(() => true);
							}
							return TPromise.wrapError(errors.canceled());
						});
				}
				return true;
208
			});
S
Sandeep Somavarapu 已提交
209 210
	}

S
Sandeep Somavarapu 已提交
211
	private installFromZipPath(identifier: IExtensionIdentifier, zipPath: string, metadata: IGalleryMetadata, manifest: IExtensionManifest): TPromise<ILocalExtension> {
S
Sandeep Somavarapu 已提交
212 213 214 215 216 217
		return this.installExtension({ zipPath, id: identifier.id, metadata })
			.then(local => {
				if (this.galleryService.isEnabled() && local.manifest.extensionDependencies && local.manifest.extensionDependencies.length) {
					return this.getDependenciesToInstall(local.manifest.extensionDependencies)
						.then(dependenciesToInstall => this.downloadAndInstallExtensions(metadata ? dependenciesToInstall.filter(d => d.identifier.uuid !== metadata.id) : dependenciesToInstall))
						.then(() => local, error => {
S
Sandeep Somavarapu 已提交
218
							this.uninstallExtension(local);
S
Sandeep Somavarapu 已提交
219
							return TPromise.wrapError(new Error(nls.localize('errorInstallingDependencies', "Error while installing dependencies. {0}", error instanceof Error ? error.message : error)));
S
Sandeep Somavarapu 已提交
220 221 222 223 224
						});
				}
				return local;
			})
			.then(
M
Matt Bierner 已提交
225 226
				local => { this._onDidInstallExtension.fire({ identifier, zipPath, local }); return local; },
				error => { this._onDidInstallExtension.fire({ identifier, zipPath, error }); return TPromise.wrapError(error); }
S
Sandeep Somavarapu 已提交
227
			);
E
Erich Gamma 已提交
228 229
	}

S
Sandeep Somavarapu 已提交
230
	installFromGallery(extension: IGalleryExtension): TPromise<ILocalExtension> {
S
Sandeep Somavarapu 已提交
231 232 233
		this.onInstallExtensions([extension]);
		return this.collectExtensionsToInstall(extension)
			.then(
M
Matt Bierner 已提交
234 235 236 237 238 239 240 241 242 243 244
				extensionsToInstall => {
					if (extensionsToInstall.length > 1) {
						this.onInstallExtensions(extensionsToInstall.slice(1));
					}
					return this.downloadAndInstallExtensions(extensionsToInstall)
						.then(
							locals => this.onDidInstallExtensions(extensionsToInstall, locals, [])
								.then(() => locals.filter(l => areSameExtensions({ id: getGalleryExtensionIdFromLocal(l), uuid: l.identifier.uuid }, extension.identifier)[0])),
							errors => this.onDidInstallExtensions(extensionsToInstall, [], errors));
				},
				error => this.onDidInstallExtensions([extension], [], [error]));
S
Sandeep Somavarapu 已提交
245 246
	}

S
Sandeep Somavarapu 已提交
247
	reinstall(extension: ILocalExtension): TPromise<ILocalExtension> {
S
Sandeep Somavarapu 已提交
248
		if (!this.galleryService.isEnabled()) {
249
			return TPromise.wrapError(new Error(nls.localize('MarketPlaceDisabled', "Marketplace is not enabled")));
S
Sandeep Somavarapu 已提交
250 251 252 253
		}
		return this.findGalleryExtension(extension)
			.then(galleryExtension => {
				if (galleryExtension) {
254 255 256
					return this.uninstallExtension(extension)
						.then(() => this.removeUninstalledExtension(extension)
							.then(
M
Matt Bierner 已提交
257 258
								() => this.installFromGallery(galleryExtension),
								e => TPromise.wrapError(new Error(nls.localize('removeError', "Error while removing the extension: {0}. Please Quit and Start VS Code before trying again.", toErrorMessage(e))))));
S
Sandeep Somavarapu 已提交
259
				}
260
				return TPromise.wrapError(new Error(nls.localize('Not a Marketplace extension', "Only Marketplace Extensions can be reinstalled")));
S
Sandeep Somavarapu 已提交
261 262 263
			});
	}

S
Sandeep Somavarapu 已提交
264 265 266 267
	private collectExtensionsToInstall(extension: IGalleryExtension): TPromise<IGalleryExtension[]> {
		return this.galleryService.loadCompatibleVersion(extension)
			.then(compatible => {
				if (!compatible) {
S
Sandeep Somavarapu 已提交
268
					return TPromise.wrapError<IGalleryExtension[]>(new ExtensionManagementError(nls.localize('notFoundCompatible', "Unable to install '{0}'; there is no available version compatible with VS Code '{1}'.", extension.identifier.id, pkg.version), INSTALL_ERROR_INCOMPATIBLE));
S
Sandeep Somavarapu 已提交
269 270 271
				}
				return this.getDependenciesToInstall(compatible.properties.dependencies)
					.then(
M
Matt Bierner 已提交
272 273
						dependenciesToInstall => ([compatible, ...dependenciesToInstall.filter(d => d.identifier.uuid !== compatible.identifier.uuid)]),
						error => TPromise.wrapError<IGalleryExtension[]>(new ExtensionManagementError(this.joinErrors(error).message, INSTALL_ERROR_GALLERY)));
S
Sandeep Somavarapu 已提交
274
			},
M
Matt Bierner 已提交
275
				error => TPromise.wrapError<IGalleryExtension[]>(new ExtensionManagementError(this.joinErrors(error).message, INSTALL_ERROR_GALLERY)));
276 277
	}

S
Sandeep Somavarapu 已提交
278
	private downloadAndInstallExtensions(extensions: IGalleryExtension[]): TPromise<ILocalExtension[]> {
S
Sandeep Somavarapu 已提交
279 280 281 282 283 284 285
		return TPromise.join(extensions.map(extensionToInstall => this.downloadAndInstallExtension(extensionToInstall)))
			.then(null, errors => this.rollback(extensions).then(() => TPromise.wrapError(errors), () => TPromise.wrapError(errors)));
	}

	private downloadAndInstallExtension(extension: IGalleryExtension): TPromise<ILocalExtension> {
		let installingExtension = this.installingExtensions.get(extension.identifier.id);
		if (!installingExtension) {
J
Joao Moreno 已提交
286
			installingExtension = this.getExtensionsReport()
J
Joao Moreno 已提交
287 288
				.then(report => {
					if (getMaliciousExtensionsSet(report).has(extension.identifier.id)) {
J
Joao Moreno 已提交
289
						throw new Error(nls.localize('malicious extension', "Can't install extension since it was reported to be problematic."));
J
Joao Moreno 已提交
290 291 292 293
					} else {
						return extension;
					}
				})
J
Joao Moreno 已提交
294
				.then(extension => this.downloadInstallableExtension(extension))
S
Sandeep Somavarapu 已提交
295 296
				.then(installableExtension => this.installExtension(installableExtension))
				.then(
M
Matt Bierner 已提交
297 298
					local => { this.installingExtensions.delete(extension.identifier.id); return local; },
					e => { this.installingExtensions.delete(extension.identifier.id); return TPromise.wrapError(e); }
S
Sandeep Somavarapu 已提交
299 300 301
				);

			this.installingExtensions.set(extension.identifier.id, installingExtension);
S
Sandeep Somavarapu 已提交
302 303
		}
		return installingExtension;
S
Sandeep Somavarapu 已提交
304 305
	}

S
Sandeep Somavarapu 已提交
306
	private downloadInstallableExtension(extension: IGalleryExtension): TPromise<InstallableExtension> {
S
Sandeep Somavarapu 已提交
307
		const metadata = <IGalleryMetadata>{
S
Sandeep Somavarapu 已提交
308
			id: extension.identifier.uuid,
S
Sandeep Somavarapu 已提交
309 310 311
			publisherId: extension.publisherId,
			publisherDisplayName: extension.publisherDisplayName,
		};
S
Sandeep Somavarapu 已提交
312 313 314

		return this.galleryService.loadCompatibleVersion(extension)
			.then(
M
Matt Bierner 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
				compatible => {
					if (compatible) {
						this.logService.trace('Started downloading extension:', extension.name);
						return this.galleryService.download(extension)
							.then(
								zipPath => {
									this.logService.info('Downloaded extension:', extension.name);
									return validateLocalExtension(zipPath)
										.then(
											manifest => (<InstallableExtension>{ zipPath, id: getLocalExtensionIdFromManifest(manifest), metadata }),
											error => TPromise.wrapError(new ExtensionManagementError(this.joinErrors(error).message, INSTALL_ERROR_VALIDATING))
										);
								},
								error => TPromise.wrapError(new ExtensionManagementError(this.joinErrors(error).message, INSTALL_ERROR_DOWNLOADING)));
					} else {
						return TPromise.wrapError<InstallableExtension>(new ExtensionManagementError(nls.localize('notFoundCompatibleDependency', "Unable to install because, the depending extension '{0}' compatible with current version '{1}' of VS Code is not found.", extension.identifier.id, pkg.version), INSTALL_ERROR_INCOMPATIBLE));
					}
				},
				error => TPromise.wrapError<InstallableExtension>(new ExtensionManagementError(this.joinErrors(error).message, INSTALL_ERROR_GALLERY)));
S
Sandeep Somavarapu 已提交
334 335 336 337
	}

	private onInstallExtensions(extensions: IGalleryExtension[]): void {
		for (const extension of extensions) {
338
			this.logService.info('Installing extension:', extension.name);
S
Sandeep Somavarapu 已提交
339
			const id = getLocalExtensionIdFromGallery(extension, extension.version);
S
Sandeep Somavarapu 已提交
340
			this._onInstallExtension.fire({ identifier: { id, uuid: extension.identifier.uuid }, gallery: extension });
341
		}
342 343
	}

344
	private onDidInstallExtensions(extensions: IGalleryExtension[], locals: ILocalExtension[], errors: Error[]): TPromise<any> {
S
Sandeep Somavarapu 已提交
345
		extensions.forEach((gallery, index) => {
S
Sandeep Somavarapu 已提交
346
			const identifier = { id: getLocalExtensionIdFromGallery(gallery, gallery.version), uuid: gallery.identifier.uuid };
347 348 349
			const local = locals[index];
			const error = errors[index];
			if (local) {
350
				this.logService.info(`Extensions installed successfully:`, gallery.identifier.id);
351
				this._onDidInstallExtension.fire({ identifier, gallery, local });
S
Sandeep Somavarapu 已提交
352
			} else {
353
				const errorCode = error && (<ExtensionManagementError>error).code ? (<ExtensionManagementError>error).code : INSTALL_ERROR_UNKNOWN;
354
				this.logService.error(`Failed to install extension:`, gallery.identifier.id, error ? error.message : errorCode);
355
				this._onDidInstallExtension.fire({ identifier, gallery, error: errorCode });
S
Sandeep Somavarapu 已提交
356 357
			}
		});
358
		return errors.length ? TPromise.wrapError(this.joinErrors(errors)) : TPromise.as(null);
359 360
	}

S
Sandeep Somavarapu 已提交
361
	private getDependenciesToInstall(dependencies: string[]): TPromise<IGalleryExtension[]> {
S
Sandeep Somavarapu 已提交
362
		if (dependencies.length) {
S
Sandeep Somavarapu 已提交
363 364 365 366 367 368 369 370 371 372 373 374
			return this.getInstalled()
				.then(installed => {
					const uninstalledDeps = dependencies.filter(d => installed.every(i => getGalleryExtensionId(i.manifest.publisher, i.manifest.name) !== d));
					if (uninstalledDeps.length) {
						return this.galleryService.loadAllDependencies(uninstalledDeps.map(id => (<IExtensionIdentifier>{ id })))
							.then(allDependencies => allDependencies.filter(d => {
								const extensionId = getLocalExtensionIdFromGallery(d, d.version);
								return installed.every(({ identifier }) => identifier.id !== extensionId);
							}));
					}
					return [];
				});
S
Sandeep Somavarapu 已提交
375 376
		}
		return TPromise.as([]);
377 378
	}

379 380 381
	private installExtension(installableExtension: InstallableExtension): TPromise<ILocalExtension> {
		return this.unsetUninstalledAndGetLocal(installableExtension.id)
			.then(
M
Matt Bierner 已提交
382 383 384 385 386 387 388 389 390 391 392 393
				local => {
					if (local) {
						return local;
					}
					return this.extractAndInstall(installableExtension);
				},
				e => {
					if (isMacintosh) {
						return TPromise.wrapError<ILocalExtension>(new ExtensionManagementError(nls.localize('quitCode', "Unable to install the extension. Please Quit and Start VS Code before reinstalling."), INSTALL_ERROR_UNSET_UNINSTALLED));
					}
					return TPromise.wrapError<ILocalExtension>(new ExtensionManagementError(nls.localize('exitCode', "Unable to install the extension. Please Exit and Start VS Code before reinstalling."), INSTALL_ERROR_UNSET_UNINSTALLED));
				});
394
	}
J
Joao Moreno 已提交
395

396 397 398 399
	private unsetUninstalledAndGetLocal(id: string): TPromise<ILocalExtension> {
		return this.isUninstalled(id)
			.then(isUninstalled => {
				if (isUninstalled) {
400
					this.logService.trace('Removing the extension from uninstalled list:', id);
401 402
					// If the same version of extension is marked as uninstalled, remove it from there and return the local.
					return this.unsetUninstalled(id)
403
						.then(() => {
404
							this.logService.info('Removed the extension from uninstalled list:', id);
405 406
							return this.getInstalled(LocalExtensionType.User);
						})
407 408 409 410 411 412
						.then(installed => installed.filter(i => i.identifier.id === id)[0]);
				}
				return null;
			});
	}

S
Sandeep Somavarapu 已提交
413
	private extractAndInstall({ zipPath, id, metadata }: InstallableExtension): TPromise<ILocalExtension> {
414 415 416 417 418 419 420 421 422 423 424
		const extractPath = path.join(this.extensionsPath, `.${id}`); // Extract to temp path
		return this.extract(id, zipPath, extractPath, { sourcePath: 'extension', overwrite: true })
			.then(() => this.completeInstall(id, extractPath))
			.then(() => this.scanExtension(id, this.extensionsPath, LocalExtensionType.User))
			.then(local => {
				if (metadata) {
					local.metadata = metadata;
					return this.saveMetadataForLocalExtension(local);
				}
				return local;
			});
E
Erich Gamma 已提交
425 426
	}

427 428 429 430
	private extract(id: string, zipPath: string, extractPath: string, options: any): TPromise<void> {
		this.logService.trace(`Started extracting the extension from ${zipPath} to ${extractPath}`);
		return pfs.rimraf(extractPath)
			.then(
M
Matt Bierner 已提交
431 432 433 434 435 436
				() => extract(zipPath, extractPath, options)
					.then(
						() => this.logService.info(`Extracted extension to ${extractPath}:`, id),
						e => always(pfs.rimraf(extractPath), () => null)
							.then(() => TPromise.wrapError(new ExtensionManagementError(e.message, INSTALL_ERROR_EXTRACTING)))),
				e => TPromise.wrapError(new ExtensionManagementError(this.joinErrors(e).message, INSTALL_ERROR_DELETING)));
437 438 439
	}

	private completeInstall(id: string, extractPath: string): TPromise<void> {
440
		return this.renameWithRetry(id, extractPath)
441
			.then(
M
Matt Bierner 已提交
442 443 444 445 446 447
				() => this.logService.info('Installation compelted.', id),
				e => {
					this.logService.info('Deleting the extracted extension', id);
					return always(pfs.rimraf(extractPath), () => null)
						.then(() => TPromise.wrapError(e));
				});
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
	}

	private renameWithRetry(id: string, extractPath: string): TPromise<void> {
		const retry = (task: () => TPromise<any>, shouldRetry: (err: any) => boolean) => {
			return task().then(
				null,
				err => {
					if (shouldRetry(err)) {
						return retry(task, shouldRetry);
					} else {
						throw err;
					}
				});
		};

		const retryUntil = Date.now() + ExtensionManagementService.RENAME_RETRY_TIME;
		return retry(
			() => pfs.rename(extractPath, path.join(this.extensionsPath, id)),
466
			err => isWindows && err && err.code === 'EPERM' && Date.now() < retryUntil);
S
Sandeep Somavarapu 已提交
467 468 469 470 471 472 473 474 475 476
	}

	private rollback(extensions: IGalleryExtension[]): TPromise<void> {
		return this.getInstalled(LocalExtensionType.User)
			.then(installed =>
				TPromise.join(installed.filter(local => extensions.some(galleryExtension => local.identifier.id === getLocalExtensionIdFromGallery(galleryExtension, galleryExtension.version))) // Only check id (pub.name-version) because we want to rollback the exact version
					.map(local => this.uninstallExtension(local))))
			.then(() => null, () => null);
	}

477
	uninstall(extension: ILocalExtension, force = false): TPromise<void> {
S
Sandeep Somavarapu 已提交
478 479 480 481 482 483 484
		return this.getInstalled(LocalExtensionType.User)
			.then(installed => {
				const promises = installed
					.filter(e => e.manifest.publisher === extension.manifest.publisher && e.manifest.name === extension.manifest.name)
					.map(e => this.checkForDependenciesAndUninstall(e, installed, force));
				return TPromise.join(promises).then(() => null, error => TPromise.wrapError(this.joinErrors(error)));
			});
S
Sandeep Somavarapu 已提交
485 486
	}

487 488
	updateMetadata(local: ILocalExtension, metadata: IGalleryMetadata): TPromise<ILocalExtension> {
		local.metadata = metadata;
489 490 491 492 493
		return this.saveMetadataForLocalExtension(local)
			.then(localExtension => {
				this.manifestCache.invalidate();
				return localExtension;
			});
494 495 496 497 498 499 500 501 502 503 504 505 506 507
	}

	private saveMetadataForLocalExtension(local: ILocalExtension): TPromise<ILocalExtension> {
		if (!local.metadata) {
			return TPromise.as(local);
		}
		const manifestPath = path.join(this.extensionsPath, local.identifier.id, 'package.json');
		return pfs.readFile(manifestPath, 'utf8')
			.then(raw => parseManifest(raw))
			.then(({ manifest }) => assign(manifest, { __metadata: local.metadata }))
			.then(manifest => pfs.writeFile(manifestPath, JSON.stringify(manifest, null, '\t')))
			.then(() => local);
	}

S
Sandeep Somavarapu 已提交
508
	private getMetadata(extensionName: string): TPromise<IGalleryMetadata> {
S
Sandeep Somavarapu 已提交
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
		return this.findGalleryExtensionByName(extensionName)
			.then(galleryExtension => galleryExtension ? <IGalleryMetadata>{ id: galleryExtension.identifier.uuid, publisherDisplayName: galleryExtension.publisherDisplayName, publisherId: galleryExtension.publisherId } : null);
	}

	private findGalleryExtension(local: ILocalExtension): TPromise<IGalleryExtension> {
		if (local.identifier.uuid) {
			return this.findGalleryExtensionById(local.identifier.uuid)
				.then(galleryExtension => galleryExtension ? galleryExtension : this.findGalleryExtensionByName(getGalleryExtensionIdFromLocal(local)));
		}
		return this.findGalleryExtensionByName(getGalleryExtensionIdFromLocal(local));
	}

	private findGalleryExtensionById(uuid: string): TPromise<IGalleryExtension> {
		return this.galleryService.query({ ids: [uuid], pageSize: 1 }).then(galleryResult => galleryResult.firstPage[0]);
	}

	private findGalleryExtensionByName(name: string): TPromise<IGalleryExtension> {
		return this.galleryService.query({ names: [name], pageSize: 1 }).then(galleryResult => galleryResult.firstPage[0]);
S
Sandeep Somavarapu 已提交
527 528
	}

529 530
	private joinErrors(errorOrErrors: (Error | string) | ((Error | string)[])): Error {
		const errors = Array.isArray(errorOrErrors) ? errorOrErrors : [errorOrErrors];
S
Sandeep Somavarapu 已提交
531 532 533 534
		if (errors.length === 1) {
			return errors[0] instanceof Error ? <Error>errors[0] : new Error(<string>errors[0]);
		}
		return errors.reduce<Error>((previousValue: Error, currentValue: Error | string) => {
S
Sandeep Somavarapu 已提交
535
			return new Error(`${previousValue.message}${previousValue.message ? ',' : ''}${currentValue instanceof Error ? currentValue.message : currentValue}`);
S
Sandeep Somavarapu 已提交
536
		}, new Error(''));
J
Joao Moreno 已提交
537 538
	}

539
	private checkForDependenciesAndUninstall(extension: ILocalExtension, installed: ILocalExtension[], force: boolean): TPromise<void> {
J
Joao Moreno 已提交
540
		return this.preUninstallExtension(extension)
541
			.then(() => this.hasDependencies(extension, installed) ? this.promptForDependenciesAndUninstall(extension, installed, force) : this.promptAndUninstall(extension, installed, force))
542
			.then(() => this.postUninstallExtension(extension),
M
Matt Bierner 已提交
543 544 545 546
				error => {
					this.postUninstallExtension(extension, INSTALL_ERROR_LOCAL);
					return TPromise.wrapError(error);
				});
S
Sandeep Somavarapu 已提交
547 548
	}

549 550
	private hasDependencies(extension: ILocalExtension, installed: ILocalExtension[]): boolean {
		if (extension.manifest.extensionDependencies && extension.manifest.extensionDependencies.length) {
S
Sandeep Somavarapu 已提交
551
			return installed.some(i => extension.manifest.extensionDependencies.indexOf(getGalleryExtensionIdFromLocal(i)) !== -1);
552 553 554 555
		}
		return false;
	}

556 557 558 559 560 561
	private promptForDependenciesAndUninstall(extension: ILocalExtension, installed: ILocalExtension[], force: boolean): TPromise<void> {
		if (force) {
			const dependencies = distinct(this.getDependenciesToUninstallRecursively(extension, installed, [])).filter(e => e !== extension);
			return this.uninstallWithDependencies(extension, dependencies, installed);
		}

562
		const message = nls.localize('uninstallDependeciesConfirmation', "Would you like to uninstall '{0}' only or its dependencies also?", extension.manifest.displayName || extension.manifest.name);
563
		const buttons = [
S
Sandeep Somavarapu 已提交
564 565 566 567
			nls.localize('uninstallOnly', "Only"),
			nls.localize('uninstallAll', "All"),
			nls.localize('cancel', "Cancel")
		];
568
		this.logService.info('Requesting for confirmation to uninstall extension with dependencies', extension.identifier.id);
569
		return this.dialogService.show(Severity.Info, message, buttons, { cancelId: 2 })
S
Sandeep Somavarapu 已提交
570 571
			.then<void>(value => {
				if (value === 0) {
572
					return this.uninstallWithDependencies(extension, [], installed);
S
Sandeep Somavarapu 已提交
573 574
				}
				if (value === 1) {
575 576
					const dependencies = distinct(this.getDependenciesToUninstallRecursively(extension, installed, [])).filter(e => e !== extension);
					return this.uninstallWithDependencies(extension, dependencies, installed);
S
Sandeep Somavarapu 已提交
577
				}
578
				this.logService.info('Cancelled uninstalling extension:', extension.identifier.id);
S
Sandeep Somavarapu 已提交
579 580 581 582
				return TPromise.wrapError(errors.canceled());
			}, error => TPromise.wrapError(errors.canceled()));
	}

583 584 585 586 587
	private promptAndUninstall(extension: ILocalExtension, installed: ILocalExtension[], force: boolean): TPromise<void> {
		if (force) {
			return this.uninstallWithDependencies(extension, [], installed);
		}

S
Sandeep Somavarapu 已提交
588
		const message = nls.localize('uninstallConfirmation', "Are you sure you want to uninstall '{0}'?", extension.manifest.displayName || extension.manifest.name);
589
		const buttons = [
D
David Hewson 已提交
590
			nls.localize('ok', "OK"),
S
Sandeep Somavarapu 已提交
591 592
			nls.localize('cancel', "Cancel")
		];
593
		this.logService.info('Requesting for confirmation to uninstall extension', extension.identifier.id);
594
		return this.dialogService.show(Severity.Info, message, buttons, { cancelId: 1 })
S
Sandeep Somavarapu 已提交
595 596 597 598
			.then<void>(value => {
				if (value === 0) {
					return this.uninstallWithDependencies(extension, [], installed);
				}
599
				this.logService.info('Cancelled uninstalling extension:', extension.identifier.id);
S
Sandeep Somavarapu 已提交
600 601 602 603
				return TPromise.wrapError(errors.canceled());
			}, error => TPromise.wrapError(errors.canceled()));
	}

604 605
	private uninstallWithDependencies(extension: ILocalExtension, dependencies: ILocalExtension[], installed: ILocalExtension[]): TPromise<void> {
		const dependenciesToUninstall = this.filterDependents(extension, dependencies, installed);
606
		let dependents = this.getDependents(extension, installed).filter(dependent => extension !== dependent && dependenciesToUninstall.indexOf(dependent) === -1);
607
		if (dependents.length) {
608
			return TPromise.wrapError<void>(new Error(this.getDependentsErrorMessage(extension, dependents)));
609
		}
S
Sandeep Somavarapu 已提交
610
		return TPromise.join([this.uninstallExtension(extension), ...dependenciesToUninstall.map(d => this.doUninstall(d))]).then(() => null);
611 612
	}

S
Sandeep Somavarapu 已提交
613 614 615 616 617 618 619 620 621 622 623 624 625
	private getDependentsErrorMessage(extension: ILocalExtension, dependents: ILocalExtension[]): string {
		if (dependents.length === 1) {
			return nls.localize('singleDependentError', "Cannot uninstall extension '{0}'. Extension '{1}' depends on this.",
				extension.manifest.displayName || extension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name);
		}
		if (dependents.length === 2) {
			return nls.localize('twoDependentsError', "Cannot uninstall extension '{0}'. Extensions '{1}' and '{2}' depend on this.",
				extension.manifest.displayName || extension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name, dependents[1].manifest.displayName || dependents[1].manifest.name);
		}
		return nls.localize('multipleDependentsError', "Cannot uninstall extension '{0}'. Extensions '{1}', '{2}' and others depend on this.",
			extension.manifest.displayName || extension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name, dependents[1].manifest.displayName || dependents[1].manifest.name);
	}

626 627 628 629 630 631 632 633
	private getDependenciesToUninstallRecursively(extension: ILocalExtension, installed: ILocalExtension[], checked: ILocalExtension[]): ILocalExtension[] {
		if (checked.indexOf(extension) !== -1) {
			return [];
		}
		checked.push(extension);
		if (!extension.manifest.extensionDependencies || extension.manifest.extensionDependencies.length === 0) {
			return [];
		}
S
Sandeep Somavarapu 已提交
634
		const dependenciesToUninstall = installed.filter(i => extension.manifest.extensionDependencies.indexOf(getGalleryExtensionIdFromLocal(i)) !== -1);
635 636 637 638 639 640 641 642 643 644 645 646
		const depsOfDeps = [];
		for (const dep of dependenciesToUninstall) {
			depsOfDeps.push(...this.getDependenciesToUninstallRecursively(dep, installed, checked));
		}
		return [...dependenciesToUninstall, ...depsOfDeps];
	}

	private filterDependents(extension: ILocalExtension, dependencies: ILocalExtension[], installed: ILocalExtension[]): ILocalExtension[] {
		installed = installed.filter(i => i !== extension && i.manifest.extensionDependencies && i.manifest.extensionDependencies.length > 0);
		let result = dependencies.slice(0);
		for (let i = 0; i < dependencies.length; i++) {
			const dep = dependencies[i];
647
			const dependents = this.getDependents(dep, installed).filter(e => dependencies.indexOf(e) === -1);
648 649 650
			if (dependents.length) {
				result.splice(i - (dependencies.length - result.length), 1);
			}
S
Sandeep Somavarapu 已提交
651
		}
652
		return result;
S
Sandeep Somavarapu 已提交
653 654
	}

655
	private getDependents(extension: ILocalExtension, installed: ILocalExtension[]): ILocalExtension[] {
S
Sandeep Somavarapu 已提交
656
		return installed.filter(e => e.manifest.extensionDependencies && e.manifest.extensionDependencies.indexOf(getGalleryExtensionIdFromLocal(extension)) !== -1);
657 658
	}

J
Joao Moreno 已提交
659 660
	private doUninstall(extension: ILocalExtension): TPromise<void> {
		return this.preUninstallExtension(extension)
S
Sandeep Somavarapu 已提交
661
			.then(() => this.uninstallExtension(extension))
662
			.then(() => this.postUninstallExtension(extension),
M
Matt Bierner 已提交
663 664 665 666
				error => {
					this.postUninstallExtension(extension, INSTALL_ERROR_LOCAL);
					return TPromise.wrapError(error);
				});
S
Sandeep Somavarapu 已提交
667
	}
E
Erich Gamma 已提交
668

J
Joao Moreno 已提交
669
	private preUninstallExtension(extension: ILocalExtension): TPromise<void> {
S
Sandeep Somavarapu 已提交
670
		return pfs.exists(extension.path)
671
			.then(exists => exists ? null : TPromise.wrapError(new Error(nls.localize('notExists', "Could not find extension"))))
672
			.then(() => {
673
				this.logService.info('Uninstalling extension:', extension.identifier.id);
674 675
				this._onUninstallExtension.fire(extension.identifier);
			});
S
Sandeep Somavarapu 已提交
676 677
	}

S
Sandeep Somavarapu 已提交
678
	private uninstallExtension(local: ILocalExtension): TPromise<void> {
S
Sandeep Somavarapu 已提交
679
		return this.setUninstalled(local.identifier.id);
S
Sandeep Somavarapu 已提交
680 681
	}

682
	private async postUninstallExtension(extension: ILocalExtension, error?: string): TPromise<void> {
683
		if (error) {
684
			this.logService.error('Failed to uninstall extension:', extension.identifier.id, error);
S
Sandeep Somavarapu 已提交
685 686
		} else {
			this.logService.info('Successfully uninstalled extension:', extension.identifier.id);
687 688 689 690
			// only report if extension has a mapped gallery extension. UUID identifies the gallery extension.
			if (extension.identifier.uuid) {
				await this.galleryService.reportStatistic(extension.manifest.publisher, extension.manifest.name, extension.manifest.version, StatisticType.Uninstall);
			}
691
		}
S
Sandeep Somavarapu 已提交
692
		this._onDidUninstallExtension.fire({ identifier: extension.identifier, error });
E
Erich Gamma 已提交
693 694
	}

J
Joao Moreno 已提交
695 696 697 698
	getInstalled(type: LocalExtensionType = null): TPromise<ILocalExtension[]> {
		const promises = [];

		if (type === null || type === LocalExtensionType.System) {
699
			promises.push(this.scanSystemExtensions().then(null, e => new ExtensionManagementError(this.joinErrors(e).message, ERROR_SCANNING_SYS_EXTENSIONS)));
J
Joao Moreno 已提交
700 701 702
		}

		if (type === null || type === LocalExtensionType.User) {
703
			promises.push(this.scanUserExtensions(true).then(null, e => new ExtensionManagementError(this.joinErrors(e).message, ERROR_SCANNING_USER_EXTENSIONS)));
J
Joao Moreno 已提交
704 705
		}

706
		return TPromise.join<ILocalExtension[]>(promises).then(flatten, errors => TPromise.wrapError<ILocalExtension[]>(this.joinErrors(errors)));
J
Joao Moreno 已提交
707 708 709
	}

	private scanSystemExtensions(): TPromise<ILocalExtension[]> {
710
		this.logService.trace('Started scanning system extensions');
711 712
		return this.scanExtensions(SystemExtensionsRoot, LocalExtensionType.System)
			.then(result => {
713
				this.logService.info('Scanned system extensions:', result.length);
714 715
				return result;
			});
J
Joao Moreno 已提交
716 717
	}

S
Sandeep Somavarapu 已提交
718
	private scanUserExtensions(excludeOutdated: boolean): TPromise<ILocalExtension[]> {
719
		this.logService.trace('Started scanning user extensions');
S
Sandeep Somavarapu 已提交
720 721 722
		return TPromise.join([this.getUninstalledExtensions(), this.scanExtensions(this.extensionsPath, LocalExtensionType.User)])
			.then(([uninstalled, extensions]) => {
				extensions = extensions.filter(e => !uninstalled[e.identifier.id]);
S
Sandeep Somavarapu 已提交
723 724
				if (excludeOutdated) {
					const byExtension: ILocalExtension[][] = groupByExtension(extensions, e => ({ id: getGalleryExtensionIdFromLocal(e), uuid: e.identifier.uuid }));
S
Sandeep Somavarapu 已提交
725
					extensions = byExtension.map(p => p.sort((a, b) => semver.rcompare(a.manifest.version, b.manifest.version))[0]);
S
Sandeep Somavarapu 已提交
726
				}
S
Sandeep Somavarapu 已提交
727
				this.logService.info('Scanned user extensions:', extensions.length);
S
Sandeep Somavarapu 已提交
728 729
				return extensions;
			});
J
Joao Moreno 已提交
730 731
	}

J
Joao Moreno 已提交
732
	private scanExtensions(root: string, type: LocalExtensionType): TPromise<ILocalExtension[]> {
E
Erich Gamma 已提交
733
		const limiter = new Limiter(10);
S
Sandeep Somavarapu 已提交
734 735 736 737
		return pfs.readdir(root)
			.then(extensionsFolders => TPromise.join(extensionsFolders.map(extensionFolder => limiter.queue(() => this.scanExtension(extensionFolder, root, type)))))
			.then(extensions => coalesce(extensions));
	}
E
Erich Gamma 已提交
738

S
Sandeep Somavarapu 已提交
739
	private scanExtension(folderName: string, root: string, type: LocalExtensionType): TPromise<ILocalExtension> {
740 741 742
		if (type === LocalExtensionType.User && folderName.indexOf('.') === 0) { // Do not consider user exension folder starting with `.`
			return TPromise.as(null);
		}
S
Sandeep Somavarapu 已提交
743 744 745 746
		const extensionPath = path.join(root, folderName);
		return pfs.readdir(extensionPath)
			.then(children => readManifest(extensionPath)
				.then<ILocalExtension>(({ manifest, metadata }) => {
J
Joao Moreno 已提交
747 748 749 750
					const readme = children.filter(child => /^readme(\.txt|\.md|)$/i.test(child))[0];
					const readmeUrl = readme ? URI.file(path.join(extensionPath, readme)).toString() : null;
					const changelog = children.filter(child => /^changelog(\.txt|\.md|)$/i.test(child))[0];
					const changelogUrl = changelog ? URI.file(path.join(extensionPath, changelog)).toString() : null;
S
Sandeep Somavarapu 已提交
751 752 753 754 755 756 757
					if (manifest.extensionDependencies) {
						manifest.extensionDependencies = manifest.extensionDependencies.map(id => adoptToGalleryExtensionId(id));
					}
					const identifier = { id: type === LocalExtensionType.System ? folderName : getLocalExtensionIdFromManifest(manifest), uuid: metadata ? metadata.id : null };
					return { type, identifier, manifest, metadata, path: extensionPath, readmeUrl, changelogUrl };
				}))
			.then(null, () => null);
E
Erich Gamma 已提交
758 759
	}

J
Joao Moreno 已提交
760
	removeDeprecatedExtensions(): TPromise<any> {
S
Sandeep Somavarapu 已提交
761 762 763 764 765
		return this.removeUninstalledExtensions()
			.then(() => this.removeOutdatedExtensions());
	}

	private removeUninstalledExtensions(): TPromise<void> {
766
		return this.getUninstalledExtensions()
S
Sandeep Somavarapu 已提交
767 768
			.then(uninstalled => this.scanExtensions(this.extensionsPath, LocalExtensionType.User) // All user extensions
				.then(extensions => {
S
Sandeep Somavarapu 已提交
769
					const toRemove: ILocalExtension[] = extensions.filter(e => uninstalled[e.identifier.id]);
770
					return TPromise.join(toRemove.map(e => this.extensionLifecycle.uninstall(e).then(() => this.removeUninstalledExtension(e))));
S
Sandeep Somavarapu 已提交
771 772 773
				})
			).then(() => null);
	}
S
Sandeep Somavarapu 已提交
774

S
Sandeep Somavarapu 已提交
775 776 777 778
	private removeOutdatedExtensions(): TPromise<void> {
		return this.scanExtensions(this.extensionsPath, LocalExtensionType.User) // All user extensions
			.then(extensions => {
				const toRemove: ILocalExtension[] = [];
S
Sandeep Somavarapu 已提交
779

S
Sandeep Somavarapu 已提交
780 781 782 783
				// Outdated extensions
				const byExtension: ILocalExtension[][] = groupByExtension(extensions, e => ({ id: getGalleryExtensionIdFromLocal(e), uuid: e.identifier.uuid }));
				toRemove.push(...flatten(byExtension.map(p => p.sort((a, b) => semver.rcompare(a.manifest.version, b.manifest.version)).slice(1))));

S
Sandeep Somavarapu 已提交
784
				return TPromise.join(toRemove.map(extension => this.removeExtension(extension, 'outdated')));
S
Sandeep Somavarapu 已提交
785 786 787 788
			}).then(() => null);
	}

	private removeUninstalledExtension(extension: ILocalExtension): TPromise<void> {
789
		return this.removeExtension(extension, 'uninstalled')
S
Sandeep Somavarapu 已提交
790 791 792 793
			.then(() => this.withUninstalledExtensions(uninstalled => delete uninstalled[extension.identifier.id]))
			.then(() => null);
	}

S
Sandeep Somavarapu 已提交
794
	private removeExtension(extension: ILocalExtension, type: string): TPromise<void> {
795 796
		this.logService.trace(`Deleting ${type} extension from disk`, extension.identifier.id);
		return pfs.rimraf(extension.path).then(() => this.logService.info('Deleted from disk', extension.identifier.id));
J
Joao Moreno 已提交
797 798
	}

799 800
	private isUninstalled(id: string): TPromise<boolean> {
		return this.filterUninstalled(id).then(uninstalled => uninstalled.length === 1);
801 802
	}

803 804 805
	private filterUninstalled(...ids: string[]): TPromise<string[]> {
		return this.withUninstalledExtensions(allUninstalled => {
			const uninstalled = [];
806
			for (const id of ids) {
807 808
				if (!!allUninstalled[id]) {
					uninstalled.push(id);
809 810
				}
			}
811
			return uninstalled;
812
		});
813 814
	}

S
Sandeep Somavarapu 已提交
815 816
	private setUninstalled(...ids: string[]): TPromise<void> {
		return this.withUninstalledExtensions(uninstalled => assign(uninstalled, ids.reduce((result, id) => { result[id] = true; return result; }, {})));
817 818
	}

819 820
	private unsetUninstalled(id: string): TPromise<void> {
		return this.withUninstalledExtensions<void>(uninstalled => delete uninstalled[id]);
821 822
	}

823 824
	private getUninstalledExtensions(): TPromise<{ [id: string]: boolean; }> {
		return this.withUninstalledExtensions(uninstalled => uninstalled);
825 826
	}

827 828
	private withUninstalledExtensions<T>(fn: (uninstalled: { [id: string]: boolean; }) => T): TPromise<T> {
		return this.uninstalledFileLimiter.queue(() => {
829
			let result: T = null;
830
			return pfs.readFile(this.uninstalledPath, 'utf8')
R
Ron Buckton 已提交
831
				.then(null, err => err.code === 'ENOENT' ? TPromise.as('{}') : TPromise.wrapError(err))
J
Johannes Rieken 已提交
832
				.then<{ [id: string]: boolean }>(raw => { try { return JSON.parse(raw); } catch (e) { return {}; } })
833 834 835 836
				.then(uninstalled => { result = fn(uninstalled); return uninstalled; })
				.then(uninstalled => {
					if (Object.keys(uninstalled).length === 0) {
						return pfs.rimraf(this.uninstalledPath);
837
					} else {
838 839
						const raw = JSON.stringify(uninstalled);
						return pfs.writeFile(this.uninstalledPath, raw);
840 841 842 843 844
					}
				})
				.then(() => result);
		});
	}
845

846 847
	getExtensionsReport(): TPromise<IReportedExtension[]> {
		const now = new Date().getTime();
J
Joao Moreno 已提交
848

849 850 851 852
		if (!this.reportedExtensions || now - this.lastReportTimestamp > 1000 * 60 * 5) { // 5 minute cache freshness
			this.reportedExtensions = this.updateReportCache();
			this.lastReportTimestamp = now;
		}
J
Joao Moreno 已提交
853

854
		return this.reportedExtensions;
J
Joao Moreno 已提交
855 856
	}

857
	private updateReportCache(): TPromise<IReportedExtension[]> {
J
Joao Moreno 已提交
858 859
		this.logService.trace('ExtensionManagementService.refreshReportedCache');

860
		return this.galleryService.getExtensionsReport()
J
Joao Moreno 已提交
861 862
			.then(result => {
				this.logService.trace(`ExtensionManagementService.refreshReportedCache - got ${result.length} reported extensions from service`);
863 864 865 866
				return result;
			}, err => {
				this.logService.trace('ExtensionManagementService.refreshReportedCache - failed to get extension report');
				return [];
J
Joao Moreno 已提交
867 868
			});
	}
E
Erich Gamma 已提交
869
}
S
Sandeep Somavarapu 已提交
870 871 872 873 874 875 876

export function getLocalExtensionIdFromGallery(extension: IGalleryExtension, version: string): string {
	return getLocalExtensionId(extension.identifier.id, version);
}

export function getLocalExtensionIdFromManifest(manifest: IExtensionManifest): string {
	return getLocalExtensionId(getGalleryExtensionId(manifest.publisher, manifest.name), manifest.version);
877
}