Debian Codegraph @

testutil/internal/difflib.go

raw symbols SCIP
1 // Copyright (c) The EfficientGo Authors.
2 // Licensed under the Apache License 2.0.
3
4 // It provides tools to compare sequences of strings and generate textual diffs.
5 //
6 // Maintaining `GetUnifiedDiffString` here because original repository
7 // (https://github.com/pmezard/go-difflib) is no loger maintained.
8
9 package internal
10
11 import (
12 "bufio"
13 "bytes"
14 "fmt"
15 "io"
16 "strings"
17 )
18
19 func min(a, b int) int {
20 if a < b {
21 return a
22 }
23 return b
24 }
25
26 func max(a, b int) int {
27 if a > b {
28 return a
29 }
30 return b
31 }
32
33 func calculateRatio(matches, length int) float64 {
34 if length > 0 {
35 return 2.0 * float64(matches) / float64(length)
36 }
37 return 1.0
38 }
39
40 type Match struct {
41 A int
42 B int
43 Size int
44 }
45
46 type OpCode struct {
47 Tag byte
48 I1 int
49 I2 int
50 J1 int
51 J2 int
52 }
53
54 // SequenceMatcher compares sequence of strings. The basic
55 // algorithm predates, and is a little fancier than, an algorithm
56 // published in the late 1980's by Ratcliff and Obershelp under the
57 // hyperbolic name "gestalt pattern matching". The basic idea is to find
58 // the longest contiguous matching subsequence that contains no "junk"
59 // elements (R-O doesn't address junk). The same idea is then applied
60 // recursively to the pieces of the sequences to the left and to the right
61 // of the matching subsequence. This does not yield minimal edit
62 // sequences, but does tend to yield matches that "look right" to people.
63 //
64 // SequenceMatcher tries to compute a "human-friendly diff" between two
65 // sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
66 // longest *contiguous* & junk-free matching subsequence. That's what
67 // catches peoples' eyes. The Windows(tm) windiff has another interesting
68 // notion, pairing up elements that appear uniquely in each sequence.
69 // That, and the method here, appear to yield more intuitive difference
70 // reports than does diff. This method appears to be the least vulnerable
71 // to synching up on blocks of "junk lines", though (like blank lines in
72 // ordinary text files, or maybe "<P>" lines in HTML files). That may be
73 // because this is the only method of the 3 that has a *concept* of
74 // "junk" <wink>.
75 //
76 // Timing: Basic R-O is cubic time worst case and quadratic time expected
77 // case. SequenceMatcher is quadratic time for the worst case and has
78 // expected-case behavior dependent in a complicated way on how many
79 // elements the sequences have in common; best case time is linear.
80 type SequenceMatcher struct {
81 a []string
82 b []string
83 b2j map[string][]int
84 IsJunk func(string) bool
85 autoJunk bool
86 bJunk map[string]struct{}
87 matchingBlocks []Match
88 fullBCount map[string]int
89 bPopular map[string]struct{}
90 opCodes []OpCode
91 }
92
93 func NewMatcher(a, b []string) *SequenceMatcher {
94 m := SequenceMatcher{autoJunk: true}
95 m.SetSeqs(a, b)
96 return &m
97 }
98
99 func NewMatcherWithJunk(a, b []string, autoJunk bool,
100 isJunk func(string) bool,
101 ) *SequenceMatcher {
102 m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk}
103 m.SetSeqs(a, b)
104 return &m
105 }
106
107 // Set two sequences to be compared.
108 func (m *SequenceMatcher) SetSeqs(a, b []string) {
109 m.SetSeq1(a)
110 m.SetSeq2(b)
111 }
112
113 // Set the first sequence to be compared. The second sequence to be compared is
114 // not changed.
115 //
116 // SequenceMatcher computes and caches detailed information about the second
117 // sequence, so if you want to compare one sequence S against many sequences,
118 // use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other
119 // sequences.
120 //
121 // See also SetSeqs() and SetSeq2().
122 func (m *SequenceMatcher) SetSeq1(a []string) {
123 if &a == &m.a {
124 return
125 }
126 m.a = a
127 m.matchingBlocks = nil
128 m.opCodes = nil
129 }
130
131 // Set the second sequence to be compared. The first sequence to be compared is
132 // not changed.
133 func (m *SequenceMatcher) SetSeq2(b []string) {
134 if &b == &m.b {
135 return
136 }
137 m.b = b
138 m.matchingBlocks = nil
139 m.opCodes = nil
140 m.fullBCount = nil
141 m.chainB()
142 }
143
144 func (m *SequenceMatcher) chainB() {
145 // Populate line -> index mapping
146 b2j := map[string][]int{}
147 for i, s := range m.b {
148 indices := b2j[s]
149 indices = append(indices, i)
150 b2j[s] = indices
151 }
152
153 // Purge junk elements
154 m.bJunk = map[string]struct{}{}
155 if m.IsJunk != nil {
156 junk := m.bJunk
157 for s := range b2j {
158 if m.IsJunk(s) {
159 junk[s] = struct{}{}
160 }
161 }
162 for s := range junk {
163 delete(b2j, s)
164 }
165 }
166
167 // Purge remaining popular elements
168 popular := map[string]struct{}{}
169 n := len(m.b)
170 if m.autoJunk && n >= 200 {
171 ntest := n/100 + 1
172 for s, indices := range b2j {
173 if len(indices) > ntest {
174 popular[s] = struct{}{}
175 }
176 }
177 for s := range popular {
178 delete(b2j, s)
179 }
180 }
181 m.bPopular = popular
182 m.b2j = b2j
183 }
184
185 func (m *SequenceMatcher) isBJunk(s string) bool {
186 _, ok := m.bJunk[s]
187 return ok
188 }
189
190 // Find longest matching block in a[alo:ahi] and b[blo:bhi].
191 //
192 // If IsJunk is not defined:
193 //
194 // Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
195 //
196 // alo <= i <= i+k <= ahi
197 // blo <= j <= j+k <= bhi
198 //
199 // and for all (i',j',k') meeting those conditions,
200 //
201 // k >= k'
202 // i <= i'
203 // and if i == i', j <= j'
204 //
205 // In other words, of all maximal matching blocks, return one that
206 // starts earliest in a, and of all those maximal matching blocks that
207 // start earliest in a, return the one that starts earliest in b.
208 //
209 // If IsJunk is defined, first the longest matching block is
210 // determined as above, but with the additional restriction that no
211 // junk element appears in the block. Then that block is extended as
212 // far as possible by matching (only) junk elements on both sides. So
213 // the resulting block never matches on junk except as identical junk
214 // happens to be adjacent to an "interesting" match.
215 //
216 // If no blocks match, return (alo, blo, 0).
217 func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match {
218 // CAUTION: stripping common prefix or suffix would be incorrect.
219 // E.g.,
220 // ab
221 // acab
222 // Longest matching block is "ab", but if common prefix is
223 // stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
224 // strip, so ends up claiming that ab is changed to acab by
225 // inserting "ca" in the middle. That's minimal but unintuitive:
226 // "it's obvious" that someone inserted "ac" at the front.
227 // Windiff ends up at the same place as diff, but by pairing up
228 // the unique 'b's and then matching the first two 'a's.
229 besti, bestj, bestsize := alo, blo, 0
230
231 // find longest junk-free match
232 // during an iteration of the loop, j2len[j] = length of longest
233 // junk-free match ending with a[i-1] and b[j]
234 j2len := map[int]int{}
235 for i := alo; i != ahi; i++ {
236 // look at all instances of a[i] in b; note that because
237 // b2j has no junk keys, the loop is skipped if a[i] is junk
238 newj2len := map[int]int{}
239 for _, j := range m.b2j[m.a[i]] {
240 // a[i] matches b[j]
241 if j < blo {
242 continue
243 }
244 if j >= bhi {
245 break
246 }
247 k := j2len[j-1] + 1
248 newj2len[j] = k
249 if k > bestsize {
250 besti, bestj, bestsize = i-k+1, j-k+1, k
251 }
252 }
253 j2len = newj2len
254 }
255
256 // Extend the best by non-junk elements on each end. In particular,
257 // "popular" non-junk elements aren't in b2j, which greatly speeds
258 // the inner loop above, but also means "the best" match so far
259 // doesn't contain any junk *or* popular non-junk elements.
260 for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) &&
261 m.a[besti-1] == m.b[bestj-1] {
262 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
263 }
264 for besti+bestsize < ahi && bestj+bestsize < bhi &&
265 !m.isBJunk(m.b[bestj+bestsize]) &&
266 m.a[besti+bestsize] == m.b[bestj+bestsize] {
267 bestsize++
268 }
269
270 // Now that we have a wholly interesting match (albeit possibly
271 // empty!), we may as well suck up the matching junk on each
272 // side of it too. Can't think of a good reason not to, and it
273 // saves post-processing the (possibly considerable) expense of
274 // figuring out what to do with it. In the case of an empty
275 // interesting match, this is clearly the right thing to do,
276 // because no other kind of match is possible in the regions.
277 for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) &&
278 m.a[besti-1] == m.b[bestj-1] {
279 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
280 }
281 for besti+bestsize < ahi && bestj+bestsize < bhi &&
282 m.isBJunk(m.b[bestj+bestsize]) &&
283 m.a[besti+bestsize] == m.b[bestj+bestsize] {
284 bestsize++
285 }
286
287 return Match{A: besti, B: bestj, Size: bestsize}
288 }
289
290 // Return list of triples describing matching subsequences.
291 //
292 // Each triple is of the form (i, j, n), and means that
293 // a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
294 // i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are
295 // adjacent triples in the list, and the second is not the last triple in the
296 // list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe
297 // adjacent equal blocks.
298 //
299 // The last triple is a dummy, (len(a), len(b), 0), and is the only
300 // triple with n==0.
301 func (m *SequenceMatcher) GetMatchingBlocks() []Match {
302 if m.matchingBlocks != nil {
303 return m.matchingBlocks
304 }
305
306 var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match
307 matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match {
308 match := m.findLongestMatch(alo, ahi, blo, bhi)
309 i, j, k := match.A, match.B, match.Size
310 if match.Size > 0 {
311 if alo < i && blo < j {
312 matched = matchBlocks(alo, i, blo, j, matched)
313 }
314 matched = append(matched, match)
315 if i+k < ahi && j+k < bhi {
316 matched = matchBlocks(i+k, ahi, j+k, bhi, matched)
317 }
318 }
319 return matched
320 }
321 matched := matchBlocks(0, len(m.a), 0, len(m.b), nil)
322
323 // It's possible that we have adjacent equal blocks in the
324 // matching_blocks list now.
325 nonAdjacent := []Match{}
326 i1, j1, k1 := 0, 0, 0
327 for _, b := range matched {
328 // Is this block adjacent to i1, j1, k1?
329 i2, j2, k2 := b.A, b.B, b.Size
330 if i1+k1 == i2 && j1+k1 == j2 {
331 // Yes, so collapse them -- this just increases the length of
332 // the first block by the length of the second, and the first
333 // block so lengthened remains the block to compare against.
334 k1 += k2
335 } else {
336 // Not adjacent. Remember the first block (k1==0 means it's
337 // the dummy we started with), and make the second block the
338 // new block to compare against.
339 if k1 > 0 {
340 nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
341 }
342 i1, j1, k1 = i2, j2, k2
343 }
344 }
345 if k1 > 0 {
346 nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
347 }
348
349 nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0})
350 m.matchingBlocks = nonAdjacent
351 return m.matchingBlocks
352 }
353
354 // Return list of 5-tuples describing how to turn a into b.
355 //
356 // Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
357 // has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
358 // tuple preceding it, and likewise for j1 == the previous j2.
359 //
360 // The tags are characters, with these meanings:
361 //
362 // 'r' (replace): a[i1:i2] should be replaced by b[j1:j2]
363 //
364 // 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case.
365 //
366 // 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case.
367 //
368 // 'e' (equal): a[i1:i2] == b[j1:j2]
369 func (m *SequenceMatcher) GetOpCodes() []OpCode {
370 if m.opCodes != nil {
371 return m.opCodes
372 }
373 i, j := 0, 0
374 matching := m.GetMatchingBlocks()
375 opCodes := make([]OpCode, 0, len(matching))
376 for _, m := range matching {
377 // invariant: we've pumped out correct diffs to change
378 // a[:i] into b[:j], and the next matching block is
379 // a[ai:ai+size] == b[bj:bj+size]. So we need to pump
380 // out a diff to change a[i:ai] into b[j:bj], pump out
381 // the matching block, and move (i,j) beyond the match
382 ai, bj, size := m.A, m.B, m.Size
383 tag := byte(0)
384 if i < ai && j < bj {
385 tag = 'r'
386 } else if i < ai {
387 tag = 'd'
388 } else if j < bj {
389 tag = 'i'
390 }
391 if tag > 0 {
392 opCodes = append(opCodes, OpCode{tag, i, ai, j, bj})
393 }
394 i, j = ai+size, bj+size
395 // the list of matching blocks is terminated by a
396 // sentinel with size 0
397 if size > 0 {
398 opCodes = append(opCodes, OpCode{'e', ai, i, bj, j})
399 }
400 }
401 m.opCodes = opCodes
402 return m.opCodes
403 }
404
405 // Isolate change clusters by eliminating ranges with no changes.
406 //
407 // Return a generator of groups with up to n lines of context.
408 // Each group is in the same format as returned by GetOpCodes().
409 func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode {
410 if n < 0 {
411 n = 3
412 }
413 codes := m.GetOpCodes()
414 if len(codes) == 0 {
415 codes = []OpCode{{'e', 0, 1, 0, 1}}
416 }
417 // Fixup leading and trailing groups if they show no changes.
418 if codes[0].Tag == 'e' {
419 c := codes[0]
420 i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
421 codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2}
422 }
423 if codes[len(codes)-1].Tag == 'e' {
424 c := codes[len(codes)-1]
425 i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
426 codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)}
427 }
428 nn := n + n
429 groups := [][]OpCode{}
430 group := []OpCode{}
431 for _, c := range codes {
432 i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
433 // End the current group and start a new one whenever
434 // there is a large range with no changes.
435 if c.Tag == 'e' && i2-i1 > nn {
436 group = append(group, OpCode{
437 c.Tag, i1, min(i2, i1+n),
438 j1, min(j2, j1+n),
439 })
440 groups = append(groups, group)
441 group = []OpCode{}
442 i1, j1 = max(i1, i2-n), max(j1, j2-n)
443 }
444 group = append(group, OpCode{c.Tag, i1, i2, j1, j2})
445 }
446 if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') {
447 groups = append(groups, group)
448 }
449 return groups
450 }
451
452 // Return a measure of the sequences' similarity (float in [0,1]).
453 //
454 // Where T is the total number of elements in both sequences, and
455 // M is the number of matches, this is 2.0*M / T.
456 // Note that this is 1 if the sequences are identical, and 0 if
457 // they have nothing in common.
458 //
459 // .Ratio() is expensive to compute if you haven't already computed
460 // .GetMatchingBlocks() or .GetOpCodes(), in which case you may
461 // want to try .QuickRatio() or .RealQuickRation() first to get an
462 // upper bound.
463 func (m *SequenceMatcher) Ratio() float64 {
464 matches := 0
465 for _, m := range m.GetMatchingBlocks() {
466 matches += m.Size
467 }
468 return calculateRatio(matches, len(m.a)+len(m.b))
469 }
470
471 // Return an upper bound on ratio() relatively quickly.
472 //
473 // This isn't defined beyond that it is an upper bound on .Ratio(), and
474 // is faster to compute.
475 func (m *SequenceMatcher) QuickRatio() float64 {
476 // viewing a and b as multisets, set matches to the cardinality
477 // of their intersection; this counts the number of matches
478 // without regard to order, so is clearly an upper bound
479 if m.fullBCount == nil {
480 m.fullBCount = map[string]int{}
481 for _, s := range m.b {
482 m.fullBCount[s]++
483 }
484 }
485
486 // avail[x] is the number of times x appears in 'b' less the
487 // number of times we've seen it in 'a' so far ... kinda
488 avail := map[string]int{}
489 matches := 0
490 for _, s := range m.a {
491 n, ok := avail[s]
492 if !ok {
493 n = m.fullBCount[s]
494 }
495 avail[s] = n - 1
496 if n > 0 {
497 matches++
498 }
499 }
500 return calculateRatio(matches, len(m.a)+len(m.b))
501 }
502
503 // Return an upper bound on ratio() very quickly.
504 //
505 // This isn't defined beyond that it is an upper bound on .Ratio(), and
506 // is faster to compute than either .Ratio() or .QuickRatio().
507 func (m *SequenceMatcher) RealQuickRatio() float64 {
508 la, lb := len(m.a), len(m.b)
509 return calculateRatio(min(la, lb), la+lb)
510 }
511
512 // Convert range to the "ed" format
513 func formatRangeUnified(start, stop int) string {
514 // Per the diff spec at http://www.unix.org/single_unix_specification/
515 beginning := start + 1 // lines start numbering with one
516 length := stop - start
517 if length == 1 {
518 return fmt.Sprintf("%d", beginning)
519 }
520 if length == 0 {
521 beginning-- // empty ranges begin at line just before the range
522 }
523 return fmt.Sprintf("%d,%d", beginning, length)
524 }
525
526 // Unified diff parameters
527 type UnifiedDiff struct {
528 A []string // First sequence lines
529 FromFile string // First file name
530 FromDate string // First file time
531 B []string // Second sequence lines
532 ToFile string // Second file name
533 ToDate string // Second file time
534 Eol string // Headers end of line, defaults to LF
535 Context int // Number of context lines
536 }
537
538 // Compare two sequences of lines; generate the delta as a unified diff.
539 //
540 // Unified diffs are a compact way of showing line changes and a few
541 // lines of context. The number of context lines is set by 'n' which
542 // defaults to three.
543 //
544 // By default, the diff control lines (those with ---, +++, or @@) are
545 // created with a trailing newline. This is helpful so that inputs
546 // created from file.readlines() result in diffs that are suitable for
547 // file.writelines() since both the inputs and outputs have trailing
548 // newlines.
549 //
550 // For inputs that do not have trailing newlines, set the lineterm
551 // argument to "" so that the output will be uniformly newline free.
552 //
553 // The unidiff format normally has a header for filenames and modification
554 // times. Any or all of these may be specified using strings for
555 // 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
556 // The modification times are normally expressed in the ISO 8601 format.
557 func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error {
558 buf := bufio.NewWriter(writer)
559 defer buf.Flush()
560 wf := func(format string, args ...interface{}) error {
561 _, err := buf.WriteString(fmt.Sprintf(format, args...))
562 return err
563 }
564 ws := func(s string) error {
565 _, err := buf.WriteString(s)
566 return err
567 }
568
569 if len(diff.Eol) == 0 {
570 diff.Eol = "\n"
571 }
572
573 started := false
574 m := NewMatcher(diff.A, diff.B)
575 for _, g := range m.GetGroupedOpCodes(diff.Context) {
576 if !started {
577 started = true
578 fromDate := ""
579 if len(diff.FromDate) > 0 {
580 fromDate = "\t" + diff.FromDate
581 }
582 toDate := ""
583 if len(diff.ToDate) > 0 {
584 toDate = "\t" + diff.ToDate
585 }
586 if diff.FromFile != "" || diff.ToFile != "" {
587 err := wf("--- %s%s%s", diff.FromFile, fromDate, diff.Eol)
588 if err != nil {
589 return err
590 }
591 err = wf("+++ %s%s%s", diff.ToFile, toDate, diff.Eol)
592 if err != nil {
593 return err
594 }
595 }
596 }
597 first, last := g[0], g[len(g)-1]
598 range1 := formatRangeUnified(first.I1, last.I2)
599 range2 := formatRangeUnified(first.J1, last.J2)
600 if err := wf("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil {
601 return err
602 }
603 for _, c := range g {
604 i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
605 if c.Tag == 'e' {
606 for _, line := range diff.A[i1:i2] {
607 if err := ws(" " + line); err != nil {
608 return err
609 }
610 }
611 continue
612 }
613 if c.Tag == 'r' || c.Tag == 'd' {
614 for _, line := range diff.A[i1:i2] {
615 if err := ws("-" + line); err != nil {
616 return err
617 }
618 }
619 }
620 if c.Tag == 'r' || c.Tag == 'i' {
621 for _, line := range diff.B[j1:j2] {
622 if err := ws("+" + line); err != nil {
623 return err
624 }
625 }
626 }
627 }
628 }
629 return nil
630 }
631
632 // Like WriteUnifiedDiff but returns the diff a string.
633 func GetUnifiedDiffString(diff UnifiedDiff) (string, error) {
634 w := &bytes.Buffer{}
635 err := WriteUnifiedDiff(w, diff)
636 return w.String(), err
637 }
638
639 // Split a string on "\n" while preserving them. The output can be used
640 // as input for UnifiedDiff and ContextDiff structures.
641 func SplitLines(s string) []string {
642 lines := strings.SplitAfter(s, "\n")
643 lines[len(lines)-1] += "\n"
644 return lines
645 }