snippetsSync.ts 18.7 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

S
Sandeep Somavarapu 已提交
6
import { SyncStatus, IUserDataSyncStoreService, IUserDataSyncLogService, IUserDataSynchroniser, SyncResource, IUserDataSyncEnablementService, IUserDataSyncBackupStoreService, Conflict, USER_DATA_SYNC_SCHEME, PREVIEW_DIR_NAME, UserDataSyncError, UserDataSyncErrorCode, ISyncResourceHandle, ISyncPreviewResult } from 'vs/platform/userDataSync/common/userDataSync';
7 8 9 10 11 12 13
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IFileService, FileChangesEvent, IFileStat, IFileContent, FileOperationError, FileOperationResult } from 'vs/platform/files/common/files';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { AbstractSynchroniser, IRemoteUserData, ISyncData } from 'vs/platform/userDataSync/common/abstractSynchronizer';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IStringDictionary } from 'vs/base/common/collections';
import { URI } from 'vs/base/common/uri';
14
import { joinPath, extname, relativePath, isEqualOrParent, isEqual, basename, dirname } from 'vs/base/common/resources';
15 16 17 18 19
import { VSBuffer } from 'vs/base/common/buffer';
import { merge } from 'vs/platform/userDataSync/common/snippetsMerge';
import { CancelablePromise, createCancelablePromise } from 'vs/base/common/async';
import { CancellationToken } from 'vs/base/common/cancellation';

S
Sandeep Somavarapu 已提交
20
interface ISinppetsSyncPreviewResult extends ISyncPreviewResult {
21 22 23 24 25 26 27
	readonly local: IStringDictionary<IFileContent>;
	readonly remoteUserData: IRemoteUserData;
	readonly lastSyncUserData: IRemoteUserData | null;
	readonly added: IStringDictionary<string>;
	readonly updated: IStringDictionary<string>;
	readonly removed: string[];
	readonly conflicts: Conflict[];
28
	readonly resolvedConflicts: IStringDictionary<string | null>;
29 30 31 32 33 34 35 36
	readonly remote: IStringDictionary<string> | null;
}

export class SnippetsSynchroniser extends AbstractSynchroniser implements IUserDataSynchroniser {

	protected readonly version: number = 1;
	private readonly snippetsFolder: URI;
	private readonly snippetsPreviewFolder: URI;
S
Sandeep Somavarapu 已提交
37
	private syncPreviewResultPromise: CancelablePromise<ISinppetsSyncPreviewResult> | null = null;
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

	constructor(
		@IEnvironmentService environmentService: IEnvironmentService,
		@IFileService fileService: IFileService,
		@IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService,
		@IUserDataSyncBackupStoreService userDataSyncBackupStoreService: IUserDataSyncBackupStoreService,
		@IUserDataSyncLogService logService: IUserDataSyncLogService,
		@IConfigurationService configurationService: IConfigurationService,
		@IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService,
		@ITelemetryService telemetryService: ITelemetryService,
	) {
		super(SyncResource.Snippets, fileService, environmentService, userDataSyncStoreService, userDataSyncBackupStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService);
		this.snippetsFolder = environmentService.snippetsHome;
		this.snippetsPreviewFolder = joinPath(this.syncFolder, PREVIEW_DIR_NAME);
		this._register(this.fileService.watch(environmentService.userRoamingDataHome));
		this._register(this.fileService.watch(this.snippetsFolder));
		this._register(this.fileService.onDidFilesChange(e => this.onFileChanges(e)));
	}

	private onFileChanges(e: FileChangesEvent): void {
		if (!e.changes.some(change => isEqualOrParent(change.resource, this.snippetsFolder))) {
			return;
		}
		if (!this.isEnabled()) {
			return;
		}
		// Sync again if local file has changed and current status is in conflicts
		if (this.status === SyncStatus.HasConflicts) {
			this.syncPreviewResultPromise!.then(result => {
				this.cancel();
				this.doSync(result.remoteUserData, result.lastSyncUserData).then(status => this.setStatus(status));
			});
		}
		// Otherwise fire change event
		else {
73
			this.triggerLocalChange();
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
		}
	}

