Debian Codegraph @

prometheus/internal/difflib.go

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