configuration.ts 16.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*---------------------------------------------------------------------------------------------
 *  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 URI from 'vs/base/common/uri';
import * as paths from 'vs/base/common/paths';
import { TPromise } from 'vs/base/common/winjs.base';
import Event, { Emitter } from 'vs/base/common/event';
import { distinct, equals } from "vs/base/common/arrays";
import * as objects from 'vs/base/common/objects';
import * as errors from 'vs/base/common/errors';
import * as collections from 'vs/base/common/collections';
import { Disposable } from "vs/base/common/lifecycle";
import { Schemas } from "vs/base/common/network";
import { RunOnceScheduler } from 'vs/base/common/async';
import { readFile } from 'vs/base/node/pfs';
import * as extfs from 'vs/base/node/extfs';
20
import { IWorkspaceContextService, IWorkspace2, Workspace as SingleRootWorkspace, IWorkspace } from "vs/platform/workspace/common/workspace";
21 22 23
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { FileChangeType, FileChangesEvent, isEqual } from 'vs/platform/files/common/files';
import { ScopedConfigModel, WorkspaceConfigModel, WorkspaceSettingsConfigModel } from 'vs/workbench/services/configuration/common/configurationModels';
I
isidor 已提交
24
import { IConfigurationServiceEvent, ConfigurationSource, getConfigurationValue, IConfigurationOptions, Configuration } from 'vs/platform/configuration/common/configuration';
25 26
import { IWorkspaceConfigurationValues, IWorkspaceConfigurationService, IWorkspaceConfigurationValue, WORKSPACE_CONFIG_FOLDER_DEFAULT_NAME, WORKSPACE_STANDALONE_CONFIGURATIONS, WORKSPACE_CONFIG_DEFAULT_PATH } from 'vs/workbench/services/configuration/common/configuration';
import { ConfigurationService as GlobalConfigurationService } from 'vs/platform/configuration/node/configurationService';
I
isidor 已提交
27 28
import { createHash } from "crypto";
import { basename } from "path";
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

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

interface IContent {
	resource: URI;
	value: string;
}

interface IWorkspaceConfiguration<T> {
	workspace: T;
	consolidated: any;
}

type IWorkspaceFoldersConfiguration = { [rootFolder: string]: { folders: string[]; } };

48
class Workspace implements IWorkspace2 {
I
isidor 已提交
49
	private _name: string;
50

I
isidor 已提交
51 52 53 54 55
	constructor(
		public readonly id: string,
		private _roots: URI[]
	) {
		//
56 57
	}

I
isidor 已提交
58 59 60
	public set roots(roots: URI[]) {
		this._roots = roots;
		this._name = null; // will be recomputed based on roots next time accessed
61 62
	}

I
isidor 已提交
63 64
	public get roots(): URI[] {
		return this._roots;
65 66
	}

I
isidor 已提交
67 68 69 70 71 72 73
	public get name(): string {
		if (!this._name) {
			this._name = this.roots.map(root => basename(root.fsPath)).join(', ');
		}

		return this._name;
	}
74 75
}

76
export class WorkspaceConfigurationService extends Disposable implements IWorkspaceContextService, IWorkspaceConfigurationService {
77 78 79 80 81

	private static RELOAD_CONFIGURATION_DELAY = 50;

	public _serviceBrand: any;

82 83
	private readonly _onDidChangeWorkspaceRoots: Emitter<URI[]> = this._register(new Emitter<URI[]>());
	public readonly onDidChangeWorkspaceRoots: Event<URI[]> = this._onDidChangeWorkspaceRoots.event;
84 85 86 87 88 89

	private readonly _onDidUpdateConfiguration: Emitter<IConfigurationServiceEvent> = this._register(new Emitter<IConfigurationServiceEvent>());
	public readonly onDidUpdateConfiguration: Event<IConfigurationServiceEvent> = this._onDidUpdateConfiguration.event;

	private baseConfigurationService: GlobalConfigurationService<any>;

I
isidor 已提交
90
	private cachedConfig: Configuration<any>;
91 92 93
	private cachedWorkspaceConfig: WorkspaceConfigModel<any>;

