All files / diff.ts

100.00% Branches 69/69
100.00% Lines 186/186
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
x1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x2
 
x2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x2
x2
x14
x14
x56
x14
x69
x276
x69
x640
x80
x80
x205
x205
x276
x294
x302
x302
x304
x276
x329
x329
x339
x339
x339
x276
x295
x297
x297
x295
x276
x205
x215
x215
x205
x215
x215
x205
x231
x231
x231
x231
x205
x233
x234
x234
x234
x234
x234
x234
x260
x260
x260
x260
x319
x319
x80
x80
x81
x81
x80
x81
x81
x80
x80
x90
x90
x80
x80
x69
x69
x14
 
x1
 
 
 
 
 
 
 
x2
x2
x26
x78
x26
 
x2
x2
x176
x176
x505
x505
x581
x581
x581
x581
x581
x3032
x758
x1474
x176
 
x2
x2
x89
x89
x1156
x89
 
x2
x2
x17
x17
x17
x88
x88
x358
x358
x88
x352
x88
x17
x31
x31
x84
x84
x31
x17
x17
 
x2
x2
x765
x153
x153
x181
x181
x153
x179
x179
x153
x153
x153
 
x2
x2
x77
x167
x167
x77
x77
x84
x84
x84
x77
x77
x80
x77
x149
x177
x177
x149
x175
x175
x149
x77
x84
x84
x77
 
x2
x2
x17
x17
x18
x18
x18
x17
x24
x24
x31
x17
x70
x70
x31
x31
x31
x17
 
x2
x2
x42
x42
x70
x14
x14
x14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 




































































































































































































































































/**
 * Bram Cohen's patience diff algorithm TypeScript implementation
 *
 * The following code has been ported and rewritten by Simon Lecoq from Jonathan Trent's original work at:
 * https://github.com/jonTrent/PatienceDiff/blob/dev/PatienceDiff.js
 *
 * Significant changes includes:
 * - Edited to be usable as a proper EcmaScript module (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)
 * - A single exported `diff()` function which generate a unified patch instead of a list of operations
 *   - This output is supposed to match the output of the `diff` command line tool
 * - Lot of code has moved or has been rewritten to match lowlighter's coding style
 * ________________________________________________________________________________
 *
 * Copyright (c) Simon Lecoq <@lowlighter>. (MIT License)
 * https://github.com/lowlighter/libs/blob/main/LICENSE
 *
 * ________________________________________________________________________________
 *
 * Original work was public domain. (The Unlicense)
 * https://raw.githubusercontent.com/jonTrent/PatienceDiff/master/UNLICENSE.txt
 *
 * @module
 */

/**
 * Compute unified patch from diff between two strings.
 *
 * Based on {@link https://bramcohen.livejournal.com/73318.html | Bram Cohen's patience diff algorithm}.
 * This function was ported and modified by {@link https://gihub.com/lowlighter | Simon Lecoq} based on the previous work of {@link https://gihub.com/jonTrent | Jonathan Trent}.
 *
 * @example
 * ```ts
 * import { diff } from "./diff.ts"
 * diff("foo\n", "foo")
 * // Returns
 * ```
 * ```diff
 * --- a
 * +++ b
 * \@@ -1 +1 \@@
 * -foo
 * +foo
 * \ No newline at end of file
 * ```
 *
 * @author Simon Lecoq (lowlighter)
 * @author Jonathan Trent
 * @author Bram Cohen
 * @license MIT
 */
export function diff(a: string, b: string, { context = 3 } = {}): string {
  let patch = ""
  const { lines } = patience(tokenize(a), tokenize(b))
  const cursor = { a: -1, b: -1 }
  for (let i = 0; i < lines.length; i++) {
    const { a, b } = lines[i]
    Object.assign(cursor, { a: Math.max(a, cursor.a), b: Math.max(b, cursor.b) })
    if ((a < 0) || (b < 0)) {
      const hunk = { lines: [] as string[], a: -1, b: -1, context, added: 0, deleted: 0 }
      let j = Math.max(0, i - context)
      while (j < lines.length) {
        const { line, a, b } = lines[j]
        if ((a >= 0) && (b >= 0)) {
          if (line === "\n") {
            if (j === lines.length - 1) {
              break
            }
            hunk.lines.push(line)
          } else {
            hunk.lines.push(` ${line}`)
          }
          hunk.context--
          hunk.added++
          hunk.deleted++
          if (hunk.context <= 0) {
            if (!lines.slice(j, j + 2 * context - 1).some(({ a, b }) => (a < 0) || (b < 0))) {
              break
            }
          }
        }
        if ((hunk.a < 0) && (a >= 0)) {
          hunk.a = a
        }
        if ((hunk.b < 0) && (b >= 0)) {
          hunk.b = b
        }
        if (a < 0) {
          hunk.lines.push(`+${line}`)
          hunk.added++
          hunk.context = context
        }
        if (b < 0) {
          if ((j === lines.length - 1) && (line === "\n")) {
            const previous = hunk.lines.pop()!.slice(1)
            hunk.lines.push(`-${previous}`)
            hunk.lines.push(`+${previous}`)
            hunk.lines.push("\\ No newline at end of file")
            break
          }
          hunk.lines.push(`-${line}`)
          hunk.deleted++
          hunk.context = context
        }
        j++
      }
      i = j
      if (hunk.a < 0) {
        hunk.a = cursor.a
      }
      if (hunk.b < 0) {
        hunk.b = cursor.b
      }
      hunk.lines.unshift(`@@ -${hunk.a + 1}${hunk.deleted !== 1 ? `,${hunk.deleted}` : ""} +${hunk.b + 1}${hunk.added !== 1 ? `,${hunk.added}` : ""} @@\n`)
      if (!patch) {
        patch += `--- a\n+++ b\n`
      }
      patch += hunk.lines.join("")
    }
  }
  return patch
}

