config.ts 5.4 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 33 34 35
}

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

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

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

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

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

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

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

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

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

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

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

	private registerWatcher(): void {

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

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

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

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

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

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

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

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

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

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

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