	private bulkFetchFromWorkspacePromise: TPromise<any>;
I
isidor 已提交
94
	private workspaceFilePathToConfiguration: { [relativeWorkspacePath: string]: TPromise<Configuration<any>> };
95 96
	private reloadConfigurationScheduler: RunOnceScheduler;

97
	private readonly workspace: Workspace;
98

99
	constructor(private environmentService: IEnvironmentService, private singleRootWorkspace?: SingleRootWorkspace, private workspaceSettingsRootFolder: string = WORKSPACE_CONFIG_FOLDER_DEFAULT_NAME) {
100 101
		super();

I
isidor 已提交
102
		this.workspace = singleRootWorkspace ? new Workspace(createHash('md5').update(singleRootWorkspace.resource.toString()).digest('hex'), [singleRootWorkspace.resource]) : null; // TODO@Ben for now use the first root folder as id, but revisit this later
103 104

		this.workspaceFilePathToConfiguration = Object.create(null);
I
isidor 已提交
105
		this.cachedConfig = new Configuration<any>();
106 107 108 109 110 111 112 113 114
		this.cachedWorkspaceConfig = new WorkspaceConfigModel(new WorkspaceSettingsConfigModel(null), []);

		this.baseConfigurationService = this._register(new GlobalConfigurationService(environmentService));
		this.reloadConfigurationScheduler = this._register(new RunOnceScheduler(() => this.doLoadConfiguration()
			.then(config => this._onDidUpdateConfiguration.fire({
				config: config.consolidated,
				source: ConfigurationSource.Workspace,
				sourceConfig: config.workspace
			}))
115
			.done(null, errors.onUnexpectedError), WorkspaceConfigurationService.RELOAD_CONFIGURATION_DELAY));
116 117 118 119 120 121 122 123 124 125 126

		this._register(this.baseConfigurationService.onDidUpdateConfiguration(e => this.onBaseConfigurationChanged(e)));
		this._register(this.onDidUpdateConfiguration(e => this.resolveAdditionalFolders(true)));
	}

	private resolveAdditionalFolders(notify?: boolean): void {
		if (!this.workspace) {
			return; // no additional folders for empty workspaces
		}

		// Resovled configured folders for workspace
127 128
		let [master] = this.workspace.roots;
		let configuredFolders: URI[] = [master];
129 130
		const config = this.getConfiguration<IWorkspaceFoldersConfiguration>('workspace');
		if (config) {
131
			const workspaceConfig = config[master.toString()];
132 133 134 135 136 137 138 139 140 141 142 143 144
			if (workspaceConfig) {
				const additionalFolders = workspaceConfig.folders
					.map(f => URI.parse(f))
					.filter(r => r.scheme === Schemas.file); // only support files for now

				configuredFolders.push(...additionalFolders);
			}
		}

		// Remove duplicates
		configuredFolders = distinct(configuredFolders, r => r.toString());

		// Find changes
145
		const changed = !equals(this.workspace.roots, configuredFolders, (r1, r2) => r1.toString() === r2.toString());
146

I
isidor 已提交
147
		this.workspace.roots = configuredFolders;
148 149

		if (notify && changed) {
150
			this._onDidChangeWorkspaceRoots.fire(configuredFolders);
151 152 153
		}
	}

154 155
	public getWorkspace(): IWorkspace {
		return this.singleRootWorkspace;
156 157
	}

158
	public getWorkspace2(): IWorkspace2 {
159 160 161 162 163 164 165 166
		return this.workspace;
	}

	public hasWorkspace(): boolean {
		return !!this.workspace;
	}

	public isInsideWorkspace(resource: URI): boolean {
167
		return this.workspace ? this.singleRootWorkspace.isInsideWorkspace(resource) : false;
168 169 170
	}

	public toWorkspaceRelativePath(resource: URI, toOSPath?: boolean): string {
171
		return this.workspace ? this.singleRootWorkspace.toWorkspaceRelativePath(resource, toOSPath) : null;
172 173 174
	}

	public toResource(workspaceRelativePath: string): URI {
175
		return this.workspace ? this.singleRootWorkspace.toResource(workspaceRelativePath) : null;
176 177 178 179 180 181 182 183
	}

	private onBaseConfigurationChanged(event: IConfigurationServiceEvent): void {
		if (event.source === ConfigurationSource.Default) {
			this.cachedWorkspaceConfig.update();
		}

		// update cached config when base config changes
I
isidor 已提交
184
		const configModel = <Configuration<any>>this.baseConfigurationService.getCache().consolidated		// global/default values (do NOT modify)
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
			.merge(this.cachedWorkspaceConfig);		// workspace configured values

		// emit this as update to listeners if changed
		if (!objects.equals(this.cachedConfig.contents, configModel.contents)) {
			this.cachedConfig = configModel;
			this._onDidUpdateConfiguration.fire({
				config: this.cachedConfig.contents,
				source: event.source,
				sourceConfig: event.sourceConfig
			});
		}
	}

