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

'use strict';

8
import * as nls from 'vs/nls';
E
Erich Gamma 已提交
9 10
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';
14
import { flatten } from 'vs/base/common/arrays';
15
import { extract, buffer, ExtractError, zip, IFile } from 'vs/base/node/zip';
16
import { TPromise, ValueCallback, ErrorCallback } 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
	IExtensionIdentifier,
23
	IReportedExtension,
24
	InstallOperation
J
Joao Moreno 已提交
25
} from 'vs/platform/extensionManagement/common/extensionManagement';
S
Sandeep Somavarapu 已提交
26
import { getGalleryExtensionIdFromLocal, adoptToGalleryExtensionId, areSameExtensions, getGalleryExtensionId, groupByExtension, getMaliciousExtensionsSet, getLocalExtensionId, getGalleryExtensionTelemetryData, getLocalExtensionTelemetryData, getIdFromLocalExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
27
import { localizeManifest } from '../common/extensionNls';
J
Joao Moreno 已提交
28
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
29
import { Limiter, always } from 'vs/base/common/async';
M
Matt Bierner 已提交
30
import { Event, Emitter } from 'vs/base/common/event';
J
Joao Moreno 已提交
31
import * as semver from 'semver';
J
João Moreno 已提交
32
import URI from 'vs/base/common/uri';
S
Sandeep Somavarapu 已提交
33
import pkg from 'vs/platform/node/package';
34
import { isMacintosh, isWindows } from 'vs/base/common/platform';
35
import { ILogService } from 'vs/platform/log/common/log';
36
import { ExtensionsManifestCache } from 'vs/platform/extensionManagement/node/extensionsManifestCache';
37
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
38
import Severity from 'vs/base/common/severity';
S
Sandeep Somavarapu 已提交
39
import { ExtensionsLifecycle } from 'vs/platform/extensionManagement/node/extensionLifecycle';
40
import { toErrorMessage } from 'vs/base/common/errorMessage';
41
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
S
Sandeep Somavarapu 已提交
42
import { isEngineValid } from 'vs/platform/extensions/node/extensionValidator';
43 44 45
import { tmpdir } from 'os';
import { generateUuid } from 'vs/base/common/uuid';
import { IDownloadService } from 'vs/platform/download/common/download';
46
import { optional } from 'vs/platform/instantiation/common/instantiation';
E
Erich Gamma 已提交
47

48 49
const ERROR_SCANNING_SYS_EXTENSIONS = 'scanningSystem';
const ERROR_SCANNING_USER_EXTENSIONS = 'scanningUser';
50
const INSTALL_ERROR_UNSET_UNINSTALLED = 'unsetUninstalled';
S
Sandeep Somavarapu 已提交
51 52 53
const INSTALL_ERROR_INCOMPATIBLE = 'incompatible';
const INSTALL_ERROR_DOWNLOADING = 'downloading';
const INSTALL_ERROR_VALIDATING = 'validating';
54 55
const INSTALL_ERROR_GALLERY = 'gallery';
const INSTALL_ERROR_LOCAL = 'local';
56
const INSTALL_ERROR_EXTRACTING = 'extracting';
S
Sandeep Somavarapu 已提交
57
const INSTALL_ERROR_RENAMING = 'renaming';
58
const INSTALL_ERROR_DELETING = 'deleting';
59
const INSTALL_ERROR_MALICIOUS = 'malicious';
60
const ERROR_UNKNOWN = 'unknown';
S
Sandeep Somavarapu 已提交
61

62
export class ExtensionManagementError extends Error {
S
Sandeep Somavarapu 已提交
63 64 65 66
	constructor(message: string, readonly code: string) {
		super(message);
	}
}
J
Joao Moreno 已提交
67

J
Joao Moreno 已提交
68
function parseManifest(raw: string): TPromise<{ manifest: IExtensionManifest; metadata: IGalleryMetadata; }> {
69
	return new TPromise((c, e) => {
E
Erich Gamma 已提交
70
		try {
J
Joao Moreno 已提交
71 72 73 74
			const manifest = JSON.parse(raw);
			const metadata = manifest.__metadata || null;
			delete manifest.__metadata;
			c({ manifest, metadata });
E
Erich Gamma 已提交
75 76 77 78 79 80
		} catch (err) {
			e(new Error(nls.localize('invalidManifest', "Extension invalid: package.json is not a JSON file.")));
		}
	});
}

81
export function validateLocalExtension(zipPath: string): TPromise<IExtensionManifest> {
E
Erich Gamma 已提交
82 83
	return buffer(zipPath, 'extension/package.json')
		.then(buffer => parseManifest(buffer.toString('utf8')))
84
		.then(({ manifest }) => TPromise.as(manifest));
E
Erich Gamma 已提交
85 86
}

87 88 89 90 91
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 已提交
92
			.then(null, err => err.code !== 'ENOENT' ? TPromise.wrapError<string>(err) : '{}')
93 94 95 96 97 98 99 100 101 102 103
			.then(raw => JSON.parse(raw))
	];

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

S
Sandeep Somavarapu 已提交
104 105 106
interface InstallableExtension {
	zipPath: string;
	id: string;
S
Sandeep Somavarapu 已提交
107
	metadata?: IGalleryMetadata;
S
Sandeep Somavarapu 已提交
108 109
}

110
export class ExtensionManagementService extends Disposable implements IExtensionManagementService {
E
Erich Gamma 已提交
111

112
	_serviceBrand: any;
E
Erich Gamma 已提交
113

114
	private systemExtensionsPath: string;
E
Erich Gamma 已提交
115
	private extensionsPath: string;
116 117
	private uninstalledPath: string;
	private uninstalledFileLimiter: Limiter<void>;
118
	private reportedExtensions: TPromise<IReportedExtension[]> | undefined;
J
Joao Moreno 已提交
119
	private lastReportTimestamp = 0;
120
	private readonly installingExtensions: Map<string, TPromise<void>> = new Map<string, TPromise<void>>();
S
Sandeep Somavarapu 已提交
121
	private readonly uninstallingExtensions: Map<string, TPromise<void>> = new Map<string, TPromise<void>>();
122
	private readonly manifestCache: ExtensionsManifestCache;
S
Sandeep Somavarapu 已提交
123
	private readonly extensionLifecycle: ExtensionsLifecycle;
E
Erich Gamma 已提交
124

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

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

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

S
Sandeep Somavarapu 已提交
134 135
	private _onDidUninstallExtension = new Emitter<DidUninstallExtensionEvent>();
	onDidUninstallExtension: Event<DidUninstallExtensionEvent> = this._onDidUninstallExtension.event;
E
Erich Gamma 已提交
136 137

