GitHubivarvong
ply
main
1// Three-way line merge, ported from git's xdiff as merge-ort drives it (merge-ll.c: level XDL_MERGE_ZEALOUS, histogram
2// diff, no indent heuristic, style merge, favor none). Pure: bytes in, { clean, data } | { clean: false, reason } out.
3//
4// Faithful parts: record splitting (lines keep their '\n'; a last line without one is a record), xhistogram.c (find_lcs /
5// try_lcs / histogram_diff), xdl_change_compact (group sliding), xdl_build_script, xdl_do_merge (+ xdl_append_merge's
6// fusing), the refinement outcome of xdl_refine_conflicts, and xdl_fill_merge_buffer for clean results.
7// Classic Myers (xdiffi.c + xprepare.c's trim/cleanup, xdl_split's heuristics) is ported for both places git uses it in a
8// merge: the histogram fallback for a region whose common lines all occur > 64 times (every version), and the 2.54+
9// compaction re-diff (see `rediff`). The only 'undecided' left is the hash-chain limit, where git itself fails.
10// The 64-record hash-chain limit in scanA is modelled exactly (buckets of the per-diff class index): git's merge fails
11// there ("failed to execute internal merge"), so we answer 'undecided' — the 64/65 boundary is pinned against git.
13import type { Option, Result } from './result.js';
14import type { Input } from './absent.js';
15import { LIMIT_MERGE_BLOB, LIMIT_MERGE_WORK } from './limits.js';
16import { ok, err, assertNever, getOrElse, isSome, none, some } from './result.js';
17import { plyError } from './errors.js';
18import { bytesToStr, popLast } from './attributes.js';
19import { atOr, mapGet, withDefaults } from './absent.js';
21// A file split into line records. `ids` are classifier ids: equal id, equal content.
22export type Records = {
23 readonly bytes: Uint8Array;
24 readonly starts: number[];
25 readonly ends: number[];
26 readonly ids: number[];
27 readonly n: number;
28};
29export type Classify = (bytes: Uint8Array, s: number, e: number) => number;
30// What diffScript needs of a file: its ids and their count.
31export type Lines = { readonly ids: ArrayLike<number>; readonly n: number };
32export type Rediff = 'myers' | 'skip' | 'undecided';
33export type Driver = 'text' | 'union' | 'binary';
34// One change of a diff script, 0-based: base lines [i1, i1 + chg1) became side lines [i2, i2 + chg2).
35export type Change = { i1: number; i2: number; chg1: number; chg2: number };
36type Hunks = { readonly ours: number; readonly theirs: number };
37// A clean merge; under merge=union, `unioned` counts the conflicts it resolved (present only when there were any).
38export type MergeLinesResult =
39 | { readonly clean: true; readonly data: Uint8Array; readonly hunks: Hunks }
40 | { readonly clean: true; readonly data: Uint8Array; readonly hunks: Hunks; readonly unioned: number }
41 | { readonly clean: false; readonly reason: 'binary (merge attribute)' | 'too large to merge' | 'binary' }
42 | { readonly clean: false; readonly reason: 'content'; readonly conflicts: number }
43 | { readonly clean: false; readonly reason: 'undecided'; readonly detail: string };
44// Where we decline to answer (rediff 'undecided', or the hash-chain limit): the Err of a diff, a value (#80).
45export type Undecided = { readonly undecided: true; readonly detail: string };
46type Diffed<T> = Result<T, Undecided>;
47const DONE: Diffed<null> = ok(null);
48// The work bound. The histogram scan and the classic-Myers fallback add every inner-loop iteration (a line scanned, a
49// candidate tried, a diagonal advanced, a neighbour looked at) and compaction its slides to one counter per merge;
50// past `max` the diff stops and the merge is refused. `max` is absolute, per merged file (limits.ts:
51// Limits.maxMergeWork, LIMIT_MERGE_WORK), so the counted steps are bounded whatever the input's content. A step is
52// not one fixed amount of CPU: the two paths differ about 2x (measured at classicDiff).
53// The counter is the module's own, made per call and starting at zero: nothing a caller passes is read to decide a
54// refusal. A caller's meter is written once, when the call returns, with that call's total.
55export type Meter = { steps: number };
56export type Budget = { steps: number; readonly max: number };
57const unbounded = (): Budget => ({ steps: 0, max: Infinity });
58const spent = (budget: Budget): boolean => budget.steps > budget.max;
59const OVER_BUDGET = 'line diff step budget exceeded';
60// maxWork as a caller gave it: a non-negative finite number, or the default. A value that would bound nothing
61// (NaN, Infinity, a negative, a non-number) never switches the bound off and never refuses everything.
62export const maxWorkOf = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : LIMIT_MERGE_WORK);
63const stepBudget = (maxWork: unknown): Budget => ({ steps: 0, max: maxWorkOf(maxWork) });
64// The call's total, copied out to the caller's meter. The meter is never read; one that is not an object, or will not
65// take the write (frozen), is left alone (an array is an object and gets the property; a function is ignored). The
66// write runs the caller's code (a setter, a Proxy's set trap, a revoked Proxy), so what it throws is caught and
67// dropped: the result is the one the diff computed and no meter makes mergeLines or diffScript throw. Every return
68// path writes, a call that returns before any diff with 0.
69const report = (meter: unknown, steps: number): void => {
70 if (typeof meter !== 'object' || meter === null) return;
71 try { Reflect.set(meter, 'steps', steps); } catch { /* the caller's meter threw: its total is lost, the result is not */ }
72};
73// compact's invariant: the two sides' change groups move in step (equal counts of unchanged lines). Broken, it is a
74// programmer bug, so thrown, and typed (#80); the stack names the site.
75const broken = (): Error => plyError('internal', 'linemerge: groups out of step');
77const BINARY_SNIFF = 8000; // git's FIRST_FEW_BYTES: a NUL in the first 8000 bytes makes the merge binary (= conflict)
78const MAX_CHAIN = 64; // xhistogram.c max_chain_length
80export const isBinary = (bytes: Uint8Array): boolean => { const n = Math.min(bytes.length, BINARY_SNIFF); for (let i = 0; i < n; i++) if (bytes[i] === 0) return true; return false; };
82// Records: [start, end) byte offsets per line. Ids come from one classifier shared by all files of a merge, so id equality
83// is content equality (git's minimal_perfect_hash).
84export function records(bytes: Uint8Array, classify: Classify): Records {
85 const starts: number[] = [];
86 const ends: number[] = [];
87 const ids: number[] = [];
88 let p = 0;
89 while (p < bytes.length) {
90 let e = bytes.indexOf(0x0a, p); e = e < 0 ? bytes.length : e + 1;
91 starts.push(p); ends.push(e); ids.push(classify(bytes, p, e)); p = e;
92 }
93 return { bytes, starts, ends, ids, n: ids.length };
94}
95export function classifier(): Classify {
96 const map = new Map<string, number>();
97 return (bytes, s, e) => {
98 const key = bytesToStr(bytes.subarray(s, e)); // the line's bytes, one char per byte
99 const known = mapGet(map, key); if (known.tag === 'some') return known.value;
100 const id = map.size + 1; map.set(key, id); return id;
101 };
102}
104const undecided = (detail: string): Diffed<never> => err({ undecided: true, detail });
105// Unknown (a JS caller) reads as 'skip'.
106const rediffMode = (rediff: string): Rediff => (rediff === 'myers' || rediff === 'skip' || rediff === 'undecided' ? rediff : 'skip');
107// false: the compaction must stop as undecided. true: myers ran, or skip left the group where it is.
108function applyRediff(rediff: string, myers: () => void): boolean {
109 const mode = rediffMode(rediff);
110 switch (mode) {
111 case 'undecided': return false;
112 case 'myers': myers(); return true;
113 case 'skip': return true;
114 }
115 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
116 return assertNever(mode);
117}
119// ---- xhistogram.c ----
120type Lcs = { begin1: number; end1: number; begin2: number; end2: number };
121// find_lcs's outcomes: a common subsequence, none (every line differs), the classic-diff fallback (every common line
122// occurs > 64 times), the hash-chain limit where git's merge fails, or the step budget spent.
123type Found = Lcs & { readonly tag: 'lcs' } | { readonly tag: 'none' } | { readonly tag: 'fallback' } | { readonly tag: 'chain-limit' } | { readonly tag: 'over-budget' };
124// find_lcs's tables, allocated once per diff and sized to it: per class id its first line in the region (`first`) and
125// its occurrence count there (`count`, 0 = absent); per line of file 1 the next line of the same class (`next`, 0 =
126// none). Each region resets only the `count` slots it touched, so a region costs its own length and allocates nothing
127// (xhistogram.c callocs three tables per region; a Map and an object per line here made the same scan ~50x dearer).
128type Index = { readonly first: Int32Array; readonly count: Int32Array; readonly next: Int32Array };
129/* oxlint-disable eslint/max-depth, eslint/complexity, eslint/max-params -- a line-for-line port of xhistogram.c's find_lcs / try_lcs */
130// Typed-array reads below are in range (1-based lines within the region, ids below the class count); Number() only
131// types the read: this is the scan's hot path.
132function scanRegion(a: Int32Array, b: Int32Array, line1: number, count1: number, line2: number, count2: number, ix: Index, budget: Budget): Found {
133 const END1 = line1 + count1 - 1;
134 const END2 = line2 + count2 - 1;
135 const { first, count, next } = ix;
136 // scanA: first = first occurrence, next chains forward
137 let distinct = 0;
138 for (let ptr = END1; ptr >= line1; ptr--) {
139 const id = Number(a[ptr - 1]);
140 const c = Number(count[id]);
141 if (c === 0) { distinct++; next[ptr] = 0; } else next[ptr] = Number(first[id]);
142 first[id] = ptr; count[id] = c + 1;
143 }
144 // scanA's other way out: a new distinct line landing in a hash bucket that already chains 64 distinct records makes
145 // find_lcs fail (-1) and git's merge fail — never clean. Bucket = XDL_HASHLONG(class index, xdl_hashbits(count1)).
146 if (distinct > MAX_CHAIN) {
147 let bits = 0; for (let v = 1; v < count1 && bits < 32; v *= 2) bits++; bits = bits || 1;
148 const mask = 2 ** bits - 1;
149 const load = new Uint8Array(mask + 1); // a bucket's load stops at 65
150 for (let ptr = line1; ptr <= END1; ptr++) {
151 const id = Number(a[ptr - 1]);
152 if (Number(first[id]) !== ptr) continue; // once per distinct line
153 const h = (id + Math.floor(id / 2 ** bits)) & mask;
154 const l = Number(load[h]) + 1; if (l > MAX_CHAIN) return { tag: 'chain-limit' }; load[h] = l;
155 }
156 }
157 const CNT = (ptr: number): number => Number(count[Number(a[ptr - 1])]);
158 const lcs = { tag: 'lcs' as const, begin1: 0, end1: 0, begin2: 0, end2: 0 };
159 let cnt = MAX_CHAIN + 1;
160 let hasCommon = false;
161 for (let bPtr = line2; bPtr <= END2;) {
162 let bNext = bPtr + 1;
163 const recCnt = Number(count[Number(b[bPtr - 1])]);
164 if (recCnt > 0) {
165 hasCommon = true;
166 if (recCnt <= cnt) {
167 let as = Number(first[Number(b[bPtr - 1])]);
168 for (;;) {
169 const np0 = Number(next[as]);
170 let bs = bPtr;
171 let ae = as;
172 let be = bs;
173 let rc = recCnt;
174 while (line1 < as && line2 < bs && a[as - 2] === b[bs - 2]) { as--; bs--; if (rc > 1) rc = Math.min(rc, CNT(as)); }
175 while (ae < END1 && be < END2 && a[ae] === b[be]) { ae++; be++; if (rc > 1) rc = Math.min(rc, CNT(ae)); }
176 budget.steps += ae - as + 1; // the candidate's extension
177 if (bNext <= be) bNext = be + 1;
178 if (lcs.end1 - lcs.begin1 < ae - as || rc < cnt) { lcs.begin1 = as; lcs.begin2 = bs; lcs.end1 = ae; lcs.end2 = be; cnt = rc; }
179 let np = np0;
180 if (np === 0) break;
181 let stop = false;
182 while (np <= ae) { np = Number(next[np]); if (np === 0) { stop = true; break; } }
183 if (stop) break;
184 as = np;
185 }
186 if (spent(budget)) return { tag: 'over-budget' };
187 }
188 }
189 bPtr = bNext;
190 }
191 if (hasCommon && MAX_CHAIN < cnt) return { tag: 'fallback' };
192 return lcs.begin1 === 0 && lcs.begin2 === 0 ? { tag: 'none' } : lcs;
193}
194function findLcs(a: Int32Array, b: Int32Array, line1: number, count1: number, line2: number, count2: number, ix: Index, budget: Budget): Found {
195 budget.steps += count1 + count2; // scanA over file 1's region, one lookup per line of file 2's
196 if (spent(budget)) return { tag: 'over-budget' };
197 const found = scanRegion(a, b, line1, count1, line2, count2, ix, budget);
198 for (let ptr = line1; ptr < line1 + count1; ptr++) ix.count[Number(a[ptr - 1])] = 0; // leave the tables clean for the next region
199 return found;
200}
201/* oxlint-enable eslint/max-depth, eslint/complexity, eslint/max-params */
203// ---- the classic diff, as xdl_fall_back_diff runs it on a histogram region: a fresh xdl_do_diff over the two line ranges
204// with Myers — xprepare.c's xdl_trim_ends + xdl_cleanup_records (discarding lines with no match, and multi-match lines
205// amid runs of them), then xdiffi.c's xdl_recs_cmp / xdl_split with git's heuristics (need_min off: merges do not set
206// XDF_NEED_MINIMAL). Ids only need equality; class counts are per sub-range, as in the fresh environment.
207// oxlint-disable-next-line eslint/no-param-reassign -- C's loop over its argument
208const bogosqrt = (n: number): number => { let i = 1; for (; n > 0; n = Math.floor(n / 4)) i *= 2; return i; };
209const SNAKE_CNT = 20;
210const HEUR_MIN_COST = 256;
211const MAX_COST_MIN = 256;
212const K_HEUR = 4;
213const MAX_EQLIMIT = 1024;
214const SIMSCAN_WINDOW = 100;
215const KPDIS_RUN = 4;
216const LINE_MAX = Number.MAX_SAFE_INTEGER;
217const DISCARD = 0;
218const KEEP = 1;
219const INVESTIGATE = 2;
221// oxlint-disable-next-line eslint/max-params -- xdl_clean_mmatch's arguments and the diff's budget
222function cleanMmatch(action: Uint8Array, i: number, len: number, budget: Budget): boolean {
223 let s = 0;
224 let e = len - 1;
225 if (i - s > SIMSCAN_WINDOW) s = i - SIMSCAN_WINDOW;
226 if (e - i > SIMSCAN_WINDOW) e = i + SIMSCAN_WINDOW;
227 let r: number;
228 let rdis0 = 0;
229 let rpdis0 = 1;
230 let rdis1 = 0;
231 let rpdis1 = 1;
232 for (r = 1; i - r >= s; r++) { const x = action[i - r]; if (x === DISCARD) rdis0++; else if (x === INVESTIGATE) rpdis0++; else break; }
233 budget.steps += r; // the neighbours looked at, up to SIMSCAN_WINDOW each way
234 if (rdis0 === 0) return false;
235 for (r = 1; i + r <= e; r++) { const x = action[i + r]; if (x === DISCARD) rdis1++; else if (x === INVESTIGATE) rpdis1++; else break; }
236 budget.steps += r;
237 if (rdis1 === 0) return false;
238 rdis1 += rdis0; rpdis1 += rpdis0;
239 return rpdis1 * KPDIS_RUN < rpdis1 + rdis1;
240}
242type Split = { i1: number; i2: number; minLo: boolean; minHi: boolean };
243type Box = [off1: number, lim1: number, off2: number, lim2: number, needMin: boolean];
244/* oxlint-disable eslint/max-depth, eslint/complexity, eslint/max-params, eslint/no-param-reassign -- a line-for-line port of xdiffi.c's xdl_split / xdl_recs_cmp over C's argument list */
245// false: the step budget was spent before the diff finished, and nothing was marked.
246// Every loop below adds its iterations to the budget: the class counts, the trim, the cleanup and its neighbour scans,
247// each diagonal and snake of the search, the heuristics' passes over the diagonals, and the boxes' trims and marks.
248// What a counted step costs, measured at babb1b0 on a loaded 16-core machine (process.cpuUsage, median of 9 runs of
249// diffScript, rediff skip): 12.4-15.4 ns per step on this path (two unrelated random a/b/c files of 10,000 / 20,000 /
250// 40,000 lines: 5,370,282 / 10,811,747 / 34,481,049 steps in 79 / 135 / 532 ms) against 6.3-7.3 ns per step on the
251// histogram path (every adjacent pair of lines swapped, 2,000 / 4,000 lines: 3,005,997 / 9,240,577 steps in 22 /
252// 58 ms). So one budget buys about twice the CPU here that it buys on the histogram path.
253export function classicDiff(A: Int32Array, B: Int32Array, line1: number, count1: number, line2: number, count2: number, CH1: Uint8Array, CH2: Uint8Array, budget: Budget = unbounded()): boolean {
254 budget.steps += count1 + count2; // the class counts: one pass over each range
255 if (spent(budget)) return false;
256 const a = A.subarray(line1 - 1, line1 - 1 + count1);
257 const b = B.subarray(line2 - 1, line2 - 1 + count2);
258 const n1 = a.length;
259 const n2 = b.length;
260 const ch1 = new Uint8Array(n1);
261 const ch2 = new Uint8Array(n2);
262 // Indexes into the id arrays below are in range: the atOr fallbacks only satisfy the index type.
263 const len1 = new Map<number, number>();
264 const len2 = new Map<number, number>();
265 for (const x of a) len1.set(x, getOrElse(mapGet(len1, x), 0) + 1);
266 for (const x of b) len2.set(x, getOrElse(mapGet(len2, x), 0) + 1);
267 // xdl_trim_ends
268 let i = 0;
269 let lim = Math.min(n1, n2);
270 for (; i < lim; i++) if (a[i] !== b[i]) break;
271 const off = i; lim -= i;
272 for (i = 0; i < lim; i++) if (a[n1 - 1 - i] !== b[n2 - 1 - i]) break;
273 budget.steps += off + i; // the lines trimmed
274 const dend1 = n1 - i - 1;
275 const dend2 = n2 - i - 1;
276 // xdl_cleanup_records
277 const refs = (x: Int32Array, n: number, dend: number, other: ReadonlyMap<number, number>, ch: Uint8Array): Int32Array => {
278 const len = dend - off + 1;
279 const mlim = Math.min(bogosqrt(n), MAX_EQLIMIT);
280 const action = new Uint8Array(Math.max(len, 0));
281 budget.steps += 2 * Math.max(len, 0); // the two passes below
282 for (let k = 0; k < len; k++) {
283 const nm = getOrElse(mapGet(other, atOr(x, k + off, 0)), 0);
284 const many = nm < mlim ? KEEP : INVESTIGATE;
285 action[k] = nm === 0 ? DISCARD : many;
286 }
287 const ref: number[] = [];
288 for (let k = 0; k < len && !spent(budget); k++) {
289 let act = action[k];
290 if (act === INVESTIGATE) act = cleanMmatch(action, k, len, budget) ? DISCARD : KEEP;
291 if (act === KEEP) ref.push(k + off); else ch[k + off] = 1;
292 }
293 return Int32Array.from(ref);
294 };
295 const r1 = refs(a, n1, dend1, len2, ch1);
296 const r2 = refs(b, n2, dend2, len1, ch2);
297 if (spent(budget)) return false;
298 const h1 = Int32Array.from(r1, k => atOr(a, k, 0));
299 const h2 = Int32Array.from(r2, k => atOr(b, k, 0));
300 // xdl_do_diff (Myers part)
301 const nreff1 = r1.length;
302 const nreff2 = r2.length;
303 const ndiags = nreff1 + nreff2 + 3;
304 const kvd = new Float64Array(2 * ndiags + 2);
305 budget.steps += ndiags; // the kept lines copied, the k-vectors cleared
306 const F = nreff2 + 1;
307 const Bk = ndiags + nreff2 + 1;
308 const mxcost = Math.max(bogosqrt(ndiags), MAX_COST_MIN);
309 // Reads of the k-vectors are in range, as in C: a split touches diagonals [dmin - 1, dmax + 1] and kvd holds
310 // 2 x ndiags + 2 slots around the two midpoints. Number() only types the read: this is the search's hot path
311 // (through atOr each diagonal cost ~100 ns, 13x a histogram step).
312 const kf = (d: number): number => Number(kvd[F + d]);
313 const kb = (d: number): number => Number(kvd[Bk + d]);
314 const setF = (d: number, v: number): void => { kvd[F + d] = v; };
315 const setB = (d: number, v: number): void => { kvd[Bk + d] = v; };
316 const split = (off1: number, lim1: number, off2: number, lim2: number, needMin: boolean): Split => {
317 const dmin = off1 - lim2;
318 const dmax = lim1 - off2;
319 const fmid = off1 - off2;
320 const bmid = lim1 - lim2;
321 const odd = (fmid - bmid) & 1;
322 let fmin = fmid;
323 let fmax = fmid;
324 let bmin = bmid;
325 let bmax = bmid;
326 setF(fmid, off1); setB(bmid, lim1);
327 for (let ec = 1; ; ec++) {
328 let gotSnake = false;
329 let i1: number;
330 let i2: number;
331 let prev1: number;
332 if (fmin > dmin) setF(--fmin - 1, -1); else ++fmin;
333 if (fmax < dmax) setF(++fmax + 1, -1); else --fmax;
334 for (let d = fmax; d >= fmin; d -= 2) {
335 i1 = kf(d - 1) >= kf(d + 1) ? kf(d - 1) + 1 : kf(d + 1);
336 prev1 = i1; i2 = i1 - d;
337 for (; i1 < lim1 && i2 < lim2 && h1[i1] === h2[i2]; i1++, i2++);
338 budget.steps += i1 - prev1 + 1; // one diagonal and its snake
339 if (i1 - prev1 > SNAKE_CNT) gotSnake = true;
340 setF(d, i1);
341 if (odd && bmin <= d && d <= bmax && kb(d) <= i1) return { i1, i2, minLo: true, minHi: true };
342 }
343 if (bmin > dmin) setB(--bmin - 1, LINE_MAX); else ++bmin;
344 if (bmax < dmax) setB(++bmax + 1, LINE_MAX); else --bmax;
345 for (let d = bmax; d >= bmin; d -= 2) {
346 i1 = kb(d - 1) < kb(d + 1) ? kb(d - 1) : kb(d + 1) - 1;
347 prev1 = i1; i2 = i1 - d;
348 for (; i1 > off1 && i2 > off2 && h1[i1 - 1] === h2[i2 - 1]; i1--, i2--);
349 budget.steps += prev1 - i1 + 1;
350 if (prev1 - i1 > SNAKE_CNT) gotSnake = true;
351 setB(d, i1);
352 if (!odd && fmin <= d && d <= fmax && i1 <= kf(d)) return { i1, i2, minLo: true, minHi: true };
353 }
354 // budget spent: any split ends the search; the caller sees `spent` and drops the result
355 if (spent(budget)) return { i1: off1, i2: off2, minLo: false, minHi: false };
356 if (needMin) continue;
357 if (gotSnake && ec > HEUR_MIN_COST) {
358 budget.steps += (fmax - fmin) / 2 + (bmax - bmin) / 2 + 2; // the heuristic's pass over every diagonal, both ways
359 // spl is Some exactly when best > 0
360 let best = 0;
361 let spl: Option<{ readonly i1: number; readonly i2: number }> = none;
362 for (let d = fmax; d >= fmin; d -= 2) {
363 const dd = d > fmid ? d - fmid : fmid - d; i1 = kf(d); i2 = i1 - d;
364 const v = (i1 - off1) + (i2 - off2) - dd;
365 if (v > K_HEUR * ec && v > best && off1 + SNAKE_CNT <= i1 && i1 < lim1 && off2 + SNAKE_CNT <= i2 && i2 < lim2) {
366 budget.steps += SNAKE_CNT;
367 for (let k = 1; h1[i1 - k] === h2[i2 - k]; k++) if (k === SNAKE_CNT) { best = v; spl = some({ i1, i2 }); break; }
368 }
369 }
370 if (isSome(spl)) return { ...spl.value, minLo: true, minHi: false };
371 best = 0;
372 for (let d = bmax; d >= bmin; d -= 2) {
373 const dd = d > bmid ? d - bmid : bmid - d; i1 = kb(d); i2 = i1 - d;
374 const v = (lim1 - i1) + (lim2 - i2) - dd;
375 if (v > K_HEUR * ec && v > best && off1 < i1 && i1 <= lim1 - SNAKE_CNT && off2 < i2 && i2 <= lim2 - SNAKE_CNT) {
376 budget.steps += SNAKE_CNT;
377 for (let k = 0; h1[i1 + k] === h2[i2 + k]; k++) if (k === SNAKE_CNT - 1) { best = v; spl = some({ i1, i2 }); break; }
378 }
379 }
380 if (isSome(spl)) return { ...spl.value, minLo: false, minHi: true };
381 }
382 if (ec >= mxcost) {
383 budget.steps += (fmax - fmin) / 2 + (bmax - bmin) / 2 + 2; // the cutoff's pass over every diagonal, both ways
384 let fbest = -1;
385 let fbest1 = -1;
386 let bbest = LINE_MAX;
387 let bbest1 = LINE_MAX;
388 for (let d = fmax; d >= fmin; d -= 2) {
389 i1 = Math.min(kf(d), lim1); i2 = i1 - d;
390 if (lim2 < i2) { i1 = lim2 + d; i2 = lim2; }
391 if (fbest < i1 + i2) { fbest = i1 + i2; fbest1 = i1; }
392 }
393 for (let d = bmax; d >= bmin; d -= 2) {
394 i1 = Math.max(off1, kb(d)); i2 = i1 - d;
395 if (i2 < off2) { i1 = off2 + d; i2 = off2; }
396 if (i1 + i2 < bbest) { bbest = i1 + i2; bbest1 = i1; }
397 }
398 if ((lim1 + lim2) - bbest < fbest - (off1 + off2)) return { i1: fbest1, i2: fbest - fbest1, minLo: true, minHi: false };
399 return { i1: bbest1, i2: bbest - bbest1, minLo: false, minHi: true };
400 }
401 }
402 };
403 // xdl_recs_cmp, with an explicit stack (each box marks its own records; the k-vectors are scratch, reinitialized per split)
404 const stack: Box[] = [[0, nreff1, 0, nreff2, false]];
405 for (let top = popLast(stack); top.tag === 'some'; top = popLast(stack)) {
406 const box = top.value;
407 let [off1, lim1, off2, lim2] = box;
408 const span = lim1 - off1 + lim2 - off2;
409 for (; off1 < lim1 && off2 < lim2 && h1[off1] === h2[off2]; off1++, off2++);
410 for (; off1 < lim1 && off2 < lim2 && h1[lim1 - 1] === h2[lim2 - 1]; lim1--, lim2--);
411 budget.steps += 1 + span - (lim1 - off1 + lim2 - off2) + (off1 === lim1 || off2 === lim2 ? lim1 - off1 + lim2 - off2 : 0); // the box, the lines its trim passed, the lines it marks
412 if (off1 === lim1) { for (; off2 < lim2; off2++) ch2[atOr(r2, off2, 0)] = 1; }
413 else if (off2 === lim2) { for (; off1 < lim1; off1++) ch1[atOr(r1, off1, 0)] = 1; }
414 else {
415 const spl = split(off1, lim1, off2, lim2, box[4]);
416 if (spent(budget)) return false;
417 stack.push([spl.i1, lim1, spl.i2, lim2, spl.minHi], [off1, spl.i1, off2, spl.i2, spl.minLo]);
418 }
419 }
420 CH1.set(ch1, line1 - 1); CH2.set(ch2, line2 - 1);
421 return true;
422}
423/* oxlint-enable eslint/max-depth, eslint/complexity, eslint/max-params, eslint/no-param-reassign */
425// ---- xhistogram.c: histogram_diff ----
426// a, b: id arrays (0-based storage, 1-based line numbers as in C). Marks ch1 / ch2 (index = line - 1).
427type Region = [line1: number, count1: number, line2: number, count2: number];
428// oxlint-disable-next-line eslint/max-params -- the two files, their marks, the class count and the budget
429function histogramDiff(a: Int32Array, b: Int32Array, ch1: Uint8Array, ch2: Uint8Array, classes: number, budget: Budget): Diffed<null> {
430 const ix: Index = { first: new Int32Array(classes), count: new Int32Array(classes), next: new Int32Array(a.length + 1) };
431 const stack: Region[] = [[1, a.length, 1, b.length]];
432 for (let top = popLast(stack); top.tag === 'some'; top = popLast(stack)) {
433 const [line1, count1, line2, count2] = top.value;
434 if (count1 <= 0 && count2 <= 0) continue;
435 if (!count1) { for (let i = 0; i < count2; i++) ch2[line2 - 1 + i] = 1; continue; }
436 if (!count2) { for (let i = 0; i < count1; i++) ch1[line1 - 1 + i] = 1; continue; }
437 const found = findLcs(a, b, line1, count1, line2, count2, ix, budget);
438 switch (found.tag) {
439 case 'chain-limit': return undecided('histogram hash chain limit (git fails this merge)');
440 case 'over-budget': return undecided(OVER_BUDGET);
441 case 'fallback': if (!classicDiff(a, b, line1, count1, line2, count2, ch1, ch2, budget)) return undecided(OVER_BUDGET); continue; // fall_back_to_classic_diff
442 case 'none': for (let i = 0; i < count1; i++) ch1[line1 - 1 + i] = 1; for (let i = 0; i < count2; i++) ch2[line2 - 1 + i] = 1; continue;
443 case 'lcs': stack.push([found.end1 + 1, line1 + count1 - 1 - found.end1, found.end2 + 1, line2 + count2 - 1 - found.end2], [line1, found.begin1 - line1, line2, found.begin2 - line2]); continue;
444 }
445 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
446 return assertNever(found);
447 }
448 return DONE;
449}
451// ---- xdl_change_compact (no indent heuristic: merges do not set it) ----
452// ch: Uint8Array of n+2 with ch[0] and ch[n+1] as the -1 / n sentinels; C index i ↔ ch[i + 1].
453type Group = { start: number; end: number };
454/* oxlint-disable eslint/max-params, eslint/no-param-reassign, eslint/complexity, eslint/max-depth -- a line-for-line port of xdiffi.c's xdl_change_compact and its group helpers, which advance the group in place */
455export function compact(ids: Int32Array, ch: Uint8Array, n: number, idsO: Int32Array, chO: Uint8Array, nO: number, rediff: Rediff, budget: Budget = unbounded()): Diffed<null> {
456 const C = (i: number): boolean => ch[i + 1] === 1;
457 const CO = (i: number): boolean => chO[i + 1] === 1;
458 const set = (i: number, v: number): void => { ch[i + 1] = v ? 1 : 0; };
459 const g: Group = { start: 0, end: 0 };
460 const go: Group = { start: 0, end: 0 };
461 const init = (G: Group, c: (i: number) => boolean): void => { G.start = G.end = 0; while (c(G.end)) G.end++; };
462 const nextG = (G: Group, c: (i: number) => boolean, nn: number): boolean => { if (G.end === nn) return false; G.start = G.end + 1; for (G.end = G.start; c(G.end); G.end++); return true; };
463 const prevG = (G: Group, c: (i: number) => boolean): boolean => { if (G.start === 0) return false; G.end = G.start - 1; for (G.start = G.end; c(G.start - 1); G.start--); return true; };
464 const slideDown = (): boolean => { if (g.end < n && ids[g.start] === ids[g.end]) { budget.steps++; set(g.start++, 0); set(g.end++, 1); while (C(g.end)) g.end++; return true; } return false; };
465 const slideUp = (): boolean => { if (g.start > 0 && ids[g.start - 1] === ids[g.end - 1]) { budget.steps++; set(--g.start, 1); set(--g.end, 0); while (C(g.start - 1)) g.start--; return true; } return false; };
466 init(g, C); init(go, CO);
467 for (;;) {
468 if (g.end !== g.start) {
469 const orig = { start: g.start, end: g.end };
470 let groupsize: number;
471 let earliestEnd: number;
472 let endMatchingOther: number;
473 do {
474 groupsize = g.end - g.start;
475 endMatchingOther = -1;
476 while (slideUp()) if (!prevG(go, CO)) throw broken();
477 earliestEnd = g.end;
478 if (go.end > go.start) endMatchingOther = g.end;
479 for (;;) {
480 if (!slideDown()) break;
481 if (!nextG(go, CO, nO)) throw broken();
482 if (go.end > go.start) endMatchingOther = g.end;
483 }
484 } while (groupsize !== g.end - g.start);
485 if (g.end === earliestEnd) { /* no shifting was possible */ }
486 else if (endMatchingOther !== -1) {
487 while (go.end === go.start) { if (!slideUp()) throw broken(); if (!prevG(go, CO)) throw broken(); }
488 }
489 // histogram: a moved group facing a non-empty group on the other side is re-diffed with classic Myers in git.
490 // A JS caller's unknown rediff reads as 'skip', as it always has (blobMerger refuses one before this).
491 let within = true;
492 if (go.end !== go.start && (g.start !== orig.start || g.end !== orig.end) && !applyRediff(rediff, () => { within = classicDiff(ids, idsO, g.start + 1, g.end - g.start, go.start + 1, go.end - go.start, ch.subarray(1), chO.subarray(1), budget); })) return undecided('compaction needs the classic-diff fallback');
493 if (!within || spent(budget)) return undecided(OVER_BUDGET);
494 }
495 if (!nextG(g, C, n)) return DONE;
496 if (!nextG(go, CO, nO)) throw broken();
497 }
498}
499/* oxlint-enable eslint/max-params, eslint/no-param-reassign, eslint/complexity, eslint/max-depth */
501// ---- xdl_build_script: ascending list of { i1, i2, chg1, chg2 } (0-based) ----
502function buildScript(ch1: Uint8Array, n1: number, ch2: Uint8Array, n2: number): Change[] {
503 const c1 = (i: number): boolean => i >= 0 && i < n1 && ch1[i + 1] === 1;
504 const c2 = (i: number): boolean => i >= 0 && i < n2 && ch2[i + 1] === 1;
505 const out: Change[] = [];
506 for (let i1 = n1, i2 = n2; i1 >= 0 || i2 >= 0; i1--, i2--) {
507 if (c1(i1 - 1) || c2(i2 - 1)) {
508 const l1 = i1;
509 const l2 = i2;
510 while (c1(i1 - 1)) i1--;
511 while (c2(i2 - 1)) i2--;
512 out.push({ i1, i2, chg1: l1 - i1, chg2: l2 - i2 });
513 }
514 }
515 return out.toReversed();
516}
518// diff base → side as git's script (histogram + compaction both ways + build)
519// rediff: git 2.54 (yc/histogram-hunk-shift-fix) re-diffs a shifted group facing a non-empty one with Myers in
520// xdl_change_compact (histogram only). Both behaviors are git's; pick the one to match:
521// 'myers' (default) — git ≥ 2.54 (verified against master, 2.56: every merge and every diff hunk agrees);
522// 'skip' — git < 2.54 (verified against 2.43: every case agrees);
523// 'undecided' — conflict wherever the two differ: right against any version.
524function diffWith(base: Lines, side: Lines, rediff: Rediff, budget: Budget): Diffed<Change[]> {
525 const n1 = base.n;
526 const n2 = side.n;
527 const h1 = new Uint8Array(n1);
528 const h2 = new Uint8Array(n2);
529 // git classifies per diff: class index 0, 1, … in first-occurrence order over file1 (base) then file2 (side). The
530 // histogram's hash table is keyed on that index, so the chain limit below depends on it — renumber to match.
531 const local = new Map<number, number>();
532 const renum = (ids: ArrayLike<number>): Int32Array => Int32Array.from(ids, id => { const known = mapGet(local, id); if (known.tag === 'some') return known.value; const k = local.size; local.set(id, k); return k; });
533 const a = renum(base.ids);
534 const b = renum(side.ids);
535 const ch1 = new Uint8Array(n1 + 2);
536 const ch2 = new Uint8Array(n2 + 2);
537 const h = histogramDiff(a, b, h1, h2, local.size, budget); if (!h.ok) return h;
538 ch1.set(h1, 1); ch2.set(h2, 1);
539 const c1 = compact(a, ch1, n1, b, ch2, n2, rediff, budget); if (!c1.ok) return c1;
540 const c2 = compact(b, ch2, n2, a, ch1, n1, rediff, budget); if (!c2.ok) return c2;
541 return ok(buildScript(ch1, n1, ch2, n2));
542}
543// maxWork: the diff's step budget (limits.ts: LIMIT_MERGE_WORK); past it the diff is declined, detail
544// 'line diff step budget exceeded'. One that is not a non-negative finite number reads as the default. meter: an
545// object whose `steps` is set to this call's work when it returns (never read; anything else is ignored).
546export type DiffConfig = { readonly rediff: Rediff; readonly maxWork: number; readonly meter: Meter };
547export function diffScript(base: Lines, side: Lines, options: Input<DiffConfig> = {}): Diffed<Change[]> {
548 const { rediff, maxWork, meter } = withDefaults<DiffConfig>(options, { rediff: 'myers', maxWork: LIMIT_MERGE_WORK, meter: { steps: 0 } });
549 const budget = stepBudget(maxWork);
550 const script = diffWith(base, side, rediff, budget);
551 report(meter, budget.steps);
552 return script;
553}
555// ---- xdl_do_merge + xdl_append_merge ----
556// A hunk of the merge: a conflict, a change on one side only (ours / theirs), or a conflict whose two sides refine to the
557// same lines (identical, git's mode 4). git's bitmask modes 0/1/2/4; its 3 (both, ours then theirs) exists only as
558// merge=union's reading of a conflict, in fill.
559export type HunkKind = 'conflict' | 'ours' | 'theirs' | 'identical';
560// A hunk by its ours / theirs ranges; xdl_do_merge's hunks (Merged) also carry the base range, which refinement drops.
561type Hunk = { kind: HunkKind; i1: number; chg1: number; i2: number; chg2: number };
562type Merged = Hunk & { i0: number; chg0: number };
563// oxlint-disable-next-line eslint/max-params -- xdl_append_merge's argument list
564function appendMerge(list: Merged[], kind: HunkKind, i0: number, chg0: number, i1: number, chg1: number, i2: number, chg2: number): void {
565 const m = list.at(-1);
566 if (m && (i1 <= m.i1 + m.chg1 || i2 <= m.i2 + m.chg2)) {
567 if (kind !== m.kind) m.kind = 'conflict';
568 m.chg0 = i0 + chg0 - m.i0; m.chg1 = i1 + chg1 - m.i1; m.chg2 = i2 + chg2 - m.i2;
569 } else list.push({ kind, i0, chg0, i1, chg1, i2, chg2 });
570}
571const sameLines = (A: Records, i: number, B: Records, j: number, n: number): boolean => { for (let k = 0; k < n; k++) if (A.ids[i + k] !== B.ids[j + k]) return false; return true; };
573function doMerge(base: Records, ours: Records, theirs: Records, s1: readonly Change[], s2: readonly Change[]): Merged[] {
574 const c: Merged[] = [];
575 let x = 0;
576 let y = 0;
577 // a script holds no holes: a change is missing only past its end
578 for (let a = s1[x], b = s2[y]; a && b; a = s1[x], b = s2[y]) {
579 if (a.i1 + a.chg1 < b.i1) { appendMerge(c, 'ours', a.i1, a.chg1, a.i2, a.chg2, b.i2 - b.i1 + a.i1, a.chg1); x++; continue; }
580 if (b.i1 + b.chg1 < a.i1) { appendMerge(c, 'theirs', b.i1, b.chg1, a.i2 - a.i1 + b.i1, b.chg1, b.i2, b.chg2); y++; continue; }
581 if (a.i1 !== b.i1 || a.chg1 !== b.chg1 || a.chg2 !== b.chg2 || !sameLines(ours, a.i2, theirs, b.i2, a.chg2)) {
582 const off = a.i1 - b.i1;
583 const ffo = off + a.chg1 - b.chg1;
584 let i0 = a.i1;
585 let i1 = a.i2;
586 let i2 = b.i2;
587 if (off > 0) { i0 -= off; i1 -= off; } else i2 += off;
588 let chg0 = a.i1 + a.chg1 - i0;
589 let chg1 = a.i2 + a.chg2 - i1;
590 let chg2 = b.i2 + b.chg2 - i2;
591 if (ffo < 0) { chg0 -= ffo; chg1 -= ffo; } else chg2 += ffo;
592 appendMerge(c, 'conflict', i0, chg0, i1, chg1, i2, chg2);
593 }
594 const e1 = a.i1 + a.chg1;
595 const e2 = b.i1 + b.chg1;
596 if (e1 >= e2) y++;
597 if (e2 >= e1) x++;
598 }
599 for (const a of s1.slice(x)) appendMerge(c, 'ours', a.i1, a.chg1, a.i2, a.chg2, a.i1 + theirs.n - base.n, a.chg1);
600 for (const b of s2.slice(y)) appendMerge(c, 'theirs', b.i1, b.chg1, b.i1 + ours.n - base.n, b.chg1, b.i2, b.chg2);
601 return c;
602}
604// ---- xdl_refine_conflicts: re-diff each conflict's two sides (a fresh environment over just those lines, histogram +
605// compaction both ways); identical sides resolve, otherwise the conflict becomes the script's hunks ----
606// oxlint-disable-next-line eslint/max-params -- the two sides, the hunks, the mode and the merge's budget
607function refine(ours: Records, theirs: Records, c: readonly Hunk[], rediff: Rediff, budget: Budget): Diffed<Hunk[]> {
608 const out: Hunk[] = [];
609 for (const m of c) {
610 if (m.kind !== 'conflict' || m.chg1 === 0 || m.chg2 === 0) { out.push(m); continue; }
611 const sub = (F: Records, i: number, n: number): Lines => ({ ids: F.ids.slice(i, i + n), n });
612 const script = diffWith(sub(ours, m.i1, m.chg1), sub(theirs, m.i2, m.chg2), rediff, budget);
613 if (!script.ok) return script;
614 if (script.value.length === 0) { out.push({ ...m, kind: 'identical' }); continue; }
615 for (const x of script.value.toSorted((p, q) => p.i1 - q.i1)) out.push({ kind: 'conflict', i1: x.i1 + m.i1, chg1: x.chg1, i2: x.i2 + m.i2, chg2: x.chg2 });
616 }
617 return ok(out);
618}
620// ---- xdl_simplify_non_conflicts (level ZEALOUS: fuse two conflicts at most 3 lines apart, the gap included) ----
621function simplify(c: readonly Hunk[]): Hunk[] {
622 const out: Hunk[] = [];
623 for (const m of c) {
624 const prev = out.at(-1);
625 if (prev && prev.kind === 'conflict' && m.kind === 'conflict' && m.i1 - (prev.i1 + prev.chg1) <= 3) { prev.chg1 = m.i1 + m.chg1 - prev.i1; prev.chg2 = m.i2 + m.chg2 - prev.i2; }
626 else out.push({ ...m });
627 }
628 return out;
629}
631// ---- xdl_fill_merge_buffer without conflict output: clean results, and merge=union (every conflict → ours then theirs) ----
632// is_eol_crlf / is_cr_needed: a union hunk whose ours side ends without a newline gets one, CRLF if the files use CRLF.
633// Record indexes here are in range: the 0 fallback only satisfies the index type.
634function eolCrlf(F: Records, i: number): number {
635 const size = (k: number): number => atOr(F.ends, k, 0) - atOr(F.starts, k, 0);
636 // record k's byte `back` from its end (git: the byte at size - back); -1 before the file's start
637 const last = (k: number, back: number): number => atOr(F.bytes, atOr(F.ends, k, 0) - back, -1);
638 if (i < F.n - 1) return size(i) > 1 && last(i, 2) === 13 ? 1 : 0;
639 if (!F.n) return -1;
640 if (size(i) && last(i, 1) === 10) return size(i) > 1 && last(i, 2) === 13 ? 1 : 0;
641 if (!i) return -1;
642 return size(i - 1) > 1 && last(i - 1, 2) === 13 ? 1 : 0;
643}
644function crNeeded(base: Records, ours: Records, theirs: Records, m: Hunk): boolean {
645 let r = eolCrlf(ours, m.i1 ? m.i1 - 1 : 0);
646 if (r) r = eolCrlf(theirs, m.i2 ? m.i2 - 1 : 0);
647 if (r) r = eolCrlf(base, 0);
648 return r === 1;
649}
650// oxlint-disable-next-line eslint/max-params -- xdl_fill_merge_buffer's argument list
651function fill(base: Records, ours: Records, theirs: Records, c: readonly Hunk[], union: boolean): Uint8Array {
652 const parts: Uint8Array[] = []; let size = 0;
653 const push = (b: Uint8Array): void => { parts.push(b); size += b.length; };
654 // oxlint-disable-next-line eslint/max-params -- (file, first, count) and the two newline flags
655 const copy = (F: Records, i: number, n: number, needsCr = false, addNl = false): void => {
656 if (n < 1) return;
657 const s = atOr(F.starts, i, 0);
658 const e = atOr(F.ends, i + n - 1, 0);
659 push(F.bytes.subarray(s, e));
660 if (addNl && (e === s || F.bytes[e - 1] !== 10)) push(needsCr ? Uint8Array.of(13, 10) : Uint8Array.of(10));
661 };
662 let i = 0;
663 for (const m of c) {
664 // merge=union reads a conflict as both sides, ours then theirs (git's XDL_MERGE_FAVOR_UNION)
665 const kind = union && m.kind === 'conflict' ? 'both' : m.kind;
666 switch (kind) {
667 // a clean text merge holds no conflict; identical sides are ours, copied with the unchanged lines after them
668 case 'conflict': case 'identical': continue;
669 case 'ours':
670 case 'theirs':
671 case 'both':
672 copy(ours, i, m.i1 - i);
673 if (kind !== 'theirs') copy(ours, m.i1, m.chg1, crNeeded(base, ours, theirs, m), kind === 'both');
674 if (kind !== 'ours') copy(theirs, m.i2, m.chg2);
675 i = m.i1 + m.chg1;
676 continue;
677 }
678 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
679 return assertNever(kind);
680 }
681 copy(ours, i, ours.n - i);
682 const out = new Uint8Array(size); let o = 0; for (const p of parts) { out.set(p, o); o += p.length; }
683 return out;
684}
686// A diff stopped by the step budget is the input being too large to merge; any other is undecided, with its detail.
687const declined = ({ detail }: Undecided): MergeLinesResult => (detail === OVER_BUDGET ? { clean: false, reason: 'too large to merge' } : { clean: false, reason: 'undecided', detail });
688// The three files' records under one budget: both sides against base, then the conflicts' refinement.
689function mergeRecords({ driver, ours, theirs, B, O, T, rediff, budget }: { readonly driver: 'text' | 'union'; readonly ours: Uint8Array; readonly theirs: Uint8Array; readonly B: Records; readonly O: Records; readonly T: Records; readonly rediff: Rediff; readonly budget: Budget }): MergeLinesResult {
690 const s1 = diffWith(B, O, rediff, budget); if (!s1.ok) return declined(s1.error);
691 const s2 = diffWith(B, T, rediff, budget); if (!s2.ok) return declined(s2.error);
692 const hunks = { ours: s1.value.length, theirs: s2.value.length };
693 if (hunks.ours === 0) return { clean: true, data: theirs, hunks };
694 if (hunks.theirs === 0) return { clean: true, data: ours, hunks };
695 const r = refine(O, T, doMerge(B, O, T, s1.value, s2.value), rediff, budget); if (!r.ok) return declined(r.error);
696 const c = simplify(r.value);
697 const conflicts = c.filter(m => m.kind === 'conflict').length;
698 switch (driver) {
699 case 'text': return conflicts ? { clean: false, reason: 'content', conflicts } : { clean: true, data: fill(B, O, T, c, false), hunks };
700 case 'union': return { clean: true, data: fill(B, O, T, c, true), hunks, ...(conflicts ? { unioned: conflicts } : {}) };
701 }
702 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
703 return assertNever(driver);
704}
705// The merge. `maxBytes` bounds each input (git's MAX_XDIFF_SIZE is ~1 GiB; a Worker's is much smaller).
706// driver: 'text' (git's default) | 'union' (merge=union: conflicts resolve to ours then theirs) | 'binary' (merge=binary,
707// -merge: any two-sided change is a conflict). Binary content (a NUL in the first 8000 bytes) is a conflict whatever the
708// driver, as in ll_xdl_merge.
709function mergeText({ driver, base, ours, theirs, maxBytes, rediff, maxWork, meter }: { readonly driver: 'text' | 'union'; readonly base: Uint8Array; readonly ours: Uint8Array; readonly theirs: Uint8Array; readonly maxBytes: number; readonly rediff: Rediff; readonly maxWork: unknown; readonly meter: unknown }): MergeLinesResult {
710 if (Math.max(base.length, ours.length, theirs.length) > maxBytes) { report(meter, 0); return { clean: false, reason: 'too large to merge' }; }
711 if ([base, ours, theirs].some(f => isBinary(f))) { report(meter, 0); return { clean: false, reason: 'binary' }; }
712 const cl = classifier();
713 const B = records(base, cl);
714 const O = records(ours, cl);
715 const T = records(theirs, cl);
716 const budget = stepBudget(maxWork);
717 const merged = mergeRecords({ driver, ours, theirs, B, O, T, rediff, budget });
718 report(meter, budget.steps);
719 return merged;
720}
721// maxWork is the merge's step budget, absolute for this file (Limits.maxMergeWork; LIMIT_MERGE_WORK by default): past it
722// the answer is 'too large to merge', as for an input over maxBytes. A maxWork that is not a non-negative finite
723// number reads as the default. meter: an object whose `steps` is set to this call's work when it returns; it is never
724// read, so a reused or malformed one changes no result (anything that is not an object is ignored).
725export type MergeLinesConfig = { readonly maxBytes: number; readonly rediff: Rediff; readonly driver: Driver; readonly maxWork: number; readonly meter: Meter };
726export function mergeLines(base: Uint8Array, ours: Uint8Array, theirs: Uint8Array, options: Input<MergeLinesConfig> = {}): MergeLinesResult {
727 const { maxBytes, rediff, driver, maxWork, meter } = withDefaults<MergeLinesConfig>(options, { maxBytes: LIMIT_MERGE_BLOB, rediff: 'myers', driver: 'text', maxWork: LIMIT_MERGE_WORK, meter: { steps: 0 } });
728 switch (driver) {
729 case 'binary': report(meter, 0); return { clean: false, reason: 'binary (merge attribute)' };
730 case 'text':
731 case 'union': return mergeText({ driver, base, ours, theirs, maxBytes, rediff, maxWork, meter });
732 }
733 // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check
734 return assertNever(driver);
735}
Diagnostics6 git calls · 161 ms
CallStatusSizeTime0161 ms
discover200191 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=191 git.server.agent=git/github-9922ec520325-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=191 git.pkt.payload.max=36
ls-refs20012 KiB60 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=58 git.response.bytes=11990 git.response.cache=EXPIRED git.response.duration_ms=60 git.protocol.version=2 git.pkt.frames=152 git.pkt.data=151 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=11990 git.pkt.payload.max=122 git.ls_refs.count=151 git.ls_refs.head=refs/heads/main
fetchtree:0 · deepen 102004.2 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=4347 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=19912563f540228593df0c489082e5e2508e21e4 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=4347 git.pkt.payload.max=4247 git.sideband.band1.bytes=4247 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=10 git.pack.bytes=4247 git.pack.ofs_delta=0 git.pack.ref_delta=0 git.pack.chain.max=0 git.pack.trailer=a6caf8e129bea82c9bae4cbc7c130c9205add400 git.pack.full=10Open pack map
fetchtree:0200919 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=919 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=800d30ba8923860bfc460ca884b7f9ba22083588 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=919 git.pkt.payload.max=892 git.sideband.band1.bytes=892 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=892 git.pack.trailer=5323b9266eea5ded637285d1c5320699f12be76eOpen pack map
fetchtree:02002.4 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=2507 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=8f720d29ff85ce682ffdad9c393b04a3834c3203 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=2507 git.pkt.payload.max=2480 git.sideband.band1.bytes=2480 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=2480 git.pack.trailer=723b6bf1d4d6021fe5eb940c622b9ff00ee4a381Open pack map
fetch20014 KiB92 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=92 git.response.bytes=14294 git.response.cache=MISS git.response.duration_ms=92 git.fetch.wants=3bcbbb7431fdca67df2c3fce85ae5bf333c333e7 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=5 git.pkt.data=4 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=14294 git.pkt.payload.max=8192 git.sideband.band1.bytes=14262 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://github.com/ivarvong/ply
- Ref
- refs/heads/main
- Commit
- 19912563f540228593df0c489082e5e2508e21e4
- cf-ray
- a5e1ccd90964c6f8
- Request
- 089aeccb…
- Protocol
- v2 · sha1
- Agent
- git/github-9922ec520325-Linux
- Filter
- advertised
- Fetch
- shallow wait-for-done filter
- Capabilities
- agent ls-refs fetch server-option object-format