- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/src/engine/text.ts?version=76&format=json
374 linesFirst import 100%Last change First import in version 0, 1 version changed it
You're reading version 76. The newest is 318, and 2 versions since then changed this file.
1// Text helpers: line endings, splitting, and a line diff (a longest common
2// subsequence, found with Myers' O(ND) algorithm in linear space).
4/** Normalize line endings to "\n". */
5export function normalizeText(text: string): string {
6 return text.replace(/\r\n?/g, "\n");
7}
9/** Split normalized text into lines. "" -> []; a trailing "\n" ends the last line. */
10export function splitLines(text: string): string[] {
11 if (text === "") return [];
12 const body = text.endsWith("\n") ? text.slice(0, -1) : text;
13 return body.split("\n");
14}
16/** Join lines into file text. A non-empty file always ends with "\n". */
17export function joinLines(lines: readonly string[]): string {
18 return lines.length === 0 ? "" : lines.join("\n") + "\n";
19}
21/** Normalize, then make a non-empty text end with "\n" (how files are projected). */
22export function canonicalText(text: string): string {
23 return joinLines(splitLines(normalizeText(text)));
24}
26/**
27 * One hunk of a line diff: old lines [start, end) become `lines`.
28 * start === end is a pure insertion before old line `start`.
29 */
30export interface Hunk {
31 readonly start: number;
32 readonly end: number;
33 readonly lines: readonly string[];
34}
36/**
37 * Line diff of `a` (old) against `b` (new), as hunks in order. The unchanged
38 * lines are a longest common subsequence, so every hunk is as small as it can
39 * be, up to a cost: where one stretch needs more than about MAX_COST edits (a
40 * file reordered or rewritten through), the search stops there and goes on
41 * from the furthest point it reached, as git's xdiff does (abso issue 158).
42 * The diff is then close to minimal rather than minimal, and costs about the
43 * file's length times MAX_COST instead of its length squared.
44 */
45export function diffLines(a: readonly string[], b: readonly string[]): Hunk[] {
46 const matches = commonLines(a, b);
47 const hunks: Hunk[] = [];
48 let i = 0;
49 let j = 0;
50 for (let m = 0; m <= matches.length; m += 2) {
51 const mi = m < matches.length ? matches[m]! : a.length;
52 const mj = m < matches.length ? matches[m + 1]! : b.length;
53 if (mi > i || mj > j) hunks.push({ start: i, end: mi, lines: b.slice(j, mj) });
54 i = mi + 1;
55 j = mj + 1;
56 }
57 return hunks;
58}
60/**
61 * The matched pairs of a longest common subsequence of `a` and `b`, flattened
62 * as [i0, j0, i1, j1, ...] in increasing order.
63 */
64function commonLines(a: readonly string[], b: readonly string[]): number[] {
65 // Common prefix and suffix match directly.
66 let pre = 0;
67 while (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++;
68 let suf = 0;
69 while (suf < a.length - pre && suf < b.length - pre && a[a.length - 1 - suf] === b[b.length - 1 - suf]) suf++;
70 const out: number[] = [];
71 for (let k = 0; k < pre; k++) out.push(k, k);
73 // A line that occurs on only one side can never be matched; leave it out of
74 // the search (this also makes wholly different texts instant).
75 const ids = new Map<string, number>();
76 const intern = (s: string): number => {
77 let id = ids.get(s);
78 if (id === undefined) {
79 id = ids.size;
80 ids.set(s, id);
81 }
82 return id;
83 };
84 const inA = new Set<number>();
85 const inB = new Set<number>();
86 const aIds: number[] = [];
87 const bIds: number[] = [];
88 for (let i = pre; i < a.length - suf; i++) inA.add((aIds[i - pre] = intern(a[i]!)));
89 for (let j = pre; j < b.length - suf; j++) inB.add((bIds[j - pre] = intern(b[j]!)));
90 const aPos: number[] = [];
91 const bPos: number[] = [];
92 const x: number[] = [];
93 const y: number[] = [];
94 aIds.forEach((id, i) => {
95 if (inB.has(id)) {
96 aPos.push(pre + i);
97 x.push(id);
98 }
99 });
100 bIds.forEach((id, j) => {
101 if (inA.has(id)) {
102 bPos.push(pre + j);
103 y.push(id);
104 }
105 });
106 const pairs: number[] = [];
107 myers(Int32Array.from(x), Int32Array.from(y), 0, x.length, 0, y.length, pairs);
108 for (let k = 0; k < pairs.length; k += 2) out.push(aPos[pairs[k]!]!, bPos[pairs[k + 1]!]!);
110 for (let k = suf; k > 0; k--) out.push(a.length - k, b.length - k);
111 return out;
112}
114/** About how many edits one stretch of a diff searches before settling for close to minimal (git's XDL_MAX_COST_MIN). */
115export const MAX_COST = 256;
117/**
118 * Myers' linear-space diff on a[aLo, aHi) and b[bLo, bHi): pushes the pairs
119 * of a longest common subsequence, in order, onto `out`. Each step splits the
120 * problem at a point on an optimal edit path and recurses on both halves.
121 */
122function myers(a: Int32Array, b: Int32Array, aLo: number, aHi: number, bLo: number, bHi: number, out: number[]): void {
123 while (aLo < aHi && bLo < bHi && a[aLo] === b[bLo]) out.push(aLo++, bLo++);
124 let suf = 0;
125 while (aLo < aHi - suf && bLo < bHi - suf && a[aHi - 1 - suf] === b[bHi - 1 - suf]) suf++;
126 const n = aHi - suf - aLo;
127 const m = bHi - suf - bLo;
128 if (n > 0 && m > 0) {
129 const split = bisect(a, aLo, n, b, bLo, m, Math.max(MAX_COST, Math.ceil(Math.sqrt(n + m))));
130 if (split) {
131 myers(a, b, aLo, aLo + split[0], bLo, bLo + split[1], out);
132 myers(a, b, aLo + split[0], aHi - suf, bLo + split[1], bHi - suf, out);
133 }
134 }
135 for (let k = suf; k > 0; k--) out.push(aHi - k, bHi - k);
136}
138/**
139 * Where the furthest-reaching forward and backward paths of a shortest edit
140 * script between a[aLo, aLo+n) and b[bLo, bLo+m) meet: a point [x, y] on an
141 * optimal path, relative to aLo and bLo. Both inputs are non-empty and differ
142 * in their first and last elements, so the point is neither corner and both
143 * halves are strictly smaller. Diagonals that run off the edit grid are
144 * dropped from the search (as in diff-match-patch's diff_bisect). Past `cap`
145 * edits it stops and answers the furthest point a forward path reached, which
146 * is on a path of that many edits from the start, so the first half stays
147 * exact; that point is never a corner, so both halves are still smaller.
148 */
149function bisect(
150 a: Int32Array,
151 aLo: number,
152 n: number,
153 b: Int32Array,
154 bLo: number,
155 m: number,
156 cap: number,
157): [number, number] | undefined {
158 const maxD = Math.ceil((n + m) / 2);
159 let bestX = -1;
160 let bestY = -1;
161 const offset = maxD;
162 const size = 2 * maxD + 2;
163 const v1 = new Int32Array(size).fill(-1);
164 const v2 = new Int32Array(size).fill(-1);
165 v1[offset + 1] = 0;
166 v2[offset + 1] = 0;
167 const delta = n - m;
168 const front = (delta & 1) !== 0;
169 let k1start = 0;
170 let k1end = 0;
171 let k2start = 0;
172 let k2end = 0;
173 for (let d = 0; d <= maxD; d++) {
174 for (let k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
175 const i1 = offset + k1;
176 let x1 = k1 === -d || (k1 !== d && v1[i1 - 1]! < v1[i1 + 1]!) ? v1[i1 + 1]! : v1[i1 - 1]! + 1;
177 let y1 = x1 - k1;
178 while (x1 < n && y1 < m && a[aLo + x1] === b[bLo + y1]) {
179 x1++;
180 y1++;
181 }
182 v1[i1] = x1;
183 if (x1 <= n && y1 <= m && x1 + y1 > bestX + bestY && x1 + y1 < n + m) {
184 bestX = x1;
185 bestY = y1;
186 }
187 if (x1 > n) k1end += 2;
188 else if (y1 > m) k1start += 2;
189 else if (front) {
190 const i2 = offset + delta - k1;
191 if (i2 >= 0 && i2 < size && v2[i2] !== -1 && x1 >= n - v2[i2]!) return [x1, y1];
192 }
193 }
194 for (let k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
195 const i2 = offset + k2;
196 let x2 = k2 === -d || (k2 !== d && v2[i2 - 1]! < v2[i2 + 1]!) ? v2[i2 + 1]! : v2[i2 - 1]! + 1;
197 let y2 = x2 - k2;
198 while (x2 < n && y2 < m && a[aLo + n - 1 - x2] === b[bLo + m - 1 - y2]) {
199 x2++;
200 y2++;
201 }
202 v2[i2] = x2;
203 if (x2 > n) k2end += 2;
204 else if (y2 > m) k2start += 2;
205 else if (!front) {
206 const i1 = offset + delta - k2;
207 if (i1 >= 0 && i1 < size && v1[i1] !== -1) {
208 const x1 = v1[i1]!;
209 if (x1 >= n - x2) return [x1, offset + x1 - i1];
210 }
211 }
212 }
213 if (d >= cap) {
214 if (bestX + bestY > 0) return [bestX, bestY];
215 const x = n >> 1;
216 const y = m >> 1;
217 return x + y > 0 && x + y < n + m ? [x, y] : [n, 0];
218 }
219 }
220 return undefined; // not reached: the paths meet by d = ceil((n + m) / 2)
221}
223/**
224 * Three-way merge of lines, the way git merges a file: `ours` and `theirs`
225 * both started from `base`. Changes on one side only are taken; changes both
226 * sides made identically are taken once; changes that overlap or touch and
227 * differ are a conflict (counted, with ours kept in `lines`), unless
228 * `resolve` settles it: given the base span and each side's text for it, it
229 * may return the merged text. `resolved` lists where each settled span
230 * starts in `lines`.
231 */
232export function mergeLines(
233 base: readonly string[],
234 ours: readonly string[],
235 theirs: readonly string[],
236 resolve?: (
237 base: readonly string[],
238 ours: readonly string[],
239 theirs: readonly string[],
240 at: number,
241 ) => string[] | undefined,
242 conflict?: (span: MergeConflict) => string[],
243): { lines: string[]; conflicts: number; resolved: number[]; conflictsAt: { at: number; length: number }[] } {
244 const resolved: number[] = [];
245 const conflictsAt: { at: number; length: number }[] = [];
246 // How far each side's line numbers have moved from the base's, by the hunks before the current span.
247 let oShift = 0;
248 let tShift = 0;
249 const oh = diffLines(base, ours);
250 const th = diffLines(base, theirs);
251 const out: string[] = [];
252 let conflicts = 0;
253 let pos = 0;
254 let i = 0;
255 let j = 0;
256 const apply = (group: readonly Hunk[], lo: number, hi: number): string[] => {
257 const result: string[] = [];
258 let p = lo;
259 for (const h of group) {
260 result.push(...base.slice(p, h.start), ...h.lines);
261 p = h.end;
262 }
263 result.push(...base.slice(p, hi));
264 return result;
265 };
266 while (i < oh.length || j < th.length) {
267 const first = j >= th.length || (i < oh.length && oh[i]!.start <= th[j]!.start) ? oh[i++]! : th[j++]!;
268 const groupO: Hunk[] = [];
269 const groupT: Hunk[] = [];
270 (oh.includes(first) ? groupO : groupT).push(first);
271 const lo = first.start;
272 let hi = first.end;
273 // Every hunk that overlaps or touches the span joins the group.
274 for (let grew = true; grew; ) {
275 grew = false;
276 while (i < oh.length && oh[i]!.start <= hi) {
277 groupO.push(oh[i]!);
278 hi = Math.max(hi, oh[i++]!.end);
279 grew = true;
280 }
281 while (j < th.length && th[j]!.start <= hi) {
282 groupT.push(th[j]!);
283 hi = Math.max(hi, th[j++]!.end);
284 grew = true;
285 }
286 }
287 out.push(...base.slice(pos, lo));
288 const o = apply(groupO, lo, hi);
289 const t = apply(groupT, lo, hi);
290 if (groupO.length === 0) out.push(...t);
291 else if (groupT.length === 0 || (o.length === t.length && o.every((l, k) => l === t[k]))) out.push(...o);
292 else {
293 const settled = resolve?.(base.slice(lo, hi), o, t, lo);
294 if (settled) {
295 resolved.push(out.length);
296 out.push(...settled);
297 } else {
298 conflicts++;
299 const shown = conflict
300 ? conflict({
301 base: base.slice(lo, hi),
302 ours: o,
303 theirs: t,
304 baseAt: lo,
305 oursAt: lo + oShift,
306 theirsAt: lo + tShift,
307 })
308 : o;
309 conflictsAt.push({ at: out.length, length: shown.length });
310 out.push(...shown);
311 }
312 }
313 oShift += o.length - (hi - lo);
314 tShift += t.length - (hi - lo);
315 pos = hi;
316 }
317 out.push(...base.slice(pos));
318 return { lines: out, conflicts, resolved, conflictsAt };
319}
321/** A span both sides changed differently: each side's text, and where it starts in base, ours and theirs (0-based). */
322export interface MergeConflict {
323 readonly base: readonly string[];
324 readonly ours: readonly string[];
325 readonly theirs: readonly string[];
326 readonly baseAt: number;
327 readonly oursAt: number;
328 readonly theirsAt: number;
329}
331/**
332 * Merge one line both sides changed, word by word (#37): `const SYSTEMS =
333 * [a, b, c]` with d added on one side and e on the other becomes
334 * `[a, b, c, e, d]`. Words and punctuation are merged like lines. Where both
335 * inserted different things at the same point, both are kept (theirs, then
336 * ours) only when each is a list item, beginning or ending with a comma, inside
337 * `[...]` or `{...}` in the base line; call arguments and anything else are no
338 * merge. Any other overlap is no merge either (undefined).
339 */
340export function mergeWords(base: string, ours: string, theirs: string): string | undefined {
341 const words = (s: string): string[] => s.match(/[A-Za-z0-9_$]+|\s+|[^A-Za-z0-9_$\s]/g) ?? [];
342 const b = words(base);
343 const OPEN = "([{";
344 const CLOSE = ")]}";
345 const listItem = (piece: readonly string[]): boolean => {
346 const solid = piece.filter((w) => w.trim() !== "");
347 if (solid.length < 2 || (solid[0] !== "," && solid[solid.length - 1] !== ",")) return false;
348 let depth = 0;
349 for (const w of solid) {
350 if (OPEN.includes(w)) depth++;
351 else if (CLOSE.includes(w) && --depth < 0) return false;
352 }
353 return depth === 0;
354 };
355 // The bracket the insertion point sits in, in the base line.
356 const enclosing = (at: number): string | undefined => {
357 let depth = 0;
358 for (let i = at - 1; i >= 0; i--) {
359 if (CLOSE.includes(b[i]!)) depth++;
360 else if (OPEN.includes(b[i]!)) {
361 if (depth === 0) return b[i];
362 depth--;
363 }
364 }
365 return undefined;
366 };
367 const m = mergeLines(b, words(ours), words(theirs), (span, o, t, at) => {
368 const bracket = enclosing(at);
369 return span.length === 0 && (bracket === "[" || bracket === "{") && listItem(o) && listItem(t)
370 ? [...t, ...o]
371 : undefined;
372 });
373 return m.conflicts > 0 ? undefined : m.lines.join("");
374}