config.ts 5.3 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 * as path 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 14
import * as json from 'vs/base/common/json';

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

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

B
Benjamin Pasero 已提交
23
	reload(callback: (config: T) => void): void;
24 25 26 27 28 29 30 31 32 33 34
	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 已提交
35 36 37 38 39
 * 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
40 41 42
 */
export class ConfigWatcher<T> implements IConfigWatcher<T>, IDisposable {
	private cache: T;
43
	private parseErrors: json.ParseError[];
B
Benjamin Pasero 已提交
44
	private disposed: boolean;
45 46 47
	private loaded: boolean;
	private timeoutHandle: number;
	private disposables: IDisposable[];
B
Benjamin Pasero 已提交
48
	private _onDidUpdateConfiguration: Emitter<IConfigurationChangeEvent<T>>;
49

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

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

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

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

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

B
Benjamin Pasero 已提交
68
	public get onDidUpdateConfiguration(): Event<IConfigurationChangeEvent<T>> {
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 {
		try {
B
Benjamin Pasero 已提交
87
			return this.parse(fs.readFileSync(this._path).toString());
88 89 90 91 92 93
		} catch (error) {
			return this.options.defaultConfig;
		}
	}

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

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

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

B
Benjamin Pasero 已提交
112
		return res || this.options.defaultConfig;
113 114 115 116
	}

	private registerWatcher(): void {

117 118
		// Watch the parent of the path so that we detect ADD and DELETES
		const parentFolder = path.dirname(this._path);
B
Benjamin Pasero 已提交
119
		this.watch(parentFolder);
120 121

		// Check if the path is a symlink and watch its target if so
122
		fs.lstat(this._path, (err, stat) => {
123 124 125 126 127 128
			if (err || stat.isDirectory()) {
				return; // path is not a valid file
			}

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

					this.watch(realPath);
				});
			}
		});
	}

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

145 146 147
		try {
			const watcher = fs.watch(path);
			watcher.on('change', () => this.onConfigFileChange());
148

149 150 151 152 153
			this.disposables.push(toDisposable(() => {
				watcher.removeAllListeners();
				watcher.close();
			}));
		} catch (error) {
B
Benjamin Pasero 已提交
154 155 156 157 158
			fs.exists(path, exists => {
				if (exists) {
					console.warn(`Failed to watch ${path} for configuration changes (${error.toString()})`);
				}
			});
159
		}
160 161 162 163 164 165 166 167
	}

	private onConfigFileChange(): void {
		if (this.timeoutHandle) {
			global.clearTimeout(this.timeoutHandle);
			this.timeoutHandle = null;
		}

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

B
Benjamin Pasero 已提交
172 173 174 175 176 177 178 179 180 181 182 183 184 185
	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);
			}
		});
	}

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