	constructor(
138
		@IEnvironmentService environmentService: IEnvironmentService,
139
		@IDialogService private dialogService: IDialogService,
140
		@IExtensionGalleryService private galleryService: IExtensionGalleryService,
141
		@ILogService private logService: ILogService,
142
		@optional(IDownloadService) private downloadService: IDownloadService,
143
		@ITelemetryService private telemetryService: ITelemetryService,
E
Erich Gamma 已提交
144
	) {
145
		super();
146
		this.systemExtensionsPath = environmentService.builtinExtensionsPath;
J
Joao Moreno 已提交
147
		this.extensionsPath = environmentService.extensionsPath;
148 149
		this.uninstalledPath = path.join(this.extensionsPath, '.obsolete');
		this.uninstalledFileLimiter = new Limiter(1);
150
		this.manifestCache = this._register(new ExtensionsManifestCache(environmentService, this));
S
Sandeep Somavarapu 已提交
151
		this.extensionLifecycle = this._register(new ExtensionsLifecycle(this.logService));
S
Sandeep Somavarapu 已提交
152 153 154 155 156 157 158

		this._register(toDisposable(() => {
			this.installingExtensions.forEach(promise => promise.cancel());
			this.uninstallingExtensions.forEach(promise => promise.cancel());
			this.installingExtensions.clear();
			this.uninstallingExtensions.clear();
		}));
A
Alex Dima 已提交
159 160
	}

161
	zip(extension: ILocalExtension): TPromise<URI> {
S
Sandeep Somavarapu 已提交
162
		return TPromise.wrap(this.collectFiles(extension))
163 164 165 166
			.then(files => zip(path.join(tmpdir(), generateUuid()), files))
			.then(path => URI.file(path));
	}

167
	unzip(zipLocation: URI, type: LocalExtensionType): TPromise<IExtensionIdentifier> {
168 169 170
		if (!this.downloadService) {
			throw new Error('Download service is not available');
		}
171
		const downloadedLocation = path.join(tmpdir(), generateUuid());
172
		return this.downloadService.download(zipLocation, downloadedLocation).then(() => this.install(URI.file(downloadedLocation), type));
173 174
	}

S
Sandeep Somavarapu 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
	private collectFiles(extension: ILocalExtension): Promise<IFile[]> {

		const collectFilesFromDirectory = async (dir): Promise<string[]> => {
			let entries = await pfs.readdir(dir);
			entries = entries.map(e => path.join(dir, e));
			const stats = await Promise.all(entries.map(e => pfs.stat(e)));
			let promise: Promise<string[]> = Promise.resolve([]);
			stats.forEach((stat, index) => {
				const entry = entries[index];
				if (stat.isFile()) {
					promise = promise.then(result => ([...result, entry]));
				}
				if (stat.isDirectory()) {
					promise = promise
						.then(result => collectFilesFromDirectory(entry)
							.then(files => ([...result, ...files])));
191 192
				}
			});
S
Sandeep Somavarapu 已提交
193 194 195 196 197 198
			return promise;
		};

		return collectFilesFromDirectory(extension.location.fsPath)
			.then(files => files.map(f => (<IFile>{ path: `extension/${path.relative(extension.location.fsPath, f)}`, localPath: f })));

199 200
	}

201
	install(vsix: URI, type: LocalExtensionType = LocalExtensionType.User): TPromise<IExtensionIdentifier> {
202
		const zipPath = path.resolve(vsix.fsPath);
203

S
Sandeep Somavarapu 已提交
204
		return validateLocalExtension(zipPath)
S
Sandeep Somavarapu 已提交
205
			.then(manifest => {
S
Sandeep Somavarapu 已提交
206
				const identifier = { id: getLocalExtensionIdFromManifest(manifest) };
S
Sandeep Somavarapu 已提交
207
				if (manifest.engines && manifest.engines.vscode && !isEngineValid(manifest.engines.vscode)) {
208
					return TPromise.wrapError<IExtensionIdentifier>(new Error(nls.localize('incompatible', "Unable to install Extension '{0}' as it is not compatible with Code '{1}'.", identifier.id, pkg.version)));
S
Sandeep Somavarapu 已提交
209
				}
S
Sandeep Somavarapu 已提交
210
				return this.removeIfExists(identifier.id)
211
					.then(
M
Matt Bierner 已提交
212 213 214 215 216 217 218
						() => 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(
219 220
											metadata => this.installFromZipPath(identifier, zipPath, metadata, type),
											error => this.installFromZipPath(identifier, zipPath, null, type))
M
Matt Bierner 已提交
221
										.then(
222
											() => { this.logService.info('Successfully installed the extension:', identifier.id); return identifier; },
M
Matt Bierner 已提交
223 224 225 226 227 228 229 230
											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))));
231 232 233
			});
	}

S
Sandeep Somavarapu 已提交
234 235 236 237
	private removeIfExists(id: string): TPromise<void> {
		return this.getInstalled(LocalExtensionType.User)
			.then(installed => installed.filter(i => i.identifier.id === id)[0])
			.then(existing => existing ? this.removeExtension(existing, 'existing') : null);
S
Sandeep Somavarapu 已提交
238
	}
239

S
Sandeep Somavarapu 已提交
240 241
	private checkOutdated(manifest: IExtensionManifest): TPromise<boolean> {
		const extensionIdentifier = { id: getGalleryExtensionId(manifest.publisher, manifest.name) };
242
		return this.getInstalled(LocalExtensionType.User)
S
Sandeep Somavarapu 已提交
243 244 245 246
			.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?");
247
					const buttons = [
S
Sandeep Somavarapu 已提交
248 249 250
						nls.localize('override', "Override"),
						nls.localize('cancel', "Cancel")
					];
251
					return this.dialogService.show(Severity.Info, message, buttons, { cancelId: 1 })
S
Sandeep Somavarapu 已提交
252 253 254 255 256 257 258 259
						.then<boolean>(value => {
							if (value === 0) {
								return this.uninstall(newer, true).then(() => true);
							}
							return TPromise.wrapError(errors.canceled());
						});
				}
				return true;
