configurationService.ts 8.5 KB
Newer Older
E
Erich Gamma 已提交
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 paths = require('vs/base/common/paths');
import winjs = require('vs/base/common/winjs.base');
import eventEmitter = require('vs/base/common/eventEmitter');
import objects = require('vs/base/common/objects');
import errors = require('vs/base/common/errors');
import uri from 'vs/base/common/uri';
import model = require('./model');
14
import {RunOnceScheduler} from 'vs/base/common/async';
E
Erich Gamma 已提交
15 16 17 18 19 20 21 22
import lifecycle = require('vs/base/common/lifecycle');
import collections = require('vs/base/common/collections');
import {IConfigurationService, ConfigurationServiceEventTypes}  from './configuration';
import {IEventService} from 'vs/platform/event/common/event';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import Files = require('vs/platform/files/common/files');
import {IConfigurationRegistry, Extensions} from './configurationRegistry';
import {Registry} from 'vs/platform/platform';
23
import Event, {fromEventEmitter} from 'vs/base/common/event';
E
Erich Gamma 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45


// ---- service abstract implementation

export interface IStat {
	resource: uri;
	isDirectory: boolean;
	children?: { resource: uri; }[];
}

export interface IContent {
	resource: uri;
	value: string;
}

interface ILoadConfigResult {
	merged: any;
	consolidated: { contents: any; parseErrors: string[]; };
	globals: { contents: any; parseErrors: string[]; };
}

export abstract class ConfigurationService extends eventEmitter.EventEmitter implements IConfigurationService, lifecycle.IDisposable {
46

E
Erich Gamma 已提交
47 48
	public serviceId = IConfigurationService;

49 50
	private static RELOAD_CONFIGURATION_DELAY = 50;

51 52
	public onDidUpdateConfiguration: Event<{ config: any }>;

E
Erich Gamma 已提交
53 54 55 56 57 58 59 60
	protected contextService: IWorkspaceContextService;
	protected eventService: IEventService;
	protected workspaceSettingsRootFolder: string;

	private loadConfigurationPromise: winjs.TPromise<any>;
	private bulkFetchFromWorkspacePromise: winjs.TPromise<any>;
	private workspaceFilePathToConfiguration: { [relativeWorkspacePath: string]: winjs.TPromise<model.IConfigFile> };
	private callOnDispose: Function;
61
	private reloadConfigurationScheduler: RunOnceScheduler;
E
Erich Gamma 已提交
62 63 64 65 66 67 68 69 70 71 72

	constructor(contextService: IWorkspaceContextService, eventService: IEventService, workspaceSettingsRootFolder: string = '.vscode') {
		super();

		this.contextService = contextService;
		this.eventService = eventService;

		this.workspaceSettingsRootFolder = workspaceSettingsRootFolder;
		this.workspaceFilePathToConfiguration = Object.create(null);

		let unbind = this.eventService.addListener(Files.EventType.FILE_CHANGES, (events) => this.handleFileEvents(events));
73
		let subscription = (<IConfigurationRegistry>Registry.as(Extensions.Configuration)).onDidRegisterConfiguration(() => this.reloadConfiguration());
E
Erich Gamma 已提交
74 75 76
		this.callOnDispose = () => {
			unbind();
			subscription.dispose();
B
Benjamin Pasero 已提交
77
		};
78 79

		this.onDidUpdateConfiguration = fromEventEmitter(this, ConfigurationServiceEventTypes.UPDATED);
E
Erich Gamma 已提交
80 81 82 83 84 85 86 87 88
	}

	protected abstract resolveContents(resource: uri[]): winjs.TPromise<IContent[]>;

	protected abstract resolveContent(resource: uri): winjs.TPromise<IContent>;

	protected abstract resolveStat(resource: uri): winjs.TPromise<IStat>;

	public dispose(): void {
89 90 91 92
		if (this.reloadConfigurationScheduler) {
			this.reloadConfigurationScheduler.dispose();
		}

E
Erich Gamma 已提交
93 94 95 96 97 98 99 100 101 102 103
		this.callOnDispose = lifecycle.cAll(this.callOnDispose);

		super.dispose();
	}

	public loadConfiguration(section?: string): winjs.TPromise<any> {
		if (!this.loadConfigurationPromise) {
			this.loadConfigurationPromise = this.doLoadConfiguration();
		}

		return this.loadConfigurationPromise.then((res: ILoadConfigResult) => {
B
Benjamin Pasero 已提交
104
			let result = section ? res.merged[section] : res.merged;
E
Erich Gamma 已提交
105

B
Benjamin Pasero 已提交
106
			let parseErrors = res.consolidated.parseErrors;
E
Erich Gamma 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
			if (res.globals.parseErrors) {
				parseErrors.push.apply(parseErrors, res.globals.parseErrors);
			}

			if (parseErrors.length > 0) {
				if (!result) {
					result = {};
				}
				result.$parseErrors = parseErrors;
			}

			return result;
		});
	}