	async pull(): Promise<void> {
		if (!this.isEnabled()) {
			this.logService.info(`${this.syncResourceLogLabel}: Skipped pulling snippets as it is disabled.`);
			return;
		}

		this.stop();

		try {
			this.logService.info(`${this.syncResourceLogLabel}: Started pulling snippets...`);
			this.setStatus(SyncStatus.Syncing);

			const lastSyncUserData = await this.getLastSyncUserData();
			const remoteUserData = await this.getRemoteUserData(lastSyncUserData);

			if (remoteUserData.syncData !== null) {
				const local = await this.getSnippetsFileContents();
				const localSnippets = this.toSnippetsContents(local);
				const remoteSnippets = this.parseSnippets(remoteUserData.syncData);
				const { added, updated, remote, removed } = merge(localSnippets, remoteSnippets, localSnippets);
S
Sandeep Somavarapu 已提交
97 98 99 100
				this.syncPreviewResultPromise = createCancelablePromise(() => Promise.resolve<ISinppetsSyncPreviewResult>({
					added, removed, updated, remote, remoteUserData, local, lastSyncUserData, conflicts: [], resolvedConflicts: {},
					hasLocalChanged: Object.keys(added).length > 0 || removed.length > 0 || Object.keys(updated).length > 0,
					hasRemoteChanged: remote !== null
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
				}));
				await this.apply();
			}

			// No remote exists to pull
			else {
				this.logService.info(`${this.syncResourceLogLabel}: Remote snippets does not exist.`);
			}

			this.logService.info(`${this.syncResourceLogLabel}: Finished pulling snippets.`);
		} finally {
			this.setStatus(SyncStatus.Idle);
		}
	}

	async push(): Promise<void> {
		if (!this.isEnabled()) {
			this.logService.info(`${this.syncResourceLogLabel}: Skipped pushing snippets as it is disabled.`);
			return;
		}

		this.stop();

		try {
			this.logService.info(`${this.syncResourceLogLabel}: Started pushing snippets...`);
			this.setStatus(SyncStatus.Syncing);

			const local = await this.getSnippetsFileContents();
			const localSnippets = this.toSnippetsContents(local);
			const { added, removed, updated, remote } = merge(localSnippets, null, null);
			const lastSyncUserData = await this.getLastSyncUserData();
			const remoteUserData = await this.getRemoteUserData(lastSyncUserData);
S
Sandeep Somavarapu 已提交
133 134 135 136
			this.syncPreviewResultPromise = createCancelablePromise(() => Promise.resolve<ISinppetsSyncPreviewResult>({
				added, removed, updated, remote, remoteUserData, local, lastSyncUserData, conflicts: [], resolvedConflicts: {},
				hasLocalChanged: Object.keys(added).length > 0 || removed.length > 0 || Object.keys(updated).length > 0,
				hasRemoteChanged: remote !== null
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
			}));

			await this.apply(true);

			this.logService.info(`${this.syncResourceLogLabel}: Finished pushing snippets.`);
		} finally {
			this.setStatus(SyncStatus.Idle);
		}

	}

	async stop(): Promise<void> {
		await this.clearConflicts();
		this.cancel();
		this.logService.info(`${this.syncResourceLogLabel}: Stopped synchronizing ${this.syncResourceLogLabel}.`);
		this.setStatus(SyncStatus.Idle);
	}

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
	async getAssociatedResources({ uri }: ISyncResourceHandle): Promise<{ resource: URI, comparableResource?: URI }[]> {
		let content = await super.resolveContent(uri);
		if (content) {
			const syncData = this.parseSyncData(content);
			if (syncData) {
				const snippets = this.parseSnippets(syncData);
				const result = [];
				for (const snippet of Object.keys(snippets)) {
					const resource = joinPath(uri, snippet);
					const comparableResource = joinPath(this.snippetsFolder, snippet);
					const exists = await this.fileService.exists(comparableResource);
					result.push({ resource, comparableResource: exists ? comparableResource : undefined });
				}
				return result;
			}
		}
		return [];
	}

