SQL Operations Studio Public Preview 1 (0.23) release source code

This commit is contained in:
Karl Burtram
2017-11-09 14:30:27 -08:00
parent b88ecb8d93
commit 3cdac41339
8829 changed files with 759707 additions and 286 deletions

View File

@@ -0,0 +1,29 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
export const CONFIG_DEFAULT_NAME = 'settings';
// {{SQL CARBON EDIT}}
export const WORKSPACE_CONFIG_FOLDER_DEFAULT_NAME = '.sqlops';
export const WORKSPACE_CONFIG_DEFAULT_PATH = `${WORKSPACE_CONFIG_FOLDER_DEFAULT_NAME}/${CONFIG_DEFAULT_NAME}.json`;
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`
};

View File

@@ -0,0 +1,104 @@
/*---------------------------------------------------------------------------------------------
* 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>;
}

View File

@@ -0,0 +1,181 @@
/*---------------------------------------------------------------------------------------------
* 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 { clone } from 'vs/base/common/objects';
import { CustomConfigurationModel, toValuesTree } from 'vs/platform/configuration/common/model';
import { ConfigurationModel } from 'vs/platform/configuration/common/configuration';
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';
export class WorkspaceConfigurationModel<T> extends CustomConfigurationModel<T> {
private _raw: T;
private _folders: IStoredWorkspaceFolder[];
private _worksapaceSettings: ConfigurationModel<T>;
private _tasksConfiguration: ConfigurationModel<T>;
private _launchConfiguration: ConfigurationModel<T>;
private _workspaceConfiguration: ConfigurationModel<T>;
public update(content: string): void {
super.update(content);
this._worksapaceSettings = new ConfigurationModel(this._worksapaceSettings.contents, this._worksapaceSettings.keys, this.overrides);
this._workspaceConfiguration = this.consolidate();
}
get folders(): IStoredWorkspaceFolder[] {
return this._folders;
}
get workspaceConfiguration(): ConfigurationModel<T> {
return this._workspaceConfiguration;
}
protected processRaw(raw: T): 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));
}
private consolidate(): ConfigurationModel<T> {
const keys: string[] = [...this._worksapaceSettings.keys,
...this._tasksConfiguration.keys.map(key => `tasks.${key}`),
...this._launchConfiguration.keys.map(key => `launch.${key}`)];
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);
}
}
export class ScopedConfigurationModel<T> extends CustomConfigurationModel<T> {
constructor(content: string, name: string, public readonly scope: string) {
super(null, name);
this.update(content);
}
public update(content: string): void {
super.update(content);
const contents = Object.create(null);
contents[this.scope] = this.contents;
this._contents = contents;
}
}
export class FolderSettingsModel<T> extends CustomConfigurationModel<T> {
private _raw: T;
private _unsupportedKeys: string[];
protected processRaw(raw: T): 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);
}
public reprocess(): void {
this.processRaw(this._raw);
}
public get unsupportedKeys(): string[] {
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> {
return this.createScopedConfigurationModel(ConfigurationScope.WINDOW);
}
public createFolderScopedConfigurationModel(): ConfigurationModel<any> {
return this.createScopedConfigurationModel(ConfigurationScope.RESOURCE);
}
private createScopedConfigurationModel(scope: ConfigurationScope): ConfigurationModel<any> {
const workspaceRaw = <T>{};
const configurationProperties = Registry.as<IConfigurationRegistry>(Extensions.Configuration).getConfigurationProperties();
for (let key in this._raw) {
if (this.getScope(key, configurationProperties) === scope) {
workspaceRaw[key] = this._raw[key];
}
}
const workspaceContents = toValuesTree(workspaceRaw, message => console.error(`Conflict in workspace settings file: ${message}`));
const workspaceKeys = Object.keys(workspaceRaw);
return new ConfigurationModel(workspaceContents, workspaceKeys, clone(this._overrides));
}
private getScope(key: string, configurationProperties: { [qualifiedKey: string]: IConfigurationPropertySchema }): ConfigurationScope {
const propertySchema = configurationProperties[key];
return propertySchema ? propertySchema.scope : ConfigurationScope.WINDOW;
}
}
export class FolderConfigurationModel<T> extends CustomConfigurationModel<T> {
constructor(public readonly workspaceSettingsConfig: FolderSettingsModel<T>, private scopedConfigs: ScopedConfigurationModel<T>[], private scope: ConfigurationScope) {
super();
this.consolidate();
}
private consolidate(): void {
this._contents = <T>{};
this._overrides = [];
this.doMerge(this, ConfigurationScope.WINDOW === this.scope ? this.workspaceSettingsConfig : this.workspaceSettingsConfig.createFolderScopedConfigurationModel());
for (const configModel of this.scopedConfigs) {
this.doMerge(this, configModel);
}
}
public get keys(): string[] {
const keys: string[] = [...this.workspaceSettingsConfig.keys];
this.scopedConfigs.forEach(scopedConfigModel => {
Object.keys(WORKSPACE_STANDALONE_CONFIGURATIONS).forEach(scope => {
if (scopedConfigModel.scope === scope) {
keys.push(...scopedConfigModel.keys.map(key => `${scope}.${key}`));
}
});
});
return keys;
}
public update(): void {
this.workspaceSettingsConfig.reprocess();
this.consolidate();
}
}

View File

@@ -0,0 +1,41 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import URI from 'vs/base/common/uri';
import { TPromise } from 'vs/base/common/winjs.base';
import { createDecorator, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation';
export const IJSONEditingService = createDecorator<IJSONEditingService>('jsonEditingService');
export enum JSONEditingErrorCode {
/**
* Error when trying to write and save to the file while it is dirty in the editor.
*/
ERROR_FILE_DIRTY,
/**
* Error when trying to write to a file that contains JSON errors.
*/
ERROR_INVALID_FILE
}
export class JSONEditingError extends Error {
constructor(message: string, public code: JSONEditingErrorCode) {
super(message);
}
}
export interface IJSONValue {
key: string;
value: any;
}
export interface IJSONEditingService {
_serviceBrand: ServiceIdentifier<any>;
write(resource: URI, value: IJSONValue, save: boolean): TPromise<void>;
}

View File

@@ -0,0 +1,916 @@
/*---------------------------------------------------------------------------------------------
* 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 * 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 { 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';
interface IStat {
resource: URI;
isDirectory?: boolean;
children?: { resource: URI; }[];
}
interface IContent {
resource: URI;
value: string;
}
interface IWorkspaceConfiguration<T> {
workspace: T;
consolidated: any;
}
type IWorkspaceFoldersConfiguration = { [rootFolder: string]: { folders: string[]; } };
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);
}
}
}
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();
}
});
}
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 {
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 {
private _workspaceConfigPath: URI;
private _workspaceConfigurationWatcher: ConfigWatcher<WorkspaceConfigurationModel<any>>;
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();
}
this._workspaceConfigPath = workspaceConfigPath;
this._workspaceConfigurationWatcherDisposables = dispose(this._workspaceConfigurationWatcherDisposables);
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[]) => {
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);
});
}
get workspaceConfigurationModel(): WorkspaceConfigurationModel<any> {
return this._workspaceConfigurationWatcher ? this._workspaceConfigurationWatcher.getConfig() : new WorkspaceConfigurationModel();
}
private _reload(): TPromise<void> {
return new TPromise<void>(c => this._workspaceConfigurationWatcher.reload(() => c(null)));
}
dispose(): void {
dispose(this._workspaceConfigurationWatcherDisposables);
super.dispose();
}
}
class FolderConfiguration<T> extends Disposable {
private static RELOAD_CONFIGURATION_DELAY = 50;
private bulkFetchFromWorkspacePromise: TPromise<any>;
private workspaceFilePathToConfiguration: { [relativeWorkspacePath: string]: TPromise<ConfigurationModel<any>> };
private reloadConfigurationScheduler: RunOnceScheduler;
private reloadConfigurationEventEmitter: Emitter<FolderConfigurationModel<T>> = new Emitter<FolderConfigurationModel<T>>();
constructor(private folder: URI, private configFolderRelativePath: string, private scope: ConfigurationScope) {
super();
this.workspaceFilePathToConfiguration = Object.create(null);
this.reloadConfigurationScheduler = this._register(new RunOnceScheduler(() => this.loadConfiguration().then(configuration => this.reloadConfigurationEventEmitter.fire(configuration), errors.onUnexpectedError), FolderConfiguration.RELOAD_CONFIGURATION_DELAY));
}
loadConfiguration(): TPromise<FolderConfigurationModel<T>> {
// 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);
});
}
private loadWorkspaceConfigFiles<T>(): TPromise<{ [relativeWorkspacePath: string]: ConfigurationModel<T> }> {
// 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 => {
if (!stat.isDirectory) {
return TPromise.as([]);
}
return resolveContents(stat.children.filter(stat => {
const isJson = paths.extname(stat.resource.fsPath) === '.json';
if (!isJson) {
return false; // only JSON files
}
return this.isWorkspaceConfigurationFile(this.toFolderRelativePath(stat.resource)); // only workspace config files
}).map(stat => stat.resource));
}, err => [] /* never fail this call */)
.then((contents: IContent[]) => {
contents.forEach(content => this.workspaceFilePathToConfiguration[this.toFolderRelativePath(content.resource)] = TPromise.as(this.createConfigModel(content)));
}, errors.onUnexpectedError);
}
// on change: join on *all* configuration file promises so that we can merge them into a single configuration object. this
// happens whenever a config file changes, is deleted, or added
return this.bulkFetchFromWorkspacePromise.then(() => TPromise.join(this.workspaceFilePathToConfiguration));
}
public handleWorkspaceFileEvents(event: FileChangesEvent): TPromise<FolderConfigurationModel<T>> {
const events = event.changes;
let affectedByChanges = false;
// Find changes that affect workspace configuration files
for (let i = 0, len = events.length; i < len; i++) {
const resource = events[i].resource;
const isJson = paths.extname(resource.fsPath) === '.json';
const isDeletedSettingsFolder = (events[i].type === FileChangeType.DELETED && paths.isEqual(paths.basename(resource.fsPath), this.configFolderRelativePath));
if (!isJson && !isDeletedSettingsFolder) {
continue; // only JSON files or the actual settings folder
}
const workspacePath = this.toFolderRelativePath(resource);
if (!workspacePath) {
continue; // event is not inside workspace
}
// Handle case where ".vscode" got deleted
if (workspacePath === this.configFolderRelativePath && events[i].type === FileChangeType.DELETED) {
this.workspaceFilePathToConfiguration = Object.create(null);
affectedByChanges = true;
}
// only valid workspace config files
if (!this.isWorkspaceConfigurationFile(workspacePath)) {
continue;
}
// insert 'fetch-promises' for add and update events and
// remove promises for delete events
switch (events[i].type) {
case FileChangeType.DELETED:
affectedByChanges = collections.remove(this.workspaceFilePathToConfiguration, workspacePath);
break;
case FileChangeType.UPDATED:
case FileChangeType.ADDED:
this.workspaceFilePathToConfiguration[workspacePath] = resolveContent(resource).then(content => this.createConfigModel(content), errors.onUnexpectedError);
affectedByChanges = true;
}
}
if (!affectedByChanges) {
return TPromise.as(null);
}
return new TPromise((c, e) => {
let disposable = this.reloadConfigurationEventEmitter.event(configuration => {
disposable.dispose();
c(configuration);
});
// trigger reload of the configuration if we are affected by changes
if (!this.reloadConfigurationScheduler.isScheduled()) {
this.reloadConfigurationScheduler.schedule();
}
});
}
private createConfigModel<T>(content: IContent): ConfigurationModel<T> {
const path = this.toFolderRelativePath(content.resource);
if (path === WORKSPACE_CONFIG_DEFAULT_PATH) {
return new FolderSettingsModel<T>(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 CustomConfigurationModel<T>(null);
}
private isWorkspaceConfigurationFile(folderRelativePath: string): boolean {
return [WORKSPACE_CONFIG_DEFAULT_PATH, WORKSPACE_STANDALONE_CONFIGURATIONS.launch, WORKSPACE_STANDALONE_CONFIGURATIONS.tasks].some(p => p === folderRelativePath);
}
private toResource(folderRelativePath: string): URI {
if (typeof folderRelativePath === 'string') {
return URI.file(paths.join(this.folder.fsPath, folderRelativePath));
}
return null;
}
private toFolderRelativePath(resource: URI, toOSPath?: boolean): string {
if (this.contains(resource)) {
return paths.normalize(paths.relative(this.folder.fsPath, resource.fsPath), toOSPath);
}
return null;
}
private contains(resource: URI): boolean {
if (resource) {
return paths.isEqualOrParent(resource.fsPath, this.folder.fsPath, !isLinux /* ignorecase */);
}
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;
}
}

View File

@@ -0,0 +1,353 @@
/*---------------------------------------------------------------------------------------------
* 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 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';
import strings = require('vs/base/common/strings');
import { setProperty } from 'vs/base/common/jsonEdit';
import { Queue } from 'vs/base/common/async';
import { Edit } from 'vs/base/common/jsonFormatter';
import { IReference } from 'vs/base/common/lifecycle';
import * as editorCommon from 'vs/editor/common/editorCommon';
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 { 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 { 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';
interface IConfigurationEditOperation extends IConfigurationValue {
jsonPath: json.JSONPath;
resource: URI;
isWorkspaceStandalone?: boolean;
}
interface IValidationResult {
error?: ConfigurationEditingErrorCode;
exists?: boolean;
}
interface ConfigurationEditingOptions extends IConfigurationEditingOptions {
force?: boolean;
}
export class ConfigurationEditingService implements IConfigurationEditingService {
public _serviceBrand: any;
private queue: Queue<void>;
constructor(
@IConfigurationService private configurationService: IConfigurationService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IEnvironmentService private environmentService: IEnvironmentService,
@IFileService private fileService: IFileService,
@ITextModelService private textModelResolverService: ITextModelService,
@ITextFileService private textFileService: ITextFileService,
@IChoiceService private choiceService: IChoiceService,
@IMessageService private messageService: IMessageService,
@ICommandService private commandService: ICommandService
) {
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
.then(() => null,
error => {
if (!options.donotNotifyError) {
this.onError(error, target, value, options.scopes);
}
return TPromise.wrapError(error);
}));
}
private doWriteConfiguration(target: ConfigurationTarget, value: IConfigurationValue, options: ConfigurationEditingOptions): TPromise<void> {
const operation = this.getConfigurationEditOperation(target, value, options.scopes || {});
const checkDirtyConfiguration = !(options.force || options.donotSave);
const saveConfiguration = options.force || !options.donotSave;
return this.resolveAndValidate(target, operation, checkDirtyConfiguration, options.scopes || {})
.then(reference => this.writeToBuffer(reference.object.textEditorModel, operation, saveConfiguration)
.then(() => reference.dispose()));
}
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 TPromise.as(null);
}
private applyEditsToBuffer(edit: Edit, model: editorCommon.IModel): boolean {
const startPosition = model.getPositionAt(edit.offset);
const endPosition = model.getPositionAt(edit.offset + edit.length);
const range = new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
let currentText = model.getValueInRange(range);
if (edit.content !== currentText) {
const editOperation = currentText ? EditOperation.replace(range, edit.content) : EditOperation.insert(startPosition, edit.content);
model.pushEditOperations([new Selection(startPosition.lineNumber, startPosition.column, startPosition.lineNumber, startPosition.column)], [editOperation], () => []);
return true;
}
return false;
}
private onError(error: ConfigurationEditingError, target: ConfigurationTarget, value: IConfigurationValue, scopes: IConfigurationOverrides): void {
switch (error.code) {
case ConfigurationEditingErrorCode.ERROR_INVALID_CONFIGURATION:
this.onInvalidConfigurationError(error, target);
break;
case ConfigurationEditingErrorCode.ERROR_CONFIGURATION_FILE_DIRTY:
this.onConfigurationFileDirtyError(error, target, value, 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 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 openSettings(target: ConfigurationTarget): void {
this.commandService.executeCommand(ConfigurationTarget.USER === target ? 'workbench.action.openGlobalSettings' : 'workbench.action.openWorkspaceSettings');
}
private wrapError<T = never>(code: ConfigurationEditingErrorCode, target: ConfigurationTarget, operation: IConfigurationEditOperation): TPromise<T> {
const message = this.toErrorMessage(code, target, operation);
return TPromise.wrapError<T>(new ConfigurationEditingError(message, code));
}
private toErrorMessage(error: ConfigurationEditingErrorCode, target: ConfigurationTarget, operation: IConfigurationEditOperation): string {
switch (error) {
// API constraints
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_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.");
}
return nls.localize('errorInvalidConfigurationWorkspace', "Unable to write into settings. Please open **Workspace Settings** to correct errors/warnings in the file and try again.");
};
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.");
}
return nls.localize('errorConfigurationFileDirtyWorkspace', "Unable to write into settings because the file is dirty. Please save the **Workspace Settings** file and try again.");
};
}
}
private stringifyTarget(target: ConfigurationTarget): string {
switch (target) {
case ConfigurationTarget.USER:
return nls.localize('userTarget', "User Settings");
case ConfigurationTarget.WORKSPACE:
return nls.localize('workspaceTarget', "Workspace Settings");
case ConfigurationTarget.FOLDER:
return nls.localize('folderTarget', "Folder Settings");
}
}
private getEdits(model: editorCommon.IModel, edit: IConfigurationEditOperation): Edit[] {
const { tabSize, insertSpaces } = model.getOptions();
const eol = model.getEOL();
const { value, jsonPath } = edit;
// Without jsonPath, the entire configuration file is being replaced, so we just use JSON.stringify
if (!jsonPath.length) {
const content = JSON.stringify(value, null, insertSpaces ? strings.repeat(' ', tabSize) : '\t');
return [{
content,
length: content.length,
offset: 0
}];
}
return setProperty(model.getValue(), jsonPath, value, { tabSize, insertSpaces, eol });
}
private resolveModelReference(resource: URI): TPromise<IReference<ITextEditorModel>> {
return this.fileService.existsFile(resource)
.then(exists => {
const result = exists ? TPromise.as(null) : this.fileService.updateContent(resource, '{}', { encoding: encoding.UTF8 });
return result.then(() => this.textModelResolverService.createModelReference(resource));
});
}
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) {
return false;
}
const parseErrors: json.ParseError[] = [];
json.parse(model.getValue(), parseErrors, { allowTrailingComma: true });
return parseErrors.length > 0;
}
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) {
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);
}
// Target cannot be workspace or folder if no workspace opened
if ((target === ConfigurationTarget.WORKSPACE || target === ConfigurationTarget.FOLDER) && !this.contextService.hasWorkspace()) {
return this.wrapError(ConfigurationEditingErrorCode.ERROR_NO_WORKSPACE_OPENED, target, operation);
}
if (target === ConfigurationTarget.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);
}
}
return this.resolveModelReference(operation.resource)
.then(reference => {
const model = reference.object.textEditorModel;
if (this.hasParseErrors(model, operation)) {
return this.wrapError<typeof reference>(ConfigurationEditingErrorCode.ERROR_INVALID_CONFIGURATION, target, operation);
}
// Target cannot be dirty if not writing into buffer
if (checkDirty && this.textFileService.isDirty(operation.resource)) {
return this.wrapError<typeof reference>(ConfigurationEditingErrorCode.ERROR_CONFIGURATION_FILE_DIRTY, target, operation);
}
return reference;
});
}
private getConfigurationEditOperation(target: ConfigurationTarget, config: IConfigurationValue, overrides: IConfigurationOverrides): IConfigurationEditOperation {
const workspace = this.contextService.getWorkspace();
// Check for standalone workspace configurations
if (config.key) {
const standaloneConfigurationKeys = Object.keys(WORKSPACE_STANDALONE_CONFIGURATIONS);
for (let i = 0; i < standaloneConfigurationKeys.length; i++) {
const key = standaloneConfigurationKeys[i];
const resource = this.getConfigurationFileResource(target, WORKSPACE_STANDALONE_CONFIGURATIONS[key], overrides.resource);
// 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 };
}
// 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 };
}
}
}
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) };
}
const resource = this.getConfigurationFileResource(target, WORKSPACE_CONFIG_DEFAULT_PATH, overrides.resource);
if (workspace && workspace.configuration && resource && workspace.configuration.fsPath === resource.fsPath) {
jsonPath = ['settings', ...jsonPath];
}
return { key, jsonPath, value: config.value, resource };
}
private getConfigurationFileResource(target: ConfigurationTarget, relativePath: string, resource: URI): URI {
if (target === ConfigurationTarget.USER) {
return URI.file(this.environmentService.appSettingsPath);
}
const workspace = this.contextService.getWorkspace();
if (workspace) {
if (target === ConfigurationTarget.WORKSPACE) {
return this.contextService.hasMultiFolderWorkspace() ? workspace.configuration : this.toResource(relativePath, workspace.roots[0]);
}
if (target === ConfigurationTarget.FOLDER && this.contextService.hasMultiFolderWorkspace()) {
if (resource) {
const root = this.contextService.getRoot(resource);
if (root) {
return this.toResource(relativePath, root);
}
}
}
}
return null;
}
private toResource(relativePath: string, root: URI): URI {
return URI.file(paths.join(root.fsPath, relativePath));
}
}

View File

@@ -0,0 +1,134 @@
/*---------------------------------------------------------------------------------------------
* 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 { TPromise } from 'vs/base/common/winjs.base';
import URI from 'vs/base/common/uri';
import * as json from 'vs/base/common/json';
import * as encoding from 'vs/base/node/encoding';
import * as strings from 'vs/base/common/strings';
import { setProperty } from 'vs/base/common/jsonEdit';
import { Queue } from 'vs/base/common/async';
import { Edit } from 'vs/base/common/jsonFormatter';
import { IReference } from 'vs/base/common/lifecycle';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IFileService } from 'vs/platform/files/common/files';
import { ITextModelService, ITextEditorModel } from 'vs/editor/common/services/resolverService';
import { IJSONEditingService, IJSONValue, JSONEditingError, JSONEditingErrorCode } from 'vs/workbench/services/configuration/common/jsonEditing';
export class JSONEditingService implements IJSONEditingService {
public _serviceBrand: any;
private queue: Queue<void>;
constructor(
@IFileService private fileService: IFileService,
@ITextModelService private textModelResolverService: ITextModelService,
@ITextFileService private textFileService: ITextFileService
) {
this.queue = new Queue<void>();
}
write(resource: URI, value: IJSONValue, save: boolean): TPromise<void> {
return this.queue.queue(() => this.doWriteConfiguration(resource, value, save)); // queue up writes to prevent race conditions
}
private doWriteConfiguration(resource: URI, value: IJSONValue, save: boolean): TPromise<void> {
return this.resolveAndValidate(resource, save)
.then(reference => this.writeToBuffer(reference.object.textEditorModel, value));
}
private writeToBuffer(model: editorCommon.IModel, value: IJSONValue): TPromise<any> {
const edit = this.getEdits(model, value)[0];
if (this.applyEditsToBuffer(edit, model)) {
return this.textFileService.save(model.uri);
}
return TPromise.as(null);
}
private applyEditsToBuffer(edit: Edit, model: editorCommon.IModel): boolean {
const startPosition = model.getPositionAt(edit.offset);
const endPosition = model.getPositionAt(edit.offset + edit.length);
const range = new Range(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
let currentText = model.getValueInRange(range);
if (edit.content !== currentText) {
const editOperation = currentText ? EditOperation.replace(range, edit.content) : EditOperation.insert(startPosition, edit.content);
model.pushEditOperations([new Selection(startPosition.lineNumber, startPosition.column, startPosition.lineNumber, startPosition.column)], [editOperation], () => []);
return true;
}
return false;
}
private getEdits(model: editorCommon.IModel, configurationValue: IJSONValue): Edit[] {
const { tabSize, insertSpaces } = model.getOptions();
const eol = model.getEOL();
const { key, value } = configurationValue;
// Without key, the entire settings file is being replaced, so we just use JSON.stringify
if (!key) {
const content = JSON.stringify(value, null, insertSpaces ? strings.repeat(' ', tabSize) : '\t');
return [{
content,
length: content.length,
offset: 0
}];
}
return setProperty(model.getValue(), [key], value, { tabSize, insertSpaces, eol });
}
private resolveModelReference(resource: URI): TPromise<IReference<ITextEditorModel>> {
return this.fileService.existsFile(resource)
.then(exists => {
const result = exists ? TPromise.as(null) : this.fileService.updateContent(resource, '{}', { encoding: encoding.UTF8 });
return result.then(() => this.textModelResolverService.createModelReference(resource));
});
}
private hasParseErrors(model: editorCommon.IModel): boolean {
const parseErrors: json.ParseError[] = [];
json.parse(model.getValue(), parseErrors, { allowTrailingComma: true });
return parseErrors.length > 0;
}
private resolveAndValidate(resource: URI, checkDirty: boolean): TPromise<IReference<ITextEditorModel>> {
return this.resolveModelReference(resource)
.then(reference => {
const model = reference.object.textEditorModel;
if (this.hasParseErrors(model)) {
return this.wrapError<IReference<ITextEditorModel>>(JSONEditingErrorCode.ERROR_INVALID_FILE);
}
// Target cannot be dirty if not writing into buffer
if (checkDirty && this.textFileService.isDirty(resource)) {
return this.wrapError<IReference<ITextEditorModel>>(JSONEditingErrorCode.ERROR_FILE_DIRTY);
}
return reference;
});
}
private wrapError<T>(code: JSONEditingErrorCode): TPromise<T> {
const message = this.toErrorMessage(code);
return TPromise.wrapError<T>(new JSONEditingError(message, code));
}
private toErrorMessage(error: JSONEditingErrorCode): string {
switch (error) {
// User issues
case JSONEditingErrorCode.ERROR_INVALID_FILE: {
return nls.localize('errorInvalidFile', "Unable to write into the file. Please open the file to correct errors/warnings in the file and try again.");
};
case JSONEditingErrorCode.ERROR_FILE_DIRTY: {
return nls.localize('errorFileDirty', "Unable to write into the file because the file is dirty. Please save the file and try again.");
};
}
}
}

View File

@@ -0,0 +1,97 @@
/*---------------------------------------------------------------------------------------------
* 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 { FolderConfigurationModel, ScopedConfigurationModel, FolderSettingsModel } from 'vs/workbench/services/configuration/common/configurationModels';
import { ConfigurationScope } from 'vs/platform/configuration/common/configurationRegistry';
suite('ConfigurationService - Model', () => {
test('Test scoped configs are undefined', () => {
const settingsConfig = new FolderSettingsModel(JSON.stringify({
awesome: true
}));
const testObject = new FolderConfigurationModel(settingsConfig, [], ConfigurationScope.WINDOW);
assert.equal(testObject.getContentsFor('task'), undefined);
});
test('Test consolidate (settings and tasks)', () => {
const settingsConfig = new FolderSettingsModel(JSON.stringify({
awesome: true
}));
const tasksConfig = new ScopedConfigurationModel(JSON.stringify({
awesome: false
}), '', 'tasks');
const expected = {
awesome: true,
tasks: {
awesome: false
}
};
assert.deepEqual(new FolderConfigurationModel(settingsConfig, [tasksConfig], ConfigurationScope.WINDOW).contents, expected);
});
test('Test consolidate (settings and launch)', () => {
const settingsConfig = new FolderSettingsModel(JSON.stringify({
awesome: true
}));
const launchConfig = new ScopedConfigurationModel(JSON.stringify({
awesome: false
}), '', 'launch');
const expected = {
awesome: true,
launch: {
awesome: false
}
};
assert.deepEqual(new FolderConfigurationModel(settingsConfig, [launchConfig], ConfigurationScope.WINDOW).contents, expected);
});
test('Test consolidate (settings and launch and tasks) - launch/tasks wins over settings file', () => {
const settingsConfig = new FolderSettingsModel(JSON.stringify({
awesome: true,
launch: {
launchConfig: 'defined',
otherLaunchConfig: 'alsoDefined'
},
tasks: {
taskConfig: 'defined',
otherTaskConfig: 'alsoDefined'
}
}));
const tasksConfig = new ScopedConfigurationModel(JSON.stringify({
taskConfig: 'overwritten',
}), '', 'tasks');
const launchConfig = new ScopedConfigurationModel(JSON.stringify({
launchConfig: 'overwritten',
}), '', 'launch');
const expected = {
awesome: true,
launch: {
launchConfig: 'overwritten',
otherLaunchConfig: 'alsoDefined'
},
tasks: {
taskConfig: 'overwritten',
otherTaskConfig: 'alsoDefined'
}
};
assert.deepEqual(new FolderConfigurationModel(settingsConfig, [launchConfig, tasksConfig], ConfigurationScope.WINDOW).contents, expected);
assert.deepEqual(new FolderConfigurationModel(settingsConfig, [tasksConfig, launchConfig], ConfigurationScope.WINDOW).contents, expected);
});
});

View File

@@ -0,0 +1,464 @@
/*---------------------------------------------------------------------------------------------
* 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();
});
});
});
});
});
});

View File

@@ -0,0 +1,315 @@
/*---------------------------------------------------------------------------------------------
* 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 sinon from 'sinon';
import assert = require('assert');
import os = require('os');
import path = require('path');
import fs = require('fs');
import * as json from 'vs/base/common/json';
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 { 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 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 { 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 { 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 { 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 { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { IWorkspacesService } from 'vs/platform/workspaces/common/workspaces';
class SettingsTestEnvironmentService extends EnvironmentService {
constructor(args: ParsedArgs, _execPath: string, private customAppSettingsHome) {
super(args, _execPath);
}
get appSettingsPath(): string { return this.customAppSettingsHome; }
}
suite('ConfigurationEditingService', () => {
let instantiationService: TestInstantiationService;
let testObject: ConfigurationEditingService;
let parentDir;
let workspaceDir;
let globalSettingsFile;
let workspaceSettingsDir;
let choiceService;
suiteSetup(() => {
const configurationRegistry = <IConfigurationRegistry>Registry.as(ConfigurationExtensions.Configuration);
configurationRegistry.registerConfiguration({
'id': '_test',
'type': 'object',
'properties': {
'configurationEditing.service.testSetting': {
'type': 'string',
'default': 'isSet'
},
'configurationEditing.service.testSettingTwo': {
'type': 'string',
'default': 'isSet'
},
'configurationEditing.service.testSettingThree': {
'type': 'string',
'default': 'isSet'
}
}
});
});
setup(() => {
return setUpWorkspace()
.then(() => setUpServices());
});
function setUpWorkspace(): TPromise<void> {
return new TPromise<void>((c, e) => {
const id = uuid.generateUuid();
parentDir = path.join(os.tmpdir(), 'vsctests', id);
workspaceDir = path.join(parentDir, 'workspaceconfig', id);
globalSettingsFile = path.join(workspaceDir, 'config.json');
// {{SQL CARBON EDIT}}
workspaceSettingsDir = path.join(workspaceDir, '.sqlops');
extfs.mkdirp(workspaceSettingsDir, 493, (error) => {
if (error) {
e(error);
} else {
c(null);
}
});
});
}
function setUpServices(noWorkspace: boolean = false): TPromise<void> {
// Clear services if they are already created
clearServices();
instantiationService = new TestInstantiationService();
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);
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);
}
});
instantiationService.stub(IMessageService, {
show: (severity, message, options, cancelId): void => { }
});
testObject = instantiationService.createInstance(ConfigurationEditingService);
return workspaceService.initialize();
}
teardown(() => {
clearServices();
return clearWorkspace();
});
function clearServices(): void {
if (instantiationService) {
const configuraitonService = <WorkspaceService>instantiationService.get(IConfigurationService);
if (configuraitonService) {
configuraitonService.dispose();
}
instantiationService = null;
}
}
function clearWorkspace(): TPromise<void> {
return new TPromise<void>((c, e) => {
if (parentDir) {
extfs.del(parentDir, os.tmpdir(), () => c(null), () => c(null));
} else {
c(null);
}
}).then(() => parentDir = null);
}
test('errors cases - invalid key', () => {
return testObject.writeConfiguration(ConfigurationTarget.WORKSPACE, { key: 'unknown.key', value: 'value' })
.then(() => assert.fail('Should fail with ERROR_UNKNOWN_KEY'),
(error: ConfigurationEditingError) => assert.equal(error.code, ConfigurationEditingErrorCode.ERROR_UNKNOWN_KEY));
});
test('errors cases - invalid target', () => {
return testObject.writeConfiguration(ConfigurationTarget.USER, { key: 'tasks.something', value: 'value' })
.then(() => assert.fail('Should fail with ERROR_INVALID_TARGET'),
(error: ConfigurationEditingError) => assert.equal(error.code, ConfigurationEditingErrorCode.ERROR_INVALID_USER_TARGET));
});
test('errors cases - no workspace', () => {
return setUpServices(true)
.then(() => testObject.writeConfiguration(ConfigurationTarget.WORKSPACE, { key: 'configurationEditing.service.testSetting', value: 'value' }))
.then(() => assert.fail('Should fail with ERROR_NO_WORKSPACE_OPENED'),
(error: ConfigurationEditingError) => assert.equal(error.code, ConfigurationEditingErrorCode.ERROR_NO_WORKSPACE_OPENED));
});
test('errors cases - invalid configuration', () => {
fs.writeFileSync(globalSettingsFile, ',,,,,,,,,,,,,,');
return testObject.writeConfiguration(ConfigurationTarget.USER, { key: 'configurationEditing.service.testSetting', value: 'value' })
.then(() => assert.fail('Should fail with ERROR_INVALID_CONFIGURATION'),
(error: ConfigurationEditingError) => assert.equal(error.code, ConfigurationEditingErrorCode.ERROR_INVALID_CONFIGURATION));
});
test('errors cases - dirty', () => {
instantiationService.stub(ITextFileService, 'isDirty', true);
return testObject.writeConfiguration(ConfigurationTarget.USER, { key: 'configurationEditing.service.testSetting', value: 'value' })
.then(() => assert.fail('Should fail with ERROR_CONFIGURATION_FILE_DIRTY error.'),
(error: ConfigurationEditingError) => assert.equal(error.code, ConfigurationEditingErrorCode.ERROR_CONFIGURATION_FILE_DIRTY));
});
test('dirty error is not thrown if not asked to save', () => {
instantiationService.stub(ITextFileService, 'isDirty', true);
return testObject.writeConfiguration(ConfigurationTarget.USER, { key: 'configurationEditing.service.testSetting', value: 'value' }, { donotSave: true })
.then(() => null, error => assert.fail('Should not fail.'));
});
test('do not notify error', () => {
instantiationService.stub(ITextFileService, 'isDirty', true);
const target = sinon.stub();
instantiationService.stubPromise(IChoiceService, 'choose', target);
return testObject.writeConfiguration(ConfigurationTarget.USER, { key: 'configurationEditing.service.testSetting', value: 'value' }, { donotNotifyError: true })
.then(() => assert.fail('Should fail with ERROR_CONFIGURATION_FILE_DIRTY error.'),
(error: ConfigurationEditingError) => {
assert.equal(false, target.calledOnce);
assert.equal(error.code, ConfigurationEditingErrorCode.ERROR_CONFIGURATION_FILE_DIRTY);
});
});
test('write one setting - empty file', () => {
return testObject.writeConfiguration(ConfigurationTarget.USER, { key: 'configurationEditing.service.testSetting', value: 'value' })
.then(() => {
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');
});
});
test('write one setting - existing file', () => {
fs.writeFileSync(globalSettingsFile, '{ "my.super.setting": "my.super.value" }');
return testObject.writeConfiguration(ConfigurationTarget.USER, { key: 'configurationEditing.service.testSetting', value: 'value' })
.then(() => {
const contents = fs.readFileSync(globalSettingsFile).toString('utf8');
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');
});
});
test('write workspace standalone setting - empty file', () => {
return testObject.writeConfiguration(ConfigurationTarget.WORKSPACE, { key: 'tasks.service.testSetting', value: 'value' })
.then(() => {
const target = path.join(workspaceDir, WORKSPACE_STANDALONE_CONFIGURATIONS['tasks']);
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');
});
});
test('write workspace standalone setting - existing file', () => {
const target = path.join(workspaceDir, WORKSPACE_STANDALONE_CONFIGURATIONS['launch']);
fs.writeFileSync(target, '{ "my.super.setting": "my.super.value" }');
return testObject.writeConfiguration(ConfigurationTarget.WORKSPACE, { key: 'launch.service.testSetting', value: 'value' })
.then(() => {
const contents = fs.readFileSync(target).toString('utf8');
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');
});
});
test('write workspace standalone setting - empty file - full JSON', () => {
return testObject.writeConfiguration(ConfigurationTarget.WORKSPACE, { key: 'tasks', value: { 'version': '1.0.0', tasks: [{ 'taskName': 'myTask' }] } })
.then(() => {
const target = path.join(workspaceDir, WORKSPACE_STANDALONE_CONFIGURATIONS['tasks']);
const contents = fs.readFileSync(target).toString('utf8');
const parsed = json.parse(contents);
assert.equal(parsed['version'], '1.0.0');
assert.equal(parsed['tasks'][0]['taskName'], 'myTask');
});
});
test('write workspace standalone setting - existing file - full JSON', () => {
const target = path.join(workspaceDir, WORKSPACE_STANDALONE_CONFIGURATIONS['launch']);
fs.writeFileSync(target, '{ "my.super.setting": "my.super.value" }');
return testObject.writeConfiguration(ConfigurationTarget.WORKSPACE, { key: 'tasks', value: { 'version': '1.0.0', tasks: [{ 'taskName': 'myTask' }] } })
.then(() => {
const target = path.join(workspaceDir, WORKSPACE_STANDALONE_CONFIGURATIONS['tasks']);
const contents = fs.readFileSync(target).toString('utf8');
const parsed = json.parse(contents);
assert.equal(parsed['version'], '1.0.0');
assert.equal(parsed['tasks'][0]['taskName'], 'myTask');
});
});
test('write workspace standalone setting - existing file with JSON errors - full JSON', () => {
const target = path.join(workspaceDir, WORKSPACE_STANDALONE_CONFIGURATIONS['launch']);
fs.writeFileSync(target, '{ "my.super.setting": '); // invalid JSON
return testObject.writeConfiguration(ConfigurationTarget.WORKSPACE, { key: 'tasks', value: { 'version': '1.0.0', tasks: [{ 'taskName': 'myTask' }] } })
.then(() => {
const target = path.join(workspaceDir, WORKSPACE_STANDALONE_CONFIGURATIONS['tasks']);
const contents = fs.readFileSync(target).toString('utf8');
const parsed = json.parse(contents);
assert.equal(parsed['version'], '1.0.0');
assert.equal(parsed['tasks'][0]['taskName'], 'myTask');
});
});
});