config.ts 6.1 KB
Newer Older
1 2 3 4 5 6 7 8
/*---------------------------------------------------------------------------------------------
 *  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';
9
import { dirname, basename } from 'path';
10
import * as objects from 'vs/base/common/objects';
J
Johannes Rieken 已提交
11 12
import { IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle';
import Event, { Emitter } from 'vs/base/common/event';
13
import * as json from 'vs/base/common/json';
14
import * as extfs from 'vs/base/node/extfs';
15

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

export interface IConfigWatcher<T> {
21 22 23
	path: string;
	hasParseErrors: boolean;

B
Benjamin Pasero 已提交
24
	reload(callback: (config: T) => void): void;
25 26 27 28 29
	getConfig(): T;
	getValue<V>(key: string, fallback?: V): V;
}

export interface IConfigOptions<T> {
30
	onError: (error: Error | string) => void;
31 32
	defaultConfig?: T;
	changeBufferDelay?: number;
33
	parse?: (content: string, errors: any[]) => T;
34
	initCallback?: (config: T) => void;
35 36 37 38
}

/**
 * A simple helper to watch a configured file for changes and process its contents as JSON object.
B
Benjamin Pasero 已提交
39 40 41 42 43
 * 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
44 45 46
 */
export class ConfigWatcher<T> implements IConfigWatcher<T>, IDisposable {
	private cache: T;
47
	private parseErrors: json.ParseError[];
B
Benjamin Pasero 已提交
48
	private disposed: boolean;
49
	private loaded: boolean;
J
Joao Moreno 已提交
50
	private timeoutHandle: NodeJS.Timer;
51
	private disposables: IDisposable[];
B
Benjamin Pasero 已提交
52
	private _onDidUpdateConfiguration: Emitter<IConfigurationChangeEvent<T>>;
53
	private configName: string;
54

55
	constructor(private _path: string, private options: IConfigOptions<T> = { changeBufferDelay: 0, defaultConfig: Object.create(null), onError: error => console.error(error) }) {
56
		this.disposables = [];
57
		this.configName = basename(this._path);
58

B
Benjamin Pasero 已提交
59
		this._onDidUpdateConfiguration = new Emitter<IConfigurationChangeEvent<T>>();
60 61 62 63 64 65
		this.disposables.push(this._onDidUpdateConfiguration);

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

66 67 68 69 70 71 72 73
	public get path(): string {
		return this._path;
	}

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

B
Benjamin Pasero 已提交
74
	public get onDidUpdateConfiguration(): Event<IConfigurationChangeEvent<T>> {
75 76 77 78 79 80 81 82
		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
			}
83 84 85
			if (this.options.initCallback) {
				this.options.initCallback(this.getConfig());
			}
86 87 88 89 90 91 92 93 94 95
		});
	}

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

	private loadSync(): T {
		try {
B
Benjamin Pasero 已提交
96
			return this.parse(fs.readFileSync(this._path).toString());
97 98 99 100 101 102
		} catch (error) {
			return this.options.defaultConfig;
		}
	}

	private loadAsync(callback: (config: T) => void): void {
103
		fs.readFile(this._path, (error, raw) => {
104 105 106 107 108 109 110 111 112
			if (error) {
				return callback(this.options.defaultConfig);
			}

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

	private parse(raw: string): T {
B
Benjamin Pasero 已提交
113
		let res: T;
114
		try {
115
			this.parseErrors = [];
116
			res = this.options.parse ? this.options.parse(raw, this.parseErrors) : json.parse(raw, this.parseErrors);
117
		} catch (error) {
B
Benjamin Pasero 已提交
118
			// Ignore parsing errors
119 120
		}

B
Benjamin Pasero 已提交
121
		return res || this.options.defaultConfig;
122 123 124 125
	}

	private registerWatcher(): void {

126
		// Watch the parent of the path so that we detect ADD and DELETES
127 128
		const parentFolder = dirname(this._path);
		this.watch(parentFolder, true);
129 130

		// Check if the path is a symlink and watch its target if so
131
		fs.lstat(this._path, (err, stat) => {
132 133 134 135 136 137
			if (err || stat.isDirectory()) {
				return; // path is not a valid file
			}

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

143
					this.watch(realPath, false);
144 145 146 147 148
				});
			}
		});
	}

149
	private watch(path: string, isParentFolder: boolean): void {
B
Benjamin Pasero 已提交
150 151 152 153
		if (this.disposed) {
			return; // avoid watchers that will never get disposed by checking for being disposed
		}

154
		try {
155
			const watcher = extfs.watch(path, (type, file) => this.onConfigFileChange(type, file, isParentFolder));
156
			watcher.on('error', (code, signal) => this.options.onError(`Error watching ${path} for configuration changes (${code}, ${signal})`));
157

158 159 160 161 162
			this.disposables.push(toDisposable(() => {
				watcher.removeAllListeners();
				watcher.close();
			}));
		} catch (error) {
B
Benjamin Pasero 已提交
163 164
			fs.exists(path, exists => {
				if (exists) {
165
					this.options.onError(`Failed to watch ${path} for configuration changes (${error.toString()})`);
B
Benjamin Pasero 已提交
166 167
				}
			});
168
		}
169 170
	}

171 172 173 174 175
	private onConfigFileChange(eventType: string, filename: string, isParentFolder: boolean): void {
		if (isParentFolder && filename !== this.configName) {
			return; // a change to a sibling file that is not our config file
		}

176 177 178 179 180
		if (this.timeoutHandle) {
			global.clearTimeout(this.timeoutHandle);
			this.timeoutHandle = null;
		}

B
Benjamin Pasero 已提交
181 182
		// we can get multiple change events for one change, so we buffer through a timeout
		this.timeoutHandle = global.setTimeout(() => this.reload(), this.options.changeBufferDelay);
183 184
	}

B
Benjamin Pasero 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198
	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);
			}
		});
	}

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
	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 已提交
224
		this.disposed = true;
225 226 227
		this.disposables = dispose(this.disposables);
	}
}