	public initialize(): TPromise<void> {
		return this.doLoadConfiguration().then(() => null);
	}

	public getConfiguration<C>(section?: string): C
	public getConfiguration<C>(options?: IConfigurationOptions): C
	public getConfiguration<C>(arg?: any): C {
		const options = this.toOptions(arg);
I
isidor 已提交
206
		const configModel = options.overrideIdentifier ? this.cachedConfig.override<C>(options.overrideIdentifier) : this.cachedConfig;
207 208 209 210 211 212 213 214
		return options.section ? configModel.getContentsFor<C>(options.section) : configModel.contents;
	}

	public lookup<C>(key: string, overrideIdentifier?: string): IWorkspaceConfigurationValue<C> {
		const configurationValue = this.baseConfigurationService.lookup<C>(key, overrideIdentifier);
		return {
			default: configurationValue.default,
			user: configurationValue.user,
I
isidor 已提交
215 216
			workspace: objects.clone(getConfigurationValue<C>(overrideIdentifier ? this.cachedWorkspaceConfig.override(overrideIdentifier).contents : this.cachedWorkspaceConfig.contents, key)),
			value: objects.clone(getConfigurationValue<C>(overrideIdentifier ? this.cachedConfig.override(overrideIdentifier).contents : this.cachedConfig.contents, key))
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
		};
	}

	public keys() {
		const keys = this.baseConfigurationService.keys();

		return {
			default: keys.default,
			user: keys.user,
			workspace: this.cachedWorkspaceConfig.keys
		};
	}

	public values(): IWorkspaceConfigurationValues {
		const result: IWorkspaceConfigurationValues = Object.create(null);
		const keyset = this.keys();
		const keys = [...keyset.workspace, ...keyset.user, ...keyset.default].sort();

		let lastKey: string;
		for (const key of keys) {
			if (key !== lastKey) {
				lastKey = key;
				result[key] = this.lookup(key);
			}
		}

		return result;
	}

	public reloadConfiguration(section?: string): TPromise<any> {

		// Reset caches to ensure we are hitting the disk
		this.bulkFetchFromWorkspacePromise = null;
		this.workspaceFilePathToConfiguration = Object.create(null);

		// Load configuration
		return this.baseConfigurationService.reloadConfiguration().then(() => {
			const current = this.cachedConfig;
			return this.doLoadConfiguration().then(configuration => {
				// emit this as update to listeners if changed
				if (!objects.equals(current, this.cachedConfig)) {
					this._onDidUpdateConfiguration.fire({
						config: configuration.consolidated,
						source: ConfigurationSource.Workspace,
						sourceConfig: configuration.workspace
					});
				}
				return section ? configuration.consolidated[section] : configuration.consolidated;
			});
		});
	}

	private toOptions(arg: any): IConfigurationOptions {
		if (typeof arg === 'string') {
			return { section: arg };
		}
		if (typeof arg === 'object') {
			return arg;
		}
		return {};
	}