260
			});
S
Sandeep Somavarapu 已提交
261 262
	}

263
	private installFromZipPath(identifier: IExtensionIdentifier, zipPath: string, metadata: IGalleryMetadata, type: LocalExtensionType): TPromise<ILocalExtension> {
S
Sandeep Somavarapu 已提交
264
		return this.toNonCancellablePromise(this.getInstalled()
S
Sandeep Somavarapu 已提交
265 266
			.then(installed => {
				const operation = this.getOperation({ id: getIdFromLocalExtensionId(identifier.id), uuid: identifier.uuid }, installed);
267
				return this.installExtension({ zipPath, id: identifier.id, metadata }, type)
268
					.then(local => this.installDependenciesAndPackExtensions(local, null).then(() => local, error => this.uninstall(local, true).then(() => TPromise.wrapError(error), () => TPromise.wrapError(error))))
S
Sandeep Somavarapu 已提交
269 270 271 272
					.then(
						local => { this._onDidInstallExtension.fire({ identifier, zipPath, local, operation }); return local; },
						error => { this._onDidInstallExtension.fire({ identifier, zipPath, operation, error }); return TPromise.wrapError(error); }
					);
S
Sandeep Somavarapu 已提交
273
			}));
E
Erich Gamma 已提交
274 275
	}

S
Sandeep Somavarapu 已提交
276
	installFromGallery(extension: IGalleryExtension): TPromise<void> {
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
		let installingExtension = this.installingExtensions.get(extension.identifier.id);
		if (!installingExtension) {

			let successCallback: ValueCallback<void>, errorCallback: ErrorCallback;
			installingExtension = new TPromise((c, e) => { successCallback = c; errorCallback = e; });
			this.installingExtensions.set(extension.identifier.id, installingExtension);

			try {
				const startTime = new Date().getTime();
				const identifier = { id: getLocalExtensionIdFromGallery(extension, extension.version), uuid: extension.identifier.uuid };
				const telemetryData = getGalleryExtensionTelemetryData(extension);
				let operation: InstallOperation = InstallOperation.Install;

				this.logService.info('Installing extension:', extension.name);
				this._onInstallExtension.fire({ identifier, gallery: extension });

				this.checkMalicious(extension)
					.then(() => this.getInstalled(LocalExtensionType.User))
					.then(installed => {
						const existingExtension = installed.filter(i => areSameExtensions(i.galleryIdentifier, extension.identifier))[0];
						operation = existingExtension ? InstallOperation.Update : InstallOperation.Install;
						return this.downloadInstallableExtension(extension, operation)
299
							.then(installableExtension => this.installExtension(installableExtension, LocalExtensionType.User).then(local => always(pfs.rimraf(installableExtension.zipPath), () => null).then(() => local)))
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
							.then(local => this.installDependenciesAndPackExtensions(local, existingExtension)
								.then(() => local, error => this.uninstall(local, true).then(() => TPromise.wrapError(error), () => TPromise.wrapError(error))));
					})
					.then(
						local => {
							this.installingExtensions.delete(extension.identifier.id);
							this.logService.info(`Extensions installed successfully:`, extension.identifier.id);
							this._onDidInstallExtension.fire({ identifier, gallery: extension, local, operation });
							this.reportTelemetry(this.getTelemetryEvent(operation), telemetryData, new Date().getTime() - startTime, void 0);
							successCallback(null);
						},
						error => {
							this.installingExtensions.delete(extension.identifier.id);
							const errorCode = error && (<ExtensionManagementError>error).code ? (<ExtensionManagementError>error).code : ERROR_UNKNOWN;
							this.logService.error(`Failed to install extension:`, extension.identifier.id, error ? error.message : errorCode);
							this._onDidInstallExtension.fire({ identifier, gallery: extension, operation, error: errorCode });
							this.reportTelemetry(this.getTelemetryEvent(operation), telemetryData, new Date().getTime() - startTime, error);
							errorCallback(error);
						});

			} catch (error) {
				this.installingExtensions.delete(extension.identifier.id);
				errorCallback(error);
			}

		}
		return installingExtension;
S
Sandeep Somavarapu 已提交
327 328
	}

