extensionPoints.ts 22.3 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';
9
import * as pfs from 'vs/base/node/pfs';
10
import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions';
J
Johannes Rieken 已提交
11
import { TPromise } from 'vs/base/common/winjs.base';
12
import { join, normalize, extname } from 'path';
13 14
import * as json from 'vs/base/common/json';
import * as types from 'vs/base/common/types';
15
import { isValidExtensionVersion } from 'vs/platform/extensions/node/extensionValidator';
J
Joao Moreno 已提交
16
import * as semver from 'semver';
S
Sandeep Somavarapu 已提交
17
import { getIdAndVersionFromLocalExtensionId } from 'vs/platform/extensionManagement/node/extensionManagementUtil';
18
import { getParseErrorMessage } from 'vs/base/common/jsonErrorMessages';
S
Sandeep Somavarapu 已提交
19
import { groupByExtension, getGalleryExtensionId, getLocalExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
20
import { URI } from 'vs/base/common/uri';
E
Erich Gamma 已提交
21 22 23

const MANIFEST_FILE = 'package.json';

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
export interface Translations {
	[id: string]: string;
}

namespace Translations {
	export function equals(a: Translations, b: Translations): boolean {
		if (a === b) {
			return true;
		}
		let aKeys = Object.keys(a);
		let bKeys: Set<string> = new Set<string>();
		for (let key of Object.keys(b)) {
			bKeys.add(key);
		}
		if (aKeys.length !== bKeys.size) {
			return false;
		}

		for (let key of aKeys) {
			if (a[key] !== b[key]) {
				return false;
			}
			bKeys.delete(key);
		}
		return bKeys.size === 0;
	}
}

52 53 54 55
export interface NlsConfiguration {
	readonly devMode: boolean;
	readonly locale: string;
	readonly pseudo: boolean;
56
	readonly translations: Translations;
57 58
}

59
export interface ILog {
60 61 62 63 64
	error(source: string, message: string): void;
	warn(source: string, message: string): void;
	info(source: string, message: string): void;
}

65 66
abstract class ExtensionManifestHandler {

67 68 69 70
	protected readonly _ourVersion: string;
	protected readonly _log: ILog;
	protected readonly _absoluteFolderPath: string;
	protected readonly _isBuiltin: boolean;
71
	protected readonly _isUnderDevelopment: boolean;
72
	protected readonly _absoluteManifestPath: string;
73

74
	constructor(ourVersion: string, log: ILog, absoluteFolderPath: string, isBuiltin: boolean, isUnderDevelopment: boolean) {
75
		this._ourVersion = ourVersion;
76
		this._log = log;
77 78
		this._absoluteFolderPath = absoluteFolderPath;
		this._isBuiltin = isBuiltin;
79
		this._isUnderDevelopment = isUnderDevelopment;
80
		this._absoluteManifestPath = join(absoluteFolderPath, MANIFEST_FILE);
81 82 83 84
	}
}

class ExtensionManifestParser extends ExtensionManifestHandler {
S
Sandeep Somavarapu 已提交
85

86 87
	public parse(): TPromise<IExtensionDescription> {
		return pfs.readFile(this._absoluteManifestPath).then((manifestContents) => {
88
			try {
S
Sandeep Somavarapu 已提交
89 90 91 92 93 94
				const manifest = JSON.parse(manifestContents.toString());
				if (manifest.__metadata) {
					manifest.uuid = manifest.__metadata.id;
				}
				delete manifest.__metadata;
				return manifest;
95
			} catch (e) {
96
				this._log.error(this._absoluteFolderPath, nls.localize('jsonParseFail', "Failed to parse {0}: {1}.", this._absoluteManifestPath, getParseErrorMessage(e.message)));
97
			}
S
Sandeep Somavarapu 已提交
98
			return null;
99
		}, (err) => {
100 101 102 103
			if (err.code === 'ENOENT') {
				return null;
			}

104
			this._log.error(this._absoluteFolderPath, nls.localize('fileReadFail', "Cannot read file {0}: {1}.", this._absoluteManifestPath, err.message));
105 106 107 108 109 110 111
			return null;
		});
	}
}

class ExtensionManifestNLSReplacer extends ExtensionManifestHandler {

112 113
	private readonly _nlsConfig: NlsConfiguration;

114 115
	constructor(ourVersion: string, log: ILog, absoluteFolderPath: string, isBuiltin: boolean, isUnderDevelopment: boolean, nlsConfig: NlsConfiguration) {
		super(ourVersion, log, absoluteFolderPath, isBuiltin, isUnderDevelopment);
116 117 118
		this._nlsConfig = nlsConfig;
	}

J
Johannes Rieken 已提交
119
	public replaceNLS(extensionDescription: IExtensionDescription): TPromise<IExtensionDescription> {
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
		interface MessageBag {
			[key: string]: string;
		}

		interface TranslationBundle {
			contents: {
				package: MessageBag;
			};
		}

		interface LocalizedMessages {
			values: MessageBag;
			default: string;
		}

		const reportErrors = (localized: string, errors: json.ParseError[]): void => {
			errors.forEach((error) => {
				this._log.error(this._absoluteFolderPath, nls.localize('jsonsParseReportErrors', "Failed to parse {0}: {1}.", localized, getParseErrorMessage(error.error)));
			});
		};

141
		let extension = extname(this._absoluteManifestPath);
142 143
		let basename = this._absoluteManifestPath.substr(0, this._absoluteManifestPath.length - extension.length);

144 145 146 147 148 149 150 151 152 153 154 155 156
		const translationId = `${extensionDescription.publisher}.${extensionDescription.name}`;
		let translationPath = this._nlsConfig.translations[translationId];
		let localizedMessages: TPromise<LocalizedMessages>;
		if (translationPath) {
			localizedMessages = pfs.readFile(translationPath, 'utf8').then<LocalizedMessages, LocalizedMessages>((content) => {
				let errors: json.ParseError[] = [];
				let translationBundle: TranslationBundle = json.parse(content, errors);
				if (errors.length > 0) {
					reportErrors(translationPath, errors);
					return { values: undefined, default: `${basename}.nls.json` };
				} else {
					let values = translationBundle.contents ? translationBundle.contents.package : undefined;
					return { values: values, default: `${basename}.nls.json` };
157
				}
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
			}, (error) => {
				return { values: undefined, default: `${basename}.nls.json` };
			});
		} else {
			localizedMessages = pfs.fileExists(basename + '.nls' + extension).then<LocalizedMessages, undefined | LocalizedMessages>(exists => {
				if (!exists) {
					return undefined;
				}
				return ExtensionManifestNLSReplacer.findMessageBundles(this._nlsConfig, basename).then((messageBundle) => {
					if (!messageBundle.localized) {
						return { values: undefined, default: messageBundle.original };
					}
					return pfs.readFile(messageBundle.localized, 'utf8').then(messageBundleContent => {
						let errors: json.ParseError[] = [];
						let messages: MessageBag = json.parse(messageBundleContent, errors);
173
						if (errors.length > 0) {
174 175
							reportErrors(messageBundle.localized, errors);
							return { values: undefined, default: messageBundle.original };
176
						}
177 178 179
						return { values: messages, default: messageBundle.original };
					}, (err) => {
						return { values: undefined, default: messageBundle.original };
180
					});
181
				}, (err) => {
182
					return undefined;
183 184
				});
			});
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
		}

		return localizedMessages.then((localizedMessages) => {
			if (localizedMessages === undefined) {
				return extensionDescription;
			}
			let errors: json.ParseError[] = [];
			// resolveOriginalMessageBundle returns null if localizedMessages.default === undefined;
			return ExtensionManifestNLSReplacer.resolveOriginalMessageBundle(localizedMessages.default, errors).then((defaults) => {
				if (errors.length > 0) {
					reportErrors(localizedMessages.default, errors);
					return extensionDescription;
				}
				const localized = localizedMessages.values || Object.create(null);
				ExtensionManifestNLSReplacer._replaceNLStrings(this._nlsConfig, extensionDescription, localized, defaults, this._log, this._absoluteFolderPath);
				return extensionDescription;
			});
		}, (err) => {
			return extensionDescription;
204 205
		});
	}
E
Erich Gamma 已提交
206

207 208 209 210
	/**
	 * Parses original message bundle, returns null if the original message bundle is null.
	 */
	private static resolveOriginalMessageBundle(originalMessageBundle: string, errors: json.ParseError[]) {
211
		return new TPromise<{ [key: string]: string; }>((c, e) => {
212 213 214
			if (originalMessageBundle) {
				pfs.readFile(originalMessageBundle).then(originalBundleContent => {
					c(json.parse(originalBundleContent.toString(), errors));
215 216
				}, (err) => {
					c(null);
217 218 219 220 221 222 223 224 225 226 227
				});
			} else {
				c(null);
			}
		});
	}

	/**
	 * Finds localized message bundle and the original (unlocalized) one.
	 * If the localized file is not present, returns null for the original and marks original as localized.
	 */
228
	private static findMessageBundles(nlsConfig: NlsConfiguration, basename: string): TPromise<{ localized: string, original: string }> {
229
		return new TPromise<{ localized: string, original: string }>((c, e) => {
230 231 232 233
			function loop(basename: string, locale: string): void {
				let toCheck = `${basename}.nls.${locale}.json`;
				pfs.fileExists(toCheck).then(exists => {
					if (exists) {
234
						c({ localized: toCheck, original: `${basename}.nls.json` });
235 236 237
					}
					let index = locale.lastIndexOf('-');
					if (index === -1) {
238
						c({ localized: `${basename}.nls.json`, original: null });
239 240 241 242 243 244 245
					} else {
						locale = locale.substring(0, index);
						loop(basename, locale);
					}
				});
			}

246
			if (nlsConfig.devMode || nlsConfig.pseudo || !nlsConfig.locale) {
247
				return c({ localized: basename + '.nls.json', original: null });
248 249 250 251 252 253
			}
			loop(basename, nlsConfig.locale);
		});
	}

	/**
254 255
	 * This routine makes the following assumptions:
	 * The root element is an object literal
256
	 */
257
	private static _replaceNLStrings<T>(nlsConfig: NlsConfiguration, literal: T, messages: { [key: string]: string; }, originalMessages: { [key: string]: string }, log: ILog, messageScope: string): void {
258
		function processEntry(obj: any, key: string | number, command?: boolean) {
259
			let value = obj[key];
260
			if (types.isString(value)) {
261 262 263 264 265
				let str = <string>value;
				let length = str.length;
				if (length > 1 && str[0] === '%' && str[length - 1] === '%') {
					let messageKey = str.substr(1, length - 2);
					let message = messages[messageKey];
266 267 268 269 270
					// If the messages come from a language pack they might miss some keys
					// Fill them from the original messages.
					if (message === undefined && originalMessages) {
						message = originalMessages[messageKey];
					}
271 272 273 274
					if (message) {
						if (nlsConfig.pseudo) {
							// FF3B and FF3D is the Unicode zenkaku representation for [ and ]
							message = '\uFF3B' + message.replace(/[aouei]/g, '$&$&') + '\uFF3D';
275
						}
276
						obj[key] = command && (key === 'title' || key === 'category') && originalMessages ? { value: message, original: originalMessages[messageKey] } : message;
277
					} else {
278
						log.warn(messageScope, nls.localize('missingNLSKey', "Couldn't find message for key {0}.", messageKey));
279
					}
280
				}
281
			} else if (types.isObject(value)) {
282 283
				for (let k in value) {
					if (value.hasOwnProperty(k)) {
284
						k === 'commands' ? processEntry(value, k, true) : processEntry(value, k, command);
285 286
					}
				}
287
			} else if (types.isArray(value)) {
288
				for (let i = 0; i < value.length; i++) {
289
					processEntry(value, i, command);
290 291
				}
			}
292 293 294 295 296 297
		}

		for (let key in literal) {
			if (literal.hasOwnProperty(key)) {
				processEntry(literal, key);
			}
298
		}
299
	}
300 301
}

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
// Relax the readonly properties here, it is the one place where we check and normalize values
export interface IRelaxedExtensionDescription {
	id: string;
	name: string;
	version: string;
	publisher: string;
	isBuiltin: boolean;
	isUnderDevelopment: boolean;
	extensionLocation: URI;
	engines: {
		vscode: string;
	};
	main?: string;
	enableProposedApi?: boolean;
}

318
class ExtensionManifestValidator extends ExtensionManifestHandler {
A
Alex Dima 已提交
319 320
	validate(_extensionDescription: IExtensionDescription): IExtensionDescription {
		let extensionDescription = <IRelaxedExtensionDescription>_extensionDescription;
321
		extensionDescription.isBuiltin = this._isBuiltin;
322
		extensionDescription.isUnderDevelopment = this._isUnderDevelopment;
323 324

		let notices: string[] = [];
325
		if (!ExtensionManifestValidator.isValidExtensionDescription(this._ourVersion, this._absoluteFolderPath, extensionDescription, notices)) {
326
			notices.forEach((error) => {
327
				this._log.error(this._absoluteFolderPath, error);
328 329 330 331 332 333
			});
			return null;
		}

		// in this case the notices are warnings
		notices.forEach((error) => {
334
			this._log.warn(this._absoluteFolderPath, error);
335 336
		});

M
Martin Aeschlimann 已提交
337 338 339 340 341
		// allow publisher to be undefined to make the initial extension authoring experience smoother
		if (!extensionDescription.publisher) {
			extensionDescription.publisher = 'undefined_publisher';
		}

342
		// id := `publisher.name`
343
		extensionDescription.id = `${extensionDescription.publisher}.${extensionDescription.name}`;
344 345 346

		// main := absolutePath(`main`)
		if (extensionDescription.main) {
347
			extensionDescription.main = join(this._absoluteFolderPath, extensionDescription.main);
348 349
		}

350
		extensionDescription.extensionLocation = URI.file(this._absoluteFolderPath);
351 352 353

		return extensionDescription;
	}
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

	private static isValidExtensionDescription(version: string, extensionFolderPath: string, extensionDescription: IExtensionDescription, notices: string[]): boolean {

		if (!ExtensionManifestValidator.baseIsValidExtensionDescription(extensionFolderPath, extensionDescription, notices)) {
			return false;
		}

		if (!semver.valid(extensionDescription.version)) {
			notices.push(nls.localize('notSemver', "Extension version is not semver compatible."));
			return false;
		}

		return isValidExtensionVersion(version, extensionDescription, notices);
	}

	private static baseIsValidExtensionDescription(extensionFolderPath: string, extensionDescription: IExtensionDescription, notices: string[]): boolean {
		if (!extensionDescription) {
			notices.push(nls.localize('extensionDescription.empty', "Got empty extension description"));
			return false;
		}
M
Martin Aeschlimann 已提交
374 375
		if (typeof extensionDescription.publisher !== 'undefined' && typeof extensionDescription.publisher !== 'string') {
			notices.push(nls.localize('extensionDescription.publisher', "property publisher must be of type `string`."));
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
			return false;
		}
		if (typeof extensionDescription.name !== 'string') {
			notices.push(nls.localize('extensionDescription.name', "property `{0}` is mandatory and must be of type `string`", 'name'));
			return false;
		}
		if (typeof extensionDescription.version !== 'string') {
			notices.push(nls.localize('extensionDescription.version', "property `{0}` is mandatory and must be of type `string`", 'version'));
			return false;
		}
		if (!extensionDescription.engines) {
			notices.push(nls.localize('extensionDescription.engines', "property `{0}` is mandatory and must be of type `object`", 'engines'));
			return false;
		}
		if (typeof extensionDescription.engines.vscode !== 'string') {
			notices.push(nls.localize('extensionDescription.engines.vscode', "property `{0}` is mandatory and must be of type `string`", 'engines.vscode'));
			return false;
		}
		if (typeof extensionDescription.extensionDependencies !== 'undefined') {
395 396
			if (!ExtensionManifestValidator._isStringArray(extensionDescription.extensionDependencies)) {
				notices.push(nls.localize('extensionDescription.extensionDependencies', "property `{0}` can be omitted or must be of type `string[]`", 'extensionDependencies'));
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
				return false;
			}
		}
		if (typeof extensionDescription.activationEvents !== 'undefined') {
			if (!ExtensionManifestValidator._isStringArray(extensionDescription.activationEvents)) {
				notices.push(nls.localize('extensionDescription.activationEvents1', "property `{0}` can be omitted or must be of type `string[]`", 'activationEvents'));
				return false;
			}
			if (typeof extensionDescription.main === 'undefined') {
				notices.push(nls.localize('extensionDescription.activationEvents2', "properties `{0}` and `{1}` must both be specified or must both be omitted", 'activationEvents', 'main'));
				return false;
			}
		}
		if (typeof extensionDescription.main !== 'undefined') {
			if (typeof extensionDescription.main !== 'string') {
				notices.push(nls.localize('extensionDescription.main1', "property `{0}` can be omitted or must be of type `string`", 'main'));
				return false;
			} else {
				let normalizedAbsolutePath = join(extensionFolderPath, extensionDescription.main);

				if (normalizedAbsolutePath.indexOf(extensionFolderPath)) {
					notices.push(nls.localize('extensionDescription.main2', "Expected `main` ({0}) to be included inside extension's folder ({1}). This might make the extension non-portable.", normalizedAbsolutePath, extensionFolderPath));
					// not a failure case
				}
			}
			if (typeof extensionDescription.activationEvents === 'undefined') {
				notices.push(nls.localize('extensionDescription.main3', "properties `{0}` and `{1}` must both be specified or must both be omitted", 'activationEvents', 'main'));
				return false;
			}
		}
		return true;
	}

	private static _isStringArray(arr: string[]): boolean {
		if (!Array.isArray(arr)) {
			return false;
		}
		for (let i = 0, len = arr.length; i < len; i++) {
			if (typeof arr[i] !== 'string') {
				return false;
			}
		}
		return true;
	}
441
}
442

443
export class ExtensionScannerInput {
444 445 446

	public mtime: number;

447 448
	constructor(
		public readonly ourVersion: string,
449
		public readonly commit: string,
450 451 452
		public readonly locale: string,
		public readonly devMode: boolean,
		public readonly absoluteFolderPath: string,
453
		public readonly isBuiltin: boolean,
454
		public readonly isUnderDevelopment: boolean,
455
		public readonly tanslations: Translations
456
	) {
457
		// Keep empty!! (JSON.parse)
458 459 460 461 462 463
	}

	public static createNLSConfig(input: ExtensionScannerInput): NlsConfiguration {
		return {
			devMode: input.devMode,
			locale: input.locale,
464 465
			pseudo: input.locale === 'pseudo',
			translations: input.tanslations
466 467
		};
	}
468 469 470 471

	public static equals(a: ExtensionScannerInput, b: ExtensionScannerInput): boolean {
		return (
			a.ourVersion === b.ourVersion
472
			&& a.commit === b.commit
473 474 475 476
			&& a.locale === b.locale
			&& a.devMode === b.devMode
			&& a.absoluteFolderPath === b.absoluteFolderPath
			&& a.isBuiltin === b.isBuiltin
477
			&& a.isUnderDevelopment === b.isUnderDevelopment
478
			&& a.mtime === b.mtime
479
			&& Translations.equals(a.tanslations, b.tanslations)
480 481
		);
	}
482 483
}

J
Joao Moreno 已提交
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
export interface IExtensionReference {
	name: string;
	path: string;
}

export interface IExtensionResolver {
	resolveExtensions(): TPromise<IExtensionReference[]>;
}

class DefaultExtensionResolver implements IExtensionResolver {

	constructor(private root: string) { }

	resolveExtensions(): TPromise<IExtensionReference[]> {
		return pfs.readDirsInDir(this.root)
			.then(folders => folders.map(name => ({ name, path: join(this.root, name) })));
	}
}

503
export class ExtensionScanner {
A
Alex Dima 已提交
504

E
Erich Gamma 已提交
505
	/**
506
	 * Read the extension defined in `absoluteFolderPath`
E
Erich Gamma 已提交
507
	 */
508
	public static scanExtension(version: string, log: ILog, absoluteFolderPath: string, isBuiltin: boolean, isUnderDevelopment: boolean, nlsConfig: NlsConfiguration): TPromise<IExtensionDescription> {
509
		absoluteFolderPath = normalize(absoluteFolderPath);
E
Erich Gamma 已提交
510

511
		let parser = new ExtensionManifestParser(version, log, absoluteFolderPath, isBuiltin, isUnderDevelopment);
512 513
		return parser.parse().then((extensionDescription) => {
			if (extensionDescription === null) {
E
Erich Gamma 已提交
514 515
				return null;
			}
516

517
			let nlsReplacer = new ExtensionManifestNLSReplacer(version, log, absoluteFolderPath, isBuiltin, isUnderDevelopment, nlsConfig);
518 519 520
			return nlsReplacer.replaceNLS(extensionDescription);
		}).then((extensionDescription) => {
			if (extensionDescription === null) {
A
Alex Dima 已提交
521 522 523
				return null;
			}

524
			let validator = new ExtensionManifestValidator(version, log, absoluteFolderPath, isBuiltin, isUnderDevelopment);
525
			return validator.validate(extensionDescription);
E
Erich Gamma 已提交
526 527 528 529 530 531
		});
	}

	/**
	 * Scan a list of extensions defined in `absoluteFolderPath`
	 */
532
	public static async scanExtensions(input: ExtensionScannerInput, log: ILog, resolver: IExtensionResolver = null): Promise<IExtensionDescription[]> {
533 534
		const absoluteFolderPath = input.absoluteFolderPath;
		const isBuiltin = input.isBuiltin;
535
		const isUnderDevelopment = input.isUnderDevelopment;
536

J
Joao Moreno 已提交
537 538 539 540
		if (!resolver) {
			resolver = new DefaultExtensionResolver(absoluteFolderPath);
		}

A
Alex Dima 已提交
541 542 543 544 545 546 547 548 549 550
		try {
			let obsolete: { [folderName: string]: boolean; } = {};
			if (!isBuiltin) {
				try {
					const obsoleteFileContents = await pfs.readFile(join(absoluteFolderPath, '.obsolete'), 'utf8');
					obsolete = JSON.parse(obsoleteFileContents);
				} catch (err) {
					// Don't care
				}
			}
551

J
Joao Moreno 已提交
552
			let refs = await resolver.resolveExtensions();
553 554

			// Ensure the same extension order
J
Joao Moreno 已提交
555
			refs.sort((a, b) => a.name < b.name ? -1 : 1);
556

J
Joao Moreno 已提交
557
			if (!isBuiltin) {
A
Alex Dima 已提交
558
				// TODO: align with extensionsService
J
Joao Moreno 已提交
559 560
				const nonGallery: IExtensionReference[] = [];
				const gallery: IExtensionReference[] = [];
561

J
Joao Moreno 已提交
562
				refs.forEach(ref => {
563 564 565 566 567 568 569
					if (ref.name.indexOf('.') !== 0) { // Do not consider user extension folder starting with `.`
						const { id, version } = getIdAndVersionFromLocalExtensionId(ref.name);
						if (!id || !version) {
							nonGallery.push(ref);
						} else {
							gallery.push(ref);
						}
A
Alex Dima 已提交
570 571
					}
				});
J
Joao Moreno 已提交
572
				refs = [...nonGallery, ...gallery];
A
Alex Dima 已提交
573
			}
574

575
			const nlsConfig = ExtensionScannerInput.createNLSConfig(input);
576
			let extensionDescriptions = await TPromise.join(refs.map(r => this.scanExtension(input.ourVersion, log, r.path, isBuiltin, isUnderDevelopment, nlsConfig)));
S
Sandeep Somavarapu 已提交
577
			extensionDescriptions = extensionDescriptions.filter(item => item !== null && !obsolete[getLocalExtensionId(getGalleryExtensionId(item.publisher, item.name), item.version)]);
S
Sandeep Somavarapu 已提交
578 579 580 581 582 583 584

			if (!isBuiltin) {
				// Filter out outdated extensions
				const byExtension: IExtensionDescription[][] = groupByExtension(extensionDescriptions, e => ({ id: e.id, uuid: e.uuid }));
				extensionDescriptions = byExtension.map(p => p.sort((a, b) => semver.rcompare(a.version, b.version))[0]);
			}

585
			extensionDescriptions.sort((a, b) => {
A
Alex Dima 已提交
586
				if (a.extensionLocation.fsPath < b.extensionLocation.fsPath) {
587 588 589 590 591
					return -1;
				}
				return 1;
			});
			return extensionDescriptions;
A
Alex Dima 已提交
592 593 594 595
		} catch (err) {
			log.error(absoluteFolderPath, err);
			return [];
		}
E
Erich Gamma 已提交
596 597 598
	}

	/**
599 600
	 * Combination of scanExtension and scanExtensions: If an extension manifest is found at root, we load just this extension,
	 * otherwise we assume the folder contains multiple extensions.
E
Erich Gamma 已提交
601
	 */
602 603 604
	public static scanOneOrMultipleExtensions(input: ExtensionScannerInput, log: ILog): TPromise<IExtensionDescription[]> {
		const absoluteFolderPath = input.absoluteFolderPath;
		const isBuiltin = input.isBuiltin;
605
		const isUnderDevelopment = input.isUnderDevelopment;
606

607
		return pfs.fileExists(join(absoluteFolderPath, MANIFEST_FILE)).then((exists) => {
E
Erich Gamma 已提交
608
			if (exists) {
609
				const nlsConfig = ExtensionScannerInput.createNLSConfig(input);
610
				return this.scanExtension(input.ourVersion, log, absoluteFolderPath, isBuiltin, isUnderDevelopment, nlsConfig).then((extensionDescription) => {
A
Alex Dima 已提交
611
					if (extensionDescription === null) {
E
Erich Gamma 已提交
612 613
						return [];
					}
A
Alex Dima 已提交
614
					return [extensionDescription];
E
Erich Gamma 已提交
615 616
				});
			}
617
			return this.scanExtensions(input, log);
E
Erich Gamma 已提交
618
		}, (err) => {
619
			log.error(absoluteFolderPath, err);
E
Erich Gamma 已提交
620 621 622
			return [];
		});
	}
623
}