config.ts 5.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
/*---------------------------------------------------------------------------------------------
 *  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';

B
Benjamin Pasero 已提交
14
export interface IConfigurationChangeEvent<T> {
15 16 17 18
	config: T;
}

export interface IConfigWatcher<T> {
19 20 21
	path: string;
	hasParseErrors: boolean;

B
Benjamin Pasero 已提交
22
	reload(callback: (config: T) => void): void;
23 24 25 26 27 28 29 30 31 32 33
	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.
B
Benjamin Pasero 已提交
34 35 36 37 38
 * Supports:
 * - comments in JSON files and errors
 * - symlinks for the config file itself
 * - delayed processing of changes to accomodate for lots of changes
 * - configurable defaults
39 40 41
 */
export class ConfigWatcher<T> implements IConfigWatcher<T>, IDisposable {
	private cache: T;
42
	private parseErrors: json.ParseError[];
B
Benjamin Pasero 已提交
43
	private disposed: boolean;
44 45 46
	private loaded: boolean;
	private timeoutHandle: number;
	private disposables: IDisposable[];
47
	private _onDidUpdateConfiguration:Emitter<IConfigurationChangeEvent<T>>;
48

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

B
Benjamin Pasero 已提交
52
		this._onDidUpdateConfiguration = new Emitter<IConfigurationChangeEvent<T>>();
53 54 55 56 57 58
		this.disposables.push(this._onDidUpdateConfiguration);

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

59 60 61 62 63 64 65 66
	public get path(): string {
		return this._path;
	}

	public get hasParseErrors(): boolean {
		return this.parseErrors && this.parseErrors.length > 0;
	}

B
Benjamin Pasero 已提交
67
	public get onDidUpdateConfiguration(): Event<IConfigurationChangeEvent<T>> {
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
		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 {
87
			raw = fs.readFileSync(this._path).toString();
88 89 90 91 92 93 94 95
		} catch (error) {
			return this.options.defaultConfig;
		}

		return this.parse(raw);
	}

	private loadAsync(callback: (config: T) => void): void {
96
		fs.readFile(this._path, (error, raw) => {
97 98 99 100 101 102 103 104 105
			if (error) {
				return callback(this.options.defaultConfig);
			}

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

	private parse(raw: string): T {
B
Benjamin Pasero 已提交
106
		let res: T;
107
		try {
108 109
			this.parseErrors = [];
			res = json.parse(raw, this.parseErrors);
110 111 112 113
		} catch (error) {
			// Ignore loading and parsing errors
		}

B
Benjamin Pasero 已提交
114
		return res || this.options.defaultConfig;
115 116 117 118 119
	}

	private registerWatcher(): void {

		// Support for watching symlinks
120
		fs.lstat(this._path, (err, stat) => {
121 122 123 124 125 126
			if (err || stat.isDirectory()) {
				return; // path is not a valid file
			}

			// We found a symlink
			if (stat.isSymbolicLink()) {
127
				fs.readlink(this._path, (err, realPath) => {
128 129 130 131 132 133 134 135 136 137
					if (err) {
						return; // path is not a valid symlink
					}

					this.watch(realPath);
				});
			}

			// We found a normal file
			else {
138
				this.watch(this._path);
139 140 141 142 143
			}
		});
	}

	private watch(path: string): void {
B
Benjamin Pasero 已提交
144 145 146 147
		if (this.disposed) {
			return; // avoid watchers that will never get disposed by checking for being disposed
		}

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
		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 已提交
166
			this.reload();
167 168 169
		}, this.options.changeBufferDelay);
	}

B
Benjamin Pasero 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183
	public reload(callback?: (config: T) => void): void {
		this.loadAsync(currentConfig => {
			if (!objects.equals(currentConfig, this.cache)) {
				this.updateCache(currentConfig);

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

			if (callback) {
				return callback(currentConfig);
			}
		});
	}

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
	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 {
B
Benjamin Pasero 已提交
209
		this.disposed = true;
210 211 212
		this.disposables = dispose(this.disposables);
	}
}