S
Sandeep Somavarapu 已提交
329
	reinstallFromGallery(extension: ILocalExtension): TPromise<void> {
S
Sandeep Somavarapu 已提交
330
		if (!this.galleryService.isEnabled()) {
331
			return TPromise.wrapError(new Error(nls.localize('MarketPlaceDisabled', "Marketplace is not enabled")));
S
Sandeep Somavarapu 已提交
332 333 334 335
		}
		return this.findGalleryExtension(extension)
			.then(galleryExtension => {
				if (galleryExtension) {
S
Sandeep Somavarapu 已提交
336
					return this.setUninstalled(extension)
337 338
						.then(() => this.removeUninstalledExtension(extension)
							.then(
M
Matt Bierner 已提交
339 340
								() => 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 已提交
341
				}
342
				return TPromise.wrapError(new Error(nls.localize('Not a Marketplace extension', "Only Marketplace Extensions can be reinstalled")));
S
Sandeep Somavarapu 已提交
343 344 345
			});
	}

S
Sandeep Somavarapu 已提交
346 347
	private getOperation(extensionToInstall: IExtensionIdentifier, installed: ILocalExtension[]): InstallOperation {
		return installed.some(i => areSameExtensions({ id: getGalleryExtensionIdFromLocal(i), uuid: i.identifier.uuid }, extensionToInstall)) ? InstallOperation.Update : InstallOperation.Install;
S
Sandeep Somavarapu 已提交
348 349
	}

350 351
	private getTelemetryEvent(operation: InstallOperation): string {
		return operation === InstallOperation.Update ? 'extensionGallery:update' : 'extensionGallery:install';
S
Sandeep Somavarapu 已提交
352 353
	}

354 355 356 357 358 359 360 361 362
	private checkMalicious(extension: IGalleryExtension): TPromise<void> {
		return this.getExtensionsReport()
			.then(report => {
				if (getMaliciousExtensionsSet(report).has(extension.identifier.id)) {
					throw new ExtensionManagementError(INSTALL_ERROR_MALICIOUS, nls.localize('malicious extension', "Can't install extension since it was reported to be problematic."));
				} else {
					return null;
				}
			});
S
Sandeep Somavarapu 已提交
363 364
	}

S
Sandeep Somavarapu 已提交
365
	private downloadInstallableExtension(extension: IGalleryExtension, operation: InstallOperation): TPromise<InstallableExtension> {
S
Sandeep Somavarapu 已提交
366
		const metadata = <IGalleryMetadata>{
S
Sandeep Somavarapu 已提交
367
			id: extension.identifier.uuid,
S
Sandeep Somavarapu 已提交
368 369 370
			publisherId: extension.publisherId,
			publisherDisplayName: extension.publisherDisplayName,
		};
S
Sandeep Somavarapu 已提交
371 372 373

		return this.galleryService.loadCompatibleVersion(extension)
			.then(
M
Matt Bierner 已提交
374 375 376
				compatible => {
					if (compatible) {
						this.logService.trace('Started downloading extension:', extension.name);
377
						return this.galleryService.download(extension, operation)
M
Matt Bierner 已提交
378 379
							.then(
								zipPath => {
S
Sandeep Somavarapu 已提交
380
									this.logService.info('Downloaded extension:', extension.name, zipPath);
M
Matt Bierner 已提交
381 382 383 384 385 386 387 388 389 390 391 392
									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 已提交
393 394
	}

395
	private installExtension(installableExtension: InstallableExtension, type: LocalExtensionType): TPromise<ILocalExtension> {
396 397
		return this.unsetUninstalledAndGetLocal(installableExtension.id)
			.then(
M
Matt Bierner 已提交
398 399 400 401
				local => {
					if (local) {
						return local;
					}
402
					return this.extractAndInstall(installableExtension, type);
M
Matt Bierner 已提交
403 404 405 406 407 408 409
				},
				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));
				});
410
	}
J
Joao Moreno 已提交
411

412 413 414 415
	private unsetUninstalledAndGetLocal(id: string): TPromise<ILocalExtension> {
		return this.isUninstalled(id)
			.then(isUninstalled => {
				if (isUninstalled) {
416
					this.logService.trace('Removing the extension from uninstalled list:', id);
417 418
					// If the same version of extension is marked as uninstalled, remove it from there and return the local.
					return this.unsetUninstalled(id)
419
						.then(() => {
420
							this.logService.info('Removed the extension from uninstalled list:', id);
421 422
							return this.getInstalled(LocalExtensionType.User);
						})
423 424 425 426 427 428
						.then(installed => installed.filter(i => i.identifier.id === id)[0]);
				}
				return null;
			});
	}

429 430 431 432
	private extractAndInstall({ zipPath, id, metadata }: InstallableExtension, type: LocalExtensionType): TPromise<ILocalExtension> {
		const location = type === LocalExtensionType.User ? this.extensionsPath : this.systemExtensionsPath;
		const tempPath = path.join(location, `.${id}`);
		const extensionPath = path.join(location, id);
S
Sandeep Somavarapu 已提交
433 434
		return pfs.rimraf(extensionPath)
			.then(() => this.extractAndRename(id, zipPath, tempPath, extensionPath), e => TPromise.wrapError(new ExtensionManagementError(nls.localize('errorDeleting', "Unable to delete the existing folder '{0}' while installing the extension '{1}'. Please delete the folder manually and try again", extensionPath, id), INSTALL_ERROR_DELETING)))
435 436
			.then(() => {
				this.logService.info('Installation completed.', id);
437
				return this.scanExtension(id, location, type);
438
			})
439 440 441 442 443 444 445
			.then(local => {
				if (metadata) {
					local.metadata = metadata;
					return this.saveMetadataForLocalExtension(local);
				}
				return local;
			});
E
Erich Gamma 已提交
446 447
	}

S
Sandeep Somavarapu 已提交
448 449
	private extractAndRename(id: string, zipPath: string, extractPath: string, renamePath: string): TPromise<void> {
		return this.extract(id, zipPath, extractPath)
S
Sandeep Somavarapu 已提交
450
			.then(() => this.rename(id, extractPath, renamePath, Date.now() + (2 * 60 * 1000) /* Retry for 2 minutes */)
S
Sandeep Somavarapu 已提交
451 452 453 454 455 456 457 458
				.then(
					() => this.logService.info('Renamed to', renamePath),
					e => {
						this.logService.info('Rename failed. Deleting from extracted location', extractPath);
						return always(pfs.rimraf(extractPath), () => null).then(() => TPromise.wrapError(e));
					}));
	}

459
	private extract(id: string, zipPath: string, extractPath: string): TPromise<void> {
460 461 462
		this.logService.trace(`Started extracting the extension from ${zipPath} to ${extractPath}`);
		return pfs.rimraf(extractPath)
			.then(
S
Sandeep Somavarapu 已提交
463
				() => extract(zipPath, extractPath, { sourcePath: 'extension', overwrite: true }, this.logService)
M
Matt Bierner 已提交
464 465 466
					.then(
						() => this.logService.info(`Extracted extension to ${extractPath}:`, id),
						e => always(pfs.rimraf(extractPath), () => null)
S
Sandeep Somavarapu 已提交
467
							.then(() => TPromise.wrapError(new ExtensionManagementError(e.message, e instanceof ExtractError ? e.type : INSTALL_ERROR_EXTRACTING)))),
M
Matt Bierner 已提交
468
				e => TPromise.wrapError(new ExtensionManagementError(this.joinErrors(e).message, INSTALL_ERROR_DELETING)));
469 470
	}

471 472
	private rename(id: string, extractPath: string, renamePath: string, retryUntil: number): TPromise<void> {
		return pfs.rename(extractPath, renamePath)
S
Sandeep Somavarapu 已提交
473 474 475 476 477
			.then(null, error => {
				if (isWindows && error && error.code === 'EPERM' && Date.now() < retryUntil) {
					this.logService.info(`Failed renaming ${extractPath} to ${renamePath} with 'EPERM' error. Trying again...`);
					return this.rename(id, extractPath, renamePath, retryUntil);
				}
S
Sandeep Somavarapu 已提交
478
				return TPromise.wrapError(new ExtensionManagementError(error.message || nls.localize('renameError', "Unknown error while renaming {0} to {1}", extractPath, renamePath), error.code || INSTALL_ERROR_RENAMING));
S
Sandeep Somavarapu 已提交
479
			});
S
Sandeep Somavarapu 已提交
480 481
	}

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
	private installDependenciesAndPackExtensions(installed: ILocalExtension, existing: ILocalExtension): TPromise<void> {
		if (this.galleryService.isEnabled()) {
			const dependenciesAndPackExtensions: string[] = installed.manifest.extensionDependencies || [];
			if (installed.manifest.extensionPack) {
				for (const extension of installed.manifest.extensionPack) {
					// add only those extensions which are new in currently installed extension
					if (!(existing && existing.manifest.extensionPack && existing.manifest.extensionPack.some(old => areSameExtensions({ id: old }, { id: extension })))) {
						if (dependenciesAndPackExtensions.every(e => !areSameExtensions({ id: e }, { id: extension }))) {
							dependenciesAndPackExtensions.push(extension);
						}
					}
				}
			}
			if (dependenciesAndPackExtensions.length) {
				return this.getInstalled()
					.then(installed => {
						// filter out installing and installed extensions
						const names = dependenciesAndPackExtensions.filter(id => !this.installingExtensions.has(adoptToGalleryExtensionId(id)) && installed.every(({ galleryIdentifier }) => !areSameExtensions(galleryIdentifier, { id })));
						if (names.length) {
							return this.galleryService.query({ names, pageSize: dependenciesAndPackExtensions.length })
								.then(galleryResult => {
									const extensionsToInstall = galleryResult.firstPage;
									return TPromise.join(extensionsToInstall.map(e => this.installFromGallery(e)))
										.then(() => null, errors => this.rollback(extensionsToInstall).then(() => TPromise.wrapError(errors), () => TPromise.wrapError(errors)));
								});
						}
						return null;
					});
			}
		}
		return TPromise.as(null);
	}

S
Sandeep Somavarapu 已提交
515 516 517 518
	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
519
					.map(local => this.uninstall(local, true))))
S
Sandeep Somavarapu 已提交
520 521 522
			.then(() => null, () => null);
	}

523
	uninstall(extension: ILocalExtension, force = false): TPromise<void> {
S
Sandeep Somavarapu 已提交
524
		return this.toNonCancellablePromise(this.getInstalled(LocalExtensionType.User)
S
Sandeep Somavarapu 已提交
525 526 527 528 529
			.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 已提交
530
			}));
