settingsSync.ts 17.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import * as objects from 'vs/base/common/objects';
import { Disposable } from 'vs/base/common/lifecycle';
import { IFileService, FileSystemProviderErrorCode, FileSystemProviderError, IFileContent } from 'vs/platform/files/common/files';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
11
import { IRemoteUserDataService, IUserData, RemoteUserDataError, RemoteUserDataErrorCode, ISynchroniser, SyncStatus } from 'vs/workbench/services/userData/common/userData';
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
import { VSBuffer } from 'vs/base/common/buffer';
import { parse, JSONPath } from 'vs/base/common/json';
import { ITextModelService, ITextModelContentProvider } from 'vs/editor/common/services/resolverService';
import { URI } from 'vs/base/common/uri';
import { ITextModel } from 'vs/editor/common/model';
import { isEqual } from 'vs/base/common/resources';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { localize } from 'vs/nls';
import { Edit } from 'vs/base/common/jsonFormatter';
import { repeat } from 'vs/base/common/strings';
import { setProperty } from 'vs/base/common/jsonEdit';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { EditOperation } from 'vs/editor/common/core/editOperation';
28
import { Emitter, Event } from 'vs/base/common/event';
29 30 31 32 33 34 35

interface ISyncPreviewResult {
	readonly fileContent: IFileContent | null;
	readonly remoteUserData: IUserData | null;
	readonly localSettingsPreviewModel: ITextModel;
	readonly remoteSettingsPreviewModel: ITextModel;
	readonly hasChanges: boolean;
36
	readonly hasConflicts: boolean;
37 38
}

39
export class SettingsSyncService extends Disposable implements ISynchroniser, ITextModelContentProvider {
S
Sandeep Somavarapu 已提交
40
	_serviceBrand: undefined;
41 42 43 44 45 46 47 48 49

	private static LAST_SYNC_SETTINGS_STORAGE_KEY: string = 'LAST_SYNC_SETTINGS_CONTENTS';
	private static EXTERNAL_USER_DATA_SETTINGS_KEY: string = 'settings';

	private readonly remoteSettingsPreviewResource: URI;
	private readonly localSettingsPreviewResource: URI;

	private syncPreviewResultPromise: Promise<ISyncPreviewResult> | null = null;

50 51 52 53 54
	private _status: SyncStatus = SyncStatus.Idle;
	get status(): SyncStatus { return this._status; }
	private _onDidChangStatus: Emitter<SyncStatus> = this._register(new Emitter<SyncStatus>());
	readonly onDidChangeStatus: Event<SyncStatus> = this._onDidChangStatus.event;

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
	constructor(
		@IFileService private readonly fileService: IFileService,
		@IWorkbenchEnvironmentService private readonly workbenchEnvironmentService: IWorkbenchEnvironmentService,
		@IStorageService private readonly storageService: IStorageService,
		@IRemoteUserDataService private readonly remoteUserDataService: IRemoteUserDataService,
		@ITextModelService private readonly textModelResolverService: ITextModelService,
		@IModelService private readonly modelService: IModelService,
		@IModeService private readonly modeService: IModeService,
		@IEditorService private readonly editorService: IEditorService
	) {
		super();

		this.remoteSettingsPreviewResource = URI.file('remote').with({ scheme: 'vscode-settings-sync' });
		this.localSettingsPreviewResource = this.workbenchEnvironmentService.settingsResource.with({ scheme: 'vscode-settings-sync' });

		this.textModelResolverService.registerTextModelContentProvider('vscode-settings-sync', this);
	}

	provideTextContent(uri: URI): Promise<ITextModel> | null {
		if (isEqual(this.remoteSettingsPreviewResource, uri, false)) {
			return this.getPreview().then(({ remoteSettingsPreviewModel }) => remoteSettingsPreviewModel);
		}
		if (isEqual(this.localSettingsPreviewResource, uri, false)) {
			return this.getPreview().then(({ localSettingsPreviewModel }) => localSettingsPreviewModel);
		}
		return null;
	}

83 84 85 86 87 88 89 90 91 92 93 94 95 96
	private setStatus(status: SyncStatus): void {
		if (this._status !== status) {
			this._status = status;
			this._onDidChangStatus.fire(status);
		}
	}