	async resolveContent(uri: URI): Promise<string | null> {
		if (isEqualOrParent(uri.with({ scheme: this.syncFolder.scheme }), this.snippetsPreviewFolder)) {
			return this.getConflictContent(uri);
		}
		let content = await super.resolveContent(uri);
		if (content) {
			return content;
		}
		content = await super.resolveContent(dirname(uri));
		if (content) {
			const syncData = this.parseSyncData(content);
			if (syncData) {
				const snippets = this.parseSnippets(syncData);
				return snippets[basename(uri)] || null;
			}
		}
		return null;
	}

	protected async getConflictContent(conflictResource: URI): Promise<string | null> {
		if (this.syncPreviewResultPromise) {
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
			const result = await this.syncPreviewResultPromise;
			const key = relativePath(this.snippetsPreviewFolder, conflictResource.with({ scheme: this.snippetsPreviewFolder.scheme }))!;
			if (conflictResource.scheme === this.snippetsPreviewFolder.scheme) {
				return result.local[key] ? result.local[key].value.toString() : null;
			} else if (result.remoteUserData && result.remoteUserData.syncData) {
				const snippets = this.parseSnippets(result.remoteUserData.syncData);
				return snippets[key] || null;
			}
		}
		return null;
	}

	async acceptConflict(conflictResource: URI, content: string): Promise<void> {
		const conflict = this.conflicts.filter(({ local, remote }) => isEqual(local, conflictResource) || isEqual(remote, conflictResource))[0];
		if (this.status === SyncStatus.HasConflicts && conflict) {
			const key = relativePath(this.snippetsPreviewFolder, conflict.local)!;
211
			let previewResult = await this.syncPreviewResultPromise!;
S
Sandeep Somavarapu 已提交
212
			this.cancel();
213
			previewResult.resolvedConflicts[key] = content || null;
214
			this.syncPreviewResultPromise = createCancelablePromise(token => this.doGeneratePreview(previewResult.local, previewResult.remoteUserData, previewResult.lastSyncUserData, previewResult.resolvedConflicts, token));
215
			previewResult = await this.syncPreviewResultPromise;
S
Sandeep Somavarapu 已提交
216
			this.setConflicts(previewResult.conflicts);
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
			if (!this.conflicts.length) {
				await this.apply();
				this.setStatus(SyncStatus.Idle);
			}
		}
	}

	async hasLocalData(): Promise<boolean> {
		try {
			const localSnippets = await this.getSnippetsFileContents();
			if (Object.keys(localSnippets).length) {
				return true;
			}
		} catch (error) {
			/* ignore error */
		}
		return false;
	}

	protected async performSync(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null): Promise<SyncStatus> {
		try {
			const previewResult = await this.getPreview(remoteUserData, lastSyncUserData);
S
Sandeep Somavarapu 已提交
239 240
			this.setConflicts(previewResult.conflicts);
			if (this.conflicts.length) {
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
				return SyncStatus.HasConflicts;
			}
			await this.apply();
			return SyncStatus.Idle;
		} catch (e) {
			this.syncPreviewResultPromise = null;
			if (e instanceof UserDataSyncError) {
				switch (e.code) {
					case UserDataSyncErrorCode.LocalPreconditionFailed:
						// Rejected as there is a new local version. Syncing again.
						this.logService.info(`${this.syncResourceLogLabel}: Failed to synchronize snippets as there is a new local version available. Synchronizing again...`);
						return this.performSync(remoteUserData, lastSyncUserData);
				}
			}
			throw e;
		}
	}

259 260 261 262 263 264 265 266 267 268 269 270 271
	protected async performReplace(syncData: ISyncData, remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null): Promise<void> {
		const local = await this.getSnippetsFileContents();
		const localSnippets = this.toSnippetsContents(local);
		const snippets = this.parseSnippets(syncData);
		const { added, updated, removed } = merge(localSnippets, snippets, localSnippets);
		this.syncPreviewResultPromise = createCancelablePromise(() => Promise.resolve<ISinppetsSyncPreviewResult>({
			added, removed, updated, remote: snippets, remoteUserData, local, lastSyncUserData, conflicts: [], resolvedConflicts: {},
			hasLocalChanged: Object.keys(added).length > 0 || removed.length > 0 || Object.keys(updated).length > 0,
			hasRemoteChanged: true
		}));
		await this.apply();
	}

S
Sandeep Somavarapu 已提交
272
	protected getPreview(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null): Promise<ISinppetsSyncPreviewResult> {
273
		if (!this.syncPreviewResultPromise) {
274
			this.syncPreviewResultPromise = createCancelablePromise(token => this.generatePreview(remoteUserData, lastSyncUserData, token));
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
		}
		return this.syncPreviewResultPromise;
	}