S
Sandeep Somavarapu 已提交
531 532
	}

533 534
	updateMetadata(local: ILocalExtension, metadata: IGalleryMetadata): TPromise<ILocalExtension> {
		local.metadata = metadata;
535 536 537 538 539
		return this.saveMetadataForLocalExtension(local)
			.then(localExtension => {
				this.manifestCache.invalidate();
				return localExtension;
			});
540 541 542 543 544 545 546 547 548 549 550 551 552 553
	}

	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 已提交
554
	private getMetadata(extensionName: string): TPromise<IGalleryMetadata> {
S
Sandeep Somavarapu 已提交
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
		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 已提交
573 574
	}

575 576
	private joinErrors(errorOrErrors: (Error | string) | ((Error | string)[])): Error {
		const errors = Array.isArray(errorOrErrors) ? errorOrErrors : [errorOrErrors];
S
Sandeep Somavarapu 已提交
577 578 579 580
		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 已提交
581
			return new Error(`${previousValue.message}${previousValue.message ? ',' : ''}${currentValue instanceof Error ? currentValue.message : currentValue}`);
S
Sandeep Somavarapu 已提交
582
		}, new Error(''));
J
Joao Moreno 已提交
583 584
	}

585
	private checkForDependenciesAndUninstall(extension: ILocalExtension, installed: ILocalExtension[], force: boolean): TPromise<void> {
J
Joao Moreno 已提交
586
		return this.preUninstallExtension(extension)
587
			.then(() => {
588 589 590
				const packedExtensions = this.getAllPackExtensionsToUninstall(extension, installed);
				if (packedExtensions.length) {
					return this.uninstallExtensions(extension, packedExtensions, installed);
S
Sandeep Somavarapu 已提交
591 592 593
				}
				const dependencies = this.getDependenciesToUninstall(extension, installed);
				if (dependencies.length) {
594 595 596 597 598
					if (force) {
						return this.uninstallExtensions(extension, dependencies, installed);
					} else {
						return this.promptForDependenciesAndUninstall(extension, dependencies, installed);
					}
S
Sandeep Somavarapu 已提交
599
				} else {
600
					return this.uninstallExtensions(extension, [], installed);
601 602
				}
			})
603
			.then(() => this.postUninstallExtension(extension),
M
Matt Bierner 已提交
604
				error => {
605
					this.postUninstallExtension(extension, new ExtensionManagementError(error instanceof Error ? error.message : error, INSTALL_ERROR_LOCAL));
M
Matt Bierner 已提交
606 607
					return TPromise.wrapError(error);
				});
S
Sandeep Somavarapu 已提交
608 609
	}

610
	private promptForDependenciesAndUninstall(extension: ILocalExtension, dependencies: ILocalExtension[], installed: ILocalExtension[]): TPromise<void> {
S
Sandeep Somavarapu 已提交
611
		const message = nls.localize('uninstallDependeciesConfirmation', "Also uninstall the dependencies of the extension '{0}'?", extension.manifest.displayName || extension.manifest.name);
612
		const buttons = [
S
Sandeep Somavarapu 已提交
613 614
			nls.localize('yes', "Yes"),
			nls.localize('no', "No"),
S
Sandeep Somavarapu 已提交
615 616
			nls.localize('cancel', "Cancel")
		];
617
		return this.dialogService.show(Severity.Info, message, buttons, { cancelId: 2 })
S
Sandeep Somavarapu 已提交
618 619
			.then<void>(value => {
				if (value === 0) {
S
Sandeep Somavarapu 已提交
620
					return this.uninstallExtensions(extension, dependencies, installed);
S
Sandeep Somavarapu 已提交
621 622
				}
				if (value === 1) {
S
Sandeep Somavarapu 已提交
623
					return this.uninstallExtensions(extension, [], installed);
S
Sandeep Somavarapu 已提交
624
				}
625
				this.logService.info('Cancelled uninstalling extension:', extension.identifier.id);
S
Sandeep Somavarapu 已提交
626 627 628 629
				return TPromise.wrapError(errors.canceled());
			}, error => TPromise.wrapError(errors.canceled()));
	}

