mirror of
https://github.com/ckaczor/azuredatastudio.git
synced 2026-02-16 10:58:30 -05:00
Refresh master with initial release/0.24 snapshot (#332)
* Initial port of release/0.24 source code * Fix additional headers * Fix a typo in launch.json
This commit is contained in:
@@ -15,15 +15,20 @@ export const WORKSPACE_CONFIG_DEFAULT_PATH = `${WORKSPACE_CONFIG_FOLDER_DEFAULT_
|
||||
export const IWorkspaceConfigurationService = createDecorator<IWorkspaceConfigurationService>('configurationService');
|
||||
|
||||
export interface IWorkspaceConfigurationService extends IConfigurationService {
|
||||
|
||||
/**
|
||||
* Returns untrusted configuration keys for the current workspace.
|
||||
*/
|
||||
getUnsupportedWorkspaceKeys(): string[];
|
||||
|
||||
}
|
||||
|
||||
export const WORKSPACE_STANDALONE_CONFIGURATIONS = {
|
||||
'tasks': `${WORKSPACE_CONFIG_FOLDER_DEFAULT_NAME}/tasks.json`,
|
||||
'launch': `${WORKSPACE_CONFIG_FOLDER_DEFAULT_NAME}/launch.json`
|
||||
};
|
||||
export const defaultSettingsSchemaId = 'vscode://schemas/settings/default';
|
||||
export const userSettingsSchemaId = 'vscode://schemas/settings/user';
|
||||
export const workspaceSettingsSchemaId = 'vscode://schemas/settings/workspace';
|
||||
export const folderSettingsSchemaId = 'vscode://schemas/settings/folder';
|
||||
|
||||
export const TASKS_CONFIGURATION_KEY = 'tasks';
|
||||
export const LAUNCH_CONFIGURATION_KEY = 'launch';
|
||||
|
||||
export const WORKSPACE_STANDALONE_CONFIGURATIONS = {};
|
||||
WORKSPACE_STANDALONE_CONFIGURATIONS[TASKS_CONFIGURATION_KEY] = `${WORKSPACE_CONFIG_FOLDER_DEFAULT_NAME}/tasks.json`;
|
||||
WORKSPACE_STANDALONE_CONFIGURATIONS[LAUNCH_CONFIGURATION_KEY] = `${WORKSPACE_CONFIG_FOLDER_DEFAULT_NAME}/launch.json`;
|
||||
@@ -1,104 +0,0 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
'use strict';
|
||||
|
||||
import { TPromise } from 'vs/base/common/winjs.base';
|
||||
import { createDecorator, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation';
|
||||
import { IConfigurationOverrides } from 'vs/platform/configuration/common/configuration';
|
||||
|
||||
export const IConfigurationEditingService = createDecorator<IConfigurationEditingService>('configurationEditingService');
|
||||
|
||||
export enum ConfigurationEditingErrorCode {
|
||||
|
||||
/**
|
||||
* Error when trying to write a configuration key that is not registered.
|
||||
*/
|
||||
ERROR_UNKNOWN_KEY,
|
||||
|
||||
/**
|
||||
* Error when trying to write an invalid folder configuration key to folder settings.
|
||||
*/
|
||||
ERROR_INVALID_FOLDER_CONFIGURATION,
|
||||
|
||||
/**
|
||||
* Error when trying to write to user target but not supported for provided key.
|
||||
*/
|
||||
ERROR_INVALID_USER_TARGET,
|
||||
|
||||
/**
|
||||
* Error when trying to write a configuration key to folder target
|
||||
*/
|
||||
ERROR_INVALID_FOLDER_TARGET,
|
||||
|
||||
/**
|
||||
* Error when trying to write to the workspace configuration without having a workspace opened.
|
||||
*/
|
||||
ERROR_NO_WORKSPACE_OPENED,
|
||||
|
||||
/**
|
||||
* Error when trying to write and save to the configuration file while it is dirty in the editor.
|
||||
*/
|
||||
ERROR_CONFIGURATION_FILE_DIRTY,
|
||||
|
||||
/**
|
||||
* Error when trying to write to a configuration file that contains JSON errors.
|
||||
*/
|
||||
ERROR_INVALID_CONFIGURATION
|
||||
}
|
||||
|
||||
export class ConfigurationEditingError extends Error {
|
||||
constructor(message: string, public code: ConfigurationEditingErrorCode) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export enum ConfigurationTarget {
|
||||
|
||||
/**
|
||||
* Targets the user configuration file for writing.
|
||||
*/
|
||||
USER,
|
||||
|
||||
/**
|
||||
* Targets the workspace configuration file for writing. This only works if a workspace is opened.
|
||||
*/
|
||||
WORKSPACE,
|
||||
|
||||
/**
|
||||
* Targets the folder configuration file for writing. This only works if a workspace is opened.
|
||||
*/
|
||||
FOLDER
|
||||
}
|
||||
|
||||
export interface IConfigurationValue {
|
||||
key: string;
|
||||
value: any;
|
||||
}
|
||||
|
||||
export interface IConfigurationEditingOptions {
|
||||
/**
|
||||
* If `true`, do not saves the configuration. Default is `false`.
|
||||
*/
|
||||
donotSave?: boolean;
|
||||
/**
|
||||
* If `true`, do not notifies the error to user by showing the message box. Default is `false`.
|
||||
*/
|
||||
donotNotifyError?: boolean;
|
||||
/**
|
||||
* Scope of configuration to be written into.
|
||||
*/
|
||||
scopes?: IConfigurationOverrides;
|
||||
}
|
||||
|
||||
export interface IConfigurationEditingService {
|
||||
|
||||
_serviceBrand: ServiceIdentifier<any>;
|
||||
|
||||
/**
|
||||
* Allows to write the configuration value to either the user or workspace configuration file and save it if asked to save.
|
||||
* The returned promise will be in error state in any of the error cases from [ConfigurationEditingErrorCode](#ConfigurationEditingErrorCode)
|
||||
*/
|
||||
writeConfiguration(target: ConfigurationTarget, value: IConfigurationValue, options?: IConfigurationEditingOptions): TPromise<void>;
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import * as nls from 'vs/nls';
|
||||
import * as objects from 'vs/base/common/objects';
|
||||
import { Registry } from 'vs/platform/registry/common/platform';
|
||||
import { IJSONSchema } from 'vs/base/common/jsonSchema';
|
||||
import { ExtensionsRegistry, IExtensionPointUser } from 'vs/platform/extensions/common/extensionsRegistry';
|
||||
import { IConfigurationNode, IConfigurationRegistry, Extensions, editorConfigurationSchemaId, IDefaultConfigurationExtension, validateProperty, ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry';
|
||||
import { IJSONContributionRegistry, Extensions as JSONExtensions } from 'vs/platform/jsonschemas/common/jsonContributionRegistry';
|
||||
import { workspaceSettingsSchemaId } from 'vs/workbench/services/configuration/common/configuration';
|
||||
|
||||
const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration);
|
||||
|
||||
const configurationEntrySchema: IJSONSchema = {
|
||||
type: 'object',
|
||||
defaultSnippets: [{ body: { title: '', properties: {} } }],
|
||||
properties: {
|
||||
title: {
|
||||
description: nls.localize('vscode.extension.contributes.configuration.title', 'A summary of the settings. This label will be used in the settings file as separating comment.'),
|
||||
type: 'string'
|
||||
},
|
||||
properties: {
|
||||
description: nls.localize('vscode.extension.contributes.configuration.properties', 'Description of the configuration properties.'),
|
||||
type: 'object',
|
||||
additionalProperties: {
|
||||
anyOf: [
|
||||
{ $ref: 'http://json-schema.org/draft-04/schema#' },
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
isExecutable: {
|
||||
type: 'boolean'
|
||||
},
|
||||
scope: {
|
||||
type: 'string',
|
||||
enum: ['window', 'resource'],
|
||||
default: 'window',
|
||||
enumDescriptions: [
|
||||
nls.localize('scope.window.description', "Window specific configuration, which can be configured in the User or Workspace settings."),
|
||||
nls.localize('scope.resource.description', "Resource specific configuration, which can be configured in the User, Workspace or Folder settings.")
|
||||
],
|
||||
description: nls.localize('scope.description', "Scope in which the configuration is applicable. Available scopes are `window` and `resource`.")
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// BEGIN VSCode extension point `configuration`
|
||||
const configurationExtPoint = ExtensionsRegistry.registerExtensionPoint<IConfigurationNode>('configuration', [], {
|
||||
description: nls.localize('vscode.extension.contributes.configuration', 'Contributes configuration settings.'),
|
||||
oneOf: [
|
||||
configurationEntrySchema,
|
||||
{
|
||||
type: 'array',
|
||||
items: configurationEntrySchema
|
||||
}
|
||||
]
|
||||
});
|
||||
configurationExtPoint.setHandler(extensions => {
|
||||
const configurations: IConfigurationNode[] = [];
|
||||
|
||||
function handleConfiguration(node: IConfigurationNode, id: string, extension: IExtensionPointUser<any>) {
|
||||
let configuration = objects.clone(node);
|
||||
|
||||
if (configuration.title && (typeof configuration.title !== 'string')) {
|
||||
extension.collector.error(nls.localize('invalid.title', "'configuration.title' must be a string"));
|
||||
}
|
||||
|
||||
validateProperties(configuration, extension);
|
||||
|
||||
configuration.id = id;
|
||||
configurations.push(configuration);
|
||||
};
|
||||
|
||||
for (let extension of extensions) {
|
||||
const value = <IConfigurationNode | IConfigurationNode[]>extension.value;
|
||||
const id = extension.description.id;
|
||||
if (!Array.isArray(value)) {
|
||||
handleConfiguration(value, id, extension);
|
||||
} else {
|
||||
value.forEach(v => handleConfiguration(v, id, extension));
|
||||
}
|
||||
}
|
||||
configurationRegistry.registerConfigurations(configurations, false);
|
||||
});
|
||||
// END VSCode extension point `configuration`
|
||||
|
||||
// BEGIN VSCode extension point `configurationDefaults`
|
||||
const defaultConfigurationExtPoint = ExtensionsRegistry.registerExtensionPoint<IConfigurationNode>('configurationDefaults', [], {
|
||||
description: nls.localize('vscode.extension.contributes.defaultConfiguration', 'Contributes default editor configuration settings by language.'),
|
||||
type: 'object',
|
||||
defaultSnippets: [{ body: {} }],
|
||||
patternProperties: {
|
||||
'\\[.*\\]$': {
|
||||
type: 'object',
|
||||
default: {},
|
||||
$ref: editorConfigurationSchemaId,
|
||||
}
|
||||
}
|
||||
});
|
||||
defaultConfigurationExtPoint.setHandler(extensions => {
|
||||
const defaultConfigurations: IDefaultConfigurationExtension[] = extensions.map(extension => {
|
||||
const id = extension.description.id;
|
||||
const name = extension.description.name;
|
||||
const defaults = objects.clone(extension.value);
|
||||
return <IDefaultConfigurationExtension>{
|
||||
id, name, defaults
|
||||
};
|
||||
});
|
||||
configurationRegistry.registerDefaultConfigurations(defaultConfigurations);
|
||||
});
|
||||
// END VSCode extension point `configurationDefaults`
|
||||
|
||||
function validateProperties(configuration: IConfigurationNode, extension: IExtensionPointUser<any>): void {
|
||||
let properties = configuration.properties;
|
||||
if (properties) {
|
||||
if (typeof properties !== 'object') {
|
||||
extension.collector.error(nls.localize('invalid.properties', "'configuration.properties' must be an object"));
|
||||
configuration.properties = {};
|
||||
}
|
||||
for (let key in properties) {
|
||||
const message = validateProperty(key);
|
||||
const propertyConfiguration = configuration.properties[key];
|
||||
propertyConfiguration.scope = propertyConfiguration.scope && propertyConfiguration.scope.toString() === 'resource' ? ConfigurationScope.RESOURCE : ConfigurationScope.WINDOW;
|
||||
propertyConfiguration.notMultiRootAdopted = !(extension.description.isBuiltin || (Array.isArray(extension.description.keywords) && extension.description.keywords.indexOf('multi-root ready') !== -1));
|
||||
if (message) {
|
||||
extension.collector.warn(message);
|
||||
delete properties[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
let subNodes = configuration.allOf;
|
||||
if (subNodes) {
|
||||
extension.collector.error(nls.localize('invalid.allOf', "'configuration.allOf' is deprecated and should no longer be used. Instead, pass multiple configuration sections as an array to the 'configuration' contribution point."));
|
||||
for (let node of subNodes) {
|
||||
validateProperties(node, extension);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const jsonRegistry = Registry.as<IJSONContributionRegistry>(JSONExtensions.JSONContribution);
|
||||
jsonRegistry.registerSchema('vscode://schemas/workspaceConfig', {
|
||||
default: {
|
||||
folders: [
|
||||
{
|
||||
path: ''
|
||||
}
|
||||
],
|
||||
settings: {
|
||||
}
|
||||
},
|
||||
required: ['folders'],
|
||||
properties: {
|
||||
'folders': {
|
||||
minItems: 0,
|
||||
uniqueItems: true,
|
||||
description: nls.localize('workspaceConfig.folders.description', "List of folders to be loaded in the workspace."),
|
||||
items: {
|
||||
type: 'object',
|
||||
default: { path: '' },
|
||||
oneOf: [{
|
||||
properties: {
|
||||
path: {
|
||||
type: 'string',
|
||||
description: nls.localize('workspaceConfig.path.description', "A file path. e.g. `/root/folderA` or `./folderA` for a relative path that will be resolved against the location of the workspace file.")
|
||||
},
|
||||
name: {
|
||||
type: 'string',
|
||||
description: nls.localize('workspaceConfig.name.description', "An optional name for the folder. ")
|
||||
}
|
||||
},
|
||||
required: ['path']
|
||||
}, {
|
||||
properties: {
|
||||
uri: {
|
||||
type: 'string',
|
||||
description: nls.localize('workspaceConfig.uri.description', "URI of the folder")
|
||||
},
|
||||
name: {
|
||||
type: 'string',
|
||||
description: nls.localize('workspaceConfig.name.description', "An optional name for the folder. ")
|
||||
}
|
||||
},
|
||||
required: ['uri']
|
||||
}]
|
||||
}
|
||||
},
|
||||
'settings': {
|
||||
type: 'object',
|
||||
default: {},
|
||||
description: nls.localize('workspaceConfig.settings.description', "Workspace settings"),
|
||||
$ref: workspaceSettingsSchemaId
|
||||
},
|
||||
'extensions': {
|
||||
type: 'object',
|
||||
default: {},
|
||||
description: nls.localize('workspaceConfig.extensions.description', "Workspace extensions"),
|
||||
$ref: 'vscode://schemas/extensions'
|
||||
}
|
||||
},
|
||||
additionalProperties: false,
|
||||
errorMessage: nls.localize('unknownWorkspaceProperty', "Unknown workspace configuration property")
|
||||
});
|
||||
@@ -4,69 +4,74 @@
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
'use strict';
|
||||
|
||||
import { clone } from 'vs/base/common/objects';
|
||||
import { CustomConfigurationModel, toValuesTree } from 'vs/platform/configuration/common/model';
|
||||
import { ConfigurationModel } from 'vs/platform/configuration/common/configuration';
|
||||
import { clone, equals } from 'vs/base/common/objects';
|
||||
import { compare, toValuesTree, IConfigurationChangeEvent, ConfigurationTarget, IConfigurationModel, IConfigurationOverrides } from 'vs/platform/configuration/common/configuration';
|
||||
import { ConfigurationModel, Configuration as BaseConfiguration, CustomConfigurationModel, ConfigurationChangeEvent } from 'vs/platform/configuration/common/configurationModels';
|
||||
import { Registry } from 'vs/platform/registry/common/platform';
|
||||
import { IConfigurationRegistry, IConfigurationPropertySchema, Extensions, ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry';
|
||||
import { WORKSPACE_STANDALONE_CONFIGURATIONS } from 'vs/workbench/services/configuration/common/configuration';
|
||||
import { IStoredWorkspaceFolder } from 'vs/platform/workspaces/common/workspaces';
|
||||
import { Workspace } from 'vs/platform/workspace/common/workspace';
|
||||
import { StrictResourceMap } from 'vs/base/common/map';
|
||||
import URI from 'vs/base/common/uri';
|
||||
import { distinct } from 'vs/base/common/arrays';
|
||||
|
||||
export class WorkspaceConfigurationModel<T> extends CustomConfigurationModel<T> {
|
||||
export class WorkspaceConfigurationModel extends CustomConfigurationModel {
|
||||
|
||||
private _raw: T;
|
||||
private _raw: any;
|
||||
private _folders: IStoredWorkspaceFolder[];
|
||||
private _worksapaceSettings: ConfigurationModel<T>;
|
||||
private _tasksConfiguration: ConfigurationModel<T>;
|
||||
private _launchConfiguration: ConfigurationModel<T>;
|
||||
private _workspaceConfiguration: ConfigurationModel<T>;
|
||||
private _worksapaceSettings: WorkspaceSettingsModel;
|
||||
|
||||
public update(content: string): void {
|
||||
super.update(content);
|
||||
this._worksapaceSettings = new ConfigurationModel(this._worksapaceSettings.contents, this._worksapaceSettings.keys, this.overrides);
|
||||
this._workspaceConfiguration = this.consolidate();
|
||||
this._folders = (this._raw['folders'] || []) as IStoredWorkspaceFolder[];
|
||||
this._worksapaceSettings = new WorkspaceSettingsModel(this._raw['settings'] || {});
|
||||
}
|
||||
|
||||
get folders(): IStoredWorkspaceFolder[] {
|
||||
return this._folders;
|
||||
}
|
||||
|
||||
get workspaceConfiguration(): ConfigurationModel<T> {
|
||||
return this._workspaceConfiguration;
|
||||
get workspaceConfiguration(): ConfigurationModel {
|
||||
return this._worksapaceSettings || new WorkspaceSettingsModel({});
|
||||
}
|
||||
|
||||
protected processRaw(raw: T): void {
|
||||
get workspaceSettingsModel(): WorkspaceSettingsModel {
|
||||
return this._worksapaceSettings || new WorkspaceSettingsModel({});
|
||||
}
|
||||
|
||||
protected processRaw(raw: any): void {
|
||||
this._raw = raw;
|
||||
|
||||
this._folders = (this._raw['folders'] || []) as IStoredWorkspaceFolder[];
|
||||
this._worksapaceSettings = this.parseConfigurationModel('settings');
|
||||
this._tasksConfiguration = this.parseConfigurationModel('tasks');
|
||||
this._launchConfiguration = this.parseConfigurationModel('launch');
|
||||
|
||||
super.processRaw(raw);
|
||||
}
|
||||
|
||||
private parseConfigurationModel(section: string): ConfigurationModel<T> {
|
||||
const rawSection = this._raw[section] || {};
|
||||
const contents = toValuesTree(rawSection, message => console.error(`Conflict in section '${section}' of workspace configuration file ${message}`));
|
||||
return new ConfigurationModel<T>(contents, Object.keys(rawSection));
|
||||
|
||||
}
|
||||
|
||||
export class WorkspaceSettingsModel extends ConfigurationModel {
|
||||
|
||||
private _raw: any;
|
||||
private _unsupportedKeys: string[];
|
||||
|
||||
constructor(raw: any) {
|
||||
super();
|
||||
this._raw = raw;
|
||||
this.update();
|
||||
}
|
||||
|
||||
private consolidate(): ConfigurationModel<T> {
|
||||
const keys: string[] = [...this._worksapaceSettings.keys,
|
||||
...this._tasksConfiguration.keys.map(key => `tasks.${key}`),
|
||||
...this._launchConfiguration.keys.map(key => `launch.${key}`)];
|
||||
public get unsupportedKeys(): string[] {
|
||||
return this._unsupportedKeys || [];
|
||||
}
|
||||
|
||||
const mergedContents = new ConfigurationModel<T>(<T>{}, keys)
|
||||
.merge(this._worksapaceSettings)
|
||||
.merge(this._tasksConfiguration)
|
||||
.merge(this._launchConfiguration);
|
||||
|
||||
return new ConfigurationModel<T>(mergedContents.contents, keys, mergedContents.overrides);
|
||||
update(): void {
|
||||
const { unsupportedKeys, contents } = processWorkspaceSettings(this._raw);
|
||||
this._unsupportedKeys = unsupportedKeys;
|
||||
this._contents = toValuesTree(contents, message => console.error(`Conflict in workspace settings file: ${message}`));
|
||||
this._keys = Object.keys(contents);
|
||||
}
|
||||
}
|
||||
|
||||
export class ScopedConfigurationModel<T> extends CustomConfigurationModel<T> {
|
||||
export class ScopedConfigurationModel extends CustomConfigurationModel {
|
||||
|
||||
constructor(content: string, name: string, public readonly scope: string) {
|
||||
super(null, name);
|
||||
@@ -82,24 +87,38 @@ export class ScopedConfigurationModel<T> extends CustomConfigurationModel<T> {
|
||||
|
||||
}
|
||||
|
||||
export class FolderSettingsModel<T> extends CustomConfigurationModel<T> {
|
||||
function processWorkspaceSettings(content: any): { unsupportedKeys: string[], contents: any } {
|
||||
const isNotExecutable = (key: string, configurationProperties: { [qualifiedKey: string]: IConfigurationPropertySchema }): boolean => {
|
||||
const propertySchema = configurationProperties[key];
|
||||
if (!propertySchema) {
|
||||
return true; // Unknown propertis are ignored from checks
|
||||
}
|
||||
return !propertySchema.isExecutable;
|
||||
};
|
||||
|
||||
private _raw: T;
|
||||
const unsupportedKeys = [];
|
||||
const contents = {};
|
||||
const configurationProperties = Registry.as<IConfigurationRegistry>(Extensions.Configuration).getConfigurationProperties();
|
||||
for (let key in content) {
|
||||
if (isNotExecutable(key, configurationProperties)) {
|
||||
contents[key] = content[key];
|
||||
} else {
|
||||
unsupportedKeys.push(key);
|
||||
}
|
||||
}
|
||||
return { contents, unsupportedKeys };
|
||||
}
|
||||
|
||||
export class FolderSettingsModel extends CustomConfigurationModel {
|
||||
|
||||
private _raw: any;
|
||||
private _unsupportedKeys: string[];
|
||||
|
||||
protected processRaw(raw: T): void {
|
||||
protected processRaw(raw: any): void {
|
||||
this._raw = raw;
|
||||
const processedRaw = <T>{};
|
||||
this._unsupportedKeys = [];
|
||||
const configurationProperties = Registry.as<IConfigurationRegistry>(Extensions.Configuration).getConfigurationProperties();
|
||||
for (let key in raw) {
|
||||
if (this.isNotExecutable(key, configurationProperties)) {
|
||||
processedRaw[key] = raw[key];
|
||||
} else {
|
||||
this._unsupportedKeys.push(key);
|
||||
}
|
||||
}
|
||||
return super.processRaw(processedRaw);
|
||||
const { unsupportedKeys, contents } = processWorkspaceSettings(raw);
|
||||
this._unsupportedKeys = unsupportedKeys;
|
||||
return super.processRaw(contents);
|
||||
}
|
||||
|
||||
public reprocess(): void {
|
||||
@@ -110,24 +129,16 @@ export class FolderSettingsModel<T> extends CustomConfigurationModel<T> {
|
||||
return this._unsupportedKeys || [];
|
||||
}
|
||||
|
||||
private isNotExecutable(key: string, configurationProperties: { [qualifiedKey: string]: IConfigurationPropertySchema }): boolean {
|
||||
const propertySchema = configurationProperties[key];
|
||||
if (!propertySchema) {
|
||||
return true; // Unknown propertis are ignored from checks
|
||||
}
|
||||
return !propertySchema.isExecutable;
|
||||
}
|
||||
|
||||
public createWorkspaceConfigurationModel(): ConfigurationModel<any> {
|
||||
public createWorkspaceConfigurationModel(): ConfigurationModel {
|
||||
return this.createScopedConfigurationModel(ConfigurationScope.WINDOW);
|
||||
}
|
||||
|
||||
public createFolderScopedConfigurationModel(): ConfigurationModel<any> {
|
||||
public createFolderScopedConfigurationModel(): ConfigurationModel {
|
||||
return this.createScopedConfigurationModel(ConfigurationScope.RESOURCE);
|
||||
}
|
||||
|
||||
private createScopedConfigurationModel(scope: ConfigurationScope): ConfigurationModel<any> {
|
||||
const workspaceRaw = <T>{};
|
||||
private createScopedConfigurationModel(scope: ConfigurationScope): ConfigurationModel {
|
||||
const workspaceRaw = {};
|
||||
const configurationProperties = Registry.as<IConfigurationRegistry>(Extensions.Configuration).getConfigurationProperties();
|
||||
for (let key in this._raw) {
|
||||
if (this.getScope(key, configurationProperties) === scope) {
|
||||
@@ -145,15 +156,15 @@ export class FolderSettingsModel<T> extends CustomConfigurationModel<T> {
|
||||
}
|
||||
}
|
||||
|
||||
export class FolderConfigurationModel<T> extends CustomConfigurationModel<T> {
|
||||
export class FolderConfigurationModel extends CustomConfigurationModel {
|
||||
|
||||
constructor(public readonly workspaceSettingsConfig: FolderSettingsModel<T>, private scopedConfigs: ScopedConfigurationModel<T>[], private scope: ConfigurationScope) {
|
||||
constructor(public readonly workspaceSettingsConfig: FolderSettingsModel, private scopedConfigs: ScopedConfigurationModel[], private scope: ConfigurationScope) {
|
||||
super();
|
||||
this.consolidate();
|
||||
}
|
||||
|
||||
private consolidate(): void {
|
||||
this._contents = <T>{};
|
||||
this._contents = {};
|
||||
this._overrides = [];
|
||||
|
||||
this.doMerge(this, ConfigurationScope.WINDOW === this.scope ? this.workspaceSettingsConfig : this.workspaceSettingsConfig.createFolderScopedConfigurationModel());
|
||||
@@ -178,4 +189,185 @@ export class FolderConfigurationModel<T> extends CustomConfigurationModel<T> {
|
||||
this.workspaceSettingsConfig.reprocess();
|
||||
this.consolidate();
|
||||
}
|
||||
}
|
||||
|
||||
export class Configuration extends BaseConfiguration {
|
||||
|
||||
constructor(
|
||||
defaults: ConfigurationModel,
|
||||
user: ConfigurationModel,
|
||||
workspaceConfiguration: ConfigurationModel,
|
||||
protected folders: StrictResourceMap<FolderConfigurationModel>,
|
||||
memoryConfiguration: ConfigurationModel,
|
||||
memoryConfigurationByResource: StrictResourceMap<ConfigurationModel>,
|
||||
private readonly _workspace: Workspace) {
|
||||
super(defaults, user, workspaceConfiguration, folders, memoryConfiguration, memoryConfigurationByResource);
|
||||
}
|
||||
|
||||
getSection<C>(section: string = '', overrides: IConfigurationOverrides = {}): C {
|
||||
return super.getSection(section, overrides, this._workspace);
|
||||
}
|
||||
|
||||
getValue(key: string, overrides: IConfigurationOverrides = {}): any {
|
||||
return super.getValue(key, overrides, this._workspace);
|
||||
}
|
||||
|
||||
lookup<C>(key: string, overrides: IConfigurationOverrides = {}): {
|
||||
default: C,
|
||||
user: C,
|
||||
workspace: C,
|
||||
workspaceFolder: C
|
||||
memory?: C
|
||||
value: C,
|
||||
} {
|
||||
return super.lookup(key, overrides, this._workspace);
|
||||
}
|
||||
|
||||
keys(): {
|
||||
default: string[];
|
||||
user: string[];
|
||||
workspace: string[];
|
||||
workspaceFolder: string[];
|
||||
} {
|
||||
return super.keys(this._workspace);
|
||||
}
|
||||
|
||||
updateDefaultConfiguration(defaults: ConfigurationModel): void {
|
||||
this._defaults = defaults;
|
||||
this.merge();
|
||||
}
|
||||
|
||||
updateUserConfiguration(user: ConfigurationModel): ConfigurationChangeEvent {
|
||||
const { added, updated, removed } = compare(this._user, user);
|
||||
let changedKeys = [...added, ...updated, ...removed];
|
||||
if (changedKeys.length) {
|
||||
const oldConfiguartion = new Configuration(this._defaults, this._user, this._workspaceConfiguration, this.folders, this._memoryConfiguration, this._memoryConfigurationByResource, this._workspace);
|
||||
|
||||
this._user = user;
|
||||
this.merge();
|
||||
|
||||
changedKeys = changedKeys.filter(key => !equals(oldConfiguartion.getValue(key), this.getValue(key)));
|
||||
}
|
||||
return new ConfigurationChangeEvent().change(changedKeys);
|
||||
}
|
||||
|
||||
updateWorkspaceConfiguration(workspaceConfiguration: ConfigurationModel): ConfigurationChangeEvent {
|
||||
const { added, updated, removed } = compare(this._workspaceConfiguration, workspaceConfiguration);
|
||||
let changedKeys = [...added, ...updated, ...removed];
|
||||
if (changedKeys.length) {
|
||||
const oldConfiguartion = new Configuration(this._defaults, this._user, this._workspaceConfiguration, this.folders, this._memoryConfiguration, this._memoryConfigurationByResource, this._workspace);
|
||||
|
||||
this._workspaceConfiguration = workspaceConfiguration;
|
||||
this.merge();
|
||||
|
||||
changedKeys = changedKeys.filter(key => !equals(oldConfiguartion.getValue(key), this.getValue(key)));
|
||||
}
|
||||
return new ConfigurationChangeEvent().change(changedKeys);
|
||||
}
|
||||
|
||||
updateFolderConfiguration(resource: URI, configuration: FolderConfigurationModel): ConfigurationChangeEvent {
|
||||
const currentFolderConfiguration = this.folders.get(resource);
|
||||
|
||||
if (currentFolderConfiguration) {
|
||||
const { added, updated, removed } = compare(currentFolderConfiguration, configuration);
|
||||
let changedKeys = [...added, ...updated, ...removed];
|
||||
if (changedKeys.length) {
|
||||
const oldConfiguartion = new Configuration(this._defaults, this._user, this._workspaceConfiguration, this.folders, this._memoryConfiguration, this._memoryConfigurationByResource, this._workspace);
|
||||
|
||||
this.folders.set(resource, configuration);
|
||||
this.mergeFolder(resource);
|
||||
|
||||
changedKeys = changedKeys.filter(key => !equals(oldConfiguartion.getValue(key, { resource }), this.getValue(key, { resource })));
|
||||
}
|
||||
return new ConfigurationChangeEvent().change(changedKeys, resource);
|
||||
}
|
||||
|
||||
this.folders.set(resource, configuration);
|
||||
this.mergeFolder(resource);
|
||||
return new ConfigurationChangeEvent().change(configuration.keys, resource);
|
||||
}
|
||||
|
||||
deleteFolderConfiguration(folder: URI): ConfigurationChangeEvent {
|
||||
if (this._workspace && this._workspace.folders.length > 0 && this._workspace.folders[0].uri.toString() === folder.toString()) {
|
||||
// Do not remove workspace configuration
|
||||
return new ConfigurationChangeEvent();
|
||||
}
|
||||
|
||||
const keys = this.folders.get(folder).keys;
|
||||
this.folders.delete(folder);
|
||||
this._foldersConsolidatedConfigurations.delete(folder);
|
||||
return new ConfigurationChangeEvent().change(keys, folder);
|
||||
}
|
||||
|
||||
getFolderConfigurationModel(folder: URI): FolderConfigurationModel {
|
||||
return <FolderConfigurationModel>this.folders.get(folder);
|
||||
}
|
||||
|
||||
compare(other: Configuration): string[] {
|
||||
let from = other.allKeys();
|
||||
let to = this.allKeys();
|
||||
|
||||
const added = to.filter(key => from.indexOf(key) === -1);
|
||||
const removed = from.filter(key => to.indexOf(key) === -1);
|
||||
const updated = [];
|
||||
|
||||
for (const key of from) {
|
||||
const value1 = this.getValue(key);
|
||||
const value2 = other.getValue(key);
|
||||
if (!equals(value1, value2)) {
|
||||
updated.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
return [...added, ...removed, ...updated];
|
||||
}
|
||||
|
||||
allKeys(): string[] {
|
||||
let keys = this.keys();
|
||||
let all = [...keys.default, ...keys.user, ...keys.workspace];
|
||||
for (const resource of this.folders.keys()) {
|
||||
all.push(...this.folders.get(resource).keys);
|
||||
}
|
||||
return distinct(all);
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspaceConfigurationChangeEvent implements IConfigurationChangeEvent {
|
||||
|
||||
constructor(private configurationChangeEvent: IConfigurationChangeEvent, private workspace: Workspace) { }
|
||||
|
||||
get changedConfiguration(): IConfigurationModel {
|
||||
return this.configurationChangeEvent.changedConfiguration;
|
||||
}
|
||||
|
||||
get changedConfigurationByResource(): StrictResourceMap<IConfigurationModel> {
|
||||
return this.configurationChangeEvent.changedConfigurationByResource;
|
||||
}
|
||||
|
||||
get affectedKeys(): string[] {
|
||||
return this.configurationChangeEvent.affectedKeys;
|
||||
}
|
||||
|
||||
get source(): ConfigurationTarget {
|
||||
return this.configurationChangeEvent.source;
|
||||
}
|
||||
|
||||
get sourceConfig(): any {
|
||||
return this.configurationChangeEvent.sourceConfig;
|
||||
}
|
||||
|
||||
affectsConfiguration(config: string, resource?: URI): boolean {
|
||||
if (this.configurationChangeEvent.affectsConfiguration(config, resource)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (resource && this.workspace) {
|
||||
let workspaceFolder = this.workspace.getFolder(resource);
|
||||
if (workspaceFolder) {
|
||||
return this.configurationChangeEvent.affectsConfiguration(config, workspaceFolder.uri);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -2,38 +2,28 @@
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. 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 { StrictResourceMap } from 'vs/base/common/map';
|
||||
import { equals, coalesce } from 'vs/base/common/arrays';
|
||||
import * as objects from 'vs/base/common/objects';
|
||||
import { readFile } from 'vs/base/node/pfs';
|
||||
import * as errors from 'vs/base/common/errors';
|
||||
import * as collections from 'vs/base/common/collections';
|
||||
import { Disposable, toDisposable, IDisposable, dispose } from 'vs/base/common/lifecycle';
|
||||
import { Disposable, IDisposable, dispose } from 'vs/base/common/lifecycle';
|
||||
import { RunOnceScheduler } from 'vs/base/common/async';
|
||||
import { readFile, stat } from 'vs/base/node/pfs';
|
||||
import { IJSONContributionRegistry, Extensions as JSONExtensions } from 'vs/platform/jsonschemas/common/jsonContributionRegistry';
|
||||
import * as extfs from 'vs/base/node/extfs';
|
||||
import { IWorkspaceContextService, IWorkspace, Workspace, ILegacyWorkspace, LegacyWorkspace } from 'vs/platform/workspace/common/workspace';
|
||||
import { FileChangeType, FileChangesEvent } from 'vs/platform/files/common/files';
|
||||
import { isLinux } from 'vs/base/common/platform';
|
||||
import { ConfigWatcher } from 'vs/base/node/config';
|
||||
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
|
||||
import { CustomConfigurationModel } from 'vs/platform/configuration/common/model';
|
||||
import { WorkspaceConfigurationModel, ScopedConfigurationModel, FolderConfigurationModel, FolderSettingsModel } from 'vs/workbench/services/configuration/common/configurationModels';
|
||||
import { IConfigurationServiceEvent, ConfigurationSource, IConfigurationKeys, IConfigurationValue, ConfigurationModel, IConfigurationOverrides, Configuration as BaseConfiguration, IConfigurationValues, IConfigurationData } from 'vs/platform/configuration/common/configuration';
|
||||
import { IWorkspaceConfigurationService, 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';
|
||||
import * as nls from 'vs/nls';
|
||||
import { Registry } from 'vs/platform/registry/common/platform';
|
||||
import { ExtensionsRegistry, ExtensionMessageCollector } from 'vs/platform/extensions/common/extensionsRegistry';
|
||||
import { IConfigurationNode, IConfigurationRegistry, Extensions, editorConfigurationSchemaId, IDefaultConfigurationExtension, validateProperty, ConfigurationScope, schemaId } from 'vs/platform/configuration/common/configurationRegistry';
|
||||
import { createHash } from 'crypto';
|
||||
import { getWorkspaceLabel, IWorkspacesService, IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier, IStoredWorkspaceFolder } from 'vs/platform/workspaces/common/workspaces';
|
||||
import { CustomConfigurationModel, ConfigurationModel } from 'vs/platform/configuration/common/configurationModels';
|
||||
import { WorkspaceConfigurationModel, ScopedConfigurationModel, FolderConfigurationModel, FolderSettingsModel, WorkspaceSettingsModel } from 'vs/workbench/services/configuration/common/configurationModels';
|
||||
import { WORKSPACE_STANDALONE_CONFIGURATIONS, WORKSPACE_CONFIG_DEFAULT_PATH, TASKS_CONFIGURATION_KEY, LAUNCH_CONFIGURATION_KEY } from 'vs/workbench/services/configuration/common/configuration';
|
||||
import { ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry';
|
||||
import { IStoredWorkspace, IStoredWorkspaceFolder } from 'vs/platform/workspaces/common/workspaces';
|
||||
import * as extfs from 'vs/base/node/extfs';
|
||||
import { JSONEditingService } from 'vs/workbench/services/configuration/node/jsonEditingService';
|
||||
|
||||
// node.hs helper functions
|
||||
|
||||
interface IStat {
|
||||
resource: URI;
|
||||
@@ -46,602 +36,108 @@ interface IContent {
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface IWorkspaceConfiguration<T> {
|
||||
workspace: T;
|
||||
consolidated: any;
|
||||
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);
|
||||
}
|
||||
|
||||
type IWorkspaceFoldersConfiguration = { [rootFolder: string]: { folders: string[]; } };
|
||||
|
||||
const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration);
|
||||
|
||||
// BEGIN VSCode extension point `configuration`
|
||||
const configurationExtPoint = ExtensionsRegistry.registerExtensionPoint<IConfigurationNode>('configuration', [], {
|
||||
description: nls.localize('vscode.extension.contributes.configuration', 'Contributes configuration settings.'),
|
||||
type: 'object',
|
||||
defaultSnippets: [{ body: { title: '', properties: {} } }],
|
||||
properties: {
|
||||
title: {
|
||||
description: nls.localize('vscode.extension.contributes.configuration.title', 'A summary of the settings. This label will be used in the settings file as separating comment.'),
|
||||
type: 'string'
|
||||
},
|
||||
properties: {
|
||||
description: nls.localize('vscode.extension.contributes.configuration.properties', 'Description of the configuration properties.'),
|
||||
type: 'object',
|
||||
additionalProperties: {
|
||||
anyOf: [
|
||||
{ $ref: 'http://json-schema.org/draft-04/schema#' },
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
isExecutable: {
|
||||
type: 'boolean'
|
||||
},
|
||||
scope: {
|
||||
type: 'string',
|
||||
enum: ['window', 'resource'],
|
||||
default: 'window',
|
||||
enumDescriptions: [
|
||||
nls.localize('scope.window.description', "Window specific configuration, which can be configured in the User or Workspace settings."),
|
||||
nls.localize('scope.resource.description', "Resource specific configuration, which can be configured in the User, Workspace or Folder settings.")
|
||||
],
|
||||
description: nls.localize('scope.description', "Scope in which the configuration is applicable. Available scopes are `window` and `resource`.")
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
configurationExtPoint.setHandler(extensions => {
|
||||
const configurations: IConfigurationNode[] = [];
|
||||
|
||||
|
||||
for (let i = 0; i < extensions.length; i++) {
|
||||
const configuration = <IConfigurationNode>objects.clone(extensions[i].value);
|
||||
const collector = extensions[i].collector;
|
||||
|
||||
if (configuration.type && configuration.type !== 'object') {
|
||||
collector.warn(nls.localize('invalid.type', "if set, 'configuration.type' must be set to 'object"));
|
||||
} else {
|
||||
configuration.type = 'object';
|
||||
}
|
||||
|
||||
if (configuration.title && (typeof configuration.title !== 'string')) {
|
||||
collector.error(nls.localize('invalid.title', "'configuration.title' must be a string"));
|
||||
}
|
||||
|
||||
validateProperties(configuration, collector);
|
||||
|
||||
configuration.id = extensions[i].description.id;
|
||||
configurations.push(configuration);
|
||||
}
|
||||
|
||||
configurationRegistry.registerConfigurations(configurations, false);
|
||||
});
|
||||
// END VSCode extension point `configuration`
|
||||
|
||||
// BEGIN VSCode extension point `configurationDefaults`
|
||||
const defaultConfigurationExtPoint = ExtensionsRegistry.registerExtensionPoint<IConfigurationNode>('configurationDefaults', [], {
|
||||
description: nls.localize('vscode.extension.contributes.defaultConfiguration', 'Contributes default editor configuration settings by language.'),
|
||||
type: 'object',
|
||||
defaultSnippets: [{ body: {} }],
|
||||
patternProperties: {
|
||||
'\\[.*\\]$': {
|
||||
type: 'object',
|
||||
default: {},
|
||||
$ref: editorConfigurationSchemaId,
|
||||
}
|
||||
}
|
||||
});
|
||||
defaultConfigurationExtPoint.setHandler(extensions => {
|
||||
const defaultConfigurations: IDefaultConfigurationExtension[] = extensions.map(extension => {
|
||||
const id = extension.description.id;
|
||||
const name = extension.description.name;
|
||||
const defaults = objects.clone(extension.value);
|
||||
return <IDefaultConfigurationExtension>{
|
||||
id, name, defaults
|
||||
};
|
||||
});
|
||||
configurationRegistry.registerDefaultConfigurations(defaultConfigurations);
|
||||
});
|
||||
// END VSCode extension point `configurationDefaults`
|
||||
|
||||
function validateProperties(configuration: IConfigurationNode, collector: ExtensionMessageCollector): void {
|
||||
let properties = configuration.properties;
|
||||
if (properties) {
|
||||
if (typeof properties !== 'object') {
|
||||
collector.error(nls.localize('invalid.properties', "'configuration.properties' must be an object"));
|
||||
configuration.properties = {};
|
||||
}
|
||||
for (let key in properties) {
|
||||
const message = validateProperty(key);
|
||||
const propertyConfiguration = configuration.properties[key];
|
||||
propertyConfiguration.scope = propertyConfiguration.scope && propertyConfiguration.scope.toString() === 'resource' ? ConfigurationScope.RESOURCE : ConfigurationScope.WINDOW;
|
||||
if (message) {
|
||||
collector.warn(message);
|
||||
delete properties[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
let subNodes = configuration.allOf;
|
||||
if (subNodes) {
|
||||
for (let node of subNodes) {
|
||||
validateProperties(node, collector);
|
||||
}
|
||||
}
|
||||
function resolveContent(resource: URI): TPromise<IContent> {
|
||||
return readFile(resource.fsPath).then(contents => ({ resource, value: contents.toString() }));
|
||||
}
|
||||
|
||||
export class WorkspaceService extends Disposable implements IWorkspaceConfigurationService, IWorkspaceContextService {
|
||||
|
||||
public _serviceBrand: any;
|
||||
|
||||
protected workspace: Workspace = null;
|
||||
protected legacyWorkspace: LegacyWorkspace = null;
|
||||
protected _configuration: Configuration<any>;
|
||||
|
||||
protected readonly _onDidUpdateConfiguration: Emitter<IConfigurationServiceEvent> = this._register(new Emitter<IConfigurationServiceEvent>());
|
||||
public readonly onDidUpdateConfiguration: Event<IConfigurationServiceEvent> = this._onDidUpdateConfiguration.event;
|
||||
|
||||
protected readonly _onDidChangeWorkspaceRoots: Emitter<void> = this._register(new Emitter<void>());
|
||||
public readonly onDidChangeWorkspaceRoots: Event<void> = this._onDidChangeWorkspaceRoots.event;
|
||||
|
||||
protected readonly _onDidChangeWorkspaceName: Emitter<void> = this._register(new Emitter<void>());
|
||||
public readonly onDidChangeWorkspaceName: Event<void> = this._onDidChangeWorkspaceName.event;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this._configuration = new Configuration(new BaseConfiguration(new ConfigurationModel<any>(), new ConfigurationModel<any>()), new ConfigurationModel<any>(), new StrictResourceMap<FolderConfigurationModel<any>>(), this.workspace);
|
||||
}
|
||||
|
||||
public getLegacyWorkspace(): ILegacyWorkspace {
|
||||
return this.legacyWorkspace;
|
||||
}
|
||||
|
||||
public getWorkspace(): IWorkspace {
|
||||
return this.workspace;
|
||||
}
|
||||
|
||||
public hasWorkspace(): boolean {
|
||||
return !!this.workspace;
|
||||
}
|
||||
|
||||
public hasFolderWorkspace(): boolean {
|
||||
return this.workspace && !this.workspace.configuration;
|
||||
}
|
||||
|
||||
public hasMultiFolderWorkspace(): boolean {
|
||||
return this.workspace && !!this.workspace.configuration;
|
||||
}
|
||||
|
||||
public getRoot(resource: URI): URI {
|
||||
return this.workspace ? this.workspace.getRoot(resource) : null;
|
||||
}
|
||||
|
||||
private get workspaceUri(): URI {
|
||||
return this.workspace ? this.workspace.roots[0] : null;
|
||||
}
|
||||
|
||||
public isInsideWorkspace(resource: URI): boolean {
|
||||
return !!this.getRoot(resource);
|
||||
}
|
||||
|
||||
public toResource(workspaceRelativePath: string): URI {
|
||||
return this.workspace ? this.legacyWorkspace.toResource(workspaceRelativePath) : null;
|
||||
}
|
||||
|
||||
public initialize(trigger: boolean = true): TPromise<any> {
|
||||
this.resetCaches();
|
||||
return this.updateConfiguration()
|
||||
.then(() => {
|
||||
if (trigger) {
|
||||
this.triggerConfigurationChange();
|
||||
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);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public reloadConfiguration(section?: string): TPromise<any> {
|
||||
return TPromise.as(this.getConfiguration(section));
|
||||
}
|
||||
|
||||
public getConfigurationData<T>(): IConfigurationData<T> {
|
||||
return this._configuration.toData();
|
||||
}
|
||||
|
||||
public getConfiguration<C>(section?: string, overrides?: IConfigurationOverrides): C {
|
||||
return this._configuration.getValue<C>(section, overrides);
|
||||
}
|
||||
|
||||
public lookup<C>(key: string, overrides?: IConfigurationOverrides): IConfigurationValue<C> {
|
||||
return this._configuration.lookup<C>(key, overrides);
|
||||
}
|
||||
|
||||
public keys(overrides?: IConfigurationOverrides): IConfigurationKeys {
|
||||
return this._configuration.keys(overrides);
|
||||
}
|
||||
|
||||
public values<V>(): IConfigurationValues {
|
||||
return this._configuration.values();
|
||||
}
|
||||
|
||||
public getUnsupportedWorkspaceKeys(): string[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
public isInWorkspaceContext(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
protected triggerConfigurationChange(): void {
|
||||
this._onDidUpdateConfiguration.fire({ source: ConfigurationSource.Workspace, sourceConfig: void 0 });
|
||||
}
|
||||
|
||||
public handleWorkspaceFileEvents(event: FileChangesEvent): void {
|
||||
// implemented by sub classes
|
||||
}
|
||||
|
||||
protected resetCaches(): void {
|
||||
// implemented by sub classes
|
||||
}
|
||||
|
||||
protected updateConfiguration(): TPromise<boolean> {
|
||||
// implemented by sub classes
|
||||
return TPromise.as(false);
|
||||
}
|
||||
}
|
||||
|
||||
export class EmptyWorkspaceServiceImpl extends WorkspaceService {
|
||||
|
||||
private baseConfigurationService: GlobalConfigurationService<any>;
|
||||
|
||||
constructor(environmentService: IEnvironmentService) {
|
||||
super();
|
||||
this.baseConfigurationService = this._register(new GlobalConfigurationService(environmentService));
|
||||
this._register(this.baseConfigurationService.onDidUpdateConfiguration(e => this.onBaseConfigurationChanged(e)));
|
||||
this.resetCaches();
|
||||
}
|
||||
|
||||
public reloadConfiguration(section?: string): TPromise<any> {
|
||||
const current = this._configuration;
|
||||
return this.baseConfigurationService.reloadConfiguration()
|
||||
.then(() => this.initialize(false)) // Reinitialize to ensure we are hitting the disk
|
||||
.then(() => {
|
||||
// Check and trigger
|
||||
if (!this._configuration.equals(current)) {
|
||||
this.triggerConfigurationChange();
|
||||
}
|
||||
return super.reloadConfiguration(section);
|
||||
});
|
||||
}
|
||||
|
||||
private onBaseConfigurationChanged({ source, sourceConfig }: IConfigurationServiceEvent): void {
|
||||
if (this._configuration.updateBaseConfiguration(<any>this.baseConfigurationService.configuration())) {
|
||||
this._onDidUpdateConfiguration.fire({ source, sourceConfig });
|
||||
}
|
||||
}
|
||||
|
||||
protected resetCaches(): void {
|
||||
this._configuration = new Configuration(<any>this.baseConfigurationService.configuration(), new ConfigurationModel<any>(), new StrictResourceMap<FolderConfigurationModel<any>>(), null);
|
||||
}
|
||||
|
||||
protected triggerConfigurationChange(): void {
|
||||
this._onDidUpdateConfiguration.fire({ source: ConfigurationSource.User, sourceConfig: this._configuration.user.contents });
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspaceServiceImpl extends WorkspaceService {
|
||||
|
||||
public _serviceBrand: any;
|
||||
|
||||
private workspaceConfigPath: URI;
|
||||
private folderPath: URI;
|
||||
private baseConfigurationService: GlobalConfigurationService<any>;
|
||||
private workspaceConfiguration: WorkspaceConfiguration;
|
||||
private cachedFolderConfigs: StrictResourceMap<FolderConfiguration<any>>;
|
||||
|
||||
constructor(private workspaceIdentifier: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier, private environmentService: IEnvironmentService, private workspacesService: IWorkspacesService, private workspaceSettingsRootFolder: string = WORKSPACE_CONFIG_FOLDER_DEFAULT_NAME) {
|
||||
super();
|
||||
|
||||
if (isSingleFolderWorkspaceIdentifier(workspaceIdentifier)) {
|
||||
this.folderPath = URI.file(workspaceIdentifier);
|
||||
} else {
|
||||
this.workspaceConfigPath = URI.file(workspaceIdentifier.configPath);
|
||||
}
|
||||
|
||||
this.workspaceConfiguration = this._register(new WorkspaceConfiguration());
|
||||
this.baseConfigurationService = this._register(new GlobalConfigurationService(environmentService));
|
||||
}
|
||||
|
||||
public getUnsupportedWorkspaceKeys(): string[] {
|
||||
return this.hasFolderWorkspace() ? this._configuration.getFolderConfigurationModel(this.workspace.roots[0]).workspaceSettingsConfig.unsupportedKeys : [];
|
||||
}
|
||||
|
||||
public initialize(trigger: boolean = true): TPromise<any> {
|
||||
if (!this.workspace) {
|
||||
return this.initializeWorkspace()
|
||||
.then(() => super.initialize(trigger));
|
||||
}
|
||||
|
||||
if (this.hasMultiFolderWorkspace()) {
|
||||
return this.workspaceConfiguration.load(this.workspaceConfigPath)
|
||||
.then(() => super.initialize(trigger));
|
||||
}
|
||||
|
||||
return super.initialize(trigger);
|
||||
}
|
||||
|
||||
public reloadConfiguration(section?: string): TPromise<any> {
|
||||
const current = this._configuration;
|
||||
return this.baseConfigurationService.reloadConfiguration()
|
||||
.then(() => this.initialize(false)) // Reinitialize to ensure we are hitting the disk
|
||||
.then(() => {
|
||||
// Check and trigger
|
||||
if (!this._configuration.equals(current)) {
|
||||
this.triggerConfigurationChange();
|
||||
}
|
||||
return super.reloadConfiguration(section);
|
||||
});
|
||||
}
|
||||
|
||||
public handleWorkspaceFileEvents(event: FileChangesEvent): void {
|
||||
TPromise.join(this.workspace.roots.map(folder => this.cachedFolderConfigs.get(folder).handleWorkspaceFileEvents(event))) // handle file event for each folder
|
||||
.then(folderConfigurations =>
|
||||
folderConfigurations.map((configuration, index) => ({ configuration, folder: this.workspace.roots[index] }))
|
||||
.filter(folderConfiguration => !!folderConfiguration.configuration) // Filter folders which are not impacted by events
|
||||
.map(folderConfiguration => this.updateFolderConfiguration(folderConfiguration.folder, folderConfiguration.configuration, true)) // Update the configuration of impacted folders
|
||||
.reduce((result, value) => result || value, false)) // Check if the effective configuration of folder is changed
|
||||
.then(changed => changed ? this.triggerConfigurationChange() : void 0); // Trigger event if changed
|
||||
}
|
||||
|
||||
protected resetCaches(): void {
|
||||
this.cachedFolderConfigs = new StrictResourceMap<FolderConfiguration<any>>();
|
||||
this._configuration = new Configuration(<any>this.baseConfigurationService.configuration(), new ConfigurationModel<any>(), new StrictResourceMap<FolderConfigurationModel<any>>(), this.workspace);
|
||||
this.initCachesForFolders(this.workspace.roots);
|
||||
}
|
||||
|
||||
private initializeWorkspace(): TPromise<void> {
|
||||
return (this.workspaceConfigPath ? this.initializeMulitFolderWorkspace() : this.initializeSingleFolderWorkspace())
|
||||
.then(() => {
|
||||
this._register(this.baseConfigurationService.onDidUpdateConfiguration(e => this.onBaseConfigurationChanged(e)));
|
||||
});
|
||||
}
|
||||
|
||||
// TODO@Sandeep use again once we can change workspace without window reload
|
||||
// private onWorkspaceChange(configPath: URI): TPromise<void> {
|
||||
// let workspaceName = this.workspace.name;
|
||||
// this.workspaceConfigPath = configPath;
|
||||
|
||||
// // Reset the workspace if current workspace is single folder
|
||||
// if (this.hasFolderWorkspace()) {
|
||||
// this.folderPath = null;
|
||||
// this.workspace = null;
|
||||
// }
|
||||
|
||||
// // Update workspace configuration path with new path
|
||||
// else {
|
||||
// this.workspace.configuration = configPath;
|
||||
// this.workspace.name = getWorkspaceLabel({ id: this.workspace.id, configPath: this.workspace.configuration.fsPath }, this.environmentService);
|
||||
// }
|
||||
|
||||
// return this.initialize().then(() => {
|
||||
// if (workspaceName !== this.workspace.name) {
|
||||
// this._onDidChangeWorkspaceName.fire();
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
|
||||
private initializeMulitFolderWorkspace(): TPromise<void> {
|
||||
this.registerWorkspaceConfigSchema();
|
||||
return this.workspaceConfiguration.load(this.workspaceConfigPath)
|
||||
.then(() => {
|
||||
const workspaceConfigurationModel = this.workspaceConfiguration.workspaceConfigurationModel;
|
||||
const workspaceFolders = this.parseWorkspaceFolders(workspaceConfigurationModel.folders);
|
||||
if (!workspaceFolders.length) {
|
||||
return TPromise.wrapError<void>(new Error('Invalid workspace configuraton file ' + this.workspaceConfigPath));
|
||||
}
|
||||
const workspaceId = (this.workspaceIdentifier as IWorkspaceIdentifier).id;
|
||||
const workspaceName = getWorkspaceLabel({ id: workspaceId, configPath: this.workspaceConfigPath.fsPath }, this.environmentService);
|
||||
this.workspace = new Workspace(workspaceId, workspaceName, workspaceFolders, this.workspaceConfigPath);
|
||||
this.legacyWorkspace = new LegacyWorkspace(this.workspace.roots[0]);
|
||||
this._register(this.workspaceConfiguration.onDidUpdateConfiguration(() => this.onWorkspaceConfigurationChanged()));
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private parseWorkspaceFolders(configuredFolders: IStoredWorkspaceFolder[]): URI[] {
|
||||
return coalesce(configuredFolders.map(configuredFolder => {
|
||||
const path = configuredFolder.path;
|
||||
if (!path) {
|
||||
return void 0;
|
||||
}
|
||||
|
||||
if (paths.isAbsolute(path)) {
|
||||
return URI.file(path);
|
||||
}
|
||||
|
||||
return URI.file(paths.join(paths.dirname(this.workspaceConfigPath.fsPath), path));
|
||||
}));
|
||||
}
|
||||
|
||||
private registerWorkspaceConfigSchema(): void {
|
||||
const contributionRegistry = Registry.as<IJSONContributionRegistry>(JSONExtensions.JSONContribution);
|
||||
if (!contributionRegistry.getSchemaContributions().schemas['vscode://schemas/workspaceConfig']) {
|
||||
contributionRegistry.registerSchema('vscode://schemas/workspaceConfig', {
|
||||
default: {
|
||||
folders: [
|
||||
{
|
||||
path: ''
|
||||
}
|
||||
],
|
||||
settings: {
|
||||
}
|
||||
},
|
||||
required: ['folders'],
|
||||
properties: {
|
||||
'folders': {
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
description: nls.localize('workspaceConfig.folders.description', "List of folders to be loaded in the workspace. Must be a file path. e.g. `/root/folderA` or `./folderA` for a relative path that will be resolved against the location of the workspace file."),
|
||||
items: {
|
||||
type: 'object',
|
||||
default: { path: '' },
|
||||
properties: {
|
||||
path: {
|
||||
type: 'string',
|
||||
description: nls.localize('workspaceConfig.folder.description', "A file path. e.g. `/root/folderA` or `./folderA` for a relative path that will be resolved against the location of the workspace file.")
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'settings': {
|
||||
type: 'object',
|
||||
default: {},
|
||||
description: nls.localize('workspaceConfig.settings.description', "Workspace settings"),
|
||||
$ref: schemaId
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private initializeSingleFolderWorkspace(): TPromise<void> {
|
||||
return stat(this.folderPath.fsPath)
|
||||
.then(workspaceStat => {
|
||||
const ctime = isLinux ? workspaceStat.ino : workspaceStat.birthtime.getTime(); // On Linux, birthtime is ctime, so we cannot use it! We use the ino instead!
|
||||
const id = createHash('md5').update(this.folderPath.fsPath).update(ctime ? String(ctime) : '').digest('hex');
|
||||
const folder = URI.file(this.folderPath.fsPath);
|
||||
this.workspace = new Workspace(id, paths.basename(this.folderPath.fsPath), [folder], null);
|
||||
this.legacyWorkspace = new LegacyWorkspace(folder, ctime);
|
||||
return TPromise.as(null);
|
||||
});
|
||||
}
|
||||
|
||||
private initCachesForFolders(folders: URI[]): void {
|
||||
for (const folder of folders) {
|
||||
this.cachedFolderConfigs.set(folder, this._register(new FolderConfiguration(folder, this.workspaceSettingsRootFolder, this.hasMultiFolderWorkspace() ? ConfigurationScope.RESOURCE : ConfigurationScope.WINDOW)));
|
||||
this.updateFolderConfiguration(folder, new FolderConfigurationModel<any>(new FolderSettingsModel<any>(null), [], ConfigurationScope.RESOURCE), false);
|
||||
}
|
||||
}
|
||||
|
||||
protected updateConfiguration(folders: URI[] = this.workspace.roots): TPromise<boolean> {
|
||||
return TPromise.join([...folders.map(folder => this.cachedFolderConfigs.get(folder).loadConfiguration()
|
||||
.then(configuration => this.updateFolderConfiguration(folder, configuration, true)))])
|
||||
.then(changed => changed.reduce((result, value) => result || value, false))
|
||||
.then(changed => this.updateWorkspaceConfiguration(true) || changed);
|
||||
}
|
||||
|
||||
private onBaseConfigurationChanged({ source, sourceConfig }: IConfigurationServiceEvent): void {
|
||||
if (source === ConfigurationSource.Default) {
|
||||
this.workspace.roots.forEach(folder => this._configuration.getFolderConfigurationModel(folder).update());
|
||||
}
|
||||
if (this._configuration.updateBaseConfiguration(<any>this.baseConfigurationService.configuration())) {
|
||||
this._onDidUpdateConfiguration.fire({ source, sourceConfig });
|
||||
}
|
||||
}
|
||||
|
||||
private onWorkspaceConfigurationChanged(): void {
|
||||
let configuredFolders = this.parseWorkspaceFolders(this.workspaceConfiguration.workspaceConfigurationModel.folders);
|
||||
const foldersChanged = !equals(this.workspace.roots, configuredFolders, (r1, r2) => r1.fsPath === r2.fsPath);
|
||||
if (foldersChanged) { // TODO@Sandeep be smarter here about detecting changes
|
||||
this.workspace.roots = configuredFolders;
|
||||
this.onFoldersChanged()
|
||||
.then(configurationChanged => {
|
||||
this._onDidChangeWorkspaceRoots.fire();
|
||||
if (configurationChanged) {
|
||||
this.triggerConfigurationChange();
|
||||
}
|
||||
} else {
|
||||
c({
|
||||
resource,
|
||||
isDirectory: true,
|
||||
children: children.map(child => { return { resource: URI.file(paths.join(resource.fsPath, child)) }; })
|
||||
});
|
||||
} else {
|
||||
const configurationChanged = this.updateWorkspaceConfiguration(true);
|
||||
if (configurationChanged) {
|
||||
this.triggerConfigurationChange();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private onFoldersChanged(): TPromise<boolean> {
|
||||
let configurationChangedOnRemoval = false;
|
||||
|
||||
// Remove the configurations of deleted folders
|
||||
for (const key of this.cachedFolderConfigs.keys()) {
|
||||
if (!this.workspace.roots.filter(folder => folder.toString() === key.toString())[0]) {
|
||||
this.cachedFolderConfigs.delete(key);
|
||||
if (this._configuration.deleteFolderConfiguration(key)) {
|
||||
configurationChangedOnRemoval = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize the newly added folders
|
||||
const toInitialize = this.workspace.roots.filter(folder => !this.cachedFolderConfigs.has(folder));
|
||||
if (toInitialize.length) {
|
||||
this.initCachesForFolders(toInitialize);
|
||||
return this.updateConfiguration(toInitialize)
|
||||
.then(changed => configurationChangedOnRemoval || changed);
|
||||
} else if (configurationChangedOnRemoval) {
|
||||
this.updateWorkspaceConfiguration(false);
|
||||
return TPromise.as(true);
|
||||
}
|
||||
return TPromise.as(false);
|
||||
}
|
||||
|
||||
private updateFolderConfiguration(folder: URI, folderConfiguration: FolderConfigurationModel<any>, compare: boolean): boolean {
|
||||
let configurationChanged = this._configuration.updateFolderConfiguration(folder, folderConfiguration, compare);
|
||||
if (this.hasFolderWorkspace()) {
|
||||
// Workspace configuration changed
|
||||
configurationChanged = this.updateWorkspaceConfiguration(compare) || configurationChanged;
|
||||
}
|
||||
return configurationChanged;
|
||||
}
|
||||
|
||||
private updateWorkspaceConfiguration(compare: boolean): boolean {
|
||||
const workspaceConfiguration = this.hasMultiFolderWorkspace() ? this.workspaceConfiguration.workspaceConfigurationModel.workspaceConfiguration : this._configuration.getFolderConfigurationModel(this.workspace.roots[0]);
|
||||
return this._configuration.updateWorkspaceConfiguration(workspaceConfiguration, compare);
|
||||
}
|
||||
|
||||
protected triggerConfigurationChange(): void {
|
||||
this._onDidUpdateConfiguration.fire({ source: ConfigurationSource.Workspace, sourceConfig: this._configuration.getFolderConfigurationModel(this.workspace.roots[0]).contents });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
class WorkspaceConfiguration extends Disposable {
|
||||
export class WorkspaceConfiguration extends Disposable {
|
||||
|
||||
private _workspaceConfigPath: URI;
|
||||
private _workspaceConfigurationWatcher: ConfigWatcher<WorkspaceConfigurationModel<any>>;
|
||||
private _workspaceConfigurationWatcher: ConfigWatcher<WorkspaceConfigurationModel>;
|
||||
private _workspaceConfigurationWatcherDisposables: IDisposable[] = [];
|
||||
|
||||
private _onDidUpdateConfiguration: Emitter<void> = this._register(new Emitter<void>());
|
||||
public readonly onDidUpdateConfiguration: Event<void> = this._onDidUpdateConfiguration.event;
|
||||
|
||||
|
||||
load(workspaceConfigPath: URI): TPromise<void> {
|
||||
if (this._workspaceConfigPath && this._workspaceConfigPath.fsPath === workspaceConfigPath.fsPath) {
|
||||
return this._reload();
|
||||
return this.reload();
|
||||
}
|
||||
|
||||
this._workspaceConfigPath = workspaceConfigPath;
|
||||
|
||||
this._workspaceConfigurationWatcherDisposables = dispose(this._workspaceConfigurationWatcherDisposables);
|
||||
this.stopListeningToWatcher();
|
||||
return new TPromise<void>((c, e) => {
|
||||
this._workspaceConfigurationWatcher = new ConfigWatcher(this._workspaceConfigPath.fsPath, {
|
||||
changeBufferDelay: 300, onError: error => errors.onUnexpectedError(error), defaultConfig: new WorkspaceConfigurationModel(null, this._workspaceConfigPath.fsPath), parse: (content: string, parseErrors: any[]) => {
|
||||
changeBufferDelay: 300,
|
||||
onError: error => errors.onUnexpectedError(error),
|
||||
defaultConfig: new WorkspaceConfigurationModel(JSON.stringify({ folders: [] } as IStoredWorkspace, null, '\t'), this._workspaceConfigPath.fsPath),
|
||||
parse: (content: string, parseErrors: any[]) => {
|
||||
const workspaceConfigurationModel = new WorkspaceConfigurationModel(content, this._workspaceConfigPath.fsPath);
|
||||
parseErrors = [...workspaceConfigurationModel.errors];
|
||||
return workspaceConfigurationModel;
|
||||
}, initCallback: () => c(null)
|
||||
});
|
||||
this._workspaceConfigurationWatcherDisposables.push(toDisposable(() => this._workspaceConfigurationWatcher.dispose()));
|
||||
this._workspaceConfigurationWatcher.onDidUpdateConfiguration(() => this._onDidUpdateConfiguration.fire(), this, this._workspaceConfigurationWatcherDisposables);
|
||||
this.listenToWatcher();
|
||||
});
|
||||
}
|
||||
|
||||
get workspaceConfigurationModel(): WorkspaceConfigurationModel<any> {
|
||||
private get workspaceConfigurationModel(): WorkspaceConfigurationModel {
|
||||
return this._workspaceConfigurationWatcher ? this._workspaceConfigurationWatcher.getConfig() : new WorkspaceConfigurationModel();
|
||||
}
|
||||
|
||||
private _reload(): TPromise<void> {
|
||||
return new TPromise<void>(c => this._workspaceConfigurationWatcher.reload(() => c(null)));
|
||||
reload(): TPromise<void> {
|
||||
this.stopListeningToWatcher();
|
||||
return new TPromise<void>(c => this._workspaceConfigurationWatcher.reload(() => {
|
||||
this.listenToWatcher();
|
||||
c(null);
|
||||
}));
|
||||
}
|
||||
|
||||
getFolders(): IStoredWorkspaceFolder[] {
|
||||
return this.workspaceConfigurationModel.folders;
|
||||
}
|
||||
|
||||
setFolders(folders: IStoredWorkspaceFolder[], jsonEditingService: JSONEditingService): TPromise<void> {
|
||||
return jsonEditingService.write(this._workspaceConfigPath, { key: 'folders', value: folders }, true)
|
||||
.then(() => this.reload());
|
||||
}
|
||||
|
||||
getConfiguration(): ConfigurationModel {
|
||||
return this.workspaceConfigurationModel.workspaceConfiguration;
|
||||
}
|
||||
|
||||
getWorkspaceSettings(): WorkspaceSettingsModel {
|
||||
return this.workspaceConfigurationModel.workspaceSettingsModel;
|
||||
}
|
||||
|
||||
private listenToWatcher() {
|
||||
this._workspaceConfigurationWatcherDisposables.push(this._workspaceConfigurationWatcher);
|
||||
this._workspaceConfigurationWatcher.onDidUpdateConfiguration(() => this._onDidUpdateConfiguration.fire(), this, this._workspaceConfigurationWatcherDisposables);
|
||||
}
|
||||
|
||||
private stopListeningToWatcher() {
|
||||
this._workspaceConfigurationWatcherDisposables = dispose(this._workspaceConfigurationWatcherDisposables);
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
@@ -650,15 +146,15 @@ class WorkspaceConfiguration extends Disposable {
|
||||
}
|
||||
}
|
||||
|
||||
class FolderConfiguration<T> extends Disposable {
|
||||
export class FolderConfiguration extends Disposable {
|
||||
|
||||
private static RELOAD_CONFIGURATION_DELAY = 50;
|
||||
|
||||
private bulkFetchFromWorkspacePromise: TPromise<any>;
|
||||
private workspaceFilePathToConfiguration: { [relativeWorkspacePath: string]: TPromise<ConfigurationModel<any>> };
|
||||
private bulkFetchFromWorkspacePromise: TPromise;
|
||||
private workspaceFilePathToConfiguration: { [relativeWorkspacePath: string]: TPromise<ConfigurationModel> };
|
||||
|
||||
private reloadConfigurationScheduler: RunOnceScheduler;
|
||||
private reloadConfigurationEventEmitter: Emitter<FolderConfigurationModel<T>> = new Emitter<FolderConfigurationModel<T>>();
|
||||
private reloadConfigurationEventEmitter: Emitter<FolderConfigurationModel> = new Emitter<FolderConfigurationModel>();
|
||||
|
||||
constructor(private folder: URI, private configFolderRelativePath: string, private scope: ConfigurationScope) {
|
||||
super();
|
||||
@@ -667,17 +163,17 @@ class FolderConfiguration<T> extends Disposable {
|
||||
this.reloadConfigurationScheduler = this._register(new RunOnceScheduler(() => this.loadConfiguration().then(configuration => this.reloadConfigurationEventEmitter.fire(configuration), errors.onUnexpectedError), FolderConfiguration.RELOAD_CONFIGURATION_DELAY));
|
||||
}
|
||||
|
||||
loadConfiguration(): TPromise<FolderConfigurationModel<T>> {
|
||||
loadConfiguration(): TPromise<FolderConfigurationModel> {
|
||||
// Load workspace locals
|
||||
return this.loadWorkspaceConfigFiles().then(workspaceConfigFiles => {
|
||||
// Consolidate (support *.json files in the workspace settings folder)
|
||||
const workspaceSettingsConfig = <FolderSettingsModel<T>>workspaceConfigFiles[WORKSPACE_CONFIG_DEFAULT_PATH] || new FolderSettingsModel<T>(null);
|
||||
const otherConfigModels = Object.keys(workspaceConfigFiles).filter(key => key !== WORKSPACE_CONFIG_DEFAULT_PATH).map(key => <ScopedConfigurationModel<T>>workspaceConfigFiles[key]);
|
||||
return new FolderConfigurationModel<T>(workspaceSettingsConfig, otherConfigModels, this.scope);
|
||||
const workspaceSettingsConfig = <FolderSettingsModel>workspaceConfigFiles[WORKSPACE_CONFIG_DEFAULT_PATH] || new FolderSettingsModel(null);
|
||||
const otherConfigModels = Object.keys(workspaceConfigFiles).filter(key => key !== WORKSPACE_CONFIG_DEFAULT_PATH).map(key => <ScopedConfigurationModel>workspaceConfigFiles[key]);
|
||||
return new FolderConfigurationModel(workspaceSettingsConfig, otherConfigModels, this.scope);
|
||||
});
|
||||
}
|
||||
|
||||
private loadWorkspaceConfigFiles<T>(): TPromise<{ [relativeWorkspacePath: string]: ConfigurationModel<T> }> {
|
||||
private loadWorkspaceConfigFiles(): TPromise<{ [relativeWorkspacePath: string]: ConfigurationModel }> {
|
||||
// once: when invoked for the first time we fetch json files that contribute settings
|
||||
if (!this.bulkFetchFromWorkspacePromise) {
|
||||
this.bulkFetchFromWorkspacePromise = resolveStat(this.toResource(this.configFolderRelativePath)).then(stat => {
|
||||
@@ -704,7 +200,7 @@ class FolderConfiguration<T> extends Disposable {
|
||||
return this.bulkFetchFromWorkspacePromise.then(() => TPromise.join(this.workspaceFilePathToConfiguration));
|
||||
}
|
||||
|
||||
public handleWorkspaceFileEvents(event: FileChangesEvent): TPromise<FolderConfigurationModel<T>> {
|
||||
public handleWorkspaceFileEvents(event: FileChangesEvent): TPromise<FolderConfigurationModel> {
|
||||
const events = event.changes;
|
||||
let affectedByChanges = false;
|
||||
|
||||
@@ -762,22 +258,22 @@ class FolderConfiguration<T> extends Disposable {
|
||||
});
|
||||
}
|
||||
|
||||
private createConfigModel<T>(content: IContent): ConfigurationModel<T> {
|
||||
private createConfigModel(content: IContent): ConfigurationModel {
|
||||
const path = this.toFolderRelativePath(content.resource);
|
||||
if (path === WORKSPACE_CONFIG_DEFAULT_PATH) {
|
||||
return new FolderSettingsModel<T>(content.value, content.resource.toString());
|
||||
return new FolderSettingsModel(content.value, content.resource.toString());
|
||||
} else {
|
||||
const matches = /\/([^\.]*)*\.json/.exec(path);
|
||||
if (matches && matches[1]) {
|
||||
return new ScopedConfigurationModel<T>(content.value, content.resource.toString(), matches[1]);
|
||||
return new ScopedConfigurationModel(content.value, content.resource.toString(), matches[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return new CustomConfigurationModel<T>(null);
|
||||
return new CustomConfigurationModel(null);
|
||||
}
|
||||
|
||||
private isWorkspaceConfigurationFile(folderRelativePath: string): boolean {
|
||||
return [WORKSPACE_CONFIG_DEFAULT_PATH, WORKSPACE_STANDALONE_CONFIGURATIONS.launch, WORKSPACE_STANDALONE_CONFIGURATIONS.tasks].some(p => p === folderRelativePath);
|
||||
return [WORKSPACE_CONFIG_DEFAULT_PATH, WORKSPACE_STANDALONE_CONFIGURATIONS[TASKS_CONFIGURATION_KEY], WORKSPACE_STANDALONE_CONFIGURATIONS[LAUNCH_CONFIGURATION_KEY]].some(p => p === folderRelativePath);
|
||||
}
|
||||
|
||||
private toResource(folderRelativePath: string): URI {
|
||||
@@ -803,114 +299,4 @@ class FolderConfiguration<T> extends Disposable {
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 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)) }; })
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export class Configuration<T> extends BaseConfiguration<T> {
|
||||
|
||||
constructor(private _baseConfiguration: BaseConfiguration<T>, workspaceConfiguration: ConfigurationModel<T>, protected folders: StrictResourceMap<FolderConfigurationModel<T>>, workspace: Workspace) {
|
||||
super(_baseConfiguration.defaults, _baseConfiguration.user, workspaceConfiguration, folders, workspace);
|
||||
}
|
||||
|
||||
updateBaseConfiguration(baseConfiguration: BaseConfiguration<T>): boolean {
|
||||
const current = new Configuration(this._baseConfiguration, this._workspaceConfiguration, this.folders, this._workspace);
|
||||
|
||||
this._baseConfiguration = baseConfiguration;
|
||||
this._defaults = this._baseConfiguration.defaults;
|
||||
this._user = this._baseConfiguration.user;
|
||||
this.merge();
|
||||
|
||||
return !this.equals(current);
|
||||
}
|
||||
|
||||
updateWorkspaceConfiguration(workspaceConfiguration: ConfigurationModel<T>, compare: boolean = true): boolean {
|
||||
const current = new Configuration(this._baseConfiguration, this._workspaceConfiguration, this.folders, this._workspace);
|
||||
|
||||
this._workspaceConfiguration = workspaceConfiguration;
|
||||
this.merge();
|
||||
|
||||
return compare && !this.equals(current);
|
||||
}
|
||||
|
||||
updateFolderConfiguration(resource: URI, configuration: FolderConfigurationModel<T>, compare: boolean): boolean {
|
||||
const current = this.getValue(null, { resource });
|
||||
|
||||
this.folders.set(resource, configuration);
|
||||
this.mergeFolder(resource);
|
||||
|
||||
return compare && !objects.equals(current, this.getValue(null, { resource }));
|
||||
}
|
||||
|
||||
deleteFolderConfiguration(folder: URI): boolean {
|
||||
if (this._workspace && this._workspace.roots.length > 0 && this._workspace.roots[0].fsPath === folder.fsPath) {
|
||||
// Do not remove workspace configuration
|
||||
return false;
|
||||
}
|
||||
|
||||
const changed = this.folders.get(folder).keys.length > 0;
|
||||
this.folders.delete(folder);
|
||||
this._foldersConsolidatedConfigurations.delete(folder);
|
||||
return changed;
|
||||
}
|
||||
|
||||
getFolderConfigurationModel(folder: URI): FolderConfigurationModel<T> {
|
||||
return <FolderConfigurationModel<T>>this.folders.get(folder);
|
||||
}
|
||||
|
||||
equals(other: any): boolean {
|
||||
if (!other || !(other instanceof Configuration)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!objects.equals(this.getValue(), other.getValue())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this._foldersConsolidatedConfigurations.size !== other._foldersConsolidatedConfigurations.size) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const resource of this._foldersConsolidatedConfigurations.keys()) {
|
||||
if (!objects.equals(this.getValue(null, { resource }), other.getValue(null, { resource }))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@
|
||||
|
||||
import nls = require('vs/nls');
|
||||
import { TPromise } from 'vs/base/common/winjs.base';
|
||||
import * as paths from 'vs/base/common/paths';
|
||||
import URI from 'vs/base/common/uri';
|
||||
import * as json from 'vs/base/common/json';
|
||||
import * as encoding from 'vs/base/node/encoding';
|
||||
@@ -21,23 +20,93 @@ import { EditOperation } from 'vs/editor/common/core/editOperation';
|
||||
import { Registry } from 'vs/platform/registry/common/platform';
|
||||
import { Range } from 'vs/editor/common/core/range';
|
||||
import { Selection } from 'vs/editor/common/core/selection';
|
||||
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
|
||||
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
|
||||
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
|
||||
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
|
||||
import { IConfigurationService, IConfigurationOverrides } from 'vs/platform/configuration/common/configuration';
|
||||
import { keyFromOverrideIdentifier } from 'vs/platform/configuration/common/model';
|
||||
import { WORKSPACE_CONFIG_DEFAULT_PATH, WORKSPACE_STANDALONE_CONFIGURATIONS } from 'vs/workbench/services/configuration/common/configuration';
|
||||
import { IConfigurationService, IConfigurationOverrides, keyFromOverrideIdentifier, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
|
||||
import { WORKSPACE_CONFIG_DEFAULT_PATH, WORKSPACE_STANDALONE_CONFIGURATIONS, TASKS_CONFIGURATION_KEY, LAUNCH_CONFIGURATION_KEY } from 'vs/workbench/services/configuration/common/configuration';
|
||||
import { IFileService } from 'vs/platform/files/common/files';
|
||||
import { IConfigurationEditingService, ConfigurationEditingErrorCode, ConfigurationEditingError, ConfigurationTarget, IConfigurationValue, IConfigurationEditingOptions } from 'vs/workbench/services/configuration/common/configurationEditing';
|
||||
import { ITextModelService, ITextEditorModel } from 'vs/editor/common/services/resolverService';
|
||||
import { OVERRIDE_PROPERTY_PATTERN, IConfigurationRegistry, Extensions as ConfigurationExtensions, ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry';
|
||||
import { IChoiceService, IMessageService, Severity } from 'vs/platform/message/common/message';
|
||||
import { ICommandService } from 'vs/platform/commands/common/commands';
|
||||
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
|
||||
|
||||
export enum ConfigurationEditingErrorCode {
|
||||
|
||||
/**
|
||||
* Error when trying to write a configuration key that is not registered.
|
||||
*/
|
||||
ERROR_UNKNOWN_KEY,
|
||||
|
||||
/**
|
||||
* Error when trying to write an invalid folder configuration key to folder settings.
|
||||
*/
|
||||
ERROR_INVALID_FOLDER_CONFIGURATION,
|
||||
|
||||
/**
|
||||
* Error when trying to write to user target but not supported for provided key.
|
||||
*/
|
||||
ERROR_INVALID_USER_TARGET,
|
||||
|
||||
/**
|
||||
* Error when trying to write to user target but not supported for provided key.
|
||||
*/
|
||||
ERROR_INVALID_WORKSPACE_TARGET,
|
||||
|
||||
/**
|
||||
* Error when trying to write a configuration key to folder target
|
||||
*/
|
||||
ERROR_INVALID_FOLDER_TARGET,
|
||||
|
||||
/**
|
||||
* Error when trying to write to the workspace configuration without having a workspace opened.
|
||||
*/
|
||||
ERROR_NO_WORKSPACE_OPENED,
|
||||
|
||||
/**
|
||||
* Error when trying to write and save to the configuration file while it is dirty in the editor.
|
||||
*/
|
||||
ERROR_CONFIGURATION_FILE_DIRTY,
|
||||
|
||||
/**
|
||||
* Error when trying to write to a configuration file that contains JSON errors.
|
||||
*/
|
||||
ERROR_INVALID_CONFIGURATION
|
||||
}
|
||||
|
||||
export class ConfigurationEditingError extends Error {
|
||||
constructor(message: string, public code: ConfigurationEditingErrorCode) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export interface IConfigurationValue {
|
||||
key: string;
|
||||
value: any;
|
||||
}
|
||||
|
||||
export interface IConfigurationEditingOptions {
|
||||
/**
|
||||
* If `true`, do not saves the configuration. Default is `false`.
|
||||
*/
|
||||
donotSave?: boolean;
|
||||
/**
|
||||
* If `true`, do not notifies the error to user by showing the message box. Default is `false`.
|
||||
*/
|
||||
donotNotifyError?: boolean;
|
||||
/**
|
||||
* Scope of configuration to be written into.
|
||||
*/
|
||||
scopes?: IConfigurationOverrides;
|
||||
}
|
||||
|
||||
interface IConfigurationEditOperation extends IConfigurationValue {
|
||||
target: ConfigurationTarget;
|
||||
jsonPath: json.JSONPath;
|
||||
resource: URI;
|
||||
isWorkspaceStandalone?: boolean;
|
||||
workspaceStandAloneConfigurationKey?: string;
|
||||
|
||||
}
|
||||
|
||||
interface IValidationResult {
|
||||
@@ -49,7 +118,7 @@ interface ConfigurationEditingOptions extends IConfigurationEditingOptions {
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
export class ConfigurationEditingService implements IConfigurationEditingService {
|
||||
export class ConfigurationEditingService {
|
||||
|
||||
public _serviceBrand: any;
|
||||
|
||||
@@ -64,28 +133,28 @@ export class ConfigurationEditingService implements IConfigurationEditingService
|
||||
@ITextFileService private textFileService: ITextFileService,
|
||||
@IChoiceService private choiceService: IChoiceService,
|
||||
@IMessageService private messageService: IMessageService,
|
||||
@ICommandService private commandService: ICommandService
|
||||
@ICommandService private commandService: ICommandService,
|
||||
@IWorkbenchEditorService private editorService: IWorkbenchEditorService
|
||||
) {
|
||||
this.queue = new Queue<void>();
|
||||
}
|
||||
|
||||
writeConfiguration(target: ConfigurationTarget, value: IConfigurationValue, options: IConfigurationEditingOptions = {}): TPromise<void> {
|
||||
return this.queue.queue(() => this.doWriteConfiguration(target, value, options) // queue up writes to prevent race conditions
|
||||
const operation = this.getConfigurationEditOperation(target, value, options.scopes || {});
|
||||
return this.queue.queue(() => this.doWriteConfiguration(operation, options) // queue up writes to prevent race conditions
|
||||
.then(() => null,
|
||||
error => {
|
||||
if (!options.donotNotifyError) {
|
||||
this.onError(error, target, value, options.scopes);
|
||||
this.onError(error, operation, options.scopes);
|
||||
}
|
||||
return TPromise.wrapError(error);
|
||||
}));
|
||||
}
|
||||
|
||||
private doWriteConfiguration(target: ConfigurationTarget, value: IConfigurationValue, options: ConfigurationEditingOptions): TPromise<void> {
|
||||
const operation = this.getConfigurationEditOperation(target, value, options.scopes || {});
|
||||
|
||||
private doWriteConfiguration(operation: IConfigurationEditOperation, options: ConfigurationEditingOptions): TPromise<void> {
|
||||
const checkDirtyConfiguration = !(options.force || options.donotSave);
|
||||
const saveConfiguration = options.force || !options.donotSave;
|
||||
return this.resolveAndValidate(target, operation, checkDirtyConfiguration, options.scopes || {})
|
||||
return this.resolveAndValidate(operation.target, operation, checkDirtyConfiguration, options.scopes || {})
|
||||
.then(reference => this.writeToBuffer(reference.object.textEditorModel, operation, saveConfiguration)
|
||||
.then(() => reference.dispose()));
|
||||
}
|
||||
@@ -93,9 +162,7 @@ export class ConfigurationEditingService implements IConfigurationEditingService
|
||||
private writeToBuffer(model: editorCommon.IModel, operation: IConfigurationEditOperation, save: boolean): TPromise<any> {
|
||||
const edit = this.getEdits(model, operation)[0];
|
||||
if (this.applyEditsToBuffer(edit, model) && save) {
|
||||
return this.textFileService.save(operation.resource, { skipSaveParticipants: true /* programmatic change */ })
|
||||
// Reload the configuration so that we make sure all parties are updated
|
||||
.then(() => this.configurationService.reloadConfiguration());
|
||||
return this.textFileService.save(operation.resource, { skipSaveParticipants: true /* programmatic change */ });
|
||||
}
|
||||
return TPromise.as(null);
|
||||
}
|
||||
@@ -113,45 +180,97 @@ export class ConfigurationEditingService implements IConfigurationEditingService
|
||||
return false;
|
||||
}
|
||||
|
||||
private onError(error: ConfigurationEditingError, target: ConfigurationTarget, value: IConfigurationValue, scopes: IConfigurationOverrides): void {
|
||||
private onError(error: ConfigurationEditingError, operation: IConfigurationEditOperation, scopes: IConfigurationOverrides): void {
|
||||
switch (error.code) {
|
||||
case ConfigurationEditingErrorCode.ERROR_INVALID_CONFIGURATION:
|
||||
this.onInvalidConfigurationError(error, target);
|
||||
this.onInvalidConfigurationError(error, operation);
|
||||
break;
|
||||
case ConfigurationEditingErrorCode.ERROR_CONFIGURATION_FILE_DIRTY:
|
||||
this.onConfigurationFileDirtyError(error, target, value, scopes);
|
||||
this.onConfigurationFileDirtyError(error, operation, scopes);
|
||||
break;
|
||||
default:
|
||||
this.messageService.show(Severity.Error, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
private onInvalidConfigurationError(error: ConfigurationEditingError, target: ConfigurationTarget): void {
|
||||
this.choiceService.choose(Severity.Error, error.message, [nls.localize('open', "Open Settings"), nls.localize('close', "Close")], 1)
|
||||
.then(option => {
|
||||
switch (option) {
|
||||
case 0:
|
||||
this.openSettings(target);
|
||||
}
|
||||
});
|
||||
private onInvalidConfigurationError(error: ConfigurationEditingError, operation: IConfigurationEditOperation, ): void {
|
||||
const openStandAloneConfigurationActionLabel = operation.workspaceStandAloneConfigurationKey === TASKS_CONFIGURATION_KEY ? nls.localize('openTasksConfiguration', "Open Tasks Configuration")
|
||||
: operation.workspaceStandAloneConfigurationKey === LAUNCH_CONFIGURATION_KEY ? nls.localize('openLaunchConfiguration', "Open Launch Configuration")
|
||||
: null;
|
||||
if (openStandAloneConfigurationActionLabel) {
|
||||
this.choiceService.choose(Severity.Error, error.message, [openStandAloneConfigurationActionLabel, nls.localize('close', "Close")], 1)
|
||||
.then(option => {
|
||||
switch (option) {
|
||||
case 0:
|
||||
this.openFile(operation.resource);
|
||||
break;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this.choiceService.choose(Severity.Error, error.message, [nls.localize('open', "Open Settings"), nls.localize('close', "Close")], 1)
|
||||
.then(option => {
|
||||
switch (option) {
|
||||
case 0:
|
||||
this.openSettings(operation);
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private onConfigurationFileDirtyError(error: ConfigurationEditingError, target: ConfigurationTarget, value: IConfigurationValue, scopes: IConfigurationOverrides): void {
|
||||
this.choiceService.choose(Severity.Error, error.message, [nls.localize('saveAndRetry', "Save Settings and Retry"), nls.localize('open', "Open Settings"), nls.localize('close', "Close")], 2)
|
||||
.then(option => {
|
||||
switch (option) {
|
||||
case 0:
|
||||
this.writeConfiguration(target, value, <ConfigurationEditingOptions>{ force: true, scopes });
|
||||
break;
|
||||
case 1:
|
||||
this.openSettings(target);
|
||||
break;
|
||||
}
|
||||
});
|
||||
private onConfigurationFileDirtyError(error: ConfigurationEditingError, operation: IConfigurationEditOperation, scopes: IConfigurationOverrides): void {
|
||||
const openStandAloneConfigurationActionLabel = operation.workspaceStandAloneConfigurationKey === TASKS_CONFIGURATION_KEY ? nls.localize('openTasksConfiguration', "Open Tasks Configuration")
|
||||
: operation.workspaceStandAloneConfigurationKey === LAUNCH_CONFIGURATION_KEY ? nls.localize('openLaunchConfiguration', "Open Launch Configuration")
|
||||
: null;
|
||||
if (openStandAloneConfigurationActionLabel) {
|
||||
this.choiceService.choose(Severity.Error, error.message, [nls.localize('saveAndRetry', "Save and Retry"), openStandAloneConfigurationActionLabel, nls.localize('close', "Close")], 2)
|
||||
.then(option => {
|
||||
switch (option) {
|
||||
case 0:
|
||||
const key = operation.key ? `${operation.workspaceStandAloneConfigurationKey}.${operation.key}` : operation.workspaceStandAloneConfigurationKey;
|
||||
this.writeConfiguration(operation.target, { key, value: operation.value }, <ConfigurationEditingOptions>{ force: true, scopes });
|
||||
break;
|
||||
case 1:
|
||||
this.openFile(operation.resource);
|
||||
break;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this.choiceService.choose(Severity.Error, error.message, [nls.localize('saveAndRetry', "Save and Retry"), nls.localize('open', "Open Settings"), nls.localize('close', "Close")], 2)
|
||||
.then(option => {
|
||||
switch (option) {
|
||||
case 0:
|
||||
this.writeConfiguration(operation.target, { key: operation.key, value: operation.value }, <ConfigurationEditingOptions>{ force: true, scopes });
|
||||
break;
|
||||
case 1:
|
||||
this.openSettings(operation);
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private openSettings(target: ConfigurationTarget): void {
|
||||
this.commandService.executeCommand(ConfigurationTarget.USER === target ? 'workbench.action.openGlobalSettings' : 'workbench.action.openWorkspaceSettings');
|
||||
private openSettings(operation: IConfigurationEditOperation): void {
|
||||
switch (operation.target) {
|
||||
case ConfigurationTarget.USER:
|
||||
this.commandService.executeCommand('workbench.action.openGlobalSettings');
|
||||
break;
|
||||
case ConfigurationTarget.WORKSPACE:
|
||||
this.commandService.executeCommand('workbench.action.openWorkspaceSettings');
|
||||
break;
|
||||
case ConfigurationTarget.WORKSPACE_FOLDER:
|
||||
if (operation.resource) {
|
||||
const workspaceFolder = this.contextService.getWorkspaceFolder(operation.resource);
|
||||
if (workspaceFolder) {
|
||||
this.commandService.executeCommand('_workbench.action.openFolderSettings', workspaceFolder);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private openFile(resource: URI): void {
|
||||
this.editorService.openEditor({ resource });
|
||||
}
|
||||
|
||||
private wrapError<T = never>(code: ConfigurationEditingErrorCode, target: ConfigurationTarget, operation: IConfigurationEditOperation): TPromise<T> {
|
||||
@@ -167,23 +286,46 @@ export class ConfigurationEditingService implements IConfigurationEditingService
|
||||
case ConfigurationEditingErrorCode.ERROR_UNKNOWN_KEY: return nls.localize('errorUnknownKey', "Unable to write to {0} because {1} is not a registered configuration.", this.stringifyTarget(target), operation.key);
|
||||
case ConfigurationEditingErrorCode.ERROR_INVALID_FOLDER_CONFIGURATION: return nls.localize('errorInvalidFolderConfiguration', "Unable to write to Folder Settings because {0} does not support the folder resource scope.", operation.key);
|
||||
case ConfigurationEditingErrorCode.ERROR_INVALID_USER_TARGET: return nls.localize('errorInvalidUserTarget', "Unable to write to User Settings because {0} does not support for global scope.", operation.key);
|
||||
case ConfigurationEditingErrorCode.ERROR_INVALID_WORKSPACE_TARGET: return nls.localize('errorInvalidWorkspaceTarget', "Unable to write to Workspace Settings because {0} does not support for workspace scope in a multi folder workspace.", operation.key);
|
||||
case ConfigurationEditingErrorCode.ERROR_INVALID_FOLDER_TARGET: return nls.localize('errorInvalidFolderTarget', "Unable to write to Folder Settings because no resource is provided.");
|
||||
case ConfigurationEditingErrorCode.ERROR_NO_WORKSPACE_OPENED: return nls.localize('errorNoWorkspaceOpened', "Unable to write to {0} because no workspace is opened. Please open a workspace first and try again.", this.stringifyTarget(target));
|
||||
|
||||
// User issues
|
||||
case ConfigurationEditingErrorCode.ERROR_INVALID_CONFIGURATION: {
|
||||
if (target === ConfigurationTarget.USER) {
|
||||
return nls.localize('errorInvalidConfiguration', "Unable to write into settings. Please open **User Settings** to correct errors/warnings in the file and try again.");
|
||||
if (operation.workspaceStandAloneConfigurationKey === TASKS_CONFIGURATION_KEY) {
|
||||
return nls.localize('errorInvalidTaskConfiguration', "Unable to write into tasks file. Please open **Tasks** file to correct errors/warnings in it and try again.");
|
||||
}
|
||||
|
||||
return nls.localize('errorInvalidConfigurationWorkspace', "Unable to write into settings. Please open **Workspace Settings** to correct errors/warnings in the file and try again.");
|
||||
if (operation.workspaceStandAloneConfigurationKey === LAUNCH_CONFIGURATION_KEY) {
|
||||
return nls.localize('errorInvalidLaunchConfiguration', "Unable to write into launch file. Please open **Launch** file to correct errors/warnings in it and try again.");
|
||||
}
|
||||
switch (target) {
|
||||
case ConfigurationTarget.USER:
|
||||
return nls.localize('errorInvalidConfiguration', "Unable to write into user settings. Please open **User Settings** file to correct errors/warnings in it and try again.");
|
||||
case ConfigurationTarget.WORKSPACE:
|
||||
return nls.localize('errorInvalidConfigurationWorkspace', "Unable to write into workspace settings. Please open **Workspace Settings** file to correct errors/warnings in the file and try again.");
|
||||
case ConfigurationTarget.WORKSPACE_FOLDER:
|
||||
const workspaceFolderName = this.contextService.getWorkspaceFolder(operation.resource).name;
|
||||
return nls.localize('errorInvalidConfigurationFolder', "Unable to write into folder settings. Please open **Folder Settings** file under **{0}** folder to correct errors/warnings in it and try again.", workspaceFolderName);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
case ConfigurationEditingErrorCode.ERROR_CONFIGURATION_FILE_DIRTY: {
|
||||
if (target === ConfigurationTarget.USER) {
|
||||
return nls.localize('errorConfigurationFileDirty', "Unable to write into settings because the file is dirty. Please save the **User Settings** file and try again.");
|
||||
if (operation.workspaceStandAloneConfigurationKey === TASKS_CONFIGURATION_KEY) {
|
||||
return nls.localize('errorTasksConfigurationFileDirty', "Unable to write into tasks file because the file is dirty. Please save the **Tasks Configuration** file and try again.");
|
||||
}
|
||||
|
||||
return nls.localize('errorConfigurationFileDirtyWorkspace', "Unable to write into settings because the file is dirty. Please save the **Workspace Settings** file and try again.");
|
||||
if (operation.workspaceStandAloneConfigurationKey === LAUNCH_CONFIGURATION_KEY) {
|
||||
return nls.localize('errorLaunchConfigurationFileDirty', "Unable to write into launch file because the file is dirty. Please save the **Launch Configuration** file and try again.");
|
||||
}
|
||||
switch (target) {
|
||||
case ConfigurationTarget.USER:
|
||||
return nls.localize('errorConfigurationFileDirty', "Unable to write into user settings because the file is dirty. Please save the **User Settings** file and try again.");
|
||||
case ConfigurationTarget.WORKSPACE:
|
||||
return nls.localize('errorConfigurationFileDirtyWorkspace', "Unable to write into workspace settings because the file is dirty. Please save the **Workspace Settings** file and try again.");
|
||||
case ConfigurationTarget.WORKSPACE_FOLDER:
|
||||
const workspaceFolderName = this.contextService.getWorkspaceFolder(operation.resource).name;
|
||||
return nls.localize('errorConfigurationFileDirtyFolder', "Unable to write into folder settings because the file is dirty. Please save the **Folder Settings** file under **{0}** folder and try again.", workspaceFolderName);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -194,9 +336,10 @@ export class ConfigurationEditingService implements IConfigurationEditingService
|
||||
return nls.localize('userTarget', "User Settings");
|
||||
case ConfigurationTarget.WORKSPACE:
|
||||
return nls.localize('workspaceTarget', "Workspace Settings");
|
||||
case ConfigurationTarget.FOLDER:
|
||||
case ConfigurationTarget.WORKSPACE_FOLDER:
|
||||
return nls.localize('folderTarget', "Folder Settings");
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
private getEdits(model: editorCommon.IModel, edit: IConfigurationEditOperation): Edit[] {
|
||||
@@ -228,7 +371,7 @@ export class ConfigurationEditingService implements IConfigurationEditingService
|
||||
private hasParseErrors(model: editorCommon.IModel, operation: IConfigurationEditOperation): boolean {
|
||||
// If we write to a workspace standalone file and replace the entire contents (no key provided)
|
||||
// we can return here because any parse errors can safely be ignored since all contents are replaced
|
||||
if (operation.isWorkspaceStandalone && !operation.key) {
|
||||
if (operation.workspaceStandAloneConfigurationKey && !operation.key) {
|
||||
return false;
|
||||
}
|
||||
const parseErrors: json.ParseError[] = [];
|
||||
@@ -239,31 +382,40 @@ export class ConfigurationEditingService implements IConfigurationEditingService
|
||||
private resolveAndValidate(target: ConfigurationTarget, operation: IConfigurationEditOperation, checkDirty: boolean, overrides: IConfigurationOverrides): TPromise<IReference<ITextEditorModel>> {
|
||||
|
||||
// Any key must be a known setting from the registry (unless this is a standalone config)
|
||||
if (!operation.isWorkspaceStandalone) {
|
||||
if (!operation.workspaceStandAloneConfigurationKey) {
|
||||
const validKeys = this.configurationService.keys().default;
|
||||
if (validKeys.indexOf(operation.key) < 0 && !OVERRIDE_PROPERTY_PATTERN.test(operation.key)) {
|
||||
return this.wrapError(ConfigurationEditingErrorCode.ERROR_UNKNOWN_KEY, target, operation);
|
||||
}
|
||||
}
|
||||
|
||||
// Target cannot be user if is standalone
|
||||
if (operation.isWorkspaceStandalone && target === ConfigurationTarget.USER) {
|
||||
return this.wrapError(ConfigurationEditingErrorCode.ERROR_INVALID_USER_TARGET, target, operation);
|
||||
if (operation.workspaceStandAloneConfigurationKey) {
|
||||
// Global tasks and launches are not supported
|
||||
if (target === ConfigurationTarget.USER) {
|
||||
return this.wrapError(ConfigurationEditingErrorCode.ERROR_INVALID_USER_TARGET, target, operation);
|
||||
}
|
||||
|
||||
// Workspace tasks and launches are not supported
|
||||
if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE && operation.target === ConfigurationTarget.WORKSPACE) {
|
||||
return this.wrapError(ConfigurationEditingErrorCode.ERROR_INVALID_WORKSPACE_TARGET, target, operation);
|
||||
}
|
||||
}
|
||||
|
||||
// Target cannot be workspace or folder if no workspace opened
|
||||
if ((target === ConfigurationTarget.WORKSPACE || target === ConfigurationTarget.FOLDER) && !this.contextService.hasWorkspace()) {
|
||||
if ((target === ConfigurationTarget.WORKSPACE || target === ConfigurationTarget.WORKSPACE_FOLDER) && this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
|
||||
return this.wrapError(ConfigurationEditingErrorCode.ERROR_NO_WORKSPACE_OPENED, target, operation);
|
||||
}
|
||||
|
||||
if (target === ConfigurationTarget.FOLDER) {
|
||||
if (target === ConfigurationTarget.WORKSPACE_FOLDER) {
|
||||
if (!operation.resource) {
|
||||
return this.wrapError(ConfigurationEditingErrorCode.ERROR_INVALID_FOLDER_TARGET, target, operation);
|
||||
}
|
||||
|
||||
const configurationProperties = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).getConfigurationProperties();
|
||||
if (configurationProperties[operation.key].scope !== ConfigurationScope.RESOURCE) {
|
||||
return this.wrapError(ConfigurationEditingErrorCode.ERROR_INVALID_FOLDER_CONFIGURATION, target, operation);
|
||||
if (!operation.workspaceStandAloneConfigurationKey) {
|
||||
const configurationProperties = Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).getConfigurationProperties();
|
||||
if (configurationProperties[operation.key].scope !== ConfigurationScope.RESOURCE) {
|
||||
return this.wrapError(ConfigurationEditingErrorCode.ERROR_INVALID_FOLDER_CONFIGURATION, target, operation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,15 +448,15 @@ export class ConfigurationEditingService implements IConfigurationEditingService
|
||||
|
||||
// Check for prefix
|
||||
if (config.key === key) {
|
||||
const jsonPath = workspace && workspace.configuration && resource && workspace.configuration.fsPath === resource.fsPath ? [key] : [];
|
||||
return { key: jsonPath[jsonPath.length - 1], jsonPath, value: config.value, resource, isWorkspaceStandalone: true };
|
||||
const jsonPath = workspace.configuration && resource && workspace.configuration.fsPath === resource.fsPath ? [key] : [];
|
||||
return { key: jsonPath[jsonPath.length - 1], jsonPath, value: config.value, resource, workspaceStandAloneConfigurationKey: key, target };
|
||||
}
|
||||
|
||||
// Check for prefix.<setting>
|
||||
const keyPrefix = `${key}.`;
|
||||
if (config.key.indexOf(keyPrefix) === 0) {
|
||||
const jsonPath = workspace && workspace.configuration && resource && workspace.configuration.fsPath === resource.fsPath ? [key, config.key.substr(keyPrefix.length)] : [config.key.substr(keyPrefix.length)];
|
||||
return { key: jsonPath[jsonPath.length - 1], jsonPath, value: config.value, resource, isWorkspaceStandalone: true };
|
||||
const jsonPath = workspace.configuration && resource && workspace.configuration.fsPath === resource.fsPath ? [key, config.key.substr(keyPrefix.length)] : [config.key.substr(keyPrefix.length)];
|
||||
return { key: jsonPath[jsonPath.length - 1], jsonPath, value: config.value, resource, workspaceStandAloneConfigurationKey: key, target };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -312,14 +464,14 @@ export class ConfigurationEditingService implements IConfigurationEditingService
|
||||
let key = config.key;
|
||||
let jsonPath = overrides.overrideIdentifier ? [keyFromOverrideIdentifier(overrides.overrideIdentifier), key] : [key];
|
||||
if (target === ConfigurationTarget.USER) {
|
||||
return { key, jsonPath, value: config.value, resource: URI.file(this.environmentService.appSettingsPath) };
|
||||
return { key, jsonPath, value: config.value, resource: URI.file(this.environmentService.appSettingsPath), target };
|
||||
}
|
||||
|
||||
const resource = this.getConfigurationFileResource(target, WORKSPACE_CONFIG_DEFAULT_PATH, overrides.resource);
|
||||
if (workspace && workspace.configuration && resource && workspace.configuration.fsPath === resource.fsPath) {
|
||||
if (workspace.configuration && resource && workspace.configuration.fsPath === resource.fsPath) {
|
||||
jsonPath = ['settings', ...jsonPath];
|
||||
}
|
||||
return { key, jsonPath, value: config.value, resource };
|
||||
return { key, jsonPath, value: config.value, resource, target };
|
||||
}
|
||||
|
||||
private getConfigurationFileResource(target: ConfigurationTarget, relativePath: string, resource: URI): URI {
|
||||
@@ -327,27 +479,29 @@ export class ConfigurationEditingService implements IConfigurationEditingService
|
||||
return URI.file(this.environmentService.appSettingsPath);
|
||||
}
|
||||
|
||||
const workspace = this.contextService.getWorkspace();
|
||||
const workbenchState = this.contextService.getWorkbenchState();
|
||||
if (workbenchState !== WorkbenchState.EMPTY) {
|
||||
|
||||
if (workspace) {
|
||||
const workspace = this.contextService.getWorkspace();
|
||||
|
||||
if (target === ConfigurationTarget.WORKSPACE) {
|
||||
return this.contextService.hasMultiFolderWorkspace() ? workspace.configuration : this.toResource(relativePath, workspace.roots[0]);
|
||||
if (workbenchState === WorkbenchState.WORKSPACE) {
|
||||
return workspace.configuration;
|
||||
}
|
||||
if (workbenchState === WorkbenchState.FOLDER) {
|
||||
return workspace.folders[0].toResource(relativePath);
|
||||
}
|
||||
}
|
||||
|
||||
if (target === ConfigurationTarget.FOLDER && this.contextService.hasMultiFolderWorkspace()) {
|
||||
if (target === ConfigurationTarget.WORKSPACE_FOLDER) {
|
||||
if (resource) {
|
||||
const root = this.contextService.getRoot(resource);
|
||||
if (root) {
|
||||
return this.toResource(relativePath, root);
|
||||
const folder = this.contextService.getWorkspaceFolder(resource);
|
||||
if (folder) {
|
||||
return folder.toResource(relativePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private toResource(relativePath: string, root: URI): URI {
|
||||
return URI.file(paths.join(root.fsPath, relativePath));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,752 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. 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 { dirname } from 'path';
|
||||
import * as assert from 'vs/base/common/assert';
|
||||
import Event, { Emitter } from 'vs/base/common/event';
|
||||
import { StrictResourceMap } from 'vs/base/common/map';
|
||||
import { equals } from 'vs/base/common/objects';
|
||||
import { Disposable } from 'vs/base/common/lifecycle';
|
||||
import { Queue } from 'vs/base/common/async';
|
||||
import { stat, writeFile } from 'vs/base/node/pfs';
|
||||
import { IJSONContributionRegistry, Extensions as JSONExtensions } from 'vs/platform/jsonschemas/common/jsonContributionRegistry';
|
||||
import { IWorkspaceContextService, Workspace, WorkbenchState, IWorkspaceFolder, toWorkspaceFolders, IWorkspaceFoldersChangeEvent } from 'vs/platform/workspace/common/workspace';
|
||||
import { FileChangesEvent } from 'vs/platform/files/common/files';
|
||||
import { isLinux } from 'vs/base/common/platform';
|
||||
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
|
||||
import { ConfigurationModel, ConfigurationChangeEvent, AllKeysConfigurationChangeEvent } from 'vs/platform/configuration/common/configurationModels';
|
||||
import { IConfigurationChangeEvent, ConfigurationTarget, IConfigurationOverrides, keyFromOverrideIdentifier, isConfigurationOverrides, IConfigurationData } from 'vs/platform/configuration/common/configuration';
|
||||
import { FolderConfigurationModel, Configuration, WorkspaceConfigurationChangeEvent } from 'vs/workbench/services/configuration/common/configurationModels';
|
||||
import { IWorkspaceConfigurationService, WORKSPACE_CONFIG_FOLDER_DEFAULT_NAME, defaultSettingsSchemaId, userSettingsSchemaId, workspaceSettingsSchemaId, folderSettingsSchemaId } from 'vs/workbench/services/configuration/common/configuration';
|
||||
import { ConfigurationService as GlobalConfigurationService } from 'vs/platform/configuration/node/configurationService';
|
||||
import { Registry } from 'vs/platform/registry/common/platform';
|
||||
import { IConfigurationNode, IConfigurationRegistry, Extensions, ConfigurationScope, settingsSchema, resourceSettingsSchema } from 'vs/platform/configuration/common/configurationRegistry';
|
||||
import { createHash } from 'crypto';
|
||||
import { getWorkspaceLabel, IWorkspacesService, IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier, isWorkspaceIdentifier, IStoredWorkspaceFolder, isStoredWorkspaceFolder, IWorkspaceFolderCreationData } from 'vs/platform/workspaces/common/workspaces';
|
||||
import { IWindowConfiguration } from 'vs/platform/windows/common/windows';
|
||||
import { IExtensionService } from 'vs/platform/extensions/common/extensions';
|
||||
import { ICommandService } from 'vs/platform/commands/common/commands';
|
||||
import product from 'vs/platform/node/product';
|
||||
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
|
||||
import { ConfigurationEditingService } from 'vs/workbench/services/configuration/node/configurationEditingService';
|
||||
import { WorkspaceConfiguration, FolderConfiguration } from 'vs/workbench/services/configuration/node/configuration';
|
||||
import { JSONEditingService } from 'vs/workbench/services/configuration/node/jsonEditingService';
|
||||
import { Schemas } from 'vs/base/common/network';
|
||||
import { massageFolderPathForWorkspace } from 'vs/platform/workspaces/node/workspaces';
|
||||
import { distinct } from 'vs/base/common/arrays';
|
||||
|
||||
export class WorkspaceService extends Disposable implements IWorkspaceConfigurationService, IWorkspaceContextService {
|
||||
|
||||
public _serviceBrand: any;
|
||||
|
||||
private workspace: Workspace;
|
||||
private _configuration: Configuration;
|
||||
private baseConfigurationService: GlobalConfigurationService;
|
||||
private workspaceConfiguration: WorkspaceConfiguration;
|
||||
private cachedFolderConfigs: StrictResourceMap<FolderConfiguration>;
|
||||
|
||||
private workspaceEditingQueue: Queue<void>;
|
||||
|
||||
protected readonly _onDidChangeConfiguration: Emitter<IConfigurationChangeEvent> = this._register(new Emitter<IConfigurationChangeEvent>());
|
||||
public readonly onDidChangeConfiguration: Event<IConfigurationChangeEvent> = this._onDidChangeConfiguration.event;
|
||||
|
||||
protected readonly _onDidChangeWorkspaceFolders: Emitter<IWorkspaceFoldersChangeEvent> = this._register(new Emitter<IWorkspaceFoldersChangeEvent>());
|
||||
public readonly onDidChangeWorkspaceFolders: Event<IWorkspaceFoldersChangeEvent> = this._onDidChangeWorkspaceFolders.event;
|
||||
|
||||
protected readonly _onDidChangeWorkspaceName: Emitter<void> = this._register(new Emitter<void>());
|
||||
public readonly onDidChangeWorkspaceName: Event<void> = this._onDidChangeWorkspaceName.event;
|
||||
|
||||
protected readonly _onDidChangeWorkbenchState: Emitter<WorkbenchState> = this._register(new Emitter<WorkbenchState>());
|
||||
public readonly onDidChangeWorkbenchState: Event<WorkbenchState> = this._onDidChangeWorkbenchState.event;
|
||||
|
||||
private configurationEditingService: ConfigurationEditingService;
|
||||
private jsonEditingService: JSONEditingService;
|
||||
|
||||
constructor(private environmentService: IEnvironmentService, private workspacesService: IWorkspacesService, private workspaceSettingsRootFolder: string = WORKSPACE_CONFIG_FOLDER_DEFAULT_NAME) {
|
||||
super();
|
||||
|
||||
this.workspaceConfiguration = this._register(new WorkspaceConfiguration());
|
||||
this._register(this.workspaceConfiguration.onDidUpdateConfiguration(() => this.onWorkspaceConfigurationChanged()));
|
||||
|
||||
this.baseConfigurationService = this._register(new GlobalConfigurationService(environmentService));
|
||||
this._register(this.baseConfigurationService.onDidChangeConfiguration(e => this.onBaseConfigurationChanged(e)));
|
||||
this._register(Registry.as<IConfigurationRegistry>(Extensions.Configuration).onDidRegisterConfiguration(e => this.registerConfigurationSchemas()));
|
||||
|
||||
this.workspaceEditingQueue = new Queue<void>();
|
||||
}
|
||||
|
||||
// Workspace Context Service Impl
|
||||
|
||||
public getWorkspace(): Workspace {
|
||||
return this.workspace;
|
||||
}
|
||||
|
||||
public getWorkbenchState(): WorkbenchState {
|
||||
// Workspace has configuration file
|
||||
if (this.workspace.configuration) {
|
||||
return WorkbenchState.WORKSPACE;
|
||||
}
|
||||
|
||||
// Folder has single root
|
||||
if (this.workspace.folders.length === 1) {
|
||||
return WorkbenchState.FOLDER;
|
||||
}
|
||||
|
||||
// Empty
|
||||
return WorkbenchState.EMPTY;
|
||||
}
|
||||
|
||||
public getWorkspaceFolder(resource: URI): IWorkspaceFolder {
|
||||
return this.workspace.getFolder(resource);
|
||||
}
|
||||
|
||||
public addFolders(foldersToAdd: IWorkspaceFolderCreationData[]): TPromise<void> {
|
||||
assert.ok(this.jsonEditingService, 'Workbench is not initialized yet');
|
||||
return this.workspaceEditingQueue.queue(() => this.doAddFolders(foldersToAdd));
|
||||
}
|
||||
|
||||
public removeFolders(foldersToRemove: URI[]): TPromise<void> {
|
||||
assert.ok(this.jsonEditingService, 'Workbench is not initialized yet');
|
||||
return this.workspaceEditingQueue.queue(() => this.doRemoveFolders(foldersToRemove));
|
||||
}
|
||||
|
||||
public isInsideWorkspace(resource: URI): boolean {
|
||||
return !!this.getWorkspaceFolder(resource);
|
||||
}
|
||||
|
||||
public isCurrentWorkspace(workspaceIdentifier: ISingleFolderWorkspaceIdentifier | IWorkspaceIdentifier): boolean {
|
||||
switch (this.getWorkbenchState()) {
|
||||
case WorkbenchState.FOLDER:
|
||||
return isSingleFolderWorkspaceIdentifier(workspaceIdentifier) && this.pathEquals(this.workspace.folders[0].uri.fsPath, workspaceIdentifier);
|
||||
case WorkbenchState.WORKSPACE:
|
||||
return isWorkspaceIdentifier(workspaceIdentifier) && this.workspace.id === workspaceIdentifier.id;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private doAddFolders(foldersToAdd: IWorkspaceFolderCreationData[]): TPromise<void> {
|
||||
if (this.getWorkbenchState() !== WorkbenchState.WORKSPACE) {
|
||||
return TPromise.as(void 0); // we need a workspace to begin with
|
||||
}
|
||||
|
||||
const currentWorkspaceFolders = this.getWorkspace().folders;
|
||||
const currentWorkspaceFolderUris = currentWorkspaceFolders.map(folder => folder.uri);
|
||||
const currentStoredFolders = currentWorkspaceFolders.map(folder => folder.raw);
|
||||
|
||||
const storedFoldersToAdd: IStoredWorkspaceFolder[] = [];
|
||||
|
||||
const workspaceConfigFolder = dirname(this.getWorkspace().configuration.fsPath);
|
||||
|
||||
foldersToAdd.forEach(folderToAdd => {
|
||||
if (this.contains(currentWorkspaceFolderUris, folderToAdd.uri)) {
|
||||
return; // already existing
|
||||
}
|
||||
|
||||
let storedFolder: IStoredWorkspaceFolder;
|
||||
|
||||
// File resource: use "path" property
|
||||
if (folderToAdd.uri.scheme === Schemas.file) {
|
||||
storedFolder = {
|
||||
path: massageFolderPathForWorkspace(folderToAdd.uri.fsPath, workspaceConfigFolder, currentStoredFolders)
|
||||
};
|
||||
}
|
||||
|
||||
// Any other resource: use "uri" property
|
||||
else {
|
||||
storedFolder = {
|
||||
uri: folderToAdd.uri.toString(true)
|
||||
};
|
||||
}
|
||||
|
||||
if (folderToAdd.name) {
|
||||
storedFolder.name = folderToAdd.name;
|
||||
}
|
||||
|
||||
storedFoldersToAdd.push(storedFolder);
|
||||
});
|
||||
|
||||
if (storedFoldersToAdd.length > 0) {
|
||||
return this.setFolders([...currentStoredFolders, ...storedFoldersToAdd]);
|
||||
}
|
||||
|
||||
return TPromise.as(void 0);
|
||||
}
|
||||
|
||||
private doRemoveFolders(foldersToRemove: URI[]): TPromise<void> {
|
||||
if (this.getWorkbenchState() !== WorkbenchState.WORKSPACE) {
|
||||
return TPromise.as(void 0); // we need a workspace to begin with
|
||||
}
|
||||
|
||||
const currentWorkspaceFolders = this.getWorkspace().folders;
|
||||
const currentStoredFolders = currentWorkspaceFolders.map(folder => folder.raw);
|
||||
|
||||
const newStoredFolders: IStoredWorkspaceFolder[] = currentStoredFolders.filter((folder, index) => {
|
||||
if (!isStoredWorkspaceFolder(folder)) {
|
||||
return true; // keep entries which are unrelated
|
||||
}
|
||||
|
||||
return !this.contains(foldersToRemove, currentWorkspaceFolders[index].uri); // keep entries which are unrelated
|
||||
});
|
||||
|
||||
if (newStoredFolders.length !== currentStoredFolders.length) {
|
||||
return this.setFolders(newStoredFolders);
|
||||
}
|
||||
|
||||
return TPromise.as(void 0);
|
||||
}
|
||||
|
||||
private setFolders(folders: IStoredWorkspaceFolder[]): TPromise<void> {
|
||||
return this.workspaceConfiguration.setFolders(folders, this.jsonEditingService)
|
||||
.then(() => this.onWorkspaceConfigurationChanged());
|
||||
}
|
||||
|
||||
private contains(resources: URI[], toCheck: URI): boolean {
|
||||
return resources.some(resource => {
|
||||
if (isLinux) {
|
||||
return resource.toString() === toCheck.toString();
|
||||
}
|
||||
|
||||
return resource.toString().toLowerCase() === toCheck.toString().toLowerCase();
|
||||
});
|
||||
}
|
||||
|
||||
// Workspace Configuration Service Impl
|
||||
|
||||
getConfigurationData(): IConfigurationData {
|
||||
return this._configuration.toData();
|
||||
}
|
||||
|
||||
getConfiguration<T>(): T
|
||||
getConfiguration<T>(section: string): T
|
||||
getConfiguration<T>(overrides: IConfigurationOverrides): T
|
||||
getConfiguration<T>(section: string, overrides: IConfigurationOverrides): T
|
||||
getConfiguration(arg1?: any, arg2?: any): any {
|
||||
const section = typeof arg1 === 'string' ? arg1 : void 0;
|
||||
const overrides = isConfigurationOverrides(arg1) ? arg1 : isConfigurationOverrides(arg2) ? arg2 : void 0;
|
||||
return this._configuration.getSection(section, overrides);
|
||||
}
|
||||
|
||||
getValue<T>(key: string, overrides?: IConfigurationOverrides): T {
|
||||
return this._configuration.getValue(key, overrides);
|
||||
}
|
||||
|
||||
updateValue(key: string, value: any): TPromise<void>
|
||||
updateValue(key: string, value: any, overrides: IConfigurationOverrides): TPromise<void>
|
||||
updateValue(key: string, value: any, target: ConfigurationTarget): TPromise<void>
|
||||
updateValue(key: string, value: any, overrides: IConfigurationOverrides, target: ConfigurationTarget): TPromise<void>
|
||||
updateValue(key: string, value: any, overrides: IConfigurationOverrides, target: ConfigurationTarget, donotNotifyError: boolean): TPromise<void>
|
||||
updateValue(key: string, value: any, arg3?: any, arg4?: any, donotNotifyError?: any): TPromise<void> {
|
||||
assert.ok(this.configurationEditingService, 'Workbench is not initialized yet');
|
||||
const overrides = isConfigurationOverrides(arg3) ? arg3 : void 0;
|
||||
const target = this.deriveConfigurationTarget(key, value, overrides, overrides ? arg4 : arg3);
|
||||
return target ? this.writeConfigurationValue(key, value, target, overrides, donotNotifyError)
|
||||
: TPromise.as(null);
|
||||
}
|
||||
|
||||
reloadConfiguration(folder?: IWorkspaceFolder, key?: string): TPromise<void> {
|
||||
if (folder) {
|
||||
return this.reloadWorkspaceFolderConfiguration(folder, key);
|
||||
}
|
||||
return this.reloadUserConfiguration()
|
||||
.then(() => this.reloadWorkspaceConfiguration())
|
||||
.then(() => this.loadConfiguration());
|
||||
}
|
||||
|
||||
inspect<T>(key: string, overrides?: IConfigurationOverrides): {
|
||||
default: T,
|
||||
user: T,
|
||||
workspace: T,
|
||||
workspaceFolder: T,
|
||||
memory?: T,
|
||||
value: T
|
||||
} {
|
||||
return this._configuration.lookup<T>(key);
|
||||
}
|
||||
|
||||
keys(): {
|
||||
default: string[];
|
||||
user: string[];
|
||||
workspace: string[];
|
||||
workspaceFolder: string[];
|
||||
} {
|
||||
return this._configuration.keys();
|
||||
}
|
||||
|
||||
getUnsupportedWorkspaceKeys(): string[] {
|
||||
const unsupportedWorkspaceKeys = [...this.workspaceConfiguration.getWorkspaceSettings().unsupportedKeys];
|
||||
for (const folder of this.workspace.folders) {
|
||||
unsupportedWorkspaceKeys.push(...this._configuration.getFolderConfigurationModel(folder.uri).workspaceSettingsConfig.unsupportedKeys);
|
||||
}
|
||||
return distinct(unsupportedWorkspaceKeys);
|
||||
}
|
||||
|
||||
initialize(arg: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | IWindowConfiguration): TPromise<any> {
|
||||
return this.createWorkspace(arg)
|
||||
.then(workspace => this.updateWorkspaceAndInitializeConfiguration(workspace));
|
||||
}
|
||||
|
||||
setInstantiationService(instantiationService: IInstantiationService): void {
|
||||
this.configurationEditingService = instantiationService.createInstance(ConfigurationEditingService);
|
||||
this.jsonEditingService = instantiationService.createInstance(JSONEditingService);
|
||||
}
|
||||
|
||||
handleWorkspaceFileEvents(event: FileChangesEvent): TPromise<void> {
|
||||
switch (this.getWorkbenchState()) {
|
||||
case WorkbenchState.FOLDER:
|
||||
return this.onSingleFolderFileChanges(event);
|
||||
case WorkbenchState.WORKSPACE:
|
||||
return this.onWorkspaceFileChanges(event);
|
||||
}
|
||||
return TPromise.as(void 0);
|
||||
}
|
||||
|
||||
private createWorkspace(arg: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | IWindowConfiguration): TPromise<Workspace> {
|
||||
if (isWorkspaceIdentifier(arg)) {
|
||||
return this.createMulitFolderWorkspace(arg);
|
||||
}
|
||||
|
||||
if (isSingleFolderWorkspaceIdentifier(arg)) {
|
||||
return this.createSingleFolderWorkspace(arg);
|
||||
}
|
||||
|
||||
return this.createEmptyWorkspace(arg);
|
||||
}
|
||||
|
||||
private createMulitFolderWorkspace(workspaceIdentifier: IWorkspaceIdentifier): TPromise<Workspace> {
|
||||
const workspaceConfigPath = URI.file(workspaceIdentifier.configPath);
|
||||
return this.workspaceConfiguration.load(workspaceConfigPath)
|
||||
.then(() => {
|
||||
const workspaceFolders = toWorkspaceFolders(this.workspaceConfiguration.getFolders(), URI.file(paths.dirname(workspaceConfigPath.fsPath)));
|
||||
const workspaceId = workspaceIdentifier.id;
|
||||
const workspaceName = getWorkspaceLabel({ id: workspaceId, configPath: workspaceConfigPath.fsPath }, this.environmentService);
|
||||
return new Workspace(workspaceId, workspaceName, workspaceFolders, workspaceConfigPath);
|
||||
});
|
||||
}
|
||||
|
||||
private createSingleFolderWorkspace(singleFolderWorkspaceIdentifier: ISingleFolderWorkspaceIdentifier): TPromise<Workspace> {
|
||||
const folderPath = URI.file(singleFolderWorkspaceIdentifier);
|
||||
return stat(folderPath.fsPath)
|
||||
.then(workspaceStat => {
|
||||
const ctime = isLinux ? workspaceStat.ino : workspaceStat.birthtime.getTime(); // On Linux, birthtime is ctime, so we cannot use it! We use the ino instead!
|
||||
const id = createHash('md5').update(folderPath.fsPath).update(ctime ? String(ctime) : '').digest('hex');
|
||||
const folder = URI.file(folderPath.fsPath);
|
||||
return new Workspace(id, paths.basename(folderPath.fsPath), toWorkspaceFolders([{ path: folder.fsPath }]), null, ctime);
|
||||
});
|
||||
}
|
||||
|
||||
private createEmptyWorkspace(configuration: IWindowConfiguration): TPromise<Workspace> {
|
||||
let id = configuration.backupPath ? URI.from({ path: paths.basename(configuration.backupPath), scheme: 'empty' }).toString() : '';
|
||||
return TPromise.as(new Workspace(id));
|
||||
}
|
||||
|
||||
private updateWorkspaceAndInitializeConfiguration(workspace: Workspace): TPromise<void> {
|
||||
let folderChanges: IWorkspaceFoldersChangeEvent;
|
||||
if (this.workspace) {
|
||||
const currentState = this.getWorkbenchState();
|
||||
const currentWorkspacePath = this.workspace.configuration ? this.workspace.configuration.fsPath : void 0;
|
||||
const currentFolders = this.workspace.folders;
|
||||
|
||||
this.workspace.update(workspace);
|
||||
|
||||
const newState = this.getWorkbenchState();
|
||||
if (newState !== currentState) {
|
||||
this._onDidChangeWorkbenchState.fire(newState);
|
||||
}
|
||||
|
||||
const newWorkspacePath = this.workspace.configuration ? this.workspace.configuration.fsPath : void 0;
|
||||
if (newWorkspacePath !== currentWorkspacePath || newState !== currentState) {
|
||||
this._onDidChangeWorkspaceName.fire();
|
||||
}
|
||||
|
||||
folderChanges = this.compareFolders(currentFolders, this.workspace.folders);
|
||||
|
||||
} else {
|
||||
this.workspace = workspace;
|
||||
}
|
||||
|
||||
return this.initializeConfiguration().then(() => {
|
||||
// Trigger folders change after configuration initialization so that configuration is up to date.
|
||||
if (folderChanges && (folderChanges.added.length || folderChanges.removed.length || folderChanges.changed.length)) {
|
||||
this._onDidChangeWorkspaceFolders.fire(folderChanges);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private compareFolders(currentFolders: IWorkspaceFolder[], newFolders: IWorkspaceFolder[]): IWorkspaceFoldersChangeEvent {
|
||||
const result = { added: [], removed: [], changed: [] };
|
||||
result.added = newFolders.filter(newFolder => !currentFolders.some(currentFolder => newFolder.uri.toString() === currentFolder.uri.toString()));
|
||||
for (let currentIndex = 0; currentIndex < currentFolders.length; currentIndex++) {
|
||||
let currentFolder = currentFolders[currentIndex];
|
||||
let newIndex = 0;
|
||||
for (newIndex = 0; newIndex < newFolders.length && currentFolder.uri.toString() !== newFolders[newIndex].uri.toString(); newIndex++) { }
|
||||
if (newIndex < newFolders.length) {
|
||||
if (currentIndex !== newIndex || currentFolder.name !== newFolders[newIndex].name) {
|
||||
result.changed.push(currentFolder);
|
||||
}
|
||||
} else {
|
||||
result.removed.push(currentFolder);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private initializeConfiguration(): TPromise<void> {
|
||||
this.registerConfigurationSchemas();
|
||||
return this.loadConfiguration();
|
||||
}
|
||||
|
||||
private reloadUserConfiguration(key?: string): TPromise<void> {
|
||||
return this.baseConfigurationService.reloadConfiguration();
|
||||
}
|
||||
|
||||
private reloadWorkspaceConfiguration(key?: string): TPromise<void> {
|
||||
const workbenchState = this.getWorkbenchState();
|
||||
if (workbenchState === WorkbenchState.FOLDER) {
|
||||
return this.onWorkspaceFolderConfigurationChanged(this.workspace.folders[0], key);
|
||||
}
|
||||
if (workbenchState === WorkbenchState.WORKSPACE) {
|
||||
return this.workspaceConfiguration.reload().then(() => this.onWorkspaceConfigurationChanged());
|
||||
}
|
||||
return TPromise.as(null);
|
||||
}
|
||||
|
||||
private reloadWorkspaceFolderConfiguration(folder: IWorkspaceFolder, key?: string): TPromise<void> {
|
||||
return this.onWorkspaceFolderConfigurationChanged(folder, key);
|
||||
}
|
||||
|
||||
private loadConfiguration(): TPromise<void> {
|
||||
// reset caches
|
||||
this.cachedFolderConfigs = new StrictResourceMap<FolderConfiguration>();
|
||||
|
||||
const folders = this.workspace.folders;
|
||||
return this.loadFolderConfigurations(folders)
|
||||
.then((folderConfigurations) => {
|
||||
|
||||
let workspaceConfiguration = this.getWorkspaceConfigurationModel(folderConfigurations);
|
||||
const folderConfigurationModels = new StrictResourceMap<FolderConfigurationModel>();
|
||||
folderConfigurations.forEach((folderConfiguration, index) => folderConfigurationModels.set(folders[index].uri, folderConfiguration));
|
||||
|
||||
const currentConfiguration = this._configuration;
|
||||
this._configuration = new Configuration(this.baseConfigurationService.configuration.defaults, this.baseConfigurationService.configuration.user, workspaceConfiguration, folderConfigurationModels, new ConfigurationModel(), new StrictResourceMap<ConfigurationModel>(), this.getWorkbenchState() !== WorkbenchState.EMPTY ? this.workspace : null); //TODO: Sandy Avoid passing null
|
||||
|
||||
if (currentConfiguration) {
|
||||
const changedKeys = this._configuration.compare(currentConfiguration);
|
||||
this.triggerConfigurationChange(new ConfigurationChangeEvent().change(changedKeys), ConfigurationTarget.WORKSPACE);
|
||||
} else {
|
||||
this._onDidChangeConfiguration.fire(new AllKeysConfigurationChangeEvent(this._configuration.allKeys(), ConfigurationTarget.WORKSPACE, this.getTargetConfiguration(ConfigurationTarget.WORKSPACE)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private getWorkspaceConfigurationModel(folderConfigurations: FolderConfigurationModel[]): ConfigurationModel {
|
||||
switch (this.getWorkbenchState()) {
|
||||
case WorkbenchState.FOLDER:
|
||||
return folderConfigurations[0];
|
||||
case WorkbenchState.WORKSPACE:
|
||||
return this.workspaceConfiguration.getConfiguration();
|
||||
default:
|
||||
return new ConfigurationModel();
|
||||
}
|
||||
}
|
||||
|
||||
private registerConfigurationSchemas(): void {
|
||||
if (this.workspace) {
|
||||
const jsonRegistry = Registry.as<IJSONContributionRegistry>(JSONExtensions.JSONContribution);
|
||||
jsonRegistry.registerSchema(defaultSettingsSchemaId, settingsSchema);
|
||||
jsonRegistry.registerSchema(userSettingsSchemaId, settingsSchema);
|
||||
|
||||
if (WorkbenchState.WORKSPACE === this.getWorkbenchState()) {
|
||||
jsonRegistry.registerSchema(workspaceSettingsSchemaId, settingsSchema);
|
||||
jsonRegistry.registerSchema(folderSettingsSchemaId, resourceSettingsSchema);
|
||||
} else {
|
||||
jsonRegistry.registerSchema(workspaceSettingsSchemaId, settingsSchema);
|
||||
jsonRegistry.registerSchema(folderSettingsSchemaId, settingsSchema);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private onBaseConfigurationChanged(e: IConfigurationChangeEvent): void {
|
||||
if (this.workspace && this._configuration) {
|
||||
if (e.source === ConfigurationTarget.DEFAULT) {
|
||||
this.workspaceConfiguration.getWorkspaceSettings().update();
|
||||
this.workspace.folders.forEach(folder => this._configuration.getFolderConfigurationModel(folder.uri).update());
|
||||
this._configuration.updateDefaultConfiguration(this.baseConfigurationService.configuration.defaults);
|
||||
this.triggerConfigurationChange(new ConfigurationChangeEvent().change(e.affectedKeys), e.source);
|
||||
} else {
|
||||
let keys = this._configuration.updateUserConfiguration(this.baseConfigurationService.configuration.user);
|
||||
this.triggerConfigurationChange(keys, e.source);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private onWorkspaceConfigurationChanged(): TPromise<void> {
|
||||
if (this.workspace && this.workspace.configuration && this._configuration) {
|
||||
const workspaceConfigurationChangeEvent = this._configuration.updateWorkspaceConfiguration(this.workspaceConfiguration.getConfiguration());
|
||||
let configuredFolders = toWorkspaceFolders(this.workspaceConfiguration.getFolders(), URI.file(paths.dirname(this.workspace.configuration.fsPath)));
|
||||
const changes = this.compareFolders(this.workspace.folders, configuredFolders);
|
||||
if (changes.added.length || changes.removed.length || changes.changed.length) {
|
||||
this.workspace.folders = configuredFolders;
|
||||
return this.onFoldersChanged()
|
||||
.then(foldersConfigurationChangeEvent => {
|
||||
this.triggerConfigurationChange(foldersConfigurationChangeEvent.change(workspaceConfigurationChangeEvent), ConfigurationTarget.WORKSPACE_FOLDER);
|
||||
this._onDidChangeWorkspaceFolders.fire(changes);
|
||||
});
|
||||
} else {
|
||||
this.triggerConfigurationChange(workspaceConfigurationChangeEvent, ConfigurationTarget.WORKSPACE);
|
||||
}
|
||||
}
|
||||
return TPromise.as(null);
|
||||
}
|
||||
|
||||
private onWorkspaceFileChanges(event: FileChangesEvent): TPromise<void> {
|
||||
return TPromise.join(this.workspace.folders.map(folder =>
|
||||
// handle file event for each folder
|
||||
this.cachedFolderConfigs.get(folder.uri).handleWorkspaceFileEvents(event)
|
||||
// Update folder configuration if handled
|
||||
.then(folderConfiguration => folderConfiguration ? this._configuration.updateFolderConfiguration(folder.uri, folderConfiguration) : new ConfigurationChangeEvent()))
|
||||
).then(changeEvents => {
|
||||
const consolidateChangeEvent = changeEvents.reduce((consolidated, e) => consolidated.change(e), new ConfigurationChangeEvent());
|
||||
this.triggerConfigurationChange(consolidateChangeEvent, ConfigurationTarget.WORKSPACE_FOLDER);
|
||||
});
|
||||
}
|
||||
|
||||
private onSingleFolderFileChanges(event: FileChangesEvent): TPromise<void> {
|
||||
const folder = this.workspace.folders[0];
|
||||
return this.cachedFolderConfigs.get(folder.uri).handleWorkspaceFileEvents(event)
|
||||
.then(folderConfiguration => {
|
||||
if (folderConfiguration) {
|
||||
// File change handled
|
||||
this._configuration.updateFolderConfiguration(folder.uri, folderConfiguration);
|
||||
const workspaceChangedKeys = this._configuration.updateWorkspaceConfiguration(folderConfiguration);
|
||||
this.triggerConfigurationChange(workspaceChangedKeys, ConfigurationTarget.WORKSPACE);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private onWorkspaceFolderConfigurationChanged(folder: IWorkspaceFolder, key?: string): TPromise<void> {
|
||||
this.disposeFolderConfiguration(folder);
|
||||
return this.loadFolderConfigurations([folder])
|
||||
.then(([folderConfiguration]) => {
|
||||
const folderChangedKeys = this._configuration.updateFolderConfiguration(folder.uri, folderConfiguration);
|
||||
if (this.getWorkbenchState() === WorkbenchState.FOLDER) {
|
||||
const workspaceChangedKeys = this._configuration.updateWorkspaceConfiguration(folderConfiguration);
|
||||
this.triggerConfigurationChange(workspaceChangedKeys, ConfigurationTarget.WORKSPACE);
|
||||
} else {
|
||||
this.triggerConfigurationChange(folderChangedKeys, ConfigurationTarget.WORKSPACE_FOLDER);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private onFoldersChanged(): TPromise<ConfigurationChangeEvent> {
|
||||
let changeEvent = new ConfigurationChangeEvent();
|
||||
|
||||
// Remove the configurations of deleted folders
|
||||
for (const key of this.cachedFolderConfigs.keys()) {
|
||||
if (!this.workspace.folders.filter(folder => folder.uri.toString() === key.toString())[0]) {
|
||||
this.cachedFolderConfigs.delete(key);
|
||||
changeEvent = changeEvent.change(this._configuration.deleteFolderConfiguration(key));
|
||||
}
|
||||
}
|
||||
|
||||
const toInitialize = this.workspace.folders.filter(folder => !this.cachedFolderConfigs.has(folder.uri));
|
||||
if (toInitialize.length) {
|
||||
return this.loadFolderConfigurations(toInitialize)
|
||||
.then(folderConfigurations => {
|
||||
folderConfigurations.forEach((folderConfiguration, index) => {
|
||||
changeEvent = changeEvent.change(this._configuration.updateFolderConfiguration(toInitialize[index].uri, folderConfiguration));
|
||||
});
|
||||
return changeEvent;
|
||||
});
|
||||
}
|
||||
return TPromise.as(changeEvent);
|
||||
}
|
||||
|
||||
private loadFolderConfigurations(folders: IWorkspaceFolder[]): TPromise<FolderConfigurationModel[]> {
|
||||
return TPromise.join([...folders.map(folder => {
|
||||
const folderConfiguration = new FolderConfiguration(folder.uri, this.workspaceSettingsRootFolder, this.getWorkbenchState() === WorkbenchState.WORKSPACE ? ConfigurationScope.RESOURCE : ConfigurationScope.WINDOW);
|
||||
this.cachedFolderConfigs.set(folder.uri, this._register(folderConfiguration));
|
||||
return folderConfiguration.loadConfiguration();
|
||||
})]);
|
||||
}
|
||||
|
||||
private writeConfigurationValue(key: string, value: any, target: ConfigurationTarget, overrides: IConfigurationOverrides, donotNotifyError: boolean): TPromise<void> {
|
||||
if (target === ConfigurationTarget.DEFAULT) {
|
||||
return TPromise.wrapError(new Error('Invalid configuration target'));
|
||||
}
|
||||
|
||||
if (target === ConfigurationTarget.MEMORY) {
|
||||
this._configuration.updateValue(key, value, overrides);
|
||||
this.triggerConfigurationChange(new ConfigurationChangeEvent().change(overrides.overrideIdentifier ? [keyFromOverrideIdentifier(overrides.overrideIdentifier)] : [key], overrides.resource), target);
|
||||
return TPromise.as(null);
|
||||
}
|
||||
|
||||
return this.configurationEditingService.writeConfiguration(target, { key, value }, { scopes: overrides, donotNotifyError })
|
||||
.then(() => {
|
||||
switch (target) {
|
||||
case ConfigurationTarget.USER:
|
||||
return this.reloadUserConfiguration();
|
||||
case ConfigurationTarget.WORKSPACE:
|
||||
return this.reloadWorkspaceConfiguration();
|
||||
case ConfigurationTarget.WORKSPACE_FOLDER:
|
||||
const workspaceFolder = overrides && overrides.resource ? this.workspace.getFolder(overrides.resource) : null;
|
||||
if (workspaceFolder) {
|
||||
return this.reloadWorkspaceFolderConfiguration(this.workspace.getFolder(overrides.resource), key);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private deriveConfigurationTarget(key: string, value: any, overrides: IConfigurationOverrides, target: ConfigurationTarget): ConfigurationTarget {
|
||||
if (target) {
|
||||
return target;
|
||||
}
|
||||
|
||||
if (value === void 0) {
|
||||
// Ignore. But expected is to remove the value from all targets
|
||||
return void 0;
|
||||
}
|
||||
|
||||
const inspect = this.inspect(key, overrides);
|
||||
if (equals(value, inspect.value)) {
|
||||
// No change. So ignore.
|
||||
return void 0;
|
||||
}
|
||||
|
||||
if (inspect.workspaceFolder !== void 0) {
|
||||
return ConfigurationTarget.WORKSPACE_FOLDER;
|
||||
}
|
||||
|
||||
if (inspect.workspace !== void 0) {
|
||||
return ConfigurationTarget.WORKSPACE;
|
||||
}
|
||||
|
||||
return ConfigurationTarget.USER;
|
||||
}
|
||||
|
||||
private triggerConfigurationChange(configurationEvent: ConfigurationChangeEvent, target: ConfigurationTarget): void {
|
||||
if (configurationEvent.affectedKeys.length) {
|
||||
configurationEvent.telemetryData(target, this.getTargetConfiguration(target));
|
||||
this._onDidChangeConfiguration.fire(new WorkspaceConfigurationChangeEvent(configurationEvent, this.workspace));
|
||||
}
|
||||
}
|
||||
|
||||
private getTargetConfiguration(target: ConfigurationTarget): any {
|
||||
switch (target) {
|
||||
case ConfigurationTarget.DEFAULT:
|
||||
return this._configuration.defaults.contents;
|
||||
case ConfigurationTarget.USER:
|
||||
return this._configuration.user.contents;
|
||||
case ConfigurationTarget.WORKSPACE:
|
||||
return this._configuration.workspace.contents;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
private pathEquals(path1: string, path2: string): boolean {
|
||||
if (!isLinux) {
|
||||
path1 = path1.toLowerCase();
|
||||
path2 = path2.toLowerCase();
|
||||
}
|
||||
|
||||
return path1 === path2;
|
||||
}
|
||||
|
||||
private disposeFolderConfiguration(folder: IWorkspaceFolder): void {
|
||||
const folderConfiguration = this.cachedFolderConfigs.get(folder.uri);
|
||||
if (folderConfiguration) {
|
||||
folderConfiguration.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface IExportedConfigurationNode {
|
||||
name: string;
|
||||
description: string;
|
||||
default: any;
|
||||
type: string | string[];
|
||||
enum?: any[];
|
||||
enumDescriptions?: string[];
|
||||
}
|
||||
|
||||
interface IConfigurationExport {
|
||||
settings: IExportedConfigurationNode[];
|
||||
buildTime: number;
|
||||
commit: string;
|
||||
buildNumber: number;
|
||||
}
|
||||
|
||||
export class DefaultConfigurationExportHelper {
|
||||
|
||||
constructor(
|
||||
@IEnvironmentService environmentService: IEnvironmentService,
|
||||
@IExtensionService private extensionService: IExtensionService,
|
||||
@ICommandService private commandService: ICommandService) {
|
||||
if (environmentService.args['export-default-configuration']) {
|
||||
this.writeConfigModelAndQuit(environmentService.args['export-default-configuration']);
|
||||
}
|
||||
}
|
||||
|
||||
private writeConfigModelAndQuit(targetPath: string): TPromise<void> {
|
||||
return this.extensionService.onReady()
|
||||
.then(() => this.writeConfigModel(targetPath))
|
||||
.then(() => this.commandService.executeCommand('workbench.action.quit'))
|
||||
.then(() => { });
|
||||
}
|
||||
|
||||
private writeConfigModel(targetPath: string): TPromise<void> {
|
||||
const config = this.getConfigModel();
|
||||
|
||||
const resultString = JSON.stringify(config, undefined, ' ');
|
||||
return writeFile(targetPath, resultString);
|
||||
}
|
||||
|
||||
private getConfigModel(): IConfigurationExport {
|
||||
const configurations = Registry.as<IConfigurationRegistry>(Extensions.Configuration).getConfigurations().slice();
|
||||
const settings: IExportedConfigurationNode[] = [];
|
||||
const processConfig = (config: IConfigurationNode) => {
|
||||
if (config.properties) {
|
||||
for (let name in config.properties) {
|
||||
const prop = config.properties[name];
|
||||
const propDetails: IExportedConfigurationNode = {
|
||||
name,
|
||||
description: prop.description,
|
||||
default: prop.default,
|
||||
type: prop.type
|
||||
};
|
||||
|
||||
if (prop.enum) {
|
||||
propDetails.enum = prop.enum;
|
||||
}
|
||||
|
||||
if (prop.enumDescriptions) {
|
||||
propDetails.enumDescriptions = prop.enumDescriptions;
|
||||
}
|
||||
|
||||
settings.push(propDetails);
|
||||
}
|
||||
}
|
||||
|
||||
if (config.allOf) {
|
||||
config.allOf.forEach(processConfig);
|
||||
}
|
||||
};
|
||||
|
||||
configurations.forEach(processConfig);
|
||||
|
||||
const result: IConfigurationExport = {
|
||||
settings: settings.sort((a, b) => a.name.localeCompare(b.name)),
|
||||
buildTime: Date.now(),
|
||||
commit: product.commit,
|
||||
buildNumber: product.settingsSearchBuildId
|
||||
};
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,8 @@ export class JSONEditingService implements IJSONEditingService {
|
||||
|
||||
private doWriteConfiguration(resource: URI, value: IJSONValue, save: boolean): TPromise<void> {
|
||||
return this.resolveAndValidate(resource, save)
|
||||
.then(reference => this.writeToBuffer(reference.object.textEditorModel, value));
|
||||
.then(reference => this.writeToBuffer(reference.object.textEditorModel, value)
|
||||
.then(() => reference.dispose()));
|
||||
}
|
||||
|
||||
private writeToBuffer(model: editorCommon.IModel, value: IJSONValue): TPromise<any> {
|
||||
|
||||
@@ -5,8 +5,13 @@
|
||||
'use strict';
|
||||
|
||||
import * as assert from 'assert';
|
||||
import { FolderConfigurationModel, ScopedConfigurationModel, FolderSettingsModel } from 'vs/workbench/services/configuration/common/configurationModels';
|
||||
import { join } from 'vs/base/common/paths';
|
||||
import { FolderConfigurationModel, ScopedConfigurationModel, FolderSettingsModel, WorkspaceConfigurationChangeEvent } from 'vs/workbench/services/configuration/common/configurationModels';
|
||||
import { ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry';
|
||||
import { Workspace, WorkspaceFolder } from 'vs/platform/workspace/common/workspace';
|
||||
import URI from 'vs/base/common/uri';
|
||||
import { ConfigurationChangeEvent } from 'vs/platform/configuration/common/configurationModels';
|
||||
import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
|
||||
|
||||
suite('ConfigurationService - Model', () => {
|
||||
|
||||
@@ -17,7 +22,7 @@ suite('ConfigurationService - Model', () => {
|
||||
|
||||
const testObject = new FolderConfigurationModel(settingsConfig, [], ConfigurationScope.WINDOW);
|
||||
|
||||
assert.equal(testObject.getContentsFor('task'), undefined);
|
||||
assert.equal(testObject.getSectionContents('task'), undefined);
|
||||
});
|
||||
|
||||
test('Test consolidate (settings and tasks)', () => {
|
||||
@@ -94,4 +99,99 @@ suite('ConfigurationService - Model', () => {
|
||||
assert.deepEqual(new FolderConfigurationModel(settingsConfig, [launchConfig, tasksConfig], ConfigurationScope.WINDOW).contents, expected);
|
||||
assert.deepEqual(new FolderConfigurationModel(settingsConfig, [tasksConfig, launchConfig], ConfigurationScope.WINDOW).contents, expected);
|
||||
});
|
||||
});
|
||||
|
||||
suite('WorkspaceConfigurationChangeEvent', () => {
|
||||
|
||||
test('changeEvent affecting workspace folders', () => {
|
||||
let configurationChangeEvent = new ConfigurationChangeEvent();
|
||||
configurationChangeEvent.change(['window.title']);
|
||||
configurationChangeEvent.change(['window.zoomLevel'], URI.file('folder1'));
|
||||
configurationChangeEvent.change(['workbench.editor.enablePreview'], URI.file('folder2'));
|
||||
configurationChangeEvent.change(['window.restoreFullscreen'], URI.file('folder1'));
|
||||
configurationChangeEvent.change(['window.restoreWindows'], URI.file('folder2'));
|
||||
configurationChangeEvent.telemetryData(ConfigurationTarget.WORKSPACE, {});
|
||||
|
||||
let testObject = new WorkspaceConfigurationChangeEvent(configurationChangeEvent, new Workspace('id', 'name',
|
||||
[new WorkspaceFolder({ index: 0, name: '1', uri: URI.file('folder1') }),
|
||||
new WorkspaceFolder({ index: 1, name: '2', uri: URI.file('folder2') }),
|
||||
new WorkspaceFolder({ index: 2, name: '3', uri: URI.file('folder3') })]));
|
||||
|
||||
assert.deepEqual(testObject.affectedKeys, ['window.title', 'window.zoomLevel', 'window.restoreFullscreen', 'workbench.editor.enablePreview', 'window.restoreWindows']);
|
||||
assert.equal(testObject.source, ConfigurationTarget.WORKSPACE);
|
||||
|
||||
assert.ok(testObject.affectsConfiguration('window.zoomLevel'));
|
||||
assert.ok(testObject.affectsConfiguration('window.zoomLevel', URI.file('folder1')));
|
||||
assert.ok(testObject.affectsConfiguration('window.zoomLevel', URI.file(join('folder1', 'file1'))));
|
||||
assert.ok(!testObject.affectsConfiguration('window.zoomLevel', URI.file('file1')));
|
||||
assert.ok(!testObject.affectsConfiguration('window.zoomLevel', URI.file('file2')));
|
||||
assert.ok(!testObject.affectsConfiguration('window.zoomLevel', URI.file(join('folder2', 'file2'))));
|
||||
assert.ok(!testObject.affectsConfiguration('window.zoomLevel', URI.file(join('folder3', 'file3'))));
|
||||
|
||||
assert.ok(testObject.affectsConfiguration('window.restoreFullscreen'));
|
||||
assert.ok(testObject.affectsConfiguration('window.restoreFullscreen', URI.file(join('folder1', 'file1'))));
|
||||
assert.ok(testObject.affectsConfiguration('window.restoreFullscreen', URI.file('folder1')));
|
||||
assert.ok(!testObject.affectsConfiguration('window.restoreFullscreen', URI.file('file1')));
|
||||
assert.ok(!testObject.affectsConfiguration('window.restoreFullscreen', URI.file('file2')));
|
||||
assert.ok(!testObject.affectsConfiguration('window.restoreFullscreen', URI.file(join('folder2', 'file2'))));
|
||||
assert.ok(!testObject.affectsConfiguration('window.restoreFullscreen', URI.file(join('folder3', 'file3'))));
|
||||
|
||||
assert.ok(testObject.affectsConfiguration('window.restoreWindows'));
|
||||
assert.ok(testObject.affectsConfiguration('window.restoreWindows', URI.file('folder2')));
|
||||
assert.ok(testObject.affectsConfiguration('window.restoreWindows', URI.file(join('folder2', 'file2'))));
|
||||
assert.ok(!testObject.affectsConfiguration('window.restoreWindows', URI.file('file2')));
|
||||
assert.ok(!testObject.affectsConfiguration('window.restoreWindows', URI.file(join('folder1', 'file1'))));
|
||||
assert.ok(!testObject.affectsConfiguration('window.restoreWindows', URI.file(join('folder3', 'file3'))));
|
||||
|
||||
assert.ok(testObject.affectsConfiguration('window.title'));
|
||||
assert.ok(testObject.affectsConfiguration('window.title', URI.file('folder1')));
|
||||
assert.ok(testObject.affectsConfiguration('window.title', URI.file(join('folder1', 'file1'))));
|
||||
assert.ok(testObject.affectsConfiguration('window.title', URI.file('folder2')));
|
||||
assert.ok(testObject.affectsConfiguration('window.title', URI.file(join('folder2', 'file2'))));
|
||||
assert.ok(testObject.affectsConfiguration('window.title', URI.file('folder3')));
|
||||
assert.ok(testObject.affectsConfiguration('window.title', URI.file(join('folder3', 'file3'))));
|
||||
assert.ok(testObject.affectsConfiguration('window.title', URI.file('file1')));
|
||||
assert.ok(testObject.affectsConfiguration('window.title', URI.file('file2')));
|
||||
assert.ok(testObject.affectsConfiguration('window.title', URI.file('file3')));
|
||||
|
||||
assert.ok(testObject.affectsConfiguration('window'));
|
||||
assert.ok(testObject.affectsConfiguration('window', URI.file('folder1')));
|
||||
assert.ok(testObject.affectsConfiguration('window', URI.file(join('folder1', 'file1'))));
|
||||
assert.ok(testObject.affectsConfiguration('window', URI.file('folder2')));
|
||||
assert.ok(testObject.affectsConfiguration('window', URI.file(join('folder2', 'file2'))));
|
||||
assert.ok(testObject.affectsConfiguration('window', URI.file('folder3')));
|
||||
assert.ok(testObject.affectsConfiguration('window', URI.file(join('folder3', 'file3'))));
|
||||
assert.ok(testObject.affectsConfiguration('window', URI.file('file1')));
|
||||
assert.ok(testObject.affectsConfiguration('window', URI.file('file2')));
|
||||
assert.ok(testObject.affectsConfiguration('window', URI.file('file3')));
|
||||
|
||||
assert.ok(testObject.affectsConfiguration('workbench.editor.enablePreview'));
|
||||
assert.ok(testObject.affectsConfiguration('workbench.editor.enablePreview', URI.file('folder2')));
|
||||
assert.ok(testObject.affectsConfiguration('workbench.editor.enablePreview', URI.file(join('folder2', 'file2'))));
|
||||
assert.ok(!testObject.affectsConfiguration('workbench.editor.enablePreview', URI.file('folder1')));
|
||||
assert.ok(!testObject.affectsConfiguration('workbench.editor.enablePreview', URI.file(join('folder1', 'file1'))));
|
||||
assert.ok(!testObject.affectsConfiguration('workbench.editor.enablePreview', URI.file('folder3')));
|
||||
|
||||
assert.ok(testObject.affectsConfiguration('workbench.editor'));
|
||||
assert.ok(testObject.affectsConfiguration('workbench.editor', URI.file('folder2')));
|
||||
assert.ok(testObject.affectsConfiguration('workbench.editor', URI.file(join('folder2', 'file2'))));
|
||||
assert.ok(!testObject.affectsConfiguration('workbench.editor', URI.file('folder1')));
|
||||
assert.ok(!testObject.affectsConfiguration('workbench.editor', URI.file(join('folder1', 'file1'))));
|
||||
assert.ok(!testObject.affectsConfiguration('workbench.editor', URI.file('folder3')));
|
||||
|
||||
assert.ok(testObject.affectsConfiguration('workbench'));
|
||||
assert.ok(testObject.affectsConfiguration('workbench', URI.file('folder2')));
|
||||
assert.ok(testObject.affectsConfiguration('workbench', URI.file(join('folder2', 'file2'))));
|
||||
assert.ok(!testObject.affectsConfiguration('workbench', URI.file('folder1')));
|
||||
assert.ok(!testObject.affectsConfiguration('workbench', URI.file('folder3')));
|
||||
|
||||
assert.ok(!testObject.affectsConfiguration('files'));
|
||||
assert.ok(!testObject.affectsConfiguration('files', URI.file('folder1')));
|
||||
assert.ok(!testObject.affectsConfiguration('files', URI.file(join('folder1', 'file1'))));
|
||||
assert.ok(!testObject.affectsConfiguration('files', URI.file('folder2')));
|
||||
assert.ok(!testObject.affectsConfiguration('files', URI.file(join('folder2', 'file2'))));
|
||||
assert.ok(!testObject.affectsConfiguration('files', URI.file('folder3')));
|
||||
assert.ok(!testObject.affectsConfiguration('files', URI.file(join('folder3', 'file3'))));
|
||||
});
|
||||
|
||||
});
|
||||
@@ -1,464 +0,0 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
'use strict';
|
||||
|
||||
import assert = require('assert');
|
||||
import os = require('os');
|
||||
import path = require('path');
|
||||
import fs = require('fs');
|
||||
import * as sinon from 'sinon';
|
||||
import URI from 'vs/base/common/uri';
|
||||
import { TPromise } from 'vs/base/common/winjs.base';
|
||||
import { Registry } from 'vs/platform/registry/common/platform';
|
||||
import { ParsedArgs } from 'vs/platform/environment/common/environment';
|
||||
import { EnvironmentService } from 'vs/platform/environment/node/environmentService';
|
||||
import { parseArgs } from 'vs/platform/environment/node/argv';
|
||||
import extfs = require('vs/base/node/extfs');
|
||||
import uuid = require('vs/base/common/uuid');
|
||||
import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from 'vs/platform/configuration/common/configurationRegistry';
|
||||
import { WorkspaceServiceImpl, WorkspaceService } from 'vs/workbench/services/configuration/node/configuration';
|
||||
import { FileChangeType, FileChangesEvent } from 'vs/platform/files/common/files';
|
||||
|
||||
class SettingsTestEnvironmentService extends EnvironmentService {
|
||||
|
||||
constructor(args: ParsedArgs, _execPath: string, private customAppSettingsHome) {
|
||||
super(args, _execPath);
|
||||
}
|
||||
|
||||
get appSettingsPath(): string { return this.customAppSettingsHome; }
|
||||
}
|
||||
|
||||
suite('WorkspaceConfigurationService - Node', () => {
|
||||
|
||||
function createWorkspace(callback: (workspaceDir: string, globalSettingsFile: string, cleanUp: (callback: () => void) => void) => void): void {
|
||||
const id = uuid.generateUuid();
|
||||
const parentDir = path.join(os.tmpdir(), 'vsctests', id);
|
||||
const workspaceDir = path.join(parentDir, 'workspaceconfig', id);
|
||||
// {{SQL CARBON EDIT}}
|
||||
const workspaceSettingsDir = path.join(workspaceDir, '.sqlops');
|
||||
const globalSettingsFile = path.join(workspaceDir, 'config.json');
|
||||
|
||||
extfs.mkdirp(workspaceSettingsDir, 493, (error) => {
|
||||
callback(workspaceDir, globalSettingsFile, (callback) => extfs.del(parentDir, os.tmpdir(), () => { }, callback));
|
||||
});
|
||||
}
|
||||
|
||||
function createService(workspaceDir: string, globalSettingsFile: string): TPromise<WorkspaceService> {
|
||||
const environmentService = new SettingsTestEnvironmentService(parseArgs(process.argv), process.execPath, globalSettingsFile);
|
||||
const service = new WorkspaceServiceImpl(workspaceDir, environmentService, null);
|
||||
|
||||
return service.initialize().then(() => service);
|
||||
}
|
||||
|
||||
test('defaults', (done: () => void) => {
|
||||
interface ITestSetting {
|
||||
workspace: {
|
||||
service: {
|
||||
testSetting: string;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const configurationRegistry = <IConfigurationRegistry>Registry.as(ConfigurationExtensions.Configuration);
|
||||
configurationRegistry.registerConfiguration({
|
||||
'id': '_test_workspace',
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'workspace.service.testSetting': {
|
||||
'type': 'string',
|
||||
'default': 'isSet'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
createWorkspace((workspaceDir, globalSettingsFile, cleanUp) => {
|
||||
return createService(workspaceDir, globalSettingsFile).then(service => {
|
||||
const config = service.getConfiguration<ITestSetting>();
|
||||
assert.equal(config.workspace.service.testSetting, 'isSet');
|
||||
|
||||
service.dispose();
|
||||
|
||||
cleanUp(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('globals', (done: () => void) => {
|
||||
createWorkspace((workspaceDir, globalSettingsFile, cleanUp) => {
|
||||
return createService(workspaceDir, globalSettingsFile).then(service => {
|
||||
fs.writeFileSync(globalSettingsFile, '{ "testworkbench.editor.tabs": true }');
|
||||
|
||||
service.reloadConfiguration().then(() => {
|
||||
const config = service.getConfiguration<{ testworkbench: { editor: { tabs: boolean } } }>();
|
||||
assert.equal(config.testworkbench.editor.tabs, true);
|
||||
|
||||
service.dispose();
|
||||
|
||||
cleanUp(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('reload configuration emits events', (done: () => void) => {
|
||||
createWorkspace((workspaceDir, globalSettingsFile, cleanUp) => {
|
||||
return createService(workspaceDir, globalSettingsFile).then(service => {
|
||||
fs.writeFileSync(globalSettingsFile, '{ "testworkbench.editor.tabs": true }');
|
||||
|
||||
return service.initialize().then(() => {
|
||||
service.onDidUpdateConfiguration(event => {
|
||||
const config = service.getConfiguration<{ testworkbench: { editor: { tabs: boolean } } }>();
|
||||
assert.equal(config.testworkbench.editor.tabs, false);
|
||||
|
||||
service.dispose();
|
||||
|
||||
cleanUp(done);
|
||||
});
|
||||
|
||||
fs.writeFileSync(globalSettingsFile, '{ "testworkbench.editor.tabs": false }');
|
||||
|
||||
// this has to trigger the event since the config changes
|
||||
service.reloadConfiguration().done();
|
||||
});
|
||||
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('globals override defaults', (done: () => void) => {
|
||||
interface ITestSetting {
|
||||
workspace: {
|
||||
service: {
|
||||
testSetting: string;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const configurationRegistry = <IConfigurationRegistry>Registry.as(ConfigurationExtensions.Configuration);
|
||||
configurationRegistry.registerConfiguration({
|
||||
'id': '_test_workspace',
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'workspace.service.testSetting': {
|
||||
'type': 'string',
|
||||
'default': 'isSet'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
createWorkspace((workspaceDir, globalSettingsFile, cleanUp) => {
|
||||
return createService(workspaceDir, globalSettingsFile).then(service => {
|
||||
fs.writeFileSync(globalSettingsFile, '{ "workspace.service.testSetting": "isChanged" }');
|
||||
|
||||
service.reloadConfiguration().then(() => {
|
||||
const config = service.getConfiguration<ITestSetting>();
|
||||
assert.equal(config.workspace.service.testSetting, 'isChanged');
|
||||
|
||||
service.dispose();
|
||||
|
||||
cleanUp(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('workspace settings', (done: () => void) => {
|
||||
createWorkspace((workspaceDir, globalSettingsFile, cleanUp) => {
|
||||
return createService(workspaceDir, globalSettingsFile).then(service => {
|
||||
// {{SQL CARBON EDIT}}
|
||||
fs.writeFileSync(path.join(workspaceDir, '.sqlops', 'settings.json'), '{ "testworkbench.editor.icons": true }');
|
||||
|
||||
service.reloadConfiguration().then(() => {
|
||||
const config = service.getConfiguration<{ testworkbench: { editor: { icons: boolean } } }>();
|
||||
assert.equal(config.testworkbench.editor.icons, true);
|
||||
|
||||
service.dispose();
|
||||
|
||||
cleanUp(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('workspace settings override user settings', (done: () => void) => {
|
||||
createWorkspace((workspaceDir, globalSettingsFile, cleanUp) => {
|
||||
return createService(workspaceDir, globalSettingsFile).then(service => {
|
||||
fs.writeFileSync(globalSettingsFile, '{ "testworkbench.editor.icons": false, "testworkbench.other.setting": true }');
|
||||
// {{SQL CARBON EDIT}}
|
||||
fs.writeFileSync(path.join(workspaceDir, '.sqlops', 'settings.json'), '{ "testworkbench.editor.icons": true }');
|
||||
|
||||
service.reloadConfiguration().then(() => {
|
||||
const config = service.getConfiguration<{ testworkbench: { editor: { icons: boolean }, other: { setting: string } } }>();
|
||||
assert.equal(config.testworkbench.editor.icons, true);
|
||||
assert.equal(config.testworkbench.other.setting, true);
|
||||
|
||||
service.dispose();
|
||||
|
||||
cleanUp(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('workspace change triggers event', (done: () => void) => {
|
||||
createWorkspace((workspaceDir, globalSettingsFile, cleanUp) => {
|
||||
return createService(workspaceDir, globalSettingsFile).then(service => {
|
||||
service.onDidUpdateConfiguration(event => {
|
||||
const config = service.getConfiguration<{ testworkbench: { editor: { icons: boolean } } }>();
|
||||
assert.equal(config.testworkbench.editor.icons, true);
|
||||
assert.equal(service.getConfiguration<any>().testworkbench.editor.icons, true);
|
||||
|
||||
service.dispose();
|
||||
|
||||
cleanUp(done);
|
||||
});
|
||||
|
||||
// {{SQL CARBON EDIT}}
|
||||
const settingsFile = path.join(workspaceDir, '.sqlops', 'settings.json');
|
||||
fs.writeFileSync(settingsFile, '{ "testworkbench.editor.icons": true }');
|
||||
|
||||
const event = new FileChangesEvent([{ resource: URI.file(settingsFile), type: FileChangeType.ADDED }]);
|
||||
service.handleWorkspaceFileEvents(event);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('workspace reload should triggers event if content changed', (done: () => void) => {
|
||||
createWorkspace((workspaceDir, globalSettingsFile, cleanUp) => {
|
||||
return createService(workspaceDir, globalSettingsFile).then(service => {
|
||||
// {{SQL CARBON EDIT}}
|
||||
const settingsFile = path.join(workspaceDir, '.sqlops', 'settings.json');
|
||||
fs.writeFileSync(settingsFile, '{ "testworkbench.editor.icons": true }');
|
||||
|
||||
const target = sinon.stub();
|
||||
service.onDidUpdateConfiguration(event => target());
|
||||
|
||||
fs.writeFileSync(settingsFile, '{ "testworkbench.editor.icons": false }');
|
||||
|
||||
service.reloadConfiguration().done(() => {
|
||||
assert.ok(target.calledOnce);
|
||||
service.dispose();
|
||||
|
||||
cleanUp(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('workspace reload should not trigger event if nothing changed', (done: () => void) => {
|
||||
createWorkspace((workspaceDir, globalSettingsFile, cleanUp) => {
|
||||
return createService(workspaceDir, globalSettingsFile).then(service => {
|
||||
// {{SQL CARBON EDIT}}
|
||||
const settingsFile = path.join(workspaceDir, '.sqlops', 'settings.json');
|
||||
fs.writeFileSync(settingsFile, '{ "testworkbench.editor.icons": true }');
|
||||
|
||||
service.reloadConfiguration().done(() => {
|
||||
const target = sinon.stub();
|
||||
service.onDidUpdateConfiguration(event => target());
|
||||
|
||||
service.reloadConfiguration().done(() => {
|
||||
assert.ok(!target.called);
|
||||
service.dispose();
|
||||
|
||||
cleanUp(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('workspace reload should not trigger event if there is no model', (done: () => void) => {
|
||||
createWorkspace((workspaceDir, globalSettingsFile, cleanUp) => {
|
||||
return createService(workspaceDir, globalSettingsFile).then(service => {
|
||||
const target = sinon.stub();
|
||||
service.onDidUpdateConfiguration(event => target());
|
||||
service.reloadConfiguration().done(() => {
|
||||
assert.ok(!target.called);
|
||||
service.dispose();
|
||||
cleanUp(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
test('lookup', (done: () => void) => {
|
||||
const configurationRegistry = <IConfigurationRegistry>Registry.as(ConfigurationExtensions.Configuration);
|
||||
configurationRegistry.registerConfiguration({
|
||||
'id': '_test',
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'workspaceLookup.service.testSetting': {
|
||||
'type': 'string',
|
||||
'default': 'isSet'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
createWorkspace((workspaceDir, globalSettingsFile, cleanUp) => {
|
||||
return createService(workspaceDir, globalSettingsFile).then(service => {
|
||||
let res = service.lookup('something.missing');
|
||||
assert.ok(!res.default);
|
||||
assert.ok(!res.user);
|
||||
assert.ok(!res.workspace);
|
||||
assert.ok(!res.value);
|
||||
|
||||
res = service.lookup('workspaceLookup.service.testSetting');
|
||||
assert.equal(res.default, 'isSet');
|
||||
assert.equal(res.value, 'isSet');
|
||||
assert.ok(!res.user);
|
||||
assert.ok(!res.workspace);
|
||||
|
||||
fs.writeFileSync(globalSettingsFile, '{ "workspaceLookup.service.testSetting": true }');
|
||||
|
||||
return service.reloadConfiguration().then(() => {
|
||||
res = service.lookup('workspaceLookup.service.testSetting');
|
||||
assert.equal(res.default, 'isSet');
|
||||
assert.equal(res.user, true);
|
||||
assert.equal(res.value, true);
|
||||
assert.ok(!res.workspace);
|
||||
|
||||
// {{SQL CARBON EDIT}}
|
||||
const settingsFile = path.join(workspaceDir, '.sqlops', 'settings.json');
|
||||
fs.writeFileSync(settingsFile, '{ "workspaceLookup.service.testSetting": 55 }');
|
||||
|
||||
return service.reloadConfiguration().then(() => {
|
||||
res = service.lookup('workspaceLookup.service.testSetting');
|
||||
assert.equal(res.default, 'isSet');
|
||||
assert.equal(res.user, true);
|
||||
assert.equal(res.workspace, 55);
|
||||
assert.equal(res.value, 55);
|
||||
|
||||
service.dispose();
|
||||
|
||||
cleanUp(done);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('keys', (done: () => void) => {
|
||||
const configurationRegistry = <IConfigurationRegistry>Registry.as(ConfigurationExtensions.Configuration);
|
||||
configurationRegistry.registerConfiguration({
|
||||
'id': '_test',
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'workspaceLookup.service.testSetting': {
|
||||
'type': 'string',
|
||||
'default': 'isSet'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function contains(array: string[], key: string): boolean {
|
||||
return array.indexOf(key) >= 0;
|
||||
}
|
||||
|
||||
createWorkspace((workspaceDir, globalSettingsFile, cleanUp) => {
|
||||
return createService(workspaceDir, globalSettingsFile).then(service => {
|
||||
let keys = service.keys();
|
||||
|
||||
assert.ok(!contains(keys.default, 'something.missing'));
|
||||
assert.ok(!contains(keys.user, 'something.missing'));
|
||||
assert.ok(!contains(keys.workspace, 'something.missing'));
|
||||
|
||||
assert.ok(contains(keys.default, 'workspaceLookup.service.testSetting'));
|
||||
assert.ok(!contains(keys.user, 'workspaceLookup.service.testSetting'));
|
||||
assert.ok(!contains(keys.workspace, 'workspaceLookup.service.testSetting'));
|
||||
|
||||
fs.writeFileSync(globalSettingsFile, '{ "workspaceLookup.service.testSetting": true }');
|
||||
|
||||
return service.reloadConfiguration().then(() => {
|
||||
keys = service.keys();
|
||||
|
||||
assert.ok(contains(keys.default, 'workspaceLookup.service.testSetting'));
|
||||
assert.ok(contains(keys.user, 'workspaceLookup.service.testSetting'));
|
||||
assert.ok(!contains(keys.workspace, 'workspaceLookup.service.testSetting'));
|
||||
|
||||
// {{SQL CARBON EDIT}}
|
||||
const settingsFile = path.join(workspaceDir, '.sqlops', 'settings.json');
|
||||
fs.writeFileSync(settingsFile, '{ "workspaceLookup.service.testSetting": 55 }');
|
||||
|
||||
return service.reloadConfiguration().then(() => {
|
||||
keys = service.keys();
|
||||
|
||||
assert.ok(contains(keys.default, 'workspaceLookup.service.testSetting'));
|
||||
assert.ok(contains(keys.user, 'workspaceLookup.service.testSetting'));
|
||||
assert.ok(contains(keys.workspace, 'workspaceLookup.service.testSetting'));
|
||||
|
||||
// {{SQL CARBON EDIT}}
|
||||
const settingsFile = path.join(workspaceDir, '.sqlops', 'tasks.json');
|
||||
fs.writeFileSync(settingsFile, '{ "workspaceLookup.service.taskTestSetting": 55 }');
|
||||
|
||||
return service.reloadConfiguration().then(() => {
|
||||
keys = service.keys();
|
||||
|
||||
assert.ok(!contains(keys.default, 'tasks.workspaceLookup.service.taskTestSetting'));
|
||||
assert.ok(!contains(keys.user, 'tasks.workspaceLookup.service.taskTestSetting'));
|
||||
assert.ok(contains(keys.workspace, 'tasks.workspaceLookup.service.taskTestSetting'));
|
||||
|
||||
service.dispose();
|
||||
|
||||
cleanUp(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('values', (done: () => void) => {
|
||||
const configurationRegistry = <IConfigurationRegistry>Registry.as(ConfigurationExtensions.Configuration);
|
||||
configurationRegistry.registerConfiguration({
|
||||
'id': '_test',
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'workspaceLookup.service.testSetting': {
|
||||
'type': 'string',
|
||||
'default': 'isSet'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
createWorkspace((workspaceDir, globalSettingsFile, cleanUp) => {
|
||||
return createService(workspaceDir, globalSettingsFile).then(service => {
|
||||
let values = service.values();
|
||||
let value = values['workspaceLookup.service.testSetting'];
|
||||
|
||||
assert.ok(value);
|
||||
assert.equal(value.default, 'isSet');
|
||||
|
||||
fs.writeFileSync(globalSettingsFile, '{ "workspaceLookup.service.testSetting": true }');
|
||||
|
||||
return service.reloadConfiguration().then(() => {
|
||||
values = service.values();
|
||||
value = values['workspaceLookup.service.testSetting'];
|
||||
|
||||
assert.ok(value);
|
||||
assert.equal(value.user, true);
|
||||
|
||||
// {{SQL CARBON EDIT}}
|
||||
const settingsFile = path.join(workspaceDir, '.sqlops', 'settings.json');
|
||||
fs.writeFileSync(settingsFile, '{ "workspaceLookup.service.testSetting": 55 }');
|
||||
|
||||
return service.reloadConfiguration().then(() => {
|
||||
values = service.values();
|
||||
value = values['workspaceLookup.service.testSetting'];
|
||||
|
||||
assert.ok(value);
|
||||
assert.equal(value.user, true);
|
||||
assert.equal(value.workspace, 55);
|
||||
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -18,33 +18,23 @@ import { parseArgs } from 'vs/platform/environment/node/argv';
|
||||
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
|
||||
import { EnvironmentService } from 'vs/platform/environment/node/environmentService';
|
||||
import extfs = require('vs/base/node/extfs');
|
||||
import { TestTextFileService, TestEditorGroupService, TestLifecycleService, TestBackupFileService } from 'vs/workbench/test/workbenchTestServices';
|
||||
import { TestTextFileService, TestTextResourceConfigurationService, workbenchInstantiationService } from 'vs/workbench/test/workbenchTestServices';
|
||||
import uuid = require('vs/base/common/uuid');
|
||||
import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from 'vs/platform/configuration/common/configurationRegistry';
|
||||
import { WorkspaceService, EmptyWorkspaceServiceImpl, WorkspaceServiceImpl } from 'vs/workbench/services/configuration/node/configuration';
|
||||
import { WorkspaceService } from 'vs/workbench/services/configuration/node/configurationService';
|
||||
import { FileService } from 'vs/workbench/services/files/node/fileService';
|
||||
import { ConfigurationEditingService } from 'vs/workbench/services/configuration/node/configurationEditingService';
|
||||
import { ConfigurationTarget, ConfigurationEditingError, ConfigurationEditingErrorCode } from 'vs/workbench/services/configuration/common/configurationEditing';
|
||||
import { ConfigurationEditingService, ConfigurationEditingError, ConfigurationEditingErrorCode } from 'vs/workbench/services/configuration/node/configurationEditingService';
|
||||
import { IFileService } from 'vs/platform/files/common/files';
|
||||
import { WORKSPACE_STANDALONE_CONFIGURATIONS } from 'vs/workbench/services/configuration/common/configuration';
|
||||
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
|
||||
import { IUntitledEditorService, UntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
|
||||
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
|
||||
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
|
||||
import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils';
|
||||
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
|
||||
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
|
||||
import { IConfigurationService, ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
|
||||
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
|
||||
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
|
||||
import { ITextModelService } from 'vs/editor/common/services/resolverService';
|
||||
import { TextModelResolverService } from 'vs/workbench/services/textmodelResolver/common/textModelResolverService';
|
||||
import { IModeService } from 'vs/editor/common/services/modeService';
|
||||
import { ModeServiceImpl } from 'vs/editor/common/services/modeServiceImpl';
|
||||
import { IModelService } from 'vs/editor/common/services/modelService';
|
||||
import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl';
|
||||
import { IChoiceService, IMessageService } from 'vs/platform/message/common/message';
|
||||
import { IChoiceService } from 'vs/platform/message/common/message';
|
||||
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
|
||||
import { IWorkspacesService } from 'vs/platform/workspaces/common/workspaces';
|
||||
import { IWindowConfiguration } from 'vs/platform/windows/common/windows';
|
||||
|
||||
class SettingsTestEnvironmentService extends EnvironmentService {
|
||||
|
||||
@@ -63,7 +53,6 @@ suite('ConfigurationEditingService', () => {
|
||||
let workspaceDir;
|
||||
let globalSettingsFile;
|
||||
let workspaceSettingsDir;
|
||||
let choiceService;
|
||||
|
||||
suiteSetup(() => {
|
||||
const configurationRegistry = <IConfigurationRegistry>Registry.as(ConfigurationExtensions.Configuration);
|
||||
@@ -114,34 +103,19 @@ suite('ConfigurationEditingService', () => {
|
||||
// Clear services if they are already created
|
||||
clearServices();
|
||||
|
||||
instantiationService = new TestInstantiationService();
|
||||
instantiationService = <TestInstantiationService>workbenchInstantiationService();
|
||||
const environmentService = new SettingsTestEnvironmentService(parseArgs(process.argv), process.execPath, globalSettingsFile);
|
||||
instantiationService.stub(IEnvironmentService, environmentService);
|
||||
const workspacesService = instantiationService.stub(IWorkspacesService, {});
|
||||
const workspaceService = noWorkspace ? new EmptyWorkspaceServiceImpl(environmentService) : new WorkspaceServiceImpl(workspaceDir, environmentService, workspacesService);
|
||||
const workspaceService = new WorkspaceService(environmentService, workspacesService);
|
||||
instantiationService.stub(IWorkspaceContextService, workspaceService);
|
||||
instantiationService.stub(IConfigurationService, workspaceService);
|
||||
instantiationService.stub(ILifecycleService, new TestLifecycleService());
|
||||
instantiationService.stub(IEditorGroupService, new TestEditorGroupService());
|
||||
instantiationService.stub(ITelemetryService, NullTelemetryService);
|
||||
instantiationService.stub(IModeService, ModeServiceImpl);
|
||||
instantiationService.stub(IModelService, instantiationService.createInstance(ModelServiceImpl));
|
||||
instantiationService.stub(IFileService, new FileService(workspaceService, new TestConfigurationService(), { disableWatcher: true }));
|
||||
instantiationService.stub(IUntitledEditorService, instantiationService.createInstance(UntitledEditorService));
|
||||
instantiationService.stub(ITextFileService, instantiationService.createInstance(TestTextFileService));
|
||||
instantiationService.stub(ITextModelService, <ITextModelService>instantiationService.createInstance(TextModelResolverService));
|
||||
instantiationService.stub(IBackupFileService, new TestBackupFileService());
|
||||
choiceService = instantiationService.stub(IChoiceService, {
|
||||
choose: (severity, message, options, cancelId): TPromise<number> => {
|
||||
return TPromise.as(cancelId);
|
||||
}
|
||||
return workspaceService.initialize(noWorkspace ? <IWindowConfiguration>{} : workspaceDir).then(() => {
|
||||
instantiationService.stub(IConfigurationService, workspaceService);
|
||||
instantiationService.stub(IFileService, new FileService(workspaceService, new TestTextResourceConfigurationService(), new TestConfigurationService(), { disableWatcher: true }));
|
||||
instantiationService.stub(ITextFileService, instantiationService.createInstance(TestTextFileService));
|
||||
instantiationService.stub(ITextModelService, <ITextModelService>instantiationService.createInstance(TextModelResolverService));
|
||||
testObject = instantiationService.createInstance(ConfigurationEditingService);
|
||||
});
|
||||
instantiationService.stub(IMessageService, {
|
||||
show: (severity, message, options, cancelId): void => { }
|
||||
});
|
||||
|
||||
testObject = instantiationService.createInstance(ConfigurationEditingService);
|
||||
return workspaceService.initialize();
|
||||
}
|
||||
|
||||
teardown(() => {
|
||||
@@ -226,7 +200,6 @@ suite('ConfigurationEditingService', () => {
|
||||
const contents = fs.readFileSync(globalSettingsFile).toString('utf8');
|
||||
const parsed = json.parse(contents);
|
||||
assert.equal(parsed['configurationEditing.service.testSetting'], 'value');
|
||||
assert.equal(instantiationService.get(IConfigurationService).lookup('configurationEditing.service.testSetting').value, 'value');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -238,10 +211,6 @@ suite('ConfigurationEditingService', () => {
|
||||
const parsed = json.parse(contents);
|
||||
assert.equal(parsed['configurationEditing.service.testSetting'], 'value');
|
||||
assert.equal(parsed['my.super.setting'], 'my.super.value');
|
||||
|
||||
const configurationService = instantiationService.get(IConfigurationService);
|
||||
assert.equal(configurationService.lookup('configurationEditing.service.testSetting').value, 'value');
|
||||
assert.equal(configurationService.lookup('my.super.setting').value, 'my.super.value');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -252,8 +221,6 @@ suite('ConfigurationEditingService', () => {
|
||||
const contents = fs.readFileSync(target).toString('utf8');
|
||||
const parsed = json.parse(contents);
|
||||
assert.equal(parsed['service.testSetting'], 'value');
|
||||
const configurationService = instantiationService.get(IConfigurationService);
|
||||
assert.equal(configurationService.lookup('tasks.service.testSetting').value, 'value');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -266,10 +233,6 @@ suite('ConfigurationEditingService', () => {
|
||||
const parsed = json.parse(contents);
|
||||
assert.equal(parsed['service.testSetting'], 'value');
|
||||
assert.equal(parsed['my.super.setting'], 'my.super.value');
|
||||
|
||||
const configurationService = instantiationService.get(IConfigurationService);
|
||||
assert.equal(configurationService.lookup('launch.service.testSetting').value, 'value');
|
||||
assert.equal(configurationService.lookup('launch.my.super.setting').value, 'my.super.value');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,696 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the Source EULA. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
'use strict';
|
||||
|
||||
import * as assert from 'assert';
|
||||
import * as sinon from 'sinon';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import URI from 'vs/base/common/uri';
|
||||
import { TPromise } from 'vs/base/common/winjs.base';
|
||||
import { Registry } from 'vs/platform/registry/common/platform';
|
||||
import { ParsedArgs, IEnvironmentService } from 'vs/platform/environment/common/environment';
|
||||
import { EnvironmentService } from 'vs/platform/environment/node/environmentService';
|
||||
import { parseArgs } from 'vs/platform/environment/node/argv';
|
||||
import extfs = require('vs/base/node/extfs');
|
||||
import uuid = require('vs/base/common/uuid');
|
||||
import { IConfigurationRegistry, Extensions as ConfigurationExtensions, ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry';
|
||||
import { WorkspaceService } from 'vs/workbench/services/configuration/node/configurationService';
|
||||
import { ConfigurationEditingErrorCode } from 'vs/workbench/services/configuration/node/configurationEditingService';
|
||||
import { FileChangeType, FileChangesEvent, IFileService } from 'vs/platform/files/common/files';
|
||||
import { IWorkspaceContextService, WorkbenchState, IWorkspaceFoldersChangeEvent } from 'vs/platform/workspace/common/workspace';
|
||||
import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';
|
||||
import { workbenchInstantiationService, TestTextResourceConfigurationService, TestTextFileService } from 'vs/workbench/test/workbenchTestServices';
|
||||
import { FileService } from 'vs/workbench/services/files/node/fileService';
|
||||
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
|
||||
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
|
||||
import { ITextModelService } from 'vs/editor/common/services/resolverService';
|
||||
import { TextModelResolverService } from 'vs/workbench/services/textmodelResolver/common/textModelResolverService';
|
||||
import { IJSONEditingService } from 'vs/workbench/services/configuration/common/jsonEditing';
|
||||
import { JSONEditingService } from 'vs/workbench/services/configuration/node/jsonEditingService';
|
||||
|
||||
class SettingsTestEnvironmentService extends EnvironmentService {
|
||||
|
||||
constructor(args: ParsedArgs, _execPath: string, private customAppSettingsHome) {
|
||||
super(args, _execPath);
|
||||
}
|
||||
|
||||
get appSettingsPath(): string { return this.customAppSettingsHome; }
|
||||
}
|
||||
|
||||
function setUpFolderWorkspace(folderName: string): TPromise<{ parentDir: string, folderDir: string }> {
|
||||
const id = uuid.generateUuid();
|
||||
const parentDir = path.join(os.tmpdir(), 'vsctests', id);
|
||||
return setUpFolder(folderName, parentDir).then(folderDir => ({ parentDir, folderDir }));
|
||||
}
|
||||
|
||||
function setUpFolder(folderName: string, parentDir: string): TPromise<string> {
|
||||
const folderDir = path.join(parentDir, folderName);
|
||||
// {{SQL CARBON EDIT}}
|
||||
const workspaceSettingsDir = path.join(folderDir, '.sqlops');
|
||||
return new TPromise((c, e) => {
|
||||
extfs.mkdirp(workspaceSettingsDir, 493, (error) => {
|
||||
if (error) {
|
||||
e(error);
|
||||
return null;
|
||||
}
|
||||
c(folderDir);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function setUpWorkspace(folders: string[]): TPromise<{ parentDir: string, configPath: string }> {
|
||||
|
||||
const id = uuid.generateUuid();
|
||||
const parentDir = path.join(os.tmpdir(), 'vsctests', id);
|
||||
|
||||
return createDir(parentDir)
|
||||
.then(() => {
|
||||
const configPath = path.join(parentDir, 'vsctests.code-workspace');
|
||||
const workspace = { folders: folders.map(path => ({ path })) };
|
||||
fs.writeFileSync(configPath, JSON.stringify(workspace, null, '\t'));
|
||||
|
||||
return TPromise.join(folders.map(folder => setUpFolder(folder, parentDir)))
|
||||
.then(() => ({ parentDir, configPath }));
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
function createDir(dir: string): TPromise<void> {
|
||||
return new TPromise((c, e) => {
|
||||
extfs.mkdirp(dir, 493, (error) => {
|
||||
if (error) {
|
||||
e(error);
|
||||
return null;
|
||||
}
|
||||
c(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
suite('WorkspaceContextService - Folder', () => {
|
||||
|
||||
let workspaceName = `testWorkspace${uuid.generateUuid()}`, parentResource: string, workspaceResource: string, workspaceContextService: IWorkspaceContextService;
|
||||
|
||||
setup(() => {
|
||||
return setUpFolderWorkspace(workspaceName)
|
||||
.then(({ parentDir, folderDir }) => {
|
||||
parentResource = parentDir;
|
||||
workspaceResource = folderDir;
|
||||
const globalSettingsFile = path.join(parentDir, 'settings.json');
|
||||
const environmentService = new SettingsTestEnvironmentService(parseArgs(process.argv), process.execPath, globalSettingsFile);
|
||||
workspaceContextService = new WorkspaceService(environmentService, null);
|
||||
return (<WorkspaceService>workspaceContextService).initialize(folderDir);
|
||||
});
|
||||
});
|
||||
|
||||
teardown(done => {
|
||||
if (workspaceContextService) {
|
||||
(<WorkspaceService>workspaceContextService).dispose();
|
||||
}
|
||||
if (parentResource) {
|
||||
extfs.del(parentResource, os.tmpdir(), () => { }, done);
|
||||
}
|
||||
});
|
||||
|
||||
test('getWorkspace()', () => {
|
||||
const actual = workspaceContextService.getWorkspace();
|
||||
|
||||
assert.equal(actual.folders.length, 1);
|
||||
assert.equal(actual.folders[0].uri.fsPath, URI.file(workspaceResource).fsPath);
|
||||
assert.equal(actual.folders[0].name, workspaceName);
|
||||
assert.equal(actual.folders[0].index, 0);
|
||||
assert.ok(!actual.configuration);
|
||||
});
|
||||
|
||||
test('getWorkbenchState()', () => {
|
||||
const actual = workspaceContextService.getWorkbenchState();
|
||||
|
||||
assert.equal(actual, WorkbenchState.FOLDER);
|
||||
});
|
||||
|
||||
test('getWorkspaceFolder()', () => {
|
||||
const actual = workspaceContextService.getWorkspaceFolder(URI.file(path.join(workspaceResource, 'a')));
|
||||
|
||||
assert.equal(actual, workspaceContextService.getWorkspace().folders[0]);
|
||||
});
|
||||
|
||||
test('isCurrentWorkspace() => true', () => {
|
||||
assert.ok(workspaceContextService.isCurrentWorkspace(workspaceResource));
|
||||
});
|
||||
|
||||
test('isCurrentWorkspace() => false', () => {
|
||||
assert.ok(!workspaceContextService.isCurrentWorkspace(workspaceResource + 'abc'));
|
||||
});
|
||||
});
|
||||
|
||||
suite('WorkspaceContextService - Workspace', () => {
|
||||
|
||||
let parentResource: string, testObject: WorkspaceService;
|
||||
|
||||
setup(() => {
|
||||
return setUpWorkspace(['a', 'b'])
|
||||
.then(({ parentDir, configPath }) => {
|
||||
|
||||
parentResource = parentDir;
|
||||
|
||||
const environmentService = new SettingsTestEnvironmentService(parseArgs(process.argv), process.execPath, path.join(parentDir, 'settings.json'));
|
||||
const workspaceService = new WorkspaceService(environmentService, null);
|
||||
|
||||
const instantiationService = <TestInstantiationService>workbenchInstantiationService();
|
||||
instantiationService.stub(IWorkspaceContextService, workspaceService);
|
||||
instantiationService.stub(IConfigurationService, workspaceService);
|
||||
instantiationService.stub(IEnvironmentService, environmentService);
|
||||
|
||||
return workspaceService.initialize({ id: configPath, configPath }).then(() => {
|
||||
|
||||
instantiationService.stub(IFileService, new FileService(<IWorkspaceContextService>workspaceService, new TestTextResourceConfigurationService(), workspaceService, { disableWatcher: true }));
|
||||
instantiationService.stub(ITextFileService, instantiationService.createInstance(TestTextFileService));
|
||||
instantiationService.stub(ITextModelService, <ITextModelService>instantiationService.createInstance(TextModelResolverService));
|
||||
workspaceService.setInstantiationService(instantiationService);
|
||||
|
||||
testObject = workspaceService;
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
teardown(done => {
|
||||
if (testObject) {
|
||||
(<WorkspaceService>testObject).dispose();
|
||||
}
|
||||
if (parentResource) {
|
||||
extfs.del(parentResource, os.tmpdir(), () => { }, done);
|
||||
}
|
||||
});
|
||||
|
||||
test('workspace folders', () => {
|
||||
const actual = testObject.getWorkspace().folders;
|
||||
|
||||
assert.equal(actual.length, 2);
|
||||
assert.equal(path.basename(actual[0].uri.fsPath), 'a');
|
||||
assert.equal(path.basename(actual[1].uri.fsPath), 'b');
|
||||
});
|
||||
|
||||
test('add folders', () => {
|
||||
const workspaceDir = path.dirname(testObject.getWorkspace().folders[0].uri.fsPath);
|
||||
return testObject.addFolders([{ uri: URI.file(path.join(workspaceDir, 'd')) }, { uri: URI.file(path.join(workspaceDir, 'c')) }])
|
||||
.then(() => {
|
||||
const actual = testObject.getWorkspace().folders;
|
||||
|
||||
assert.equal(actual.length, 4);
|
||||
assert.equal(path.basename(actual[0].uri.fsPath), 'a');
|
||||
assert.equal(path.basename(actual[1].uri.fsPath), 'b');
|
||||
assert.equal(path.basename(actual[2].uri.fsPath), 'd');
|
||||
assert.equal(path.basename(actual[3].uri.fsPath), 'c');
|
||||
});
|
||||
});
|
||||
|
||||
test('add folders (with name)', () => {
|
||||
const workspaceDir = path.dirname(testObject.getWorkspace().folders[0].uri.fsPath);
|
||||
return testObject.addFolders([{ uri: URI.file(path.join(workspaceDir, 'd')), name: 'DDD' }, { uri: URI.file(path.join(workspaceDir, 'c')), name: 'CCC' }])
|
||||
.then(() => {
|
||||
const actual = testObject.getWorkspace().folders;
|
||||
|
||||
assert.equal(actual.length, 4);
|
||||
assert.equal(path.basename(actual[0].uri.fsPath), 'a');
|
||||
assert.equal(path.basename(actual[1].uri.fsPath), 'b');
|
||||
assert.equal(path.basename(actual[2].uri.fsPath), 'd');
|
||||
assert.equal(path.basename(actual[3].uri.fsPath), 'c');
|
||||
assert.equal(actual[2].name, 'DDD');
|
||||
assert.equal(actual[3].name, 'CCC');
|
||||
});
|
||||
});
|
||||
|
||||
test('add folders triggers change event', () => {
|
||||
const target = sinon.spy();
|
||||
testObject.onDidChangeWorkspaceFolders(target);
|
||||
const workspaceDir = path.dirname(testObject.getWorkspace().folders[0].uri.fsPath);
|
||||
const addedFolders = [{ uri: URI.file(path.join(workspaceDir, 'd')) }, { uri: URI.file(path.join(workspaceDir, 'c')) }];
|
||||
return testObject.addFolders(addedFolders)
|
||||
.then(() => {
|
||||
assert.ok(target.calledOnce);
|
||||
const actual = <IWorkspaceFoldersChangeEvent>target.args[0][0];
|
||||
assert.deepEqual(actual.added.map(r => r.uri.toString()), addedFolders.map(a => a.uri.toString()));
|
||||
assert.deepEqual(actual.removed, []);
|
||||
assert.deepEqual(actual.changed, []);
|
||||
});
|
||||
});
|
||||
|
||||
test('remove folders', () => {
|
||||
return testObject.removeFolders([testObject.getWorkspace().folders[0].uri])
|
||||
.then(() => {
|
||||
const actual = testObject.getWorkspace().folders;
|
||||
assert.equal(actual.length, 1);
|
||||
assert.equal(path.basename(actual[0].uri.fsPath), 'b');
|
||||
});
|
||||
});
|
||||
|
||||
test('remove folders triggers change event', () => {
|
||||
const target = sinon.spy();
|
||||
testObject.onDidChangeWorkspaceFolders(target);
|
||||
const removedFolder = testObject.getWorkspace().folders[0];
|
||||
return testObject.removeFolders([removedFolder.uri])
|
||||
.then(() => {
|
||||
assert.ok(target.calledOnce);
|
||||
const actual = <IWorkspaceFoldersChangeEvent>target.args[0][0];
|
||||
assert.deepEqual(actual.added, []);
|
||||
assert.deepEqual(actual.removed.map(r => r.uri.toString()), [removedFolder.uri.toString()]);
|
||||
assert.deepEqual(actual.changed.map(c => c.uri.toString()), [testObject.getWorkspace().folders[0].uri.toString()]);
|
||||
});
|
||||
});
|
||||
|
||||
test('reorder folders trigger change event', () => {
|
||||
const target = sinon.spy();
|
||||
testObject.onDidChangeWorkspaceFolders(target);
|
||||
const workspace = { folders: [{ path: testObject.getWorkspace().folders[1].uri.fsPath }, { path: testObject.getWorkspace().folders[0].uri.fsPath }] };
|
||||
fs.writeFileSync(testObject.getWorkspace().configuration.fsPath, JSON.stringify(workspace, null, '\t'));
|
||||
return testObject.reloadConfiguration()
|
||||
.then(() => {
|
||||
assert.ok(target.calledOnce);
|
||||
const actual = <IWorkspaceFoldersChangeEvent>target.args[0][0];
|
||||
assert.deepEqual(actual.added, []);
|
||||
assert.deepEqual(actual.removed, []);
|
||||
assert.deepEqual(actual.changed.map(c => c.uri.toString()), testObject.getWorkspace().folders.map(f => f.uri.toString()).reverse());
|
||||
});
|
||||
});
|
||||
|
||||
test('rename folders trigger change event', () => {
|
||||
const target = sinon.spy();
|
||||
testObject.onDidChangeWorkspaceFolders(target);
|
||||
const workspace = { folders: [{ path: testObject.getWorkspace().folders[0].uri.fsPath, name: '1' }, { path: testObject.getWorkspace().folders[1].uri.fsPath }] };
|
||||
fs.writeFileSync(testObject.getWorkspace().configuration.fsPath, JSON.stringify(workspace, null, '\t'));
|
||||
return testObject.reloadConfiguration()
|
||||
.then(() => {
|
||||
assert.ok(target.calledOnce);
|
||||
const actual = <IWorkspaceFoldersChangeEvent>target.args[0][0];
|
||||
assert.deepEqual(actual.added, []);
|
||||
assert.deepEqual(actual.removed, []);
|
||||
assert.deepEqual(actual.changed.map(c => c.uri.toString()), [testObject.getWorkspace().folders[0].uri.toString()]);
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
suite('WorkspaceConfigurationService - Folder', () => {
|
||||
|
||||
let workspaceName = `testWorkspace${uuid.generateUuid()}`, parentResource: string, workspaceDir: string, testObject: IConfigurationService, globalSettingsFile: string;
|
||||
|
||||
suiteSetup(() => {
|
||||
const configurationRegistry = <IConfigurationRegistry>Registry.as(ConfigurationExtensions.Configuration);
|
||||
configurationRegistry.registerConfiguration({
|
||||
'id': '_test',
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'configurationService.folder.testSetting': {
|
||||
'type': 'string',
|
||||
'default': 'isSet'
|
||||
},
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
setup(() => {
|
||||
return setUpFolderWorkspace(workspaceName)
|
||||
.then(({ parentDir, folderDir }) => {
|
||||
|
||||
parentResource = parentDir;
|
||||
workspaceDir = folderDir;
|
||||
globalSettingsFile = path.join(parentDir, 'settings.json');
|
||||
|
||||
const instantiationService = <TestInstantiationService>workbenchInstantiationService();
|
||||
const environmentService = new SettingsTestEnvironmentService(parseArgs(process.argv), process.execPath, globalSettingsFile);
|
||||
const workspaceService = new WorkspaceService(environmentService, null);
|
||||
instantiationService.stub(IWorkspaceContextService, workspaceService);
|
||||
instantiationService.stub(IConfigurationService, workspaceService);
|
||||
instantiationService.stub(IEnvironmentService, environmentService);
|
||||
|
||||
return workspaceService.initialize(folderDir).then(() => {
|
||||
instantiationService.stub(IFileService, new FileService(<IWorkspaceContextService>workspaceService, new TestTextResourceConfigurationService(), workspaceService, { disableWatcher: true }));
|
||||
instantiationService.stub(ITextFileService, instantiationService.createInstance(TestTextFileService));
|
||||
instantiationService.stub(ITextModelService, <ITextModelService>instantiationService.createInstance(TextModelResolverService));
|
||||
workspaceService.setInstantiationService(instantiationService);
|
||||
testObject = workspaceService;
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
teardown(done => {
|
||||
if (testObject) {
|
||||
(<WorkspaceService>testObject).dispose();
|
||||
}
|
||||
if (parentResource) {
|
||||
extfs.del(parentResource, os.tmpdir(), () => { }, done);
|
||||
}
|
||||
});
|
||||
|
||||
test('defaults', () => {
|
||||
assert.deepEqual(testObject.getValue('configurationService'), { 'folder': { 'testSetting': 'isSet' } });
|
||||
});
|
||||
|
||||
test('globals override defaults', () => {
|
||||
fs.writeFileSync(globalSettingsFile, '{ "configurationService.folder.testSetting": "userValue" }');
|
||||
return testObject.reloadConfiguration()
|
||||
.then(() => assert.equal(testObject.getValue('configurationService.folder.testSetting'), 'userValue'));
|
||||
});
|
||||
|
||||
test('globals', () => {
|
||||
fs.writeFileSync(globalSettingsFile, '{ "testworkbench.editor.tabs": true }');
|
||||
return testObject.reloadConfiguration()
|
||||
.then(() => assert.equal(testObject.getValue('testworkbench.editor.tabs'), true));
|
||||
});
|
||||
|
||||
test('workspace settings', () => {
|
||||
// {{SQL CARBON EDIT}}
|
||||
fs.writeFileSync(path.join(workspaceDir, '.sqlops', 'settings.json'), '{ "testworkbench.editor.icons": true }');
|
||||
return testObject.reloadConfiguration()
|
||||
.then(() => assert.equal(testObject.getValue('testworkbench.editor.icons'), true));
|
||||
});
|
||||
|
||||
test('workspace settings override user settings', () => {
|
||||
fs.writeFileSync(globalSettingsFile, '{ "configurationService.folder.testSetting": "userValue" }');
|
||||
// {{SQL CARBON EDIT}}
|
||||
fs.writeFileSync(path.join(workspaceDir, '.sqlops', 'settings.json'), '{ "configurationService.folder.testSetting": "workspaceValue" }');
|
||||
return testObject.reloadConfiguration()
|
||||
.then(() => assert.equal(testObject.getValue('configurationService.folder.testSetting'), 'workspaceValue'));
|
||||
});
|
||||
|
||||
test('workspace change triggers event', () => {
|
||||
// {{SQL CARBON EDIT}}
|
||||
const settingsFile = path.join(workspaceDir, '.sqlops', 'settings.json');
|
||||
fs.writeFileSync(settingsFile, '{ "configurationService.folder.testSetting": "workspaceValue" }');
|
||||
const event = new FileChangesEvent([{ resource: URI.file(settingsFile), type: FileChangeType.ADDED }]);
|
||||
const target = sinon.spy();
|
||||
testObject.onDidChangeConfiguration(target);
|
||||
return (<WorkspaceService>testObject).handleWorkspaceFileEvents(event)
|
||||
.then(() => {
|
||||
assert.equal(testObject.getValue('configurationService.folder.testSetting'), 'workspaceValue');
|
||||
assert.ok(target.called);
|
||||
});
|
||||
});
|
||||
|
||||
test('reload configuration emits events after global configuraiton changes', () => {
|
||||
fs.writeFileSync(globalSettingsFile, '{ "testworkbench.editor.tabs": true }');
|
||||
const target = sinon.spy();
|
||||
testObject.onDidChangeConfiguration(target);
|
||||
return testObject.reloadConfiguration().then(() => assert.ok(target.called));
|
||||
});
|
||||
|
||||
test('reload configuration emits events after workspace configuraiton changes', () => {
|
||||
// {{SQL CARBON EDIT}}
|
||||
fs.writeFileSync(path.join(workspaceDir, '.sqlops', 'settings.json'), '{ "configurationService.folder.testSetting": "workspaceValue" }');
|
||||
const target = sinon.spy();
|
||||
testObject.onDidChangeConfiguration(target);
|
||||
return testObject.reloadConfiguration().then(() => assert.ok(target.called));
|
||||
});
|
||||
|
||||
test('reload configuration should not emit event if no changes', () => {
|
||||
fs.writeFileSync(globalSettingsFile, '{ "testworkbench.editor.tabs": true }');
|
||||
// {{SQL CARBON EDIT}}
|
||||
fs.writeFileSync(path.join(workspaceDir, '.sqlops', 'settings.json'), '{ "configurationService.folder.testSetting": "workspaceValue" }');
|
||||
return testObject.reloadConfiguration()
|
||||
.then(() => {
|
||||
const target = sinon.spy();
|
||||
testObject.onDidChangeConfiguration(() => { target(); });
|
||||
return testObject.reloadConfiguration()
|
||||
.then(() => assert.ok(!target.called));
|
||||
});
|
||||
});
|
||||
|
||||
test('inspect', () => {
|
||||
let actual = testObject.inspect('something.missing');
|
||||
assert.equal(actual.default, void 0);
|
||||
assert.equal(actual.user, void 0);
|
||||
assert.equal(actual.workspace, void 0);
|
||||
assert.equal(actual.workspaceFolder, void 0);
|
||||
assert.equal(actual.value, void 0);
|
||||
|
||||
actual = testObject.inspect('configurationService.folder.testSetting');
|
||||
assert.equal(actual.default, 'isSet');
|
||||
assert.equal(actual.user, void 0);
|
||||
assert.equal(actual.workspace, void 0);
|
||||
assert.equal(actual.workspaceFolder, void 0);
|
||||
assert.equal(actual.value, 'isSet');
|
||||
|
||||
fs.writeFileSync(globalSettingsFile, '{ "configurationService.folder.testSetting": "userValue" }');
|
||||
return testObject.reloadConfiguration()
|
||||
.then(() => {
|
||||
actual = testObject.inspect('configurationService.folder.testSetting');
|
||||
assert.equal(actual.default, 'isSet');
|
||||
assert.equal(actual.user, 'userValue');
|
||||
assert.equal(actual.workspace, void 0);
|
||||
assert.equal(actual.workspaceFolder, void 0);
|
||||
assert.equal(actual.value, 'userValue');
|
||||
|
||||
// {{SQL CARBON EDIT}}
|
||||
fs.writeFileSync(path.join(workspaceDir, '.sqlops', 'settings.json'), '{ "configurationService.folder.testSetting": "workspaceValue" }');
|
||||
|
||||
return testObject.reloadConfiguration()
|
||||
.then(() => {
|
||||
actual = testObject.inspect('configurationService.folder.testSetting');
|
||||
assert.equal(actual.default, 'isSet');
|
||||
assert.equal(actual.user, 'userValue');
|
||||
assert.equal(actual.workspace, 'workspaceValue');
|
||||
assert.equal(actual.workspaceFolder, void 0);
|
||||
assert.equal(actual.value, 'workspaceValue');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('keys', () => {
|
||||
let actual = testObject.keys();
|
||||
assert.ok(actual.default.indexOf('configurationService.folder.testSetting') !== -1);
|
||||
assert.deepEqual(actual.user, []);
|
||||
assert.deepEqual(actual.workspace, []);
|
||||
assert.deepEqual(actual.workspaceFolder, []);
|
||||
|
||||
fs.writeFileSync(globalSettingsFile, '{ "configurationService.folder.testSetting": "userValue" }');
|
||||
return testObject.reloadConfiguration()
|
||||
.then(() => {
|
||||
actual = testObject.keys();
|
||||
assert.ok(actual.default.indexOf('configurationService.folder.testSetting') !== -1);
|
||||
assert.deepEqual(actual.user, ['configurationService.folder.testSetting']);
|
||||
assert.deepEqual(actual.workspace, []);
|
||||
assert.deepEqual(actual.workspaceFolder, []);
|
||||
|
||||
// {{SQL CARBON EDIT}}
|
||||
fs.writeFileSync(path.join(workspaceDir, '.sqlops', 'settings.json'), '{ "configurationService.folder.testSetting": "workspaceValue" }');
|
||||
|
||||
return testObject.reloadConfiguration()
|
||||
.then(() => {
|
||||
actual = testObject.keys();
|
||||
assert.ok(actual.default.indexOf('configurationService.folder.testSetting') !== -1);
|
||||
assert.deepEqual(actual.user, ['configurationService.folder.testSetting']);
|
||||
assert.deepEqual(actual.workspace, ['configurationService.folder.testSetting']);
|
||||
assert.deepEqual(actual.workspaceFolder, []);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('update user configuration', () => {
|
||||
return testObject.updateValue('configurationService.folder.testSetting', 'value', ConfigurationTarget.USER)
|
||||
.then(() => assert.equal(testObject.getValue('configurationService.folder.testSetting'), 'value'));
|
||||
});
|
||||
|
||||
test('update workspace configuration', () => {
|
||||
return testObject.updateValue('tasks.service.testSetting', 'value', ConfigurationTarget.WORKSPACE)
|
||||
.then(() => assert.equal(testObject.getValue('tasks.service.testSetting'), 'value'));
|
||||
});
|
||||
|
||||
test('update tasks configuration', () => {
|
||||
return testObject.updateValue('tasks', { 'version': '1.0.0', tasks: [{ 'taskName': 'myTask' }] }, ConfigurationTarget.WORKSPACE)
|
||||
.then(() => assert.deepEqual(testObject.getValue('tasks'), { 'version': '1.0.0', tasks: [{ 'taskName': 'myTask' }] }));
|
||||
});
|
||||
|
||||
test('update user configuration should trigger change event before promise is resolve', () => {
|
||||
const target = sinon.spy();
|
||||
testObject.onDidChangeConfiguration(target);
|
||||
return testObject.updateValue('configurationService.folder.testSetting', 'value', ConfigurationTarget.USER)
|
||||
.then(() => assert.ok(target.called));
|
||||
});
|
||||
|
||||
test('update workspace configuration should trigger change event before promise is resolve', () => {
|
||||
const target = sinon.spy();
|
||||
testObject.onDidChangeConfiguration(target);
|
||||
return testObject.updateValue('configurationService.folder.testSetting', 'value', ConfigurationTarget.WORKSPACE)
|
||||
.then(() => assert.ok(target.called));
|
||||
});
|
||||
|
||||
test('update task configuration should trigger change event before promise is resolve', () => {
|
||||
const target = sinon.spy();
|
||||
testObject.onDidChangeConfiguration(target);
|
||||
return testObject.updateValue('tasks', { 'version': '1.0.0', tasks: [{ 'taskName': 'myTask' }] }, ConfigurationTarget.WORKSPACE)
|
||||
.then(() => assert.ok(target.called));
|
||||
});
|
||||
|
||||
test('initialize with different folder triggers configuration event if there are changes', () => {
|
||||
return setUpFolderWorkspace(`testWorkspace${uuid.generateUuid()}`)
|
||||
.then(({ folderDir }) => {
|
||||
const target = sinon.spy();
|
||||
testObject.onDidChangeConfiguration(target);
|
||||
|
||||
// {{SQL CARBON EDIT}}
|
||||
fs.writeFileSync(path.join(folderDir, '.sqlops', 'settings.json'), '{ "configurationService.folder.testSetting": "workspaceValue2" }');
|
||||
return (<WorkspaceService>testObject).initialize(folderDir)
|
||||
.then(() => {
|
||||
assert.equal(testObject.getValue('configurationService.folder.testSetting'), 'workspaceValue2');
|
||||
assert.ok(target.called);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('initialize with different folder triggers configuration event if there are no changes', () => {
|
||||
fs.writeFileSync(globalSettingsFile, '{ "configurationService.folder.testSetting": "workspaceValue2" }');
|
||||
return testObject.reloadConfiguration()
|
||||
.then(() => setUpFolderWorkspace(`testWorkspace${uuid.generateUuid()}`))
|
||||
.then(({ folderDir }) => {
|
||||
const target = sinon.spy();
|
||||
testObject.onDidChangeConfiguration(() => target());
|
||||
// {{SQL CARBON EDIT}}
|
||||
fs.writeFileSync(path.join(folderDir, '.sqlops', 'settings.json'), '{ "configurationService.folder.testSetting": "workspaceValue2" }');
|
||||
return (<WorkspaceService>testObject).initialize(folderDir)
|
||||
.then(() => {
|
||||
assert.equal(testObject.getValue('configurationService.folder.testSetting'), 'workspaceValue2');
|
||||
assert.ok(!target.called);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
suite('WorkspaceConfigurationService - Update (Multiroot)', () => {
|
||||
|
||||
let parentResource: string, workspaceContextService: IWorkspaceContextService, jsonEditingServce: IJSONEditingService, testObject: IConfigurationService;
|
||||
|
||||
suiteSetup(() => {
|
||||
const configurationRegistry = <IConfigurationRegistry>Registry.as(ConfigurationExtensions.Configuration);
|
||||
configurationRegistry.registerConfiguration({
|
||||
'id': '_test',
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'configurationService.workspace.testSetting': {
|
||||
'type': 'string',
|
||||
'default': 'isSet'
|
||||
},
|
||||
'configurationService.workspace.testResourceSetting': {
|
||||
'type': 'string',
|
||||
'default': 'isSet',
|
||||
scope: ConfigurationScope.RESOURCE
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
setup(() => {
|
||||
return setUpWorkspace(['1', '2'])
|
||||
.then(({ parentDir, configPath }) => {
|
||||
|
||||
parentResource = parentDir;
|
||||
|
||||
const environmentService = new SettingsTestEnvironmentService(parseArgs(process.argv), process.execPath, path.join(parentDir, 'settings.json'));
|
||||
const workspaceService = new WorkspaceService(environmentService, null);
|
||||
|
||||
const instantiationService = <TestInstantiationService>workbenchInstantiationService();
|
||||
instantiationService.stub(IWorkspaceContextService, workspaceService);
|
||||
instantiationService.stub(IConfigurationService, workspaceService);
|
||||
instantiationService.stub(IEnvironmentService, environmentService);
|
||||
|
||||
return workspaceService.initialize({ id: configPath, configPath }).then(() => {
|
||||
|
||||
instantiationService.stub(IFileService, new FileService(<IWorkspaceContextService>workspaceService, new TestTextResourceConfigurationService(), workspaceService, { disableWatcher: true }));
|
||||
instantiationService.stub(ITextFileService, instantiationService.createInstance(TestTextFileService));
|
||||
instantiationService.stub(ITextModelService, <ITextModelService>instantiationService.createInstance(TextModelResolverService));
|
||||
workspaceService.setInstantiationService(instantiationService);
|
||||
|
||||
workspaceContextService = workspaceService;
|
||||
jsonEditingServce = instantiationService.createInstance(JSONEditingService);
|
||||
testObject = workspaceService;
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
teardown(done => {
|
||||
if (testObject) {
|
||||
(<WorkspaceService>testObject).dispose();
|
||||
}
|
||||
if (parentResource) {
|
||||
extfs.del(parentResource, os.tmpdir(), () => { }, done);
|
||||
}
|
||||
});
|
||||
|
||||
test('update user configuration', () => {
|
||||
return testObject.updateValue('configurationService.workspace.testSetting', 'userValue', ConfigurationTarget.USER)
|
||||
.then(() => assert.equal(testObject.getValue('configurationService.workspace.testSetting'), 'userValue'));
|
||||
});
|
||||
|
||||
test('update user configuration should trigger change event before promise is resolve', () => {
|
||||
const target = sinon.spy();
|
||||
testObject.onDidChangeConfiguration(target);
|
||||
return testObject.updateValue('configurationService.workspace.testSetting', 'userValue', ConfigurationTarget.USER)
|
||||
.then(() => assert.ok(target.called));
|
||||
});
|
||||
|
||||
test('update workspace configuration', () => {
|
||||
return testObject.updateValue('configurationService.workspace.testSetting', 'workspaceValue', ConfigurationTarget.WORKSPACE)
|
||||
.then(() => assert.equal(testObject.getValue('configurationService.workspace.testSetting'), 'workspaceValue'));
|
||||
});
|
||||
|
||||
test('update workspace configuration should trigger change event before promise is resolve', () => {
|
||||
const target = sinon.spy();
|
||||
testObject.onDidChangeConfiguration(target);
|
||||
return testObject.updateValue('configurationService.workspace.testSetting', 'workspaceValue', ConfigurationTarget.WORKSPACE)
|
||||
.then(() => assert.ok(target.called));
|
||||
});
|
||||
|
||||
test('update workspace folder configuration', () => {
|
||||
const workspace = workspaceContextService.getWorkspace();
|
||||
return testObject.updateValue('configurationService.workspace.testResourceSetting', 'workspaceFolderValue', { resource: workspace.folders[0].uri }, ConfigurationTarget.WORKSPACE_FOLDER)
|
||||
.then(() => assert.equal(testObject.getValue('configurationService.workspace.testResourceSetting', { resource: workspace.folders[0].uri }), 'workspaceFolderValue'));
|
||||
});
|
||||
|
||||
test('update workspace folder configuration should trigger change event before promise is resolve', () => {
|
||||
const workspace = workspaceContextService.getWorkspace();
|
||||
const target = sinon.spy();
|
||||
testObject.onDidChangeConfiguration(target);
|
||||
return testObject.updateValue('configurationService.workspace.testResourceSetting', 'workspaceFolderValue', { resource: workspace.folders[0].uri }, ConfigurationTarget.WORKSPACE_FOLDER)
|
||||
.then(() => assert.ok(target.called));
|
||||
});
|
||||
|
||||
test('update tasks configuration in a folder', () => {
|
||||
const workspace = workspaceContextService.getWorkspace();
|
||||
return testObject.updateValue('tasks', { 'version': '1.0.0', tasks: [{ 'taskName': 'myTask' }] }, { resource: workspace.folders[0].uri }, ConfigurationTarget.WORKSPACE_FOLDER)
|
||||
.then(() => assert.deepEqual(testObject.getValue('tasks', { resource: workspace.folders[0].uri }), { 'version': '1.0.0', tasks: [{ 'taskName': 'myTask' }] }));
|
||||
});
|
||||
|
||||
test('update tasks configuration in a workspace is not supported', () => {
|
||||
const workspace = workspaceContextService.getWorkspace();
|
||||
return testObject.updateValue('tasks', { 'version': '1.0.0', tasks: [{ 'taskName': 'myTask' }] }, { resource: workspace.folders[0].uri }, ConfigurationTarget.WORKSPACE, true)
|
||||
.then(() => assert.fail('Should not be supported'), (e) => assert.equal(e.code, ConfigurationEditingErrorCode.ERROR_INVALID_WORKSPACE_TARGET));
|
||||
});
|
||||
|
||||
test('update launch configuration in a workspace is not supported', () => {
|
||||
const workspace = workspaceContextService.getWorkspace();
|
||||
return testObject.updateValue('launch', { 'version': '1.0.0', configurations: [{ 'name': 'myLaunch' }] }, { resource: workspace.folders[0].uri }, ConfigurationTarget.WORKSPACE, true)
|
||||
.then(() => assert.fail('Should not be supported'), (e) => assert.equal(e.code, ConfigurationEditingErrorCode.ERROR_INVALID_WORKSPACE_TARGET));
|
||||
});
|
||||
|
||||
test('task configurations are not read from workspace', () => {
|
||||
return jsonEditingServce.write(workspaceContextService.getWorkspace().configuration, { key: 'tasks', value: { 'version': '1.0' } }, true)
|
||||
.then(() => testObject.reloadConfiguration())
|
||||
.then(() => {
|
||||
const actual = testObject.inspect('tasks.version');
|
||||
assert.equal(actual.workspace, void 0);
|
||||
});
|
||||
});
|
||||
|
||||
test('launch configurations are not read from workspace', () => {
|
||||
return jsonEditingServce.write(workspaceContextService.getWorkspace().configuration, { key: 'launch', value: { 'version': '1.0' } }, true)
|
||||
.then(() => testObject.reloadConfiguration())
|
||||
.then(() => {
|
||||
const actual = testObject.inspect('launch.version');
|
||||
assert.equal(actual.workspace, void 0);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user