	async sync(): Promise<boolean> {

		if (this.status !== SyncStatus.Idle) {
			return false;
		}

		this.setStatus(SyncStatus.Syncing);
97

S
Sandeep Somavarapu 已提交
98 99 100 101 102 103 104 105 106 107 108
		try {
			const result = await this.getPreview();
			if (result.hasConflicts) {
				this.setStatus(SyncStatus.HasConflicts);
				return false;
			}
			await this.apply();
			return true;
		} catch (e) {
			this.setStatus(SyncStatus.Idle);
			throw e;
109
		}
110
	}
111

112 113 114 115 116 117 118 119 120 121 122 123 124
	resolveConflicts(): void {
		if (this.status === SyncStatus.HasConflicts) {
			this.editorService.openEditor({
				leftResource: this.remoteSettingsPreviewResource,
				rightResource: this.localSettingsPreviewResource,
				label: localize('fileReplaceChanges', "Remote Settings ↔ Local Settings (Settings Preview)"),
				options: {
					preserveFocus: false,
					pinned: true,
					revealIfVisible: true
				}
			});
		}
125 126
	}

127 128 129 130 131 132 133 134 135 136 137 138 139
	async apply(): Promise<void> {
		if (this.syncPreviewResultPromise) {
			const { fileContent, remoteUserData, localSettingsPreviewModel, remoteSettingsPreviewModel, hasChanges } = await this.syncPreviewResultPromise;
			if (hasChanges) {
				const syncedRemoteUserData = remoteUserData && remoteUserData.content === remoteSettingsPreviewModel.getValue() ? remoteUserData : { content: remoteSettingsPreviewModel.getValue(), version: remoteUserData ? remoteUserData.version + 1 : 1 };
				if (!(remoteUserData && remoteUserData.version === syncedRemoteUserData.version)) {
					await this.writeToRemote(syncedRemoteUserData);
				}
				await this.writeToLocal(localSettingsPreviewModel.getValue(), fileContent, syncedRemoteUserData);
			}
			if (remoteUserData) {
				this.updateLastSyncValue(remoteUserData);
			}
140
		}
141 142
		this.syncPreviewResultPromise = null;
		this.setStatus(SyncStatus.Idle);
143 144 145 146 147 148 149 150 151 152 153
	}

	private getPreview(): Promise<ISyncPreviewResult> {
		if (!this.syncPreviewResultPromise) {
			this.syncPreviewResultPromise = this.generatePreview();
		}
		return this.syncPreviewResultPromise;
	}

	private async generatePreview(): Promise<ISyncPreviewResult> {
		const remoteUserData = await this.remoteUserDataService.read(SettingsSyncService.EXTERNAL_USER_DATA_SETTINGS_KEY);
154
		const fileContent = await this.getLocalFileContent();
155 156

		const localSettingsPreviewModel = this.modelService.getModel(this.localSettingsPreviewResource) || this.modelService.createModel('', this.modeService.create('jsonc'), this.localSettingsPreviewResource);
157
		const remoteSettingsPreviewModel = this.modelService.getModel(this.remoteSettingsPreviewResource) || this.modelService.createModel('', this.modeService.create('jsonc'), this.remoteSettingsPreviewResource);
158 159 160 161 162 163

		if (fileContent && !remoteUserData) {
			// Remote does not exist, so sync with local.
			const localContent = fileContent.value.toString();
			localSettingsPreviewModel.setValue(localContent);
			remoteSettingsPreviewModel.setValue(localContent);
164
			return { fileContent, remoteUserData, localSettingsPreviewModel, remoteSettingsPreviewModel, hasChanges: true, hasConflicts: false };
165 166 167 168 169 170 171
		}

		if (remoteUserData && !fileContent) {
			// Settings file does not exist, so sync with remote contents.
			const remoteContent = remoteUserData.content;
			localSettingsPreviewModel.setValue(remoteContent);
			remoteSettingsPreviewModel.setValue(remoteContent);
172
			return { fileContent, remoteUserData, localSettingsPreviewModel, remoteSettingsPreviewModel, hasChanges: true, hasConflicts: false };
173 174 175 176 177 178 179 180 181 182 183 184
		}

		if (fileContent && remoteUserData) {

			const localContent: string = fileContent.value.toString();
			const remoteContent: string = remoteUserData.content;
			const lastSyncData = this.getLastSyncUserData();

			// Already in Sync.
			if (localContent === remoteUserData.content) {
				localSettingsPreviewModel.setValue(localContent);
				remoteSettingsPreviewModel.setValue(remoteContent);
185
				return { fileContent, remoteUserData, localSettingsPreviewModel, remoteSettingsPreviewModel, hasChanges: false, hasConflicts: false };
186 187 188 189 190 191
			}

			// Not synced till now
			if (!lastSyncData) {
				localSettingsPreviewModel.setValue(localContent);
				remoteSettingsPreviewModel.setValue(remoteContent);
192 193
				const hasConflicts = await this.mergeContents(localSettingsPreviewModel, remoteSettingsPreviewModel, null);
				return { fileContent, remoteUserData, localSettingsPreviewModel, remoteSettingsPreviewModel, hasChanges: true, hasConflicts };
194 195 196 197 198 199 200 201 202
			}

			// Remote data is newer than last synced data
			if (remoteUserData.version > lastSyncData.version) {

				// Local content is same as last synced. So, sync with remote content.
				if (lastSyncData.content === localContent) {
					localSettingsPreviewModel.setValue(remoteContent);
					remoteSettingsPreviewModel.setValue(remoteContent);
203
					return { fileContent, remoteUserData, localSettingsPreviewModel, remoteSettingsPreviewModel, hasChanges: true, hasConflicts: false };
204 205 206 207 208
				}

				// Local content is diverged from last synced. Required merge and sync.
				localSettingsPreviewModel.setValue(localContent);
				remoteSettingsPreviewModel.setValue(remoteContent);
209 210
				const hasConflicts = await this.mergeContents(localSettingsPreviewModel, remoteSettingsPreviewModel, lastSyncData.content);
				return { fileContent, remoteUserData, localSettingsPreviewModel, remoteSettingsPreviewModel, hasChanges: true, hasConflicts };
211 212 213 214 215 216 217
			}

			// Remote data is same as last synced data
			if (lastSyncData.version === remoteUserData.version) {

				// Local contents are same as last synced data. No op.
				if (lastSyncData.content === localContent) {
218
					return { fileContent, remoteUserData, localSettingsPreviewModel, remoteSettingsPreviewModel, hasChanges: false, hasConflicts: false };
219 220 221 222 223
				}

				// New local contents. Sync with Local.
				localSettingsPreviewModel.setValue(localContent);
				remoteSettingsPreviewModel.setValue(localContent);
224
				return { fileContent, remoteUserData, localSettingsPreviewModel, remoteSettingsPreviewModel, hasChanges: true, hasConflicts: false };
225 226 227 228
			}

		}

229
		return { fileContent, remoteUserData, localSettingsPreviewModel, remoteSettingsPreviewModel, hasChanges: false, hasConflicts: false };
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251

	}