630 631 632 633 634 635
	private uninstallExtensions(extension: ILocalExtension, otherExtensionsToUninstall: ILocalExtension[], installed: ILocalExtension[]): TPromise<void> {
		const dependents = this.getDependents(extension, installed);
		if (dependents.length) {
			const remainingDependents = dependents.filter(dependent => extension !== dependent && otherExtensionsToUninstall.indexOf(dependent) === -1);
			if (remainingDependents.length) {
				return TPromise.wrapError<void>(new Error(this.getDependentsErrorMessage(extension, remainingDependents)));
636 637
			}
		}
638
		return TPromise.join([this.uninstallExtension(extension), ...otherExtensionsToUninstall.map(d => this.doUninstall(d))]).then(() => null);
639 640
	}

S
Sandeep Somavarapu 已提交
641 642 643 644 645 646 647 648 649 650 651 652 653
	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);
	}

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
	private getDependenciesToUninstall(extension: ILocalExtension, installed: ILocalExtension[]): ILocalExtension[] {
		const dependencies = this.getAllDependenciesToUninstall(extension, installed).filter(e => e !== extension);

		const dependenciesToUninstall = dependencies.slice(0);
		for (let index = 0; index < dependencies.length; index++) {
			const dep = dependencies[index];
			const dependents = this.getDependents(dep, installed);
			// Remove the dependency from the uninstall list if there is a dependent which will not be uninstalled.
			if (dependents.some(e => e !== extension && dependencies.indexOf(e) === -1)) {
				dependenciesToUninstall.splice(index - (dependencies.length - dependenciesToUninstall.length), 1);
			}
		}

		return dependenciesToUninstall;
	}

670
	private getAllDependenciesToUninstall(extension: ILocalExtension, installed: ILocalExtension[], checked: ILocalExtension[] = []): ILocalExtension[] {
671 672 673 674 675 676 677
		if (checked.indexOf(extension) !== -1) {
			return [];
		}
		checked.push(extension);
		if (!extension.manifest.extensionDependencies || extension.manifest.extensionDependencies.length === 0) {
			return [];
		}
678
		const dependenciesToUninstall = installed.filter(i => extension.manifest.extensionDependencies.some(id => areSameExtensions({ id }, i.galleryIdentifier)));
679 680
		const depsOfDeps = [];
		for (const dep of dependenciesToUninstall) {
681
			depsOfDeps.push(...this.getAllDependenciesToUninstall(dep, installed, checked));
682 683 684 685
		}
		return [...dependenciesToUninstall, ...depsOfDeps];
	}

686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
	private getAllPackExtensionsToUninstall(extension: ILocalExtension, installed: ILocalExtension[], checked: ILocalExtension[] = []): ILocalExtension[] {
		if (checked.indexOf(extension) !== -1) {
			return [];
		}
		checked.push(extension);
		if (!extension.manifest.extensionPack || extension.manifest.extensionPack.length === 0) {
			return [];
		}
		const packedExtensions = installed.filter(i => extension.manifest.extensionPack.some(id => areSameExtensions({ id }, i.galleryIdentifier)));
		const packOfPackedExtensions = [];
		for (const packedExtension of packedExtensions) {
			packOfPackedExtensions.push(...this.getAllPackExtensionsToUninstall(packedExtension, installed, checked));
		}
		return [...packedExtensions, ...packOfPackedExtensions];
	}

	private getDependents(extension: ILocalExtension, installed: ILocalExtension[]): ILocalExtension[] {
703
		return installed.filter(e => e.manifest.extensionDependencies && e.manifest.extensionDependencies.some(id => areSameExtensions({ id }, extension.galleryIdentifier)));
704 705
	}

J
Joao Moreno 已提交
706 707
	private doUninstall(extension: ILocalExtension): TPromise<void> {
		return this.preUninstallExtension(extension)
S
Sandeep Somavarapu 已提交
708
			.then(() => this.uninstallExtension(extension))
709
			.then(() => this.postUninstallExtension(extension),
M
Matt Bierner 已提交
710
				error => {
711
					this.postUninstallExtension(extension, new ExtensionManagementError(error instanceof Error ? error.message : error, INSTALL_ERROR_LOCAL));
M
Matt Bierner 已提交
712 713
					return TPromise.wrapError(error);
				});
S
Sandeep Somavarapu 已提交
714
	}
E
Erich Gamma 已提交
715

J
Joao Moreno 已提交
716
	private preUninstallExtension(extension: ILocalExtension): TPromise<void> {
S
Sandeep Somavarapu 已提交
717
		return pfs.exists(extension.location.fsPath)
718
			.then(exists => exists ? null : TPromise.wrapError(new Error(nls.localize('notExists', "Could not find extension"))))
719
			.then(() => {
720
				this.logService.info('Uninstalling extension:', extension.identifier.id);
721 722
				this._onUninstallExtension.fire(extension.identifier);
			});
S
Sandeep Somavarapu 已提交
723 724
	}

S
Sandeep Somavarapu 已提交
725
	private uninstallExtension(local: ILocalExtension): TPromise<void> {
S
Sandeep Somavarapu 已提交
726 727 728 729 730 731 732 733 734 735
		const id = getGalleryExtensionIdFromLocal(local);
		let promise = this.uninstallingExtensions.get(id);
		if (!promise) {
			// Set all versions of the extension as uninstalled
			promise = this.scanUserExtensions(false)
				.then(userExtensions => this.setUninstalled(...userExtensions.filter(u => areSameExtensions({ id: getGalleryExtensionIdFromLocal(u), uuid: u.identifier.uuid }, { id, uuid: local.identifier.uuid }))))
				.then(() => { this.uninstallingExtensions.delete(id); });
			this.uninstallingExtensions.set(id, promise);
		}
		return promise;
S
Sandeep Somavarapu 已提交
736 737
	}

