config.ts 4.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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 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 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
/*---------------------------------------------------------------------------------------------
 *  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 * as fs from 'fs';
import * as objects from 'vs/base/common/objects';
import {IDisposable, dispose, toDisposable} from 'vs/base/common/lifecycle';
import Event, {Emitter} from 'vs/base/common/event';
import * as json from 'vs/base/common/json';

export interface IConfigurationServiceEvent<T> {
	config: T;
}

export interface IConfigWatcher<T> {
	getConfig(): T;
	getValue<V>(key: string, fallback?: V): V;
}

export interface IConfigOptions<T> {
	defaultConfig?: T;
	changeBufferDelay?: number;
}

/**
 * A simple helper to watch a configured file for changes and process its contents as JSON object.
 */
export class ConfigWatcher<T> implements IConfigWatcher<T>, IDisposable {
	private cache: T;
	private loaded: boolean;
	private timeoutHandle: number;
	private disposables: IDisposable[];
	private _onDidUpdateConfiguration;

	constructor(private path: string, private options: IConfigOptions<T> = { changeBufferDelay: 0, defaultConfig: Object.create(null) }) {
		this.disposables = [];

		this._onDidUpdateConfiguration = new Emitter<IConfigurationServiceEvent<T>>();
		this.disposables.push(this._onDidUpdateConfiguration);

		this.registerWatcher();
		this.initAsync();
	}

	public get onDidUpdateConfiguration(): Event<IConfigurationServiceEvent<T>> {
		return this._onDidUpdateConfiguration.event;
	}

	private initAsync(): void {
		this.loadAsync(config => {
			if (!this.loaded) {
				this.updateCache(config); // prevent race condition if config was loaded sync already
			}
		});
	}

	private updateCache(value: T): void {
		this.cache = value;
		this.loaded = true;
	}

	private loadSync(): T {
		let raw: string;
		try {
			raw = fs.readFileSync(this.path).toString();
		} catch (error) {
			return this.options.defaultConfig;
		}

		return this.parse(raw);
	}

	private loadAsync(callback: (config: T) => void): void {
		fs.readFile(this.path, (error, raw) => {
			if (error) {
				return callback(this.options.defaultConfig);
			}

			return callback(this.parse(raw.toString()));
		});
	}

	private parse(raw: string): T {
		try {
			return json.parse(raw) || this.options.defaultConfig;
		} catch (error) {
			// Ignore loading and parsing errors
		}

		return this.options.defaultConfig;
	}

	private registerWatcher(): void {

		// Support for watching symlinks
		fs.lstat(this.path, (err, stat) => {
			if (err || stat.isDirectory()) {
				return; // path is not a valid file
			}

			// We found a symlink
			if (stat.isSymbolicLink()) {
				fs.readlink(this.path, (err, realPath) => {
					if (err) {
						return; // path is not a valid symlink
					}

					this.watch(realPath);
				});
			}

			// We found a normal file
			else {
				this.watch(this.path);
			}
		});
	}

	private watch(path: string): void {
		const watcher = fs.watch(path);
		watcher.on('change', () => this.onConfigFileChange());

		this.disposables.push(toDisposable(() => {
			watcher.removeAllListeners();
			watcher.close();
		}));
	}

	private onConfigFileChange(): void {

		// we can get multiple change events for one change, so we buffer through a timeout
		if (this.timeoutHandle) {
			global.clearTimeout(this.timeoutHandle);
			this.timeoutHandle = null;
		}

		this.timeoutHandle = global.setTimeout(() => {
B
Benjamin Pasero 已提交
141
			this.loadAsync(currentConfig => {
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
				if (!objects.equals(currentConfig, this.cache)) {
					this.updateCache(currentConfig);

					this._onDidUpdateConfiguration.fire({ config: this.cache });
				}
			});
		}, this.options.changeBufferDelay);
	}

	public getConfig(): T {
		this.ensureLoaded();

		return this.cache;
	}

	public getValue<V>(key: string, fallback?: V): V {
		this.ensureLoaded();

		if (!key) {
			return fallback;
		}

		const value = this.cache ? this.cache[key] : void 0;

		return typeof value !== 'undefined' ? value : fallback;
	}

	private ensureLoaded(): void {
		if (!this.loaded) {
			this.updateCache(this.loadSync());
		}
	}

	public dispose(): void {
		this.disposables = dispose(this.disposables);
	}
}