	private getLastSyncUserData(): IUserData | null {
		const lastSyncStorageContents = this.storageService.get(SettingsSyncService.LAST_SYNC_SETTINGS_STORAGE_KEY, StorageScope.GLOBAL, undefined);
		if (lastSyncStorageContents) {
			return JSON.parse(lastSyncStorageContents);
		}
		return null;
	}

	private async getLocalFileContent(): Promise<IFileContent | null> {
		try {
			return await this.fileService.readFile(this.workbenchEnvironmentService.settingsResource);
		} catch (error) {
			if (error instanceof FileSystemProviderError && error.code !== FileSystemProviderErrorCode.FileNotFound) {
				return null;
			}
			throw error;
		}
	}

252
	private async mergeContents(localSettingsPreviewModel: ITextModel, remoteSettingsPreviewModel: ITextModel, lastSyncedContent: string | null): Promise<boolean> {
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
		const local = parse(localSettingsPreviewModel.getValue());
		const remote = parse(remoteSettingsPreviewModel.getValue());
		const base = lastSyncedContent ? parse(lastSyncedContent) : null;

		const baseToLocal = base ? this.compare(base, local) : { added: new Set<string>(), removed: new Set<string>(), updated: new Set<string>() };
		const baseToRemote = base ? this.compare(base, remote) : { added: new Set<string>(), removed: new Set<string>(), updated: new Set<string>() };
		const localToRemote = this.compare(local, remote);

		const conflicts: Set<string> = new Set<string>();

		// Removed settings in Local
		for (const key of baseToLocal.removed.keys()) {
			// Got updated in remote
			if (baseToRemote.updated.has(key)) {
				conflicts.add(key);
			} else {
				this.removeSetting(remoteSettingsPreviewModel, key);
			}
		}

		// Removed settings in Remote
		for (const key of baseToRemote.removed.keys()) {
			// Got updated in local
			if (baseToLocal.updated.has(key)) {
				conflicts.add(key);
			} else {
				this.removeSetting(localSettingsPreviewModel, key);
			}
		}

		// Added settings in Local
		for (const key of baseToLocal.added.keys()) {
			// Got added in remote
			if (baseToRemote.added.has(key)) {
				// Has different value
				if (localToRemote.updated.has(key)) {
					conflicts.add(key);
				}
			} else {
				const edit = this.getEdit(remoteSettingsPreviewModel, [key], local[key]);
				if (edit) {
					this.applyEditsToBuffer(edit, remoteSettingsPreviewModel);
				}
			}
		}

		// Added settings in remote
		for (const key of baseToRemote.added.keys()) {
			// Got added in local
			if (baseToLocal.added.has(key)) {
				// Has different value
				if (localToRemote.updated.has(key)) {
					conflicts.add(key);
				}
			} else {
				const edit = this.getEdit(localSettingsPreviewModel, [key], remote[key]);
				if (edit) {
					this.applyEditsToBuffer(edit, localSettingsPreviewModel);
				}
			}
		}

		// Updated settings in Local
		for (const key of baseToLocal.updated.keys()) {
			// Got updated in remote
			if (baseToRemote.updated.has(key)) {
				// Has different value
				if (localToRemote.updated.has(key)) {
					conflicts.add(key);
				}
			} else {
				const edit = this.getEdit(remoteSettingsPreviewModel, [key], local[key]);
				if (edit) {
					this.applyEditsToBuffer(edit, remoteSettingsPreviewModel);
				}
			}
		}

		// Updated settings in Remote
		for (const key of baseToRemote.updated.keys()) {
			// Got updated in local
			if (baseToLocal.updated.has(key)) {
				// Has different value
				if (localToRemote.updated.has(key)) {
					conflicts.add(key);
				}
			} else {
				const edit = this.getEdit(localSettingsPreviewModel, [key], remote[key]);
				if (edit) {
					this.applyEditsToBuffer(edit, localSettingsPreviewModel);
				}
			}
		}
346 347

		return conflicts.size > 0;
348 349 350 351 352 353 354 355 356 357
	}

