1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
14 // A pair is a pair of values tracked for both the x and y side of a diff.
15 // It is typically a pair of line indexes.
16 type pair struct{ x, y int }
18 // Diff returns an anchored diff of the two texts old and new
19 // in the “unified diff” format. If old and new are identical,
20 // Diff returns a nil slice (no output).
22 // Unix diff implementations typically look for a diff with
23 // the smallest number of lines inserted and removed,
24 // which can in the worst case take time quadratic in the
25 // number of lines in the texts. As a result, many implementations
26 // either can be made to run for a long time or cut off the search
27 // after a predetermined amount of work.
29 // In contrast, this implementation looks for a diff with the
30 // smallest number of “unique” lines inserted and removed,
31 // where unique means a line that appears just once in both old and new.
32 // We call this an “anchored diff” because the unique lines anchor
33 // the chosen matching regions. An anchored diff is usually clearer
34 // than a standard diff, because the algorithm does not try to
35 // reuse unrelated blank lines or closing braces.
36 // The algorithm also guarantees to run in O(n log n) time
37 // instead of the standard O(n²) time.
39 // Some systems call this approach a “patience diff,” named for
40 // the “patience sorting” algorithm, itself named for a solitaire card game.
41 // We avoid that name for two reasons. First, the name has been used
42 // for a few different variants of the algorithm, so it is imprecise.
43 // Second, the name is frequently interpreted as meaning that you have
44 // to wait longer (to be patient) for the diff, meaning that it is a slower algorithm,
45 // when in fact the algorithm is faster than the standard one.
46 func Diff(oldName string, old []byte, newName string, new []byte) []byte {
47 if bytes.Equal(old, new) {
55 fmt.Fprintf(&out, "diff %s %s\n", oldName, newName)
56 fmt.Fprintf(&out, "--- %s\n", oldName)
57 fmt.Fprintf(&out, "+++ %s\n", newName)
59 // Loop over matches to consider,
60 // expanding each match to include surrounding lines,
61 // and then printing diff chunks.
62 // To avoid setup/teardown cases outside the loop,
63 // tgs returns a leading {0,0} and trailing {len(x), len(y)} pair
64 // in the sequence of matches.
66 done pair // printed up to x[:done.x] and y[:done.y]
67 chunk pair // start lines of current chunk
68 count pair // number of lines from each side in current chunk
69 ctext []string // lines for current chunk
71 for _, m := range tgs(x, y) {
73 // Already handled scanning forward from earlier match.
77 // Expand matching lines as far possible,
78 // establishing that x[start.x:end.x] == y[start.y:end.y].
79 // Note that on the first (or last) iteration we may (or definitely do)
80 // have an empty match: start.x==end.x and start.y==end.y.
82 for start.x > done.x && start.y > done.y && x[start.x-1] == y[start.y-1] {
87 for end.x < len(x) && end.y < len(y) && x[end.x] == y[end.y] {
92 // Emit the mismatched lines before start into this chunk.
93 // (No effect on first sentinel iteration, when start = {0,0}.)
94 for _, s := range x[done.x:start.x] {
95 ctext = append(ctext, "-"+s)
98 for _, s := range y[done.y:start.y] {
99 ctext = append(ctext, "+"+s)
103 // If we're not at EOF and have too few common lines,
104 // the chunk includes all the common lines and continues.
105 const C = 3 // number of context lines
106 if (end.x < len(x) || end.y < len(y)) &&
107 (end.x-start.x < C || (len(ctext) > 0 && end.x-start.x < 2*C)) {
108 for _, s := range x[start.x:end.x] {
109 ctext = append(ctext, " "+s)
117 // End chunk with common lines for context.
123 for _, s := range x[start.x : start.x+n] {
124 ctext = append(ctext, " "+s)
128 done = pair{start.x + n, start.y + n}
130 // Format and emit chunk.
131 // Convert line numbers to 1-indexed.
132 // Special case: empty file shows up as 0,0 not 1,0.
139 fmt.Fprintf(&out, "@@ -%d,%d +%d,%d @@\n", chunk.x, count.x, chunk.y, count.y)
140 for _, s := range ctext {
148 // If we reached EOF, we're done.
149 if end.x >= len(x) && end.y >= len(y) {
153 // Otherwise start a new chunk.
154 chunk = pair{end.x - C, end.y - C}
155 for _, s := range x[chunk.x:end.x] {
156 ctext = append(ctext, " "+s)
166 // lines returns the lines in the file x, including newlines.
167 // If the file does not end in a newline, one is supplied
168 // along with a warning about the missing newline.
169 func lines(x []byte) []string {
170 l := strings.SplitAfter(string(x), "\n")
171 if l[len(l)-1] == "" {
174 // Treat last line as having a message about the missing newline attached,
175 // using the same text as BSD/GNU diff (including the leading backslash).
176 l[len(l)-1] += "\n\\ No newline at end of file\n"
181 // tgs returns the pairs of indexes of the longest common subsequence
182 // of unique lines in x and y, where a unique line is one that appears
183 // once in x and once in y.
185 // The longest common subsequence algorithm is as described in
186 // Thomas G. Szymanski, “A Special Case of the Maximal Common
187 // Subsequence Problem,” Princeton TR #170 (January 1975),
188 // available at https://research.swtch.com/tgs170.pdf.
189 func tgs(x, y []string) []pair {
190 // Count the number of times each string appears in a and b.
191 // We only care about 0, 1, many, counted as 0, -1, -2
192 // for the x side and 0, -4, -8 for the y side.
193 // Using negative numbers now lets us distinguish positive line numbers later.
194 m := make(map[string]int)
195 for _, s := range x {
196 if c := m[s]; c > -2 {
200 for _, s := range y {
201 if c := m[s]; c > -8 {
206 // Now unique strings can be identified by m[s] = -1+-4.
208 // Gather the indexes of those strings in x and y, building:
209 // xi[i] = increasing indexes of unique strings in x.
210 // yi[i] = increasing indexes of unique strings in y.
211 // inv[i] = index j such that x[xi[i]] = y[yi[j]].
212 var xi, yi, inv []int
213 for i, s := range y {
219 for i, s := range x {
220 if j, ok := m[s]; ok && j >= 0 {
226 // Apply Algorithm A from Szymanski's paper.
227 // In those terms, A = J = inv and B = [0, n).
228 // We add sentinel pairs {0,0}, and {len(x),len(y)}
229 // to the returned sequence, to help the processing loop.
237 for i := 0; i < n; i++ {
238 k := sort.Search(n, func(k int) bool {
245 for _, v := range L {
250 seq := make([]pair, 2+k)
251 seq[1+k] = pair{len(x), len(y)} // sentinel at end
253 for i := n - 1; i >= 0; i-- {
254 if L[i] == k && J[i] < lastj {
255 seq[k] = pair{xi[i], yi[J[i]]}
259 seq[0] = pair{0, 0} // sentinel at start