	private doLoadConfiguration<T>(): TPromise<IWorkspaceConfiguration<T>> {

		// Load workspace locals
		return this.loadWorkspaceConfigFiles().then(workspaceConfigFiles => {

			// Consolidate (support *.json files in the workspace settings folder)
			const workspaceSettingsConfig = <WorkspaceSettingsConfigModel<T>>workspaceConfigFiles[WORKSPACE_CONFIG_DEFAULT_PATH] || new WorkspaceSettingsConfigModel<T>(null);
			const otherConfigModels = Object.keys(workspaceConfigFiles).filter(key => key !== WORKSPACE_CONFIG_DEFAULT_PATH).map(key => <ScopedConfigModel<T>>workspaceConfigFiles[key]);
			this.cachedWorkspaceConfig = new WorkspaceConfigModel<T>(workspaceSettingsConfig, otherConfigModels);

			// Override base (global < user) with workspace locals (global < user < workspace)
I
isidor 已提交
290
			this.cachedConfig = <Configuration<any>>this.baseConfigurationService.getCache().consolidated		// global/default values (do NOT modify)
291 292 293 294 295 296 297 298 299
				.merge(this.cachedWorkspaceConfig);		// workspace configured values

			return {
				consolidated: this.cachedConfig.contents,
				workspace: this.cachedWorkspaceConfig.contents
			};
		});
	}

I
isidor 已提交
300
	private loadWorkspaceConfigFiles<T>(): TPromise<{ [relativeWorkspacePath: string]: Configuration<T> }> {
301 302 303 304 305 306 307 308

		// Return early if we don't have a workspace
		if (!this.workspace) {
			return TPromise.as(Object.create(null));
		}

		// once: when invoked for the first time we fetch json files that contribute settings
		if (!this.bulkFetchFromWorkspacePromise) {
309
			this.bulkFetchFromWorkspacePromise = resolveStat(this.toResource(this.workspaceSettingsRootFolder)).then(stat => {
310 311 312 313 314 315 316 317 318 319
				if (!stat.isDirectory) {
					return TPromise.as([]);
				}

				return resolveContents(stat.children.filter(stat => {
					const isJson = paths.extname(stat.resource.fsPath) === '.json';
					if (!isJson) {
						return false; // only JSON files
					}

320
					return this.isWorkspaceConfigurationFile(this.toWorkspaceRelativePath(stat.resource)); // only workspace config files
321 322 323
				}).map(stat => stat.resource));
			}, err => [] /* never fail this call */)
				.then((contents: IContent[]) => {
324
					contents.forEach(content => this.workspaceFilePathToConfiguration[this.toWorkspaceRelativePath(content.resource)] = TPromise.as(this.createConfigModel(content)));
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
				}, 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(() => TPromise.join(this.workspaceFilePathToConfiguration));
	}

	public handleWorkspaceFileEvents(event: FileChangesEvent): void {
		if (!this.workspace) {
			return; // only enabled when we have a known workspace
		}

		const events = event.changes;
		let affectedByChanges = false;

		// Find changes that affect workspace configuration files
		for (let i = 0, len = events.length; i < len; i++) {
			const resource = events[i].resource;
			const isJson = paths.extname(resource.fsPath) === '.json';
			const isDeletedSettingsFolder = (events[i].type === FileChangeType.DELETED && isEqual(paths.basename(resource.fsPath), this.workspaceSettingsRootFolder));
			if (!isJson && !isDeletedSettingsFolder) {
				continue; // only JSON files or the actual settings folder
			}

350
			const workspacePath = this.toWorkspaceRelativePath(resource);
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
			if (!workspacePath) {
				continue; // event is not inside workspace
			}

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

			// only valid workspace config files
			if (!this.isWorkspaceConfigurationFile(workspacePath)) {
				continue;
			}

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

		// trigger reload of the configuration if we are affected by changes
		if (affectedByChanges && !this.reloadConfigurationScheduler.isScheduled()) {
			this.reloadConfigurationScheduler.schedule();
		}
	}

I
isidor 已提交
385
	private createConfigModel<T>(content: IContent): Configuration<T> {
386
		const path = this.toWorkspaceRelativePath(content.resource);
387 388 389 390 391 392 393 394 395
		if (path === WORKSPACE_CONFIG_DEFAULT_PATH) {
			return new WorkspaceSettingsConfigModel<T>(content.value, content.resource.toString());
		} else {
			const matches = /\/([^\.]*)*\.json/.exec(path);
			if (matches && matches[1]) {
				return new ScopedConfigModel<T>(content.value, content.resource.toString(), matches[1]);
			}
		}

I
isidor 已提交
396
		return new Configuration<T>();
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
	}

	private isWorkspaceConfigurationFile(workspaceRelativePath: string): boolean {
		return [WORKSPACE_CONFIG_DEFAULT_PATH, WORKSPACE_STANDALONE_CONFIGURATIONS.launch, WORKSPACE_STANDALONE_CONFIGURATIONS.tasks].some(p => p === workspaceRelativePath);
	}

	public getUnsupportedWorkspaceKeys(): string[] {
		return this.cachedWorkspaceConfig.workspaceSettingsConfig.unsupportedKeys;
	}

}

// node.hs helper functions

function resolveContents(resources: URI[]): TPromise<IContent[]> {
	const contents: IContent[] = [];

	return TPromise.join(resources.map(resource => {
		return resolveContent(resource).then(content => {
			contents.push(content);
		});
	})).then(() => contents);
}

function resolveContent(resource: URI): TPromise<IContent> {
	return readFile(resource.fsPath).then(contents => ({ resource, value: contents.toString() }));
}

function resolveStat(resource: URI): TPromise<IStat> {
	return new TPromise<IStat>((c, e) => {
		extfs.readdir(resource.fsPath, (error, children) => {
			if (error) {
				if ((<any>error).code === 'ENOTDIR') {
					c({ resource });
				} else {
					e(error);
				}
			} else {
				c({
					resource,
					isDirectory: true,
					children: children.map(child => { return { resource: URI.file(paths.join(resource.fsPath, child)) }; })
				});
			}
		});
	});
I
isidor 已提交
443
}