Repository navigation
Expand file tree
/
Copy pathbuilder.js
More file actions
367 lines (310 loc) · 11.7 KB
/
Copy pathbuilder.js
File metadata and controls
367 lines (310 loc) · 11.7 KB
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
import PatchBuffer from './patch-buffer';
import Hunk from './hunk';
import File, {nullFile} from './file';
import Patch, {DEFERRED, EXPANDED, REMOVED} from './patch';
import {Unchanged, Addition, Deletion, NoNewline} from './region';
import FilePatch from './file-patch';
import MultiFilePatch from './multi-file-patch';
export const DEFAULT_OPTIONS = {
// Number of lines after which we consider the diff "large"
largeDiffThreshold: 800,
// Map of file path (relative to repository root) to Patch render status (EXPANDED, COLLAPSED, DEFERRED)
renderStatusOverrides: {},
// Existing patch buffer to render onto
patchBuffer: null,
// Store off what-the-diff file patch
preserveOriginal: false,
// Paths of file patches that have been removed from the patch before parsing
removed: new Set(),
};
export function buildFilePatch(diffs, options) {
const opts = {...DEFAULT_OPTIONS, ...options};
const patchBuffer = new PatchBuffer();
let filePatch;
if (diffs.length === 0) {
filePatch = emptyDiffFilePatch();
} else if (diffs.length === 1) {
filePatch = singleDiffFilePatch(diffs[0], patchBuffer, opts);
} else if (diffs.length === 2) {
filePatch = dualDiffFilePatch(diffs[0], diffs[1], patchBuffer, opts);
} else {
throw new Error(`Unexpected number of diffs: ${diffs.length}`);
}
// Delete the trailing newline.
patchBuffer.deleteLastNewline();
return new MultiFilePatch({patchBuffer, filePatches: [filePatch]});
}
export function buildMultiFilePatch(diffs, options) {
const opts = {...DEFAULT_OPTIONS, ...options};
const patchBuffer = new PatchBuffer();
const byPath = new Map();
const actions = [];
let index = 0;
for (const diff of diffs) {
const thePath = diff.oldPath || diff.newPath;
if (diff.status === 'added' || diff.status === 'deleted') {
// Potential paired diff. Either a symlink deletion + content addition or a symlink addition +
// content deletion.
const otherHalf = byPath.get(thePath);
if (otherHalf) {
// The second half. Complete the paired diff, or fail if they have unexpected statuses or modes.
const [otherDiff, otherIndex] = otherHalf;
actions[otherIndex] = (function(_diff, _otherDiff) {
return () => dualDiffFilePatch(_diff, _otherDiff, patchBuffer, opts);
})(diff, otherDiff);
byPath.delete(thePath);
} else {
// The first half we've seen.
byPath.set(thePath, [diff, index]);
index++;
}
} else {
actions[index] = (function(_diff) {
return () => singleDiffFilePatch(_diff, patchBuffer, opts);
})(diff);
index++;
}
}
// Populate unpaired diffs that looked like they could be part of a pair, but weren't.
for (const [unpairedDiff, originalIndex] of byPath.values()) {
actions[originalIndex] = (function(_unpairedDiff) {
return () => singleDiffFilePatch(_unpairedDiff, patchBuffer, opts);
})(unpairedDiff);
}
const filePatches = actions.map(action => action());
// Delete the final trailing newline from the last non-empty patch.
patchBuffer.deleteLastNewline();
// Append hidden patches corresponding to each removed file.
for (const removedPath of opts.removed) {
const removedFile = new File({path: removedPath});
const removedMarker = patchBuffer.markPosition(
Patch.layerName,
patchBuffer.getBuffer().getEndPosition(),
{invalidate: 'never', exclusive: false},
);
filePatches.push(FilePatch.createHiddenFilePatch(
removedFile,
removedFile,
removedMarker,
REMOVED,
/* istanbul ignore next */
() => { throw new Error(`Attempt to expand removed file patch ${removedPath}`); },
));
}
return new MultiFilePatch({patchBuffer, filePatches});
}
function emptyDiffFilePatch() {
return FilePatch.createNull();
}
function singleDiffFilePatch(diff, patchBuffer, opts) {
const wasSymlink = diff.oldMode === File.modes.SYMLINK;
const isSymlink = diff.newMode === File.modes.SYMLINK;
let oldSymlink = null;
let newSymlink = null;
if (wasSymlink && !isSymlink) {
oldSymlink = diff.hunks[0].lines[0].slice(1);
} else if (!wasSymlink && isSymlink) {
newSymlink = diff.hunks[0].lines[0].slice(1);
} else if (wasSymlink && isSymlink) {
oldSymlink = diff.hunks[0].lines[0].slice(1);
newSymlink = diff.hunks[0].lines[2].slice(1);
}
const oldFile = diff.oldPath !== null || diff.oldMode !== null
? new File({path: diff.oldPath, mode: diff.oldMode, symlink: oldSymlink})
: nullFile;
const newFile = diff.newPath !== null || diff.newMode !== null
? new File({path: diff.newPath, mode: diff.newMode, symlink: newSymlink})
: nullFile;
const renderStatusOverride =
(oldFile.isPresent() && opts.renderStatusOverrides[oldFile.getPath()]) ||
(newFile.isPresent() && opts.renderStatusOverrides[newFile.getPath()]) ||
undefined;
const renderStatus = renderStatusOverride ||
(isDiffLarge([diff], opts) && DEFERRED) ||
EXPANDED;
if (!renderStatus.isVisible()) {
const patchMarker = patchBuffer.markPosition(
Patch.layerName,
patchBuffer.getBuffer().getEndPosition(),
{invalidate: 'never', exclusive: false},
);
return FilePatch.createHiddenFilePatch(
oldFile, newFile, patchMarker, renderStatus,
() => {
const subPatchBuffer = new PatchBuffer();
const [hunks, nextPatchMarker] = buildHunks(diff, subPatchBuffer);
const nextPatch = new Patch({status: diff.status, hunks, marker: nextPatchMarker});
subPatchBuffer.deleteLastNewline();
return {patch: nextPatch, patchBuffer: subPatchBuffer};
},
);
} else {
const [hunks, patchMarker] = buildHunks(diff, patchBuffer);
const patch = new Patch({status: diff.status, hunks, marker: patchMarker});
const rawPatches = opts.preserveOriginal ? {content: diff} : null;
return new FilePatch(oldFile, newFile, patch, rawPatches);
}
}
function dualDiffFilePatch(diff1, diff2, patchBuffer, opts) {
let modeChangeDiff, contentChangeDiff;
if (diff1.oldMode === File.modes.SYMLINK || diff1.newMode === File.modes.SYMLINK) {
modeChangeDiff = diff1;
contentChangeDiff = diff2;
} else {
modeChangeDiff = diff2;
contentChangeDiff = diff1;
}
const filePath = contentChangeDiff.oldPath || contentChangeDiff.newPath;
const symlink = modeChangeDiff.hunks[0].lines[0].slice(1);
let status;
let oldMode, newMode;
let oldSymlink = null;
let newSymlink = null;
if (modeChangeDiff.status === 'added') {
// contents were deleted and replaced with symlink
status = 'deleted';
oldMode = contentChangeDiff.oldMode;
newMode = modeChangeDiff.newMode;
newSymlink = symlink;
} else if (modeChangeDiff.status === 'deleted') {
// contents were added after symlink was deleted
status = 'added';
oldMode = modeChangeDiff.oldMode;
oldSymlink = symlink;
newMode = contentChangeDiff.newMode;
} else {
throw new Error(`Invalid mode change diff status: ${modeChangeDiff.status}`);
}
const oldFile = new File({path: filePath, mode: oldMode, symlink: oldSymlink});
const newFile = new File({path: filePath, mode: newMode, symlink: newSymlink});
const renderStatus = opts.renderStatusOverrides[filePath] ||
(isDiffLarge([contentChangeDiff], opts) && DEFERRED) ||
EXPANDED;
if (!renderStatus.isVisible()) {
const patchMarker = patchBuffer.markPosition(
Patch.layerName,
patchBuffer.getBuffer().getEndPosition(),
{invalidate: 'never', exclusive: false},
);
return FilePatch.createHiddenFilePatch(
oldFile, newFile, patchMarker, renderStatus,
() => {
const subPatchBuffer = new PatchBuffer();
const [hunks, nextPatchMarker] = buildHunks(contentChangeDiff, subPatchBuffer);
const nextPatch = new Patch({status, hunks, marker: nextPatchMarker});
subPatchBuffer.deleteLastNewline();
return {patch: nextPatch, patchBuffer: subPatchBuffer};
},
);
} else {
const [hunks, patchMarker] = buildHunks(contentChangeDiff, patchBuffer);
const patch = new Patch({status, hunks, marker: patchMarker});
const rawPatches = opts.preserveOriginal ? {content: contentChangeDiff, mode: modeChangeDiff} : null;
return new FilePatch(oldFile, newFile, patch, rawPatches);
}
}
const CHANGEKIND = {
'+': Addition,
'-': Deletion,
' ': Unchanged,
'\\': NoNewline,
};
function buildHunks(diff, patchBuffer) {
const inserter = patchBuffer.createInserterAtEnd()
.keepBefore(patchBuffer.findAllMarkers({endPosition: patchBuffer.getInsertionPoint()}));
let patchMarker = null;
let firstHunk = true;
const hunks = [];
inserter.markWhile(Patch.layerName, () => {
for (const rawHunk of diff.hunks) {
let firstRegion = true;
const regions = [];
// Separate hunks with an unmarked newline
if (firstHunk) {
firstHunk = false;
} else {
inserter.insert('\n');
}
inserter.markWhile(Hunk.layerName, () => {
let firstRegionLine = true;
let currentRegionText = '';
let CurrentRegionKind = null;
function finishRegion() {
if (CurrentRegionKind === null) {
return;
}
// Separate regions with an unmarked newline
if (firstRegion) {
firstRegion = false;
} else {
inserter.insert('\n');
}
inserter.insertMarked(currentRegionText, CurrentRegionKind.layerName, {
invalidate: 'never',
exclusive: false,
callback: (function(_regions, _CurrentRegionKind) {
return regionMarker => { _regions.push(new _CurrentRegionKind(regionMarker)); };
})(regions, CurrentRegionKind),
});
}
for (const rawLine of rawHunk.lines) {
const NextRegionKind = CHANGEKIND[rawLine[0]];
if (NextRegionKind === undefined) {
throw new Error(`Unknown diff status character: "${rawLine[0]}"`);
}
const nextLine = rawLine.slice(1);
let separator = '';
if (firstRegionLine) {
firstRegionLine = false;
} else {
separator = '\n';
}
if (NextRegionKind === CurrentRegionKind) {
currentRegionText += separator + nextLine;
continue;
} else {
finishRegion();
CurrentRegionKind = NextRegionKind;
currentRegionText = nextLine;
}
}
finishRegion();
}, {
invalidate: 'never',
exclusive: false,
callback: (function(_hunks, _rawHunk, _regions) {
return hunkMarker => {
_hunks.push(new Hunk({
oldStartRow: _rawHunk.oldStartLine,
newStartRow: _rawHunk.newStartLine,
oldRowCount: _rawHunk.oldLineCount,
newRowCount: _rawHunk.newLineCount,
sectionHeading: _rawHunk.heading,
marker: hunkMarker,
regions: _regions,
}));
};
})(hunks, rawHunk, regions),
});
}
}, {
invalidate: 'never',
exclusive: false,
callback: marker => { patchMarker = marker; },
});
// Separate multiple non-empty patches on the same buffer with an unmarked newline. The newline after the final
// non-empty patch (if there is one) should be deleted before MultiFilePatch construction.
if (diff.hunks.length > 0) {
inserter.insert('\n');
}
inserter.apply();
return [hunks, patchMarker];
}
function isDiffLarge(diffs, opts) {
const size = diffs.reduce((diffSizeCounter, diff) => {
return diffSizeCounter + diff.hunks.reduce((hunkSizeCounter, hunk) => {
return hunkSizeCounter + hunk.lines.length;
}, 0);
}, 0);
return size > opts.largeDiffThreshold;
}