extHostConfiguration.ts 2.0 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';

import {clone} from 'vs/base/common/objects';
8
import {illegalState} from 'vs/base/common/errors';
E
Erich Gamma 已提交
9 10 11
import Event, {Emitter} from 'vs/base/common/event';
import {WorkspaceConfiguration} from 'vscode';

12
export class ExtHostConfiguration {
E
Erich Gamma 已提交
13 14 15 16 17

	private _config: any;
	private _hasConfig: boolean;
	private _onDidChangeConfiguration: Emitter<void>;

18
	constructor() {
E
Erich Gamma 已提交
19 20 21
		this._onDidChangeConfiguration = new Emitter<void>();
	}

J
Johannes Rieken 已提交
22
	get onDidChangeConfiguration(): Event<void> {
E
Erich Gamma 已提交
23 24 25
		return this._onDidChangeConfiguration && this._onDidChangeConfiguration.event;
	}

26
	public $acceptConfigurationChanged(config: any) {
E
Erich Gamma 已提交
27 28 29 30 31 32 33
		this._config = config;
		this._hasConfig = true;
		this._onDidChangeConfiguration.fire(undefined);
	}

	public getConfiguration(section?: string): WorkspaceConfiguration {
		if (!this._hasConfig) {
34
			throw illegalState('missing config');
E
Erich Gamma 已提交
35 36 37
		}

		const config = section
38
			? ExtHostConfiguration._lookUp(section, this._config)
E
Erich Gamma 已提交
39 40
			: this._config;

41 42 43 44 45 46 47
		let result: any;
		if (typeof config !== 'object') {
			// this catches missing config and accessing values
			result = {};
		} else {
			result = clone(config);
		}
E
Erich Gamma 已提交
48 49

		result.has = function(key: string): boolean {
50
			return typeof ExtHostConfiguration._lookUp(key, config) !== 'undefined';
B
Benjamin Pasero 已提交
51
		};
E
Erich Gamma 已提交
52
		result.get = function <T>(key: string, defaultValue?: T): T {
53
			let result = ExtHostConfiguration._lookUp(key, config);
E
Erich Gamma 已提交
54 55 56 57
			if (typeof result === 'undefined') {
				result = defaultValue;
			}
			return result;
B
Benjamin Pasero 已提交
58
		};
E
Erich Gamma 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
		return result;
	}

	private static _lookUp(section: string, config: any) {
		if (!section) {
			return;
		}
		let parts = section.split('.');
		let node = config;
		while (node && parts.length) {
			node = node[parts.shift()];
		}

		return node;
	}
}