	protected cancel(): void {
		if (this.syncPreviewResultPromise) {
			this.syncPreviewResultPromise.cancel();
			this.syncPreviewResultPromise = null;
		}
	}

	private async clearConflicts(): Promise<void> {
		if (this.conflicts.length) {
			await Promise.all(this.conflicts.map(({ local }) => this.fileService.del(local)));
			this.setConflicts([]);
		}
	}

293 294 295 296 297 298
	protected async generatePreview(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, token: CancellationToken = CancellationToken.None): Promise<ISinppetsSyncPreviewResult> {
		return this.getSnippetsFileContents()
			.then(local => this.doGeneratePreview(local, remoteUserData, lastSyncUserData, {}, token));
	}

	private async doGeneratePreview(local: IStringDictionary<IFileContent>, remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, resolvedConflicts: IStringDictionary<string | null> = {}, token: CancellationToken = CancellationToken.None): Promise<ISinppetsSyncPreviewResult> {
S
Sandeep Somavarapu 已提交
299
		const localSnippets = this.toSnippetsContents(local);
300
		const remoteSnippets: IStringDictionary<string> | null = remoteUserData.syncData ? this.parseSnippets(remoteUserData.syncData) : null;
S
Sandeep Somavarapu 已提交
301
		const lastSyncSnippets: IStringDictionary<string> | null = lastSyncUserData && lastSyncUserData.syncData ? this.parseSnippets(lastSyncUserData.syncData) : null;
302 303 304 305 306 307 308

		if (remoteSnippets) {
			this.logService.trace(`${this.syncResourceLogLabel}: Merging remote snippets with local snippets...`);
		} else {
			this.logService.trace(`${this.syncResourceLogLabel}: Remote snippets does not exist. Synchronizing snippets for the first time.`);
		}

S
Sandeep Somavarapu 已提交
309 310
		const mergeResult = merge(localSnippets, remoteSnippets, lastSyncSnippets, resolvedConflicts);

311 312 313 314 315 316 317 318 319 320
		const conflicts: Conflict[] = [];
		for (const key of mergeResult.conflicts) {
			const localPreview = joinPath(this.snippetsPreviewFolder, key);
			conflicts.push({ local: localPreview, remote: localPreview.with({ scheme: USER_DATA_SYNC_SCHEME }) });
			const content = local[key];
			if (!token.isCancellationRequested) {
				await this.fileService.writeFile(localPreview, content ? content.value : VSBuffer.fromString(''));
			}
		}

S
Sandeep Somavarapu 已提交
321 322 323 324 325 326 327 328 329 330 331
		for (const conflict of this.conflicts) {
			// clear obsolete conflicts
			if (!conflicts.some(({ local }) => isEqual(local, conflict.local))) {
				try {
					await this.fileService.del(conflict.local);
				} catch (error) {
					// Ignore & log
					this.logService.error(error);
				}
			}
		}
332

S
Sandeep Somavarapu 已提交
333 334 335 336 337 338 339 340 341 342 343 344
		return {
			remoteUserData, local,
			lastSyncUserData,
			added: mergeResult.added,
			removed: mergeResult.removed,
			updated: mergeResult.updated,
			conflicts,
			remote: mergeResult.remote,
			resolvedConflicts,
			hasLocalChanged: Object.keys(mergeResult.added).length > 0 || mergeResult.removed.length > 0 || Object.keys(mergeResult.updated).length > 0,
			hasRemoteChanged: mergeResult.remote !== null
		};
345 346 347 348 349 350 351
	}