	private doLoadConfiguration(): winjs.TPromise<ILoadConfigResult> {

		// Load globals
		return this.loadGlobalConfiguration().then((globals) => {

			// Load workspace locals
			return this.loadWorkspaceConfiguration().then((values) => {

				// Consolidate
B
Benjamin Pasero 已提交
131
				let consolidated = model.consolidate(values);
E
Erich Gamma 已提交
132 133

				// Override with workspace locals
B
Benjamin Pasero 已提交
134
				let merged = objects.mixin(
E
Erich Gamma 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
					objects.clone(globals.contents), 	// target: global/default values (but dont modify!)
					consolidated.contents,				// source: workspace configured values
					true								// overwrite
				);

				return {
					merged: merged,
					consolidated: consolidated,
					globals: globals
				};
			});
		});
	}

	protected loadGlobalConfiguration(): winjs.TPromise<{ contents: any; parseErrors: string[]; }> {
		return winjs.TPromise.as({
			contents: model.getDefaultValues()
		});
	}

	public hasWorkspaceConfiguration(): boolean {
		return !!this.workspaceFilePathToConfiguration['.vscode/' + model.CONFIG_DEFAULT_NAME + '.json'];
	}

	protected loadWorkspaceConfiguration(section?: string): winjs.TPromise<{ [relativeWorkspacePath: string]: model.IConfigFile }> {

		// once: when invoked for the first time we fetch *all* json
		// files using the bulk stats and content routes
		if (!this.bulkFetchFromWorkspacePromise) {
			this.bulkFetchFromWorkspacePromise = this.resolveStat(this.contextService.toResource(this.workspaceSettingsRootFolder)).then((stat) => {
				if (!stat.isDirectory) {
					return winjs.TPromise.as([]);
				}

				return this.resolveContents(stat.children.filter((stat) => paths.extname(stat.resource.fsPath) === '.json').map(stat => stat.resource));
			}, (err) => {
				if (err) {
					return []; // never fail this call
				}
			}).then((contents: IContent[]) => {
				contents.forEach(content => this.workspaceFilePathToConfiguration[this.contextService.toWorkspaceRelativePath(content.resource)] = winjs.TPromise.as(model.newConfigFile(content.value)));
			}, errors.onUnexpectedError);
		}

		// on change: join on *all* configuration file promises so that
		// we can merge them into a single configuration object. this
		// happens whenever a config file changes, is deleted, or added
		return this.bulkFetchFromWorkspacePromise.then(() => {
			return winjs.TPromise.join(this.workspaceFilePathToConfiguration);
		});
	}

187 188 189 190 191 192 193 194 195 196
	protected reloadConfiguration(): void {
		if (!this.reloadConfigurationScheduler) {
			this.reloadConfigurationScheduler = new RunOnceScheduler(() => {
				this.doReloadConfiguration().then((config) => this.emit(ConfigurationServiceEventTypes.UPDATED, { config: config })).done(null, errors.onUnexpectedError);
			}, ConfigurationService.RELOAD_CONFIGURATION_DELAY);
		}

		if (!this.reloadConfigurationScheduler.isScheduled()) {
			this.reloadConfigurationScheduler.schedule();
		}
E
Erich Gamma 已提交
197 198
	}

199
	private doReloadConfiguration(section?: string): winjs.TPromise<any> {
E
Erich Gamma 已提交
200 201 202 203 204 205
		this.loadConfigurationPromise = null;

		return this.loadConfiguration(section);
	}

	private handleFileEvents(event: Files.FileChangesEvent): void {
B
Benjamin Pasero 已提交
206 207 208 209
		let events = event.changes;
		let affectedByChanges = false;
		for (let i = 0, len = events.length; i < len; i++) {
			let workspacePath = this.contextService.toWorkspaceRelativePath(events[i].resource);
E
Erich Gamma 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
			if (!workspacePath) {
				continue; // event is not inside workspace
			}

			// Handle case where ".vscode" got deleted
			if (workspacePath === this.workspaceSettingsRootFolder && events[i].type === Files.FileChangeType.DELETED) {
				this.workspaceFilePathToConfiguration = Object.create(null);
				affectedByChanges = true;
			}

			// outside my folder or not a *.json file
			if (paths.extname(workspacePath) !== '.json' || !paths.isEqualOrParent(workspacePath, this.workspaceSettingsRootFolder)) {
				continue;
			}

			// insert 'fetch-promises' for add and update events and
			// remove promises for delete events
			switch (events[i].type) {
				case Files.FileChangeType.DELETED:
					affectedByChanges = collections.remove(this.workspaceFilePathToConfiguration, workspacePath);
					break;
				case Files.FileChangeType.UPDATED:
				case Files.FileChangeType.ADDED:
					this.workspaceFilePathToConfiguration[workspacePath] = this.resolveContent(events[i].resource).then(content => model.newConfigFile(content.value), errors.onUnexpectedError);
					affectedByChanges = true;
			}
		}

		if (affectedByChanges) {
239
			this.reloadConfiguration();
E
Erich Gamma 已提交
240 241 242
		}
	}
}