	private compare(from: { [key: string]: any }, to: { [key: string]: any }): { added: Set<string>, removed: Set<string>, updated: Set<string> } {
		const fromKeys = Object.keys(from);
		const toKeys = Object.keys(to);
		const added = toKeys.filter(key => fromKeys.indexOf(key) === -1).reduce((r, key) => { r.add(key); return r; }, new Set<string>());
		const removed = fromKeys.filter(key => toKeys.indexOf(key) === -1).reduce((r, key) => { r.add(key); return r; }, new Set<string>());
		const updated: Set<string> = new Set<string>();

		for (const key of fromKeys) {
358 359 360
			if (removed.has(key)) {
				continue;
			}
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
			const value1 = from[key];
			const value2 = to[key];
			if (!objects.equals(value1, value2)) {
				updated.add(key);
			}
		}

		return { added, removed, updated };
	}

	private removeSetting(model: ITextModel, key: string): void {
		const edit = this.getEdit(model, [key], undefined);
		if (edit) {
			this.applyEditsToBuffer(edit, model);
		}
	}

	private applyEditsToBuffer(edit: Edit, model: ITextModel): void {
		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], () => []);
		}
	}

	private getEdit(model: ITextModel, jsonPath: JSONPath, value: any): Edit | undefined {
390 391
		const insertSpaces = false;
		const tabSize = 4;
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
		const eol = model.getEOL();

		// 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 ? repeat(' ', tabSize) : '\t');
			return {
				content,
				length: model.getValue().length,
				offset: 0
			};
		}

		return setProperty(model.getValue(), jsonPath, value, { tabSize, insertSpaces, eol })[0];
	}

	private async writeToRemote(userData: IUserData): Promise<void> {
		try {
			await this.remoteUserDataService.write(SettingsSyncService.EXTERNAL_USER_DATA_SETTINGS_KEY, userData.version, userData.content);
		} catch (e) {
411
			if (e instanceof RemoteUserDataError && e.code === RemoteUserDataErrorCode.VersionExists) {
412
				// Rejected as there is a new version. Sync again
413
				await this.sync();
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
			}
			// An unknown error
			throw e;
		}
	}

	private async writeToLocal(newContent: string, oldContent: IFileContent | null, remoteUserData: IUserData): Promise<void> {
		if (oldContent) {
			try {
				// file exists before
				await this.fileService.writeFile(this.workbenchEnvironmentService.settingsResource, VSBuffer.fromString(newContent), oldContent);
			} catch (error) {
				// Error to check for dirty to sync again
				throw error;
			}
		} else {
			try {
				// file does not exist before
				await this.fileService.createFile(this.workbenchEnvironmentService.settingsResource, VSBuffer.fromString(newContent), { overwrite: false });
			} catch (error) {
				if (error instanceof FileSystemProviderError && error.code === FileSystemProviderErrorCode.FileExists) {
435
					await this.sync();
436 437 438 439 440
				}
				throw error;
			}
		}

441 442 443
	}

	private updateLastSyncValue(remoteUserData: IUserData): void {
444 445 446 447
		this.storageService.store(SettingsSyncService.LAST_SYNC_SETTINGS_STORAGE_KEY, JSON.stringify(remoteUserData), StorageScope.GLOBAL);
	}

}