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

'use strict';

import nls = require('vs/nls');
import { tmpdir } from 'os';
import * as path from 'path';
import types = require('vs/base/common/types');
import { ServiceEvent } from 'vs/base/common/service';
import errors = require('vs/base/common/errors');
import * as pfs from 'vs/base/node/pfs';
import { assign } from 'vs/base/common/objects';
J
Joao Moreno 已提交
16
import { flatten } from 'vs/base/common/arrays';
E
Erich Gamma 已提交
17 18 19
import { extract, buffer } from 'vs/base/node/zip';
import { Promise, TPromise } from 'vs/base/common/winjs.base';
import { IExtensionsService, IExtension, IExtensionManifest, IGalleryInformation } from 'vs/workbench/parts/extensions/common/extensions';
J
Joao Moreno 已提交
20
import { download } from 'vs/base/node/request';
21
import { getProxyAgent } from 'vs/base/node/proxy';
E
Erich Gamma 已提交
22 23 24
import { IWorkspaceContextService } from 'vs/workbench/services/workspace/common/contextService';
import { Limiter } from 'vs/base/common/async';
import Event, { Emitter } from 'vs/base/common/event';
25
import { UserSettings } from 'vs/workbench/node/userSettings';
J
Joao Moreno 已提交
26 27
import * as semver from 'semver';
import {groupBy, values} from 'vs/base/common/collections';
E
Erich Gamma 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

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