	private async apply(forcePush?: boolean): Promise<void> {
		if (!this.syncPreviewResultPromise) {
			return;
		}

S
Sandeep Somavarapu 已提交
352
		let { added, removed, updated, local, remote, remoteUserData, lastSyncUserData, hasLocalChanged, hasRemoteChanged } = await this.syncPreviewResultPromise;
353

S
Sandeep Somavarapu 已提交
354
		if (!hasLocalChanged && !hasRemoteChanged) {
355 356 357
			this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing snippets.`);
		}

S
Sandeep Somavarapu 已提交
358
		if (hasLocalChanged) {
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
			// back up all snippets
			await this.backupLocal(JSON.stringify(this.toSnippetsContents(local)));
			await this.updateLocalSnippets(added, removed, updated, local);
		}

		if (remote) {
			// update remote
			this.logService.trace(`${this.syncResourceLogLabel}: Updating remote snippets...`);
			const content = JSON.stringify(remote);
			remoteUserData = await this.updateRemoteUserData(content, forcePush ? null : remoteUserData.ref);
			this.logService.info(`${this.syncResourceLogLabel}: Updated remote snippets`);
		}

		if (lastSyncUserData?.ref !== remoteUserData.ref) {
			// update last sync
			this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized snippets...`);
			await this.updateLastSyncUserData(remoteUserData);
			this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized snippets`);
		}

		this.syncPreviewResultPromise = null;
	}

	private async updateLocalSnippets(added: IStringDictionary<string>, removed: string[], updated: IStringDictionary<string>, local: IStringDictionary<IFileContent>): Promise<void> {
		for (const key of removed) {
			const resource = joinPath(this.snippetsFolder, key);
			this.logService.trace(`${this.syncResourceLogLabel}: Deleting snippet...`, basename(resource));
			await this.fileService.del(resource);
			this.logService.info(`${this.syncResourceLogLabel}: Deleted snippet`, basename(resource));
		}

		for (const key of Object.keys(added)) {
			const resource = joinPath(this.snippetsFolder, key);
			this.logService.trace(`${this.syncResourceLogLabel}: Creating snippet...`, basename(resource));
			await this.fileService.createFile(resource, VSBuffer.fromString(added[key]), { overwrite: false });
			this.logService.info(`${this.syncResourceLogLabel}: Created snippet`, basename(resource));
		}

		for (const key of Object.keys(updated)) {
			const resource = joinPath(this.snippetsFolder, key);
			this.logService.trace(`${this.syncResourceLogLabel}: Updating snippet...`, basename(resource));
			await this.fileService.writeFile(resource, VSBuffer.fromString(updated[key]), local[key]);
			this.logService.info(`${this.syncResourceLogLabel}: Updated snippet`, basename(resource));
		}
	}

	private parseSnippets(syncData: ISyncData): IStringDictionary<string> {
		return JSON.parse(syncData.content);
	}

	private toSnippetsContents(snippetsFileContents: IStringDictionary<IFileContent>): IStringDictionary<string> {
		const snippets: IStringDictionary<string> = {};
		for (const key of Object.keys(snippetsFileContents)) {
			snippets[key] = snippetsFileContents[key].value.toString();
		}
		return snippets;
	}

	private async getSnippetsFileContents(): Promise<IStringDictionary<IFileContent>> {
		const snippets: IStringDictionary<IFileContent> = {};
		let stat: IFileStat;
		try {
			stat = await this.fileService.resolve(this.snippetsFolder);
		} catch (e) {
			// No snippets
			if (e instanceof FileOperationError && e.fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
				return snippets;
			} else {
				throw e;
			}
		}
		for (const entry of stat.children || []) {
			const resource = entry.resource;
S
Sandeep Somavarapu 已提交
432
			const extension = extname(resource);
S
Sandeep Somavarapu 已提交
433
			if (extension === '.json' || extension === '.code-snippets') {
434 435 436 437 438 439 440 441
				const key = relativePath(this.snippetsFolder, resource)!;
				const content = await this.fileService.readFile(resource);
				snippets[key] = content;
			}
		}
		return snippets;
	}
}