1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { distinct } from 'vs/base/common/arrays';
import { IStringDictionary } from 'vs/base/common/collections';
import { JSONVisitor, parse, visit } from 'vs/base/common/json';
import { applyEdits, setProperty, withFormatting } from 'vs/base/common/jsonEdit';
import { Edit, FormattingOptions, getEOL } from 'vs/base/common/jsonFormatter';
import * as objects from 'vs/base/common/objects';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import * as contentUtil from 'vs/platform/userDataSync/common/content';
import { getDisallowedIgnoredSettings, IConflictSetting } from 'vs/platform/userDataSync/common/userDataSync';
export interface IMergeResult {
localContent: string | null;
remoteContent: string | null;
hasConflicts: boolean;
conflictsSettings: IConflictSetting[];
}
export function getIgnoredSettings(defaultIgnoredSettings: string[], configurationService: IConfigurationService, settingsContent?: string): string[] {
let value: ReadonlyArray<string> = [];
if (settingsContent) {
value = getIgnoredSettingsFromContent(settingsContent);
} else {
value = getIgnoredSettingsFromConfig(configurationService);
}
const added: string[] = [], removed: string[] = [...getDisallowedIgnoredSettings()];
if (Array.isArray(value)) {
for (const key of value) {
if (key.startsWith('-')) {
removed.push(key.substring(1));
} else {
added.push(key);
}
}
}
return distinct([...defaultIgnoredSettings, ...added,].filter(setting => removed.indexOf(setting) === -1));
}
function getIgnoredSettingsFromConfig(configurationService: IConfigurationService): ReadonlyArray<string> {
let userValue = configurationService.inspect<string[]>('settingsSync.ignoredSettings').userValue;
if (userValue !== undefined) {
return userValue;
}
userValue = configurationService.inspect<string[]>('sync.ignoredSettings').userValue;
if (userValue !== undefined) {
return userValue;
}
return configurationService.getValue<string[]>('settingsSync.ignoredSettings') || [];
}
function getIgnoredSettingsFromContent(settingsContent: string): string[] {
const parsed = parse(settingsContent);
return parsed ? parsed['settingsSync.ignoredSettings'] || parsed['sync.ignoredSettings'] || [] : [];
}
export function updateIgnoredSettings(targetContent: string, sourceContent: string, ignoredSettings: string[], formattingOptions: FormattingOptions): string {
if (ignoredSettings.length) {
const sourceTree = parseSettings(sourceContent);
const source = parse(sourceContent) || {};
const target = parse(targetContent);
if (!target) {
return targetContent;
}
const settingsToAdd: INode[] = [];
for (const key of ignoredSettings) {
const sourceValue = source[key];
const targetValue = target[key];
// Remove in target
if (sourceValue === undefined) {
targetContent = contentUtil.edit(targetContent, [key], undefined, formattingOptions);
}
// Update in target
else if (targetValue !== undefined) {
targetContent = contentUtil.edit(targetContent, [key], sourceValue, formattingOptions);
}
else {
settingsToAdd.push(findSettingNode(key, sourceTree)!);
}
}
settingsToAdd.sort((a, b) => a.startOffset - b.startOffset);
settingsToAdd.forEach(s => targetContent = addSetting(s.setting!.key, sourceContent, targetContent, formattingOptions));
}
return targetContent;
}
export function merge(originalLocalContent: string, originalRemoteContent: string, baseContent: string | null, ignoredSettings: string[], resolvedConflicts: { key: string; value: any | undefined }[], formattingOptions: FormattingOptions): IMergeResult {
const localContentWithoutIgnoredSettings = updateIgnoredSettings(originalLocalContent, originalRemoteContent, ignoredSettings, formattingOptions);
const localForwarded = baseContent !== localContentWithoutIgnoredSettings;
const remoteForwarded = baseContent !== originalRemoteContent;
/* no changes */
if (!localForwarded && !remoteForwarded) {
return { conflictsSettings: [], localContent: null, remoteContent: null, hasConflicts: false };
}
/* local has changed and remote has not */
if (localForwarded && !remoteForwarded) {
return { conflictsSettings: [], localContent: null, remoteContent: localContentWithoutIgnoredSettings, hasConflicts: false };
}
/* remote has changed and local has not */
if (remoteForwarded && !localForwarded) {
return { conflictsSettings: [], localContent: updateIgnoredSettings(originalRemoteContent, originalLocalContent, ignoredSettings, formattingOptions), remoteContent: null, hasConflicts: false };
}
/* local is empty and not synced before */
if (baseContent === null && isEmpty(originalLocalContent)) {
const localContent = areSame(originalLocalContent, originalRemoteContent, ignoredSettings) ? null : updateIgnoredSettings(originalRemoteContent, originalLocalContent, ignoredSettings, formattingOptions);
return { conflictsSettings: [], localContent, remoteContent: null, hasConflicts: false };
}
/* remote and local has changed */
let localContent = originalLocalContent;
let remoteContent = originalRemoteContent;
const local = parse(originalLocalContent);
const remote = parse(originalRemoteContent);
const base = baseContent ? parse(baseContent) : null;
const ignored = ignoredSettings.reduce((set, key) => { set.add(key); return set; }, new Set<string>());
const localToRemote = compare(local, remote, ignored);
const baseToLocal = compare(base, local, ignored);
const baseToRemote = compare(base, remote, ignored);
const conflicts: Map<string, IConflictSetting> = new Map<string, IConflictSetting>();
const handledConflicts: Set<string> = new Set<string>();
const handleConflict = (conflictKey: string): void => {
handledConflicts.add(conflictKey);
const resolvedConflict = resolvedConflicts.filter(({ key }) => key === conflictKey)[0];
if (resolvedConflict) {
localContent = contentUtil.edit(localContent, [conflictKey], resolvedConflict.value, formattingOptions);
remoteContent = contentUtil.edit(remoteContent, [conflictKey], resolvedConflict.value, formattingOptions);
} else {
conflicts.set(conflictKey, { key: conflictKey, localValue: local[conflictKey], remoteValue: remote[conflictKey] });
}
};
// Removed settings in Local
for (const key of baseToLocal.removed.values()) {
// Conflict - Got updated in remote.
if (baseToRemote.updated.has(key)) {
handleConflict(key);
}
// Also remove in remote
else {
remoteContent = contentUtil.edit(remoteContent, [key], undefined, formattingOptions);
}
}
// Removed settings in Remote
for (const key of baseToRemote.removed.values()) {
if (handledConflicts.has(key)) {
continue;
}
// Conflict - Got updated in local
if (baseToLocal.updated.has(key)) {
handleConflict(key);
}
// Also remove in locals
else {
localContent = contentUtil.edit(localContent, [key], undefined, formattingOptions);
}
}
// Updated settings in Local
for (const key of baseToLocal.updated.values()) {
if (handledConflicts.has(key)) {
continue;
}
// Got updated in remote
if (baseToRemote.updated.has(key)) {
// Has different value
if (localToRemote.updated.has(key)) {
handleConflict(key);
}
} else {
remoteContent = contentUtil.edit(remoteContent, [key], local[key], formattingOptions);
}
}
// Updated settings in Remote
for (const key of baseToRemote.updated.values()) {
if (handledConflicts.has(key)) {
continue;
}
// Got updated in local
if (baseToLocal.updated.has(key)) {
// Has different value
if (localToRemote.updated.has(key)) {
handleConflict(key);
}
} else {
localContent = contentUtil.edit(localContent, [key], remote[key], formattingOptions);
}
}
// Added settings in Local
for (const key of baseToLocal.added.values()) {
if (handledConflicts.has(key)) {
continue;
}
// Got added in remote
if (baseToRemote.added.has(key)) {
// Has different value
if (localToRemote.updated.has(key)) {
handleConflict(key);
}
} else {
remoteContent = addSetting(key, localContent, remoteContent, formattingOptions);
}
}
// Added settings in remote
for (const key of baseToRemote.added.values()) {
if (handledConflicts.has(key)) {
continue;
}
// Got added in local
if (baseToLocal.added.has(key)) {
// Has different value
if (localToRemote.updated.has(key)) {
handleConflict(key);
}
} else {
localContent = addSetting(key, remoteContent, localContent, formattingOptions);
}
}
const hasConflicts = conflicts.size > 0 || !areSame(localContent, remoteContent, ignoredSettings);
const hasLocalChanged = hasConflicts || !areSame(localContent, originalLocalContent, []);
const hasRemoteChanged = hasConflicts || !areSame(remoteContent, originalRemoteContent, []);
return { localContent: hasLocalChanged ? localContent : null, remoteContent: hasRemoteChanged ? remoteContent : null, conflictsSettings: [...conflicts.values()], hasConflicts };
}
export function areSame(localContent: string, remoteContent: string, ignoredSettings: string[]): boolean {
if (localContent === remoteContent) {
return true;
}
const local = parse(localContent);
const remote = parse(remoteContent);
const ignored = ignoredSettings.reduce((set, key) => { set.add(key); return set; }, new Set<string>());
const localTree = parseSettings(localContent).filter(node => !(node.setting && ignored.has(node.setting.key)));
const remoteTree = parseSettings(remoteContent).filter(node => !(node.setting && ignored.has(node.setting.key)));
if (localTree.length !== remoteTree.length) {
return false;
}
for (let index = 0; index < localTree.length; index++) {
const localNode = localTree[index];
const remoteNode = remoteTree[index];
if (localNode.setting && remoteNode.setting) {
if (localNode.setting.key !== remoteNode.setting.key) {
return false;
}
if (!objects.equals(local[localNode.setting.key], remote[localNode.setting.key])) {
return false;
}
} else if (!localNode.setting && !remoteNode.setting) {
if (localNode.value !== remoteNode.value) {
return false;
}
} else {
return false;
}
}
return true;
}
export function isEmpty(content: string): boolean {
if (content) {
const nodes = parseSettings(content);
return nodes.length === 0;
}
return true;
}
function compare(from: IStringDictionary<any> | null, to: IStringDictionary<any>, ignored: Set<string>): { added: Set<string>; removed: Set<string>; updated: Set<string> } {
const fromKeys = from ? Object.keys(from).filter(key => !ignored.has(key)) : [];
const toKeys = Object.keys(to).filter(key => !ignored.has(key));
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>();
if (from) {
for (const key of fromKeys) {
if (removed.has(key)) {
continue;
}
const value1 = from[key];
const value2 = to[key];
if (!objects.equals(value1, value2)) {
updated.add(key);
}
}
}
return { added, removed, updated };
}
export function addSetting(key: string, sourceContent: string, targetContent: string, formattingOptions: FormattingOptions): string {
const source = parse(sourceContent);
const sourceTree = parseSettings(sourceContent);
const targetTree = parseSettings(targetContent);
const insertLocation = getInsertLocation(key, sourceTree, targetTree);
return insertAtLocation(targetContent, key, source[key], insertLocation, targetTree, formattingOptions);
}
interface InsertLocation {
index: number;
insertAfter: boolean;
}
function getInsertLocation(key: string, sourceTree: INode[], targetTree: INode[]): InsertLocation {
const sourceNodeIndex = sourceTree.findIndex(node => node.setting?.key === key);
const sourcePreviousNode: INode = sourceTree[sourceNodeIndex - 1];
if (sourcePreviousNode) {
/*
Previous node in source is a setting.
Find the same setting in the target.
Insert it after that setting
*/
if (sourcePreviousNode.setting) {
const targetPreviousSetting = findSettingNode(sourcePreviousNode.setting.key, targetTree);
if (targetPreviousSetting) {
/* Insert after target's previous setting */
return { index: targetTree.indexOf(targetPreviousSetting), insertAfter: true };
}
}
/* Previous node in source is a comment */
else {
const sourcePreviousSettingNode = findPreviousSettingNode(sourceNodeIndex, sourceTree);
/*
Source has a setting defined before the setting to be added.
Find the same previous setting in the target.
If found, insert before its next setting so that comments are retrieved.
Otherwise, insert at the end.
*/
if (sourcePreviousSettingNode) {
const targetPreviousSetting = findSettingNode(sourcePreviousSettingNode.setting!.key, targetTree);
if (targetPreviousSetting) {
const targetNextSetting = findNextSettingNode(targetTree.indexOf(targetPreviousSetting), targetTree);
const sourceCommentNodes = findNodesBetween(sourceTree, sourcePreviousSettingNode, sourceTree[sourceNodeIndex]);
if (targetNextSetting) {
const targetCommentNodes = findNodesBetween(targetTree, targetPreviousSetting, targetNextSetting);
const targetCommentNode = findLastMatchingTargetCommentNode(sourceCommentNodes, targetCommentNodes);
if (targetCommentNode) {
return { index: targetTree.indexOf(targetCommentNode), insertAfter: true }; /* Insert after comment */
} else {
return { index: targetTree.indexOf(targetNextSetting), insertAfter: false }; /* Insert before target next setting */
}
} else {
const targetCommentNodes = findNodesBetween(targetTree, targetPreviousSetting, targetTree[targetTree.length - 1]);
const targetCommentNode = findLastMatchingTargetCommentNode(sourceCommentNodes, targetCommentNodes);
if (targetCommentNode) {
return { index: targetTree.indexOf(targetCommentNode), insertAfter: true }; /* Insert after comment */
} else {
return { index: targetTree.length - 1, insertAfter: true }; /* Insert at the end */
}
}
}
}
}
const sourceNextNode = sourceTree[sourceNodeIndex + 1];
if (sourceNextNode) {
/*
Next node in source is a setting.
Find the same setting in the target.
Insert it before that setting
*/
if (sourceNextNode.setting) {
const targetNextSetting = findSettingNode(sourceNextNode.setting.key, targetTree);
if (targetNextSetting) {
/* Insert before target's next setting */
return { index: targetTree.indexOf(targetNextSetting), insertAfter: false };
}
}
/* Next node in source is a comment */
else {
const sourceNextSettingNode = findNextSettingNode(sourceNodeIndex, sourceTree);
/*
Source has a setting defined after the setting to be added.
Find the same next setting in the target.
If found, insert after its previous setting so that comments are retrieved.
Otherwise, insert at the beginning.
*/
if (sourceNextSettingNode) {
const targetNextSetting = findSettingNode(sourceNextSettingNode.setting!.key, targetTree);
if (targetNextSetting) {
const targetPreviousSetting = findPreviousSettingNode(targetTree.indexOf(targetNextSetting), targetTree);
const sourceCommentNodes = findNodesBetween(sourceTree, sourceTree[sourceNodeIndex], sourceNextSettingNode);
if (targetPreviousSetting) {
const targetCommentNodes = findNodesBetween(targetTree, targetPreviousSetting, targetNextSetting);
const targetCommentNode = findLastMatchingTargetCommentNode(sourceCommentNodes.reverse(), targetCommentNodes.reverse());
if (targetCommentNode) {
return { index: targetTree.indexOf(targetCommentNode), insertAfter: false }; /* Insert before comment */
} else {
return { index: targetTree.indexOf(targetPreviousSetting), insertAfter: true }; /* Insert after target previous setting */
}
} else {
const targetCommentNodes = findNodesBetween(targetTree, targetTree[0], targetNextSetting);
const targetCommentNode = findLastMatchingTargetCommentNode(sourceCommentNodes.reverse(), targetCommentNodes.reverse());
if (targetCommentNode) {
return { index: targetTree.indexOf(targetCommentNode), insertAfter: false }; /* Insert before comment */
} else {
return { index: 0, insertAfter: false }; /* Insert at the beginning */
}
}
}
}
}
}
}
/* Insert at the end */
return { index: targetTree.length - 1, insertAfter: true };
}
function insertAtLocation(content: string, key: string, value: any, location: InsertLocation, tree: INode[], formattingOptions: FormattingOptions): string {
let edits: Edit[];
/* Insert at the end */
if (location.index === -1) {
edits = setProperty(content, [key], value, formattingOptions);
} else {
edits = getEditToInsertAtLocation(content, key, value, location, tree, formattingOptions).map(edit => withFormatting(content, edit, formattingOptions)[0]);
}
return applyEdits(content, edits);
}
function getEditToInsertAtLocation(content: string, key: string, value: any, location: InsertLocation, tree: INode[], formattingOptions: FormattingOptions): Edit[] {
const newProperty = `${JSON.stringify(key)}: ${JSON.stringify(value)}`;
const eol = getEOL(formattingOptions, content);
const node = tree[location.index];
if (location.insertAfter) {
const edits: Edit[] = [];
/* Insert after a setting */
if (node.setting) {
edits.push({ offset: node.endOffset, length: 0, content: ',' + newProperty });
}
/* Insert after a comment */
else {
const nextSettingNode = findNextSettingNode(location.index, tree);
const previousSettingNode = findPreviousSettingNode(location.index, tree);
const previousSettingCommaOffset = previousSettingNode?.setting?.commaOffset;
/* If there is a previous setting and it does not has comma then add it */
if (previousSettingNode && previousSettingCommaOffset === undefined) {
edits.push({ offset: previousSettingNode.endOffset, length: 0, content: ',' });
}
const isPreviouisSettingIncludesComment = previousSettingCommaOffset !== undefined && previousSettingCommaOffset > node.endOffset;
edits.push({
offset: isPreviouisSettingIncludesComment ? previousSettingCommaOffset! + 1 : node.endOffset,
length: 0,
content: nextSettingNode ? eol + newProperty + ',' : eol + newProperty
});
}
return edits;
}
else {
/* Insert before a setting */
if (node.setting) {
return [{ offset: node.startOffset, length: 0, content: newProperty + ',' }];
}
/* Insert before a comment */
const content = (tree[location.index - 1] && !tree[location.index - 1].setting /* previous node is comment */ ? eol : '')
+ newProperty
+ (findNextSettingNode(location.index, tree) ? ',' : '')
+ eol;
return [{ offset: node.startOffset, length: 0, content }];
}
}
function findSettingNode(key: string, tree: INode[]): INode | undefined {
return tree.filter(node => node.setting?.key === key)[0];
}
function findPreviousSettingNode(index: number, tree: INode[]): INode | undefined {
for (let i = index - 1; i >= 0; i--) {
if (tree[i].setting) {
return tree[i];
}
}
return undefined;
}
function findNextSettingNode(index: number, tree: INode[]): INode | undefined {
for (let i = index + 1; i < tree.length; i++) {
if (tree[i].setting) {
return tree[i];
}
}
return undefined;
}
function findNodesBetween(nodes: INode[], from: INode, till: INode): INode[] {
const fromIndex = nodes.indexOf(from);
const tillIndex = nodes.indexOf(till);
return nodes.filter((node, index) => fromIndex < index && index < tillIndex);
}
function findLastMatchingTargetCommentNode(sourceComments: INode[], targetComments: INode[]): INode | undefined {
if (sourceComments.length && targetComments.length) {
let index = 0;
for (; index < targetComments.length && index < sourceComments.length; index++) {
if (sourceComments[index].value !== targetComments[index].value) {
return targetComments[index - 1];
}
}
return targetComments[index - 1];
}
return undefined;
}
interface INode {
readonly startOffset: number;
readonly endOffset: number;
readonly value: string;
readonly setting?: {
readonly key: string;
readonly commaOffset: number | undefined;
};
readonly comment?: string;
}
function parseSettings(content: string): INode[] {
const nodes: INode[] = [];
let hierarchyLevel = -1;
let startOffset: number;
let key: string;
const visitor: JSONVisitor = {
onObjectBegin: (offset: number) => {
hierarchyLevel++;
},
onObjectProperty: (name: string, offset: number, length: number) => {
if (hierarchyLevel === 0) {
// this is setting key
startOffset = offset;
key = name;
}
},
onObjectEnd: (offset: number, length: number) => {
hierarchyLevel--;
if (hierarchyLevel === 0) {
nodes.push({
startOffset,
endOffset: offset + length,
value: content.substring(startOffset, offset + length),
setting: {
key,
commaOffset: undefined
}
});
}
},
onArrayBegin: (offset: number, length: number) => {
hierarchyLevel++;
},
onArrayEnd: (offset: number, length: number) => {
hierarchyLevel--;
if (hierarchyLevel === 0) {
nodes.push({
startOffset,
endOffset: offset + length,
value: content.substring(startOffset, offset + length),
setting: {
key,
commaOffset: undefined
}
});
}
},
onLiteralValue: (value: any, offset: number, length: number) => {
if (hierarchyLevel === 0) {
nodes.push({
startOffset,
endOffset: offset + length,
value: content.substring(startOffset, offset + length),
setting: {
key,
commaOffset: undefined
}
});
}
},
onSeparator: (sep: string, offset: number, length: number) => {
if (hierarchyLevel === 0) {
if (sep === ',') {
let index = nodes.length - 1;
for (; index >= 0; index--) {
if (nodes[index].setting) {
break;
}
}
const node = nodes[index];
if (node) {
nodes.splice(index, 1, {
startOffset: node.startOffset,
endOffset: node.endOffset,
value: node.value,
setting: {
key: node.setting!.key,
commaOffset: offset
}
});
}
}
}
},
onComment: (offset: number, length: number) => {
if (hierarchyLevel === 0) {
nodes.push({
startOffset: offset,
endOffset: offset + length,
value: content.substring(offset, offset + length),
});
}
}
};
visit(content, visitor);
return nodes;
}
|