J
Joao Moreno 已提交
738
	private async postUninstallExtension(extension: ILocalExtension, error?: Error): Promise<void> {
739
		if (error) {
740
			this.logService.error('Failed to uninstall extension:', extension.identifier.id, error.message);
S
Sandeep Somavarapu 已提交
741 742
		} else {
			this.logService.info('Successfully uninstalled extension:', extension.identifier.id);
743 744 745 746
			// 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);
			}
747
		}
748 749 750
		this.reportTelemetry('extensionGallery:uninstall', getLocalExtensionTelemetryData(extension), void 0, error);
		const errorcode = error ? error instanceof ExtensionManagementError ? error.code : ERROR_UNKNOWN : void 0;
		this._onDidUninstallExtension.fire({ identifier: extension.identifier, error: errorcode });
E
Erich Gamma 已提交
751 752
	}

J
Joao Moreno 已提交
753 754 755 756
	getInstalled(type: LocalExtensionType = null): TPromise<ILocalExtension[]> {
		const promises = [];

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

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

764
		return TPromise.join<ILocalExtension[]>(promises).then(flatten, errors => TPromise.wrapError<ILocalExtension[]>(this.joinErrors(errors)));
J
Joao Moreno 已提交
765 766 767
	}

	private scanSystemExtensions(): TPromise<ILocalExtension[]> {
768
		this.logService.trace('Started scanning system extensions');
769
		return this.scanExtensions(this.systemExtensionsPath, LocalExtensionType.System)
770
			.then(result => {
771
				this.logService.info('Scanned system extensions:', result.length);
772 773
				return result;
			});
J
Joao Moreno 已提交
774 775
	}

S
Sandeep Somavarapu 已提交
776
	private scanUserExtensions(excludeOutdated: boolean): TPromise<ILocalExtension[]> {
777
		this.logService.trace('Started scanning user extensions');
S
Sandeep Somavarapu 已提交
778 779 780
		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 已提交
781 782
				if (excludeOutdated) {
					const byExtension: ILocalExtension[][] = groupByExtension(extensions, e => ({ id: getGalleryExtensionIdFromLocal(e), uuid: e.identifier.uuid }));
S
Sandeep Somavarapu 已提交
783
					extensions = byExtension.map(p => p.sort((a, b) => semver.rcompare(a.manifest.version, b.manifest.version))[0]);
S
Sandeep Somavarapu 已提交
784
				}
S
Sandeep Somavarapu 已提交
785
				this.logService.info('Scanned user extensions:', extensions.length);
S
Sandeep Somavarapu 已提交
786 787
				return extensions;
			});
J
Joao Moreno 已提交
788 789
	}

J
Joao Moreno 已提交
790
	private scanExtensions(root: string, type: LocalExtensionType): TPromise<ILocalExtension[]> {
E
Erich Gamma 已提交
791
		const limiter = new Limiter(10);
S
Sandeep Somavarapu 已提交
792
		return pfs.readdir(root)
S
Sandeep Somavarapu 已提交
793 794
			.then(extensionsFolders => TPromise.join<ILocalExtension>(extensionsFolders.map(extensionFolder => limiter.queue(() => this.scanExtension(extensionFolder, root, type)))))
			.then(extensions => extensions.filter(e => e && e.identifier));
S
Sandeep Somavarapu 已提交
795
	}
E
Erich Gamma 已提交
796

S
Sandeep Somavarapu 已提交
797
	private scanExtension(folderName: string, root: string, type: LocalExtensionType): TPromise<ILocalExtension> {
798 799 800
		if (type === LocalExtensionType.User && folderName.indexOf('.') === 0) { // Do not consider user exension folder starting with `.`
			return TPromise.as(null);
		}
S
Sandeep Somavarapu 已提交
801 802 803 804
		const extensionPath = path.join(root, folderName);
		return pfs.readdir(extensionPath)
			.then(children => readManifest(extensionPath)
				.then<ILocalExtension>(({ manifest, metadata }) => {
J
Joao Moreno 已提交
805 806 807 808
					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;
809 810 811 812 813 814
					if (manifest.extensionDependencies) {
						manifest.extensionDependencies = manifest.extensionDependencies.map(id => adoptToGalleryExtensionId(id));
					}
					if (manifest.extensionPack) {
						manifest.extensionPack = manifest.extensionPack.map(id => adoptToGalleryExtensionId(id));
					}
S
Sandeep Somavarapu 已提交
815
					const identifier = { id: type === LocalExtensionType.System ? folderName : getLocalExtensionIdFromManifest(manifest), uuid: metadata ? metadata.id : null };
S
Sandeep Somavarapu 已提交
816 817
					const galleryIdentifier = { id: getGalleryExtensionId(manifest.publisher, manifest.name), uuid: identifier.uuid };
					return { type, identifier, galleryIdentifier, manifest, metadata, location: URI.file(extensionPath), readmeUrl, changelogUrl };
S
Sandeep Somavarapu 已提交
818 819
				}))
			.then(null, () => null);
E
Erich Gamma 已提交
820 821
	}

J
Joao Moreno 已提交
822
	removeDeprecatedExtensions(): TPromise<any> {
S
Sandeep Somavarapu 已提交
823 824 825 826 827
		return this.removeUninstalledExtensions()
			.then(() => this.removeOutdatedExtensions());
	}

	private removeUninstalledExtensions(): TPromise<void> {
828
		return this.getUninstalledExtensions()
S
Sandeep Somavarapu 已提交
829 830
			.then(uninstalled => this.scanExtensions(this.extensionsPath, LocalExtensionType.User) // All user extensions
				.then(extensions => {
S
Sandeep Somavarapu 已提交
831
					const toRemove: ILocalExtension[] = extensions.filter(e => uninstalled[e.identifier.id]);
832
					return TPromise.join(toRemove.map(e => this.extensionLifecycle.uninstall(e).then(() => this.removeUninstalledExtension(e))));
S
Sandeep Somavarapu 已提交
833 834 835
				})
			).then(() => null);
	}
S
Sandeep Somavarapu 已提交
836

