config.ts 5.6 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
	getConfig(): T;
	getValue<V>(key: string, fallback?: V): V;
}

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

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

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

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

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

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

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

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

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

	private loadSync(): T {
		try {
B
Benjamin Pasero 已提交
92
			return this.parse(fs.readFileSync(this._path).toString());
93 94 95 96 97 98
		} catch (error) {
			return this.options.defaultConfig;
		}
	}

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

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

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

B
Benjamin Pasero 已提交
117
		return res || this.options.defaultConfig;
118 119 120 121
	}

	private registerWatcher(): void {

122 123
		// Watch the parent of the path so that we detect ADD and DELETES
		const parentFolder = path.dirname(this._path);
B
Benjamin Pasero 已提交
124
		this.watch(parentFolder);
125 126

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

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

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

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

150 151 152
		try {
			const watcher = fs.watch(path);
			watcher.on('change', () => this.onConfigFileChange());
153

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

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

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

B
Benjamin Pasero 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190
	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);
			}
		});
	}

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