function validate(zipPath: string, extension?: IExtension): TPromise<IExtension> {
	return buffer(zipPath, 'extension/package.json')
		.then(buffer => parseManifest(buffer.toString('utf8')))
		.then(manifest => {
			if (extension) {
				if (extension.name !== manifest.name) {
					return Promise.wrapError(Error(nls.localize('invalidName', "Extension invalid: manifest name mismatch.")));
				}

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

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

			return Promise.as(manifest);
		});
}

function createExtension(manifest: IExtensionManifest, galleryInformation?: IGalleryInformation, path?: string): IExtension {
	const extension: IExtension = {
		name: manifest.name,
		displayName: manifest.displayName || manifest.name,
		publisher: manifest.publisher,
		version: manifest.version,
		description: manifest.description || ''
	};

	if (galleryInformation) {
		extension.galleryInformation = galleryInformation;
	}

	if (path) {
		extension.path = path;
	}

	return extension;
}

export class ExtensionsService implements IExtensionsService {

	public serviceId = IExtensionsService;

	private extensionsPath: string;

	private _onInstallExtension = new Emitter<IExtensionManifest>();
	@ServiceEvent onInstallExtension = this._onInstallExtension.event;

	private _onDidInstallExtension = new Emitter<IExtension>();
	@ServiceEvent onDidInstallExtension = this._onDidInstallExtension.event;

	private _onUninstallExtension = new Emitter<IExtension>();
	@ServiceEvent onUninstallExtension = this._onUninstallExtension.event;

	private _onDidUninstallExtension = new Emitter<IExtension>();
	@ServiceEvent onDidUninstallExtension = this._onDidUninstallExtension.event;

	constructor(
		@IWorkspaceContextService private contextService: IWorkspaceContextService
	) {
		const env = contextService.getConfiguration().env;
		this.extensionsPath = env.userPluginsHome;
	}

	public install(extension: IExtension): TPromise<IExtension>;
	public install(zipPath: string): TPromise<IExtension>;
	public install(arg: any): TPromise<IExtension> {
		if (types.isString(arg)) {
			return this.installFromZip(arg);
		}

		return this.installFromGallery(arg);
	}

	private installFromGallery(extension: IExtension): TPromise<IExtension> {
		const galleryInformation = extension.galleryInformation;

		if (!galleryInformation) {
			return TPromise.wrapError(new Error(nls.localize('missingGalleryInformation', "Gallery information is missing")));
		}

J
Joao Moreno 已提交
123
		const url = galleryInformation.downloadUrl;
E
Erich Gamma 已提交
124
		const zipPath = path.join(tmpdir(), galleryInformation.id);
J
Joao Moreno 已提交
125
		const extensionPath = path.join(this.extensionsPath, `${ extension.publisher }.${ extension.name }-${ extension.version }`);
E
Erich Gamma 已提交
126 127
		const manifestPath = path.join(extensionPath, 'package.json');

J
Joao Moreno 已提交
128 129
		const settings = TPromise.join([
			UserSettings.getValue(this.contextService, 'http.proxy'),
J
Joao Moreno 已提交
130
			UserSettings.getValue(this.contextService, 'http.proxyStrictSSL')
J
Joao Moreno 已提交
131 132
		]);

133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
		return settings.then(settings => {
			const proxyUrl: string = settings[0];
			const strictSSL: boolean = settings[1];
			const agent = getProxyAgent(url, { proxyUrl, strictSSL });

			return download(zipPath, { url, agent, strictSSL })
				.then(() => validate(zipPath, extension))
				.then(manifest => { this._onInstallExtension.fire(manifest); return manifest; })
				.then(manifest => extract(zipPath, extensionPath, { sourcePath: 'extension', overwrite: true }).then(() => manifest))
				.then(manifest => {
					manifest = assign({ __metadata: galleryInformation }, manifest);
					return pfs.writeFile(manifestPath, JSON.stringify(manifest, null, '\t'));
				})
				.then(() => { this._onDidInstallExtension.fire(extension); return extension; });
		});
E
Erich Gamma 已提交
148 149 150 151
	}

	private installFromZip(zipPath: string): TPromise<IExtension> {
		return validate(zipPath).then(manifest => {
152
			const extensionPath = path.join(this.extensionsPath, `${ manifest.publisher }.${ manifest.name }-${ manifest.version }`);
E
Erich Gamma 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
			this._onInstallExtension.fire(manifest);

			return extract(zipPath, extensionPath, { sourcePath: 'extension', overwrite: true })
				.then(() => createExtension(manifest, (<any> manifest).__metadata, extensionPath))
				.then(extension => { this._onDidInstallExtension.fire(extension); return extension; });
		});
	}

	public uninstall(extension: IExtension): TPromise<void> {
		const extensionPath = this.getInstallationPath(extension);

		return pfs.exists(extensionPath)
			.then(exists => exists ? null : Promise.wrapError(new Error(nls.localize('notExists', "Could not find extension"))))
			.then(() => this._onUninstallExtension.fire(extension))
			.then(() => pfs.rimraf(extensionPath))
			.then(() => this._onDidUninstallExtension.fire(extension));
	}

J
Joao Moreno 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
	public getInstalled(includeDuplicateVersions: boolean = false): TPromise<IExtension[]> {
		const all = this.getAllInstalled();

		if (includeDuplicateVersions) {
			return all;
		}

		return all.then(plugins => {
			const byId = values(groupBy(plugins, p => `${ p.publisher }.${ p.name }`));
			return byId.map(p => p.sort((a, b) => semver.rcompare(a.version, b.version))[0]);
		});
	}

	private getDeprecated(): TPromise<IExtension[]> {
		return this.getAllInstalled().then(plugins => {
			const byId = values(groupBy(plugins, p => `${ p.publisher }.${ p.name }`));
			return flatten(byId.map(p => p.sort((a, b) => semver.rcompare(a.version, b.version)).slice(1)));
		});
	}

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

		return pfs.readdir(this.extensionsPath)
J
Joao Moreno 已提交
195
			.then<IExtension[]>(extensions => Promise.join(extensions.map(e => {
E
Erich Gamma 已提交
196 197 198 199 200 201 202 203 204 205 206 207 208
				const extensionPath = path.join(this.extensionsPath, e);

				return limiter.queue(
					() => pfs.readFile(path.join(extensionPath, 'package.json'), 'utf8')
						.then(raw => parseManifest(raw))
						.then(manifest => createExtension(manifest, (<any> manifest).__metadata, extensionPath))
						.then(null, () => null)
				);
			})))
			.then(result => result.filter(a => !!a));
	}

	private getInstallationPath(extension: IExtension): string {
209
		return extension.path || path.join(this.extensionsPath, `${ extension.publisher }.${ extension.name }-${ extension.version }`);
E
Erich Gamma 已提交
210
	}
J
Joao Moreno 已提交
211 212 213 214 215

	public removeDeprecatedExtensions(): TPromise<void> {
		return this.getDeprecated()
			.then<void>(extensions => TPromise.join(extensions.filter(e => !!e.path).map(e => pfs.rimraf(e.path))));
		}
E
Erich Gamma 已提交
216
}