/**
 * Tokenize text into text lines
 *
 * @example
 * ```ts
 * import { tokenize } from "./diff.ts"
 * tokenize("foo\nbar")
 * ``
 */
export function tokenize(text: string): string[] {
  text += "\n"
  return [...text.matchAll(/.*(?:\r?\n)/g)].map(([token]) => token.replace(/\r\n$/, "\n")).filter((token) => token)
}

/** Find unique lines between `i` and `j` */
function unique({ lines }: operand, i: number, j: number) {
  const occurrences = new Map<string, { index: number; count: number }>()
  for (; i <= j; i++) {
    const line = lines[i]
    if (occurrences.has(line)) {
      const entry = occurrences.get(line)!
      entry.count++
      entry.index = i
      continue
    }
    occurrences.set(line, { index: i, count: 1 })
  }
  return new Map<string, number>([...occurrences].filter(([_, { count }]) => count === 1).map(([key, { index }]) => [key, index]))
}

/** Find all unique common lines between `A[Ai...Aj]` and `B[Ai...Aj]` */
function common(A: operand, B: operand, Ai: number, Aj: number, Bi: number, Bj: number) {
  const a = unique(A, Ai, Aj)
  const b = unique(B, Bi, Bj)
  return new Map<string, position>([...a].filter(([line]) => b.has(line)).map(([line, index]) => [line, { a: index, b: b.get(line)! }]))
}

/** Compute Longest Common Subsequence */
function lcs(ab: ReturnType<typeof common>) {
  const lcs = [] as Array<position & { previous?: position }>
  const subsequences = [] as Array<typeof lcs>
  for (const [_, v] of ab) {
    let i = 0
    while (subsequences.at(i)?.at(-1)?.b! < v.b) {
      i++
    }
    subsequences[i] ??= []
    subsequences[i].push({ ...v, previous: (i > 0 ? subsequences.at(i - 1)?.at(-1) : undefined) })
  }
  if (subsequences.length) {
    lcs.push(subsequences.at(-1)!.at(-1)!)
    while (lcs.at(-1)!.previous) {
      lcs.push(lcs.at(-1)!.previous!)
    }
  }
  return lcs.reverse()
}

/** Register line entry in `result` */
function register(result: result, A: operand, B: operand, a: number, b: number) {
  const line = { line: 0 <= a ? A.lines[a] : B.lines[b], a, b } as line
  switch (true) {
    case b < 0:
      result.deleted++
      break
    case a < 0:
      result.added++
      break
  }
  result.lines.push(line)
}

/** Register submatches and recurse over common lines */
function submatch(result: result, A: operand, B: operand, Ai: number, Aj: number, Bi: number, Bj: number) {
  while ((Ai <= Aj) && (Bi <= Bj) && (A.lines[Ai] === B.lines[Bi])) {
    register(result, A, B, Ai++, Bi++)
  }
  const Tj = Aj
  while ((Ai <= Aj) && (Bi <= Bj) && (A.lines[Aj] === B.lines[Bj])) {
    Aj--
    Bj--
  }
  const ab = common(A, B, Ai, Aj, Bi, Bj)
  if (ab.size) {
    recurse(result, A, B, Ai, Aj, Bi, Bj, ab)
  } else {
    while (Ai <= Aj) {
      register(result, A, B, Ai++, -1)
    }
    while (Bi <= Bj) {
      register(result, A, B, -1, Bi++)
    }
  }
  while (Aj < Tj) {
    register(result, A, B, ++Aj, ++Bj)
  }
}

/** Recurses on each LCS subsequences until there are none available */
function recurse(result: result, A: operand, B: operand, Ai: number, Aj: number, Bi: number, Bj: number, ab?: ReturnType<typeof common>) {
  const x = lcs(ab ?? common(A, B, Ai, Aj, Bi, Bj))
  if (!x.length) {
    submatch(result, A, B, Ai, Aj, Bi, Bj)
    return
  }
  if ((Ai < x[0].a) || (Bi < x[0].b)) {
    submatch(result, A, B, Ai, x[0].a - 1, Bi, x[0].b - 1)
  }
  let i = 0
  for (; i < x.length - 1; i++) {
    submatch(result, A, B, x[i].a, x[i + 1].a - 1, x[i].b, x[i + 1].b - 1)
  }
  if (+(x[i].a <= Aj) | +(x[i].b <= Bj)) {
    submatch(result, A, B, x[i].a, Aj, x[i].b, Bj)
  }
}

/** Bram Cohen's patience diff algorithm */
function patience(a: string[], b: string[]) {
  const A = { lines: a } as operand
  const B = { lines: b } as operand
  const result = { lines: [], added: 0, deleted: 0 } as result
  recurse(result, A, B, 0, A.lines.length - 1, 0, B.lines.length - 1)
  return result
}

/** Result */
type result = {
  lines: line[]
  added: number
  deleted: number
}

/** Line entry */
type line = { line: string } & position

/** Line position */
type position = { a: number; b: number }

/** Diff operand */
type operand = { lines: string[] }