S
Sandeep Somavarapu 已提交
837 838 839 840
	private removeOutdatedExtensions(): TPromise<void> {
		return this.scanExtensions(this.extensionsPath, LocalExtensionType.User) // All user extensions
			.then(extensions => {
				const toRemove: ILocalExtension[] = [];
S
Sandeep Somavarapu 已提交
841

S
Sandeep Somavarapu 已提交
842 843 844 845
				// 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 已提交
846
				return TPromise.join(toRemove.map(extension => this.removeExtension(extension, 'outdated')));
S
Sandeep Somavarapu 已提交
847 848 849 850
			}).then(() => null);
	}

	private removeUninstalledExtension(extension: ILocalExtension): TPromise<void> {
851
		return this.removeExtension(extension, 'uninstalled')
S
Sandeep Somavarapu 已提交
852 853 854 855
			.then(() => this.withUninstalledExtensions(uninstalled => delete uninstalled[extension.identifier.id]))
			.then(() => null);
	}

S
Sandeep Somavarapu 已提交
856
	private removeExtension(extension: ILocalExtension, type: string): TPromise<void> {
857
		this.logService.trace(`Deleting ${type} extension from disk`, extension.identifier.id);
S
Sandeep Somavarapu 已提交
858
		return pfs.rimraf(extension.location.fsPath).then(() => this.logService.info('Deleted from disk', extension.identifier.id));
J
Joao Moreno 已提交
859 860
	}

861 862
	private isUninstalled(id: string): TPromise<boolean> {
		return this.filterUninstalled(id).then(uninstalled => uninstalled.length === 1);
863 864
	}

865 866 867
	private filterUninstalled(...ids: string[]): TPromise<string[]> {
		return this.withUninstalledExtensions(allUninstalled => {
			const uninstalled = [];
868
			for (const id of ids) {
869 870
				if (!!allUninstalled[id]) {
					uninstalled.push(id);
871 872
				}
			}
873
			return uninstalled;
874
		});
875 876
	}

S
Sandeep Somavarapu 已提交
877 878
	private setUninstalled(...extensions: ILocalExtension[]): TPromise<void> {
		const ids = extensions.map(e => e.identifier.id);
S
Sandeep Somavarapu 已提交
879
		return this.withUninstalledExtensions(uninstalled => assign(uninstalled, ids.reduce((result, id) => { result[id] = true; return result; }, {})));
880 881
	}

882 883
	private unsetUninstalled(id: string): TPromise<void> {
		return this.withUninstalledExtensions<void>(uninstalled => delete uninstalled[id]);
884 885
	}

886 887
	private getUninstalledExtensions(): TPromise<{ [id: string]: boolean; }> {
		return this.withUninstalledExtensions(uninstalled => uninstalled);
888 889
	}

890 891
	private withUninstalledExtensions<T>(fn: (uninstalled: { [id: string]: boolean; }) => T): TPromise<T> {
		return this.uninstalledFileLimiter.queue(() => {
892
			let result: T = null;
893
			return pfs.readFile(this.uninstalledPath, 'utf8')
R
Ron Buckton 已提交
894
				.then(null, err => err.code === 'ENOENT' ? TPromise.as('{}') : TPromise.wrapError(err))
J
Johannes Rieken 已提交
895
				.then<{ [id: string]: boolean }>(raw => { try { return JSON.parse(raw); } catch (e) { return {}; } })
896 897 898 899
				.then(uninstalled => { result = fn(uninstalled); return uninstalled; })
				.then(uninstalled => {
					if (Object.keys(uninstalled).length === 0) {
						return pfs.rimraf(this.uninstalledPath);
900
					} else {
901 902
						const raw = JSON.stringify(uninstalled);
						return pfs.writeFile(this.uninstalledPath, raw);
903 904 905 906 907
					}
				})
				.then(() => result);
		});
	}
908

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

912 913 914 915
		if (!this.reportedExtensions || now - this.lastReportTimestamp > 1000 * 60 * 5) { // 5 minute cache freshness
			this.reportedExtensions = this.updateReportCache();
			this.lastReportTimestamp = now;
		}
J
Joao Moreno 已提交
916

917
		return this.reportedExtensions;
J
Joao Moreno 已提交
918 919
	}

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

923
		return this.galleryService.getExtensionsReport()
J
Joao Moreno 已提交
924 925
			.then(result => {
				this.logService.trace(`ExtensionManagementService.refreshReportedCache - got ${result.length} reported extensions from service`);
926 927 928 929
				return result;
			}, err => {
				this.logService.trace('ExtensionManagementService.refreshReportedCache - failed to get extension report');
				return [];
J
Joao Moreno 已提交
930 931
			});
	}
932

S
Sandeep Somavarapu 已提交
933 934 935 936
	private toNonCancellablePromise<T>(promise: TPromise<T>): TPromise<T> {
		return new TPromise((c, e) => promise.then(result => c(result), error => e(error)), () => this.logService.debug('Request Cancelled'));
	}

937 938 939 940 941 942 943
	private reportTelemetry(eventName: string, extensionData: any, duration: number, error?: Error): void {
		const errorcode = error ? error instanceof ExtensionManagementError ? error.code : ERROR_UNKNOWN : void 0;
		/* __GDPR__
			"extensionGallery:install" : {
				"success": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
				"duration" : { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
				"errorcode": { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
944
				"recommendationReason": { "retiredFromVersion": "1.23.0", "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
				"${include}": [
					"${GalleryExtensionTelemetryData}"
				]
			}
		*/
		/* __GDPR__
			"extensionGallery:uninstall" : {
				"success": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
				"duration" : { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
				"errorcode": { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
				"${include}": [
					"${GalleryExtensionTelemetryData}"
				]
			}
		*/
960 961 962 963 964 965 966 967 968 969
		/* __GDPR__
			"extensionGallery:update" : {
				"success": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
				"duration" : { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
				"errorcode": { "classification": "CallstackOrException", "purpose": "PerformanceAndHealth" },
				"${include}": [
					"${GalleryExtensionTelemetryData}"
				]
			}
		*/
970 971
		this.telemetryService.publicLog(eventName, assign(extensionData, { success: !error, duration, errorcode }));
	}
E
Erich Gamma 已提交
972
}
S
Sandeep Somavarapu 已提交
973 974 975 976 977 978 979

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);
980
}