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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x4
 
x4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x4
x4
x16
x16
x64
x16
x71
x284
x71
x656
x82
x82
x207
x207
x278
x296
x304
x304
x306
x278
x331
x331
x341
x341
x341
x278
x297
x299
x299
x297
x278
x207
x217
x217
x207
x217
x217
x207
x233
x233
x233
x233
x207
x235
x236
x236
x236
x236
x236
x236
x262
x262
x262
x262
x321
x321
x82
x82
x83
x83
x82
x83
x83
x82
x82
x92
x92
x82
x82
x71
x71
x16
 
x1
 
 
 
 
 
 
 
x4
x4
x28
x84
x28
 
x4
x4
x178
x178
x507
x507
x583
x583
x583
x583
x583
x3040
x760
x1486
x178
 
x4
x4
x91
x91
x1174
x91
 
x4
x4
x19
x19
x19
x90
x90
x360
x360
x90
x360
x90
x19
x33
x33
x86
x86
x33
x19
x19
 
x4
x4
x775
x155
x155
x183
x183
x155
x181
x181
x155
x155
x155
 
x4
x4
x79
x169
x169
x79
x79
x86
x86
x86
x79
x79
x82
x79
x151
x179
x179
x151
x177
x177
x151
x79
x86
x86
x79
 
x4
x4
x19
x19
x20
x20
x20
x19
x26
x26
x33
x19
x72
x72
x33
x33
x33
x19
 
x4
x4
x48
x48
x80
x16
x16
x16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 




































































































































































































































































/**
 * 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[] }