Debian Codegraph @

difflib/bytes/bytes.go

raw symbols SCIP
1 // Package difflib is a partial port of Python difflib module.
2 //
3 // It provides tools to compare sequences of strings and generate textual diffs.
4 //
5 // The following class and functions have been ported:
6 //
7 // - SequenceMatcher
8 //
9 // - unified_diff
10 //
11 // - context_diff
12 //
13 // Getting unified diffs was the main goal of the port. Keep in mind this code
14 // is mostly suitable to output text differences in a human friendly way, there
15 // are no guarantees generated diffs are consumable by patch(1).
16 package bytes
17
18 import (
19 "bufio"
20 "bytes"
21 "errors"
22 "fmt"
23 "io"
24 "strings"
25 "unicode"
26 "hash/adler32"
27 )
28
29 func min(a, b int) int {
30 if a < b {
31 return a
32 }
33 return b
34 }
35
36 func max(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 func listifyString(str []byte) (lst [][]byte) {
51 lst = make([][]byte, len(str))
52 for i := range str {
53 lst[i] = str[i:i+1]
54 }
55 return lst
56 }
57
58 type Match struct {
59 A int
60 B int
61 Size int
62 }
63
64 type OpCode struct {
65 Tag byte
66 I1 int
67 I2 int
68 J1 int
69 J2 int
70 }
71
72 type lineHash uint32
73
74 func _hash(line []byte) lineHash {
75 return lineHash(adler32.Checksum(line))
76 }
77
78 // This is essentially a map from lines to line numbers, so that later it can
79 // be made a bit cleverer than the standard map in that it will not need to
80 // store copies of the lines.
81 // It needs to hold a reference to the underlying slice of lines.
82 type B2J struct {
83 store map[lineHash] [][]int
84 b [][]byte
85 }
86
87 type lineType int8
88 const (
89 lineNONE lineType = 0
90 lineNORMAL lineType = 1
91 lineJUNK lineType = -1
92 linePOPULAR lineType = -2
93 )
94
95 func (b2j *B2J) _find(line *[]byte) (h lineHash, slotIndex int,
96 slot []int, lt lineType) {
97 h = _hash(*line)
98 for slotIndex, slot = range b2j.store[h] {
99 // Thanks to the qualities of sha1, the probability of having more than
100 // one line content with the same hash is very low. Nevertheless, store
101 // each of them in a different slot, that we can differentiate by
102 // looking at the line contents in the b slice.
103 // In place of all the line numbers where the line appears, a slot can
104 // also contain [lineno, -1] if b[lineno] is junk.
105 if bytes.Equal(*line, b2j.b[slot[0]]) {
106 // The content already has a slot in its hash bucket.
107 if len(slot) == 2 && slot[1] < 0 {
108 lt = lineType(slot[1])
109 } else {
110 lt = lineNORMAL
111 }
112 return // every return variable has the correct value
113 }
114 }
115 // The line content still has no slot.
116 slotIndex = -1
117 slot = nil
118 lt = lineNONE
119 return
120 }
121
122 func newB2J (b [][]byte, isJunk func([]byte) bool, autoJunk bool) *B2J {
123 b2j := B2J{store: map[lineHash] [][]int{}, b: b}
124 ntest := len(b)
125 if autoJunk && ntest >= 200 {
126 ntest = ntest/100 + 1
127 }
128 for lineno, line := range b {
129 h, slotIndex, slot, lt := b2j._find(&line)
130 switch lt {
131 case lineNORMAL:
132 if len(slot) >= ntest {
133 b2j.store[h][slotIndex] = []int{slot[0], int(linePOPULAR)}
134 } else {
135 b2j.store[h][slotIndex] = append(slot, lineno)
136 }
137 case lineNONE:
138 if isJunk != nil && isJunk(line) {
139 b2j.store[h] = append(b2j.store[h], []int{lineno, int(lineJUNK)})
140 } else {
141 b2j.store[h] = append(b2j.store[h], []int{lineno})
142 }
143 default:
144 }
145 }
146 return &b2j
147 }
148
149 func (b2j *B2J) get(line []byte) []int {
150 _, _, slot, lt := b2j._find(&line)
151 if lt == lineNORMAL {
152 return slot
153 }
154 return []int{}
155 }
156
157 func (b2j *B2J) isBJunk(line []byte) bool {
158 _, _, _, lt := b2j._find(&line)
159 return lt == lineJUNK
160 }
161
162 // SequenceMatcher compares sequence of strings. The basic
163 // algorithm predates, and is a little fancier than, an algorithm
164 // published in the late 1980's by Ratcliff and Obershelp under the
165 // hyperbolic name "gestalt pattern matching". The basic idea is to find
166 // the longest contiguous matching subsequence that contains no "junk"
167 // elements (R-O doesn't address junk). The same idea is then applied
168 // recursively to the pieces of the sequences to the left and to the right
169 // of the matching subsequence. This does not yield minimal edit
170 // sequences, but does tend to yield matches that "look right" to people.
171 //
172 // SequenceMatcher tries to compute a "human-friendly diff" between two
173 // sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
174 // longest *contiguous* & junk-free matching subsequence. That's what
175 // catches peoples' eyes. The Windows(tm) windiff has another interesting
176 // notion, pairing up elements that appear uniquely in each sequence.
177 // That, and the method here, appear to yield more intuitive difference
178 // reports than does diff. This method appears to be the least vulnerable
179 // to synching up on blocks of "junk lines", though (like blank lines in
180 // ordinary text files, or maybe "<P>" lines in HTML files). That may be
181 // because this is the only method of the 3 that has a *concept* of
182 // "junk" <wink>.
183 //
184 // Timing: Basic R-O is cubic time worst case and quadratic time expected
185 // case. SequenceMatcher is quadratic time for the worst case and has
186 // expected-case behavior dependent in a complicated way on how many
187 // elements the sequences have in common; best case time is linear.
188 type SequenceMatcher struct {
189 a [][]byte
190 b [][]byte
191 b2j B2J
192 IsJunk func([]byte) bool
193 autoJunk bool
194 matchingBlocks []Match
195 fullBCount map[lineHash]int
196 opCodes []OpCode
197 }
198
199 func NewMatcher(a, b [][]byte) *SequenceMatcher {
200 m := SequenceMatcher{autoJunk: true}
201 m.SetSeqs(a, b)
202 return &m
203 }
204
205 func NewMatcherWithJunk(a, b [][]byte, autoJunk bool,
206 isJunk func([]byte) bool) *SequenceMatcher {
207
208 m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk}
209 m.SetSeqs(a, b)
210 return &m
211 }
212
213 // Set two sequences to be compared.
214 func (m *SequenceMatcher) SetSeqs(a, b [][]byte) {
215 m.SetSeq1(a)
216 m.SetSeq2(b)
217 }
218
219 // Set the first sequence to be compared. The second sequence to be compared is
220 // not changed.
221 //
222 // SequenceMatcher computes and caches detailed information about the second
223 // sequence, so if you want to compare one sequence S against many sequences,
224 // use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other
225 // sequences.
226 //
227 // See also SetSeqs() and SetSeq2().
228 func (m *SequenceMatcher) SetSeq1(a [][]byte) {
229 if &a == &m.a {
230 return
231 }
232 m.a = a
233 m.matchingBlocks = nil
234 m.opCodes = nil
235 }
236
237 // Set the second sequence to be compared. The first sequence to be compared is
238 // not changed.
239 func (m *SequenceMatcher) SetSeq2(b [][]byte) {
240 if &b == &m.b {
241 return
242 }
243 m.b = b
244 m.matchingBlocks = nil
245 m.opCodes = nil
246 m.fullBCount = nil
247 m.chainB()
248 }
249
250 func (m *SequenceMatcher) chainB() {
251 // Populate line -> index mapping
252 b2j := *newB2J(m.b, m.IsJunk, m.autoJunk)
253 m.b2j = b2j
254 }
255
256 // Find longest matching block in a[alo:ahi] and b[blo:bhi].
257 //
258 // If IsJunk is not defined:
259 //
260 // Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
261 // alo <= i <= i+k <= ahi
262 // blo <= j <= j+k <= bhi
263 // and for all (i',j',k') meeting those conditions,
264 // k >= k'
265 // i <= i'
266 // and if i == i', j <= j'
267 //
268 // In other words, of all maximal matching blocks, return one that
269 // starts earliest in a, and of all those maximal matching blocks that
270 // start earliest in a, return the one that starts earliest in b.
271 //
272 // If IsJunk is defined, first the longest matching block is
273 // determined as above, but with the additional restriction that no
274 // junk element appears in the block. Then that block is extended as
275 // far as possible by matching (only) junk elements on both sides. So
276 // the resulting block never matches on junk except as identical junk
277 // happens to be adjacent to an "interesting" match.
278 //
279 // If no blocks match, return (alo, blo, 0).
280 func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match {
281 // CAUTION: stripping common prefix or suffix would be incorrect.
282 // E.g.,
283 // ab
284 // acab
285 // Longest matching block is "ab", but if common prefix is
286 // stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
287 // strip, so ends up claiming that ab is changed to acab by
288 // inserting "ca" in the middle. That's minimal but unintuitive:
289 // "it's obvious" that someone inserted "ac" at the front.
290 // Windiff ends up at the same place as diff, but by pairing up
291 // the unique 'b's and then matching the first two 'a's.
292 besti, bestj, bestsize := alo, blo, 0
293
294 // find longest junk-free match
295 // during an iteration of the loop, j2len[j] = length of longest
296 // junk-free match ending with a[i-1] and b[j]
297 N := bhi - blo
298 j2len := make([]int, N)
299 newj2len := make([]int, N)
300 var indices []int
301 for i := alo; i != ahi; i++ {
302 // look at all instances of a[i] in b; note that because
303 // b2j has no junk keys, the loop is skipped if a[i] is junk
304 newindices := m.b2j.get(m.a[i])
305 for _, j := range newindices {
306 // a[i] matches b[j]
307 if j < blo {
308 continue
309 }
310 if j >= bhi {
311 break
312 }
313 k := 1
314 if j > blo {
315 k = j2len[j-1-blo] + 1
316 }
317 newj2len[j-blo] = k
318 if k > bestsize {
319 besti, bestj, bestsize = i-k+1, j-k+1, k
320 }
321 }
322 // j2len = newj2len, clear and reuse j2len as newj2len
323 for _, j := range indices {
324 if j < blo {
325 continue
326 }
327 if j >= bhi {
328 break
329 }
330 j2len[j-blo] = 0
331 }
332 indices = newindices
333 j2len, newj2len = newj2len, j2len
334 }
335
336 // Extend the best by non-junk elements on each end. In particular,
337 // "popular" non-junk elements aren't in b2j, which greatly speeds
338 // the inner loop above, but also means "the best" match so far
339 // doesn't contain any junk *or* popular non-junk elements.
340 for besti > alo && bestj > blo && !m.b2j.isBJunk(m.b[bestj-1]) &&
341 bytes.Equal(m.a[besti-1], m.b[bestj-1]) {
342 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
343 }
344 for besti+bestsize < ahi && bestj+bestsize < bhi &&
345 !m.b2j.isBJunk(m.b[bestj+bestsize]) &&
346 bytes.Equal(m.a[besti+bestsize], m.b[bestj+bestsize]) {
347 bestsize += 1
348 }
349
350 // Now that we have a wholly interesting match (albeit possibly
351 // empty!), we may as well suck up the matching junk on each
352 // side of it too. Can't think of a good reason not to, and it
353 // saves post-processing the (possibly considerable) expense of
354 // figuring out what to do with it. In the case of an empty
355 // interesting match, this is clearly the right thing to do,
356 // because no other kind of match is possible in the regions.
357 for besti > alo && bestj > blo && m.b2j.isBJunk(m.b[bestj-1]) &&
358 bytes.Equal(m.a[besti-1], m.b[bestj-1]) {
359 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
360 }
361 for besti+bestsize < ahi && bestj+bestsize < bhi &&
362 m.b2j.isBJunk(m.b[bestj+bestsize]) &&
363 bytes.Equal(m.a[besti+bestsize], m.b[bestj+bestsize]) {
364 bestsize += 1
365 }
366
367 return Match{A: besti, B: bestj, Size: bestsize}
368 }
369
370 // Return list of triples describing matching subsequences.
371 //
372 // Each triple is of the form (i, j, n), and means that
373 // a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
374 // i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are
375 // adjacent triples in the list, and the second is not the last triple in the
376 // list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe
377 // adjacent equal blocks.
378 //
379 // The last triple is a dummy, (len(a), len(b), 0), and is the only
380 // triple with n==0.
381 func (m *SequenceMatcher) GetMatchingBlocks() []Match {
382 if m.matchingBlocks != nil {
383 return m.matchingBlocks
384 }
385
386 var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match
387 matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match {
388 match := m.findLongestMatch(alo, ahi, blo, bhi)
389 i, j, k := match.A, match.B, match.Size
390 if match.Size > 0 {
391 if alo < i && blo < j {
392 matched = matchBlocks(alo, i, blo, j, matched)
393 }
394 matched = append(matched, match)
395 if i+k < ahi && j+k < bhi {
396 matched = matchBlocks(i+k, ahi, j+k, bhi, matched)
397 }
398 }
399 return matched
400 }
401 matched := matchBlocks(0, len(m.a), 0, len(m.b), nil)
402
403 // It's possible that we have adjacent equal blocks in the
404 // matching_blocks list now.
405 nonAdjacent := []Match{}
406 i1, j1, k1 := 0, 0, 0
407 for _, b := range matched {
408 // Is this block adjacent to i1, j1, k1?
409 i2, j2, k2 := b.A, b.B, b.Size
410 if i1+k1 == i2 && j1+k1 == j2 {
411 // Yes, so collapse them -- this just increases the length of
412 // the first block by the length of the second, and the first
413 // block so lengthened remains the block to compare against.
414 k1 += k2
415 } else {
416 // Not adjacent. Remember the first block (k1==0 means it's
417 // the dummy we started with), and make the second block the
418 // new block to compare against.
419 if k1 > 0 {
420 nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
421 }
422 i1, j1, k1 = i2, j2, k2
423 }
424 }
425 if k1 > 0 {
426 nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
427 }
428
429 nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0})
430 m.matchingBlocks = nonAdjacent
431 return m.matchingBlocks
432 }
433
434 // Return list of 5-tuples describing how to turn a into b.
435 //
436 // Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
437 // has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
438 // tuple preceding it, and likewise for j1 == the previous j2.
439 //
440 // The tags are characters, with these meanings:
441 //
442 // 'r' (replace): a[i1:i2] should be replaced by b[j1:j2]
443 //
444 // 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case.
445 //
446 // 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case.
447 //
448 // 'e' (equal): a[i1:i2] == b[j1:j2]
449 func (m *SequenceMatcher) GetOpCodes() []OpCode {
450 if m.opCodes != nil {
451 return m.opCodes
452 }
453 i, j := 0, 0
454 matching := m.GetMatchingBlocks()
455 opCodes := make([]OpCode, 0, len(matching))
456 for _, m := range matching {
457 // invariant: we've pumped out correct diffs to change
458 // a[:i] into b[:j], and the next matching block is
459 // a[ai:ai+size] == b[bj:bj+size]. So we need to pump
460 // out a diff to change a[i:ai] into b[j:bj], pump out
461 // the matching block, and move (i,j) beyond the match
462 ai, bj, size := m.A, m.B, m.Size
463 tag := byte(0)
464 if i < ai && j < bj {
465 tag = 'r'
466 } else if i < ai {
467 tag = 'd'
468 } else if j < bj {
469 tag = 'i'
470 }
471 if tag > 0 {
472 opCodes = append(opCodes, OpCode{tag, i, ai, j, bj})
473 }
474 i, j = ai+size, bj+size
475 // the list of matching blocks is terminated by a
476 // sentinel with size 0
477 if size > 0 {
478 opCodes = append(opCodes, OpCode{'e', ai, i, bj, j})
479 }
480 }
481 m.opCodes = opCodes
482 return m.opCodes
483 }
484
485 // Isolate change clusters by eliminating ranges with no changes.
486 //
487 // Return a generator of groups with up to n lines of context.
488 // Each group is in the same format as returned by GetOpCodes().
489 func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode {
490 if n < 0 {
491 n = 3
492 }
493 codes := m.GetOpCodes()
494 if len(codes) == 0 {
495 codes = []OpCode{OpCode{'e', 0, 1, 0, 1}}
496 }
497 // Fixup leading and trailing groups if they show no changes.
498 if codes[0].Tag == 'e' {
499 c := codes[0]
500 i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
501 codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2}
502 }
503 if codes[len(codes)-1].Tag == 'e' {
504 c := codes[len(codes)-1]
505 i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
506 codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)}
507 }
508 nn := n + n
509 groups := [][]OpCode{}
510 group := []OpCode{}
511 for _, c := range codes {
512 i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
513 // End the current group and start a new one whenever
514 // there is a large range with no changes.
515 if c.Tag == 'e' && i2-i1 > nn {
516 group = append(group, OpCode{c.Tag, i1, min(i2, i1+n),
517 j1, min(j2, j1+n)})
518 groups = append(groups, group)
519 group = []OpCode{}
520 i1, j1 = max(i1, i2-n), max(j1, j2-n)
521 }
522 group = append(group, OpCode{c.Tag, i1, i2, j1, j2})
523 }
524 if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') {
525 groups = append(groups, group)
526 }
527 return groups
528 }
529
530 // Return a measure of the sequences' similarity (float in [0,1]).
531 //
532 // Where T is the total number of elements in both sequences, and
533 // M is the number of matches, this is 2.0*M / T.
534 // Note that this is 1 if the sequences are identical, and 0 if
535 // they have nothing in common.
536 //
537 // .Ratio() is expensive to compute if you haven't already computed
538 // .GetMatchingBlocks() or .GetOpCodes(), in which case you may
539 // want to try .QuickRatio() or .RealQuickRation() first to get an
540 // upper bound.
541 func (m *SequenceMatcher) Ratio() float64 {
542 matches := 0
543 for _, m := range m.GetMatchingBlocks() {
544 matches += m.Size
545 }
546 return calculateRatio(matches, len(m.a)+len(m.b))
547 }
548
549 // Return an upper bound on ratio() relatively quickly.
550 //
551 // This isn't defined beyond that it is an upper bound on .Ratio(), and
552 // is faster to compute.
553 func (m *SequenceMatcher) QuickRatio() float64 {
554 // viewing a and b as multisets, set matches to the cardinality
555 // of their intersection; this counts the number of matches
556 // without regard to order, so is clearly an upper bound. We do
557 // so on hashes of the lines themselves, so this might even be
558 // greater due hash collisions incurring false positives, but
559 // we don't care because we want an upper bound anyway.
560 if m.fullBCount == nil {
561 m.fullBCount = map[lineHash]int{}
562 for _, s := range m.b {
563 h := _hash(s)
564 m.fullBCount[h] = m.fullBCount[h] + 1
565 }
566 }
567
568 // avail[x] is the number of times x appears in 'b' less the
569 // number of times we've seen it in 'a' so far ... kinda
570 avail := map[lineHash]int{}
571 matches := 0
572 for _, s := range m.a {
573 h := _hash(s)
574 n, ok := avail[h]
575 if !ok {
576 n = m.fullBCount[h]
577 }
578 avail[h] = n - 1
579 if n > 0 {
580 matches += 1
581 }
582 }
583 return calculateRatio(matches, len(m.a)+len(m.b))
584 }
585
586 // Return an upper bound on ratio() very quickly.
587 //
588 // This isn't defined beyond that it is an upper bound on .Ratio(), and
589 // is faster to compute than either .Ratio() or .QuickRatio().
590 func (m *SequenceMatcher) RealQuickRatio() float64 {
591 la, lb := len(m.a), len(m.b)
592 return calculateRatio(min(la, lb), la+lb)
593 }
594
595 func count_leading(line []byte, ch byte) (count int) {
596 // Return number of `ch` characters at the start of `line`.
597 count = 0
598 n := len(line)
599 for (count < n) && (line[count] == ch) {
600 count++
601 }
602 return count
603 }
604
605 type DiffLine struct {
606 Tag byte
607 Line []byte
608 }
609
610 func NewDiffLine(tag byte, line []byte) (l DiffLine) {
611 l = DiffLine{}
612 l.Tag = tag
613 l.Line = line
614 return l
615 }
616
617 type Differ struct {
618 Linejunk func([]byte) bool
619 Charjunk func([]byte) bool
620 }
621
622 func NewDiffer() *Differ {
623 return &Differ{}
624 }
625
626 var MINUS = []byte("-")
627 var SPACE = []byte(" ")
628 var PLUS = []byte("+")
629 var CARET = []byte("^")
630
631 func (d *Differ) Compare(a [][]byte, b [][]byte) (diffs [][]byte, err error) {
632 // Compare two sequences of lines; generate the resulting delta.
633
634 // Each sequence must contain individual single-line strings ending with
635 // newlines. Such sequences can be obtained from the `readlines()` method
636 // of file-like objects. The delta generated also consists of newline-
637 // terminated strings, ready to be printed as-is via the writeline()
638 // method of a file-like object.
639 diffs = [][]byte{}
640 cruncher := NewMatcherWithJunk(a, b, true, d.Linejunk)
641 opcodes := cruncher.GetOpCodes()
642 for _, current := range opcodes {
643 alo := current.I1
644 ahi := current.I2
645 blo := current.J1
646 bhi := current.J2
647 var g [][]byte
648 if current.Tag == 'r' {
649 g, _ = d.FancyReplace(a, alo, ahi, b, blo, bhi)
650 } else if current.Tag == 'd' {
651 g = d.Dump(MINUS, a, alo, ahi)
652 } else if current.Tag == 'i' {
653 g = d.Dump(PLUS, b, blo, bhi)
654 } else if current.Tag == 'e' {
655 g = d.Dump(SPACE, a, alo, ahi)
656 } else {
657 return nil, errors.New(fmt.Sprintf("unknown tag %q", current.Tag))
658 }
659 diffs = append(diffs, g...)
660 }
661 return diffs, nil
662 }
663
664 func (d *Differ) StructuredDump(tag byte, x [][]byte, low int, high int) (out []DiffLine) {
665 size := high - low
666 out = make([]DiffLine, size)
667 for i := 0; i < size; i++ {
668 out[i] = NewDiffLine(tag, x[i + low])
669 }
670 return out
671 }
672
673 func (d *Differ) Dump(tag []byte, x [][]byte, low int, high int) (out [][]byte) {
674 // Generate comparison results for a same-tagged range.
675 sout := d.StructuredDump(tag[0], x, low, high)
676 out = make([][]byte, len(sout))
677 var bld bytes.Buffer
678 bld.Grow(1024)
679 for i, line := range sout {
680 bld.Reset()
681 bld.WriteByte(line.Tag)
682 bld.Write(SPACE)
683 bld.Write(line.Line)
684 out[i] = append(out[i], bld.Bytes()...)
685 }
686 return out
687 }
688
689 func (d *Differ) PlainReplace(a [][]byte, alo int, ahi int, b [][]byte, blo int, bhi int) (out [][]byte, err error) {
690 if !(alo < ahi) || !(blo < bhi) { // assertion
691 return nil, errors.New("low greater than or equal to high")
692 }
693 // dump the shorter block first -- reduces the burden on short-term
694 // memory if the blocks are of very different sizes
695 if bhi-blo < ahi-alo {
696 out = d.Dump(PLUS, b, blo, bhi)
697 out = append(out, d.Dump(MINUS, a, alo, ahi)...)
698 } else {
699 out = d.Dump(MINUS, a, alo, ahi)
700 out = append(out, d.Dump(PLUS, b, blo, bhi)...)
701 }
702 return out, nil
703 }
704
705 func (d *Differ) FancyReplace(a [][]byte, alo int, ahi int, b [][]byte, blo int, bhi int) (out [][]byte, err error) {
706 // When replacing one block of lines with another, search the blocks
707 // for *similar* lines; the best-matching pair (if any) is used as a
708 // synch point, and intraline difference marking is done on the
709 // similar pair. Lots of work, but often worth it.
710
711 // don't synch up unless the lines have a similarity score of at
712 // least cutoff; best_ratio tracks the best score seen so far
713 best_ratio := 0.74
714 cutoff := 0.75
715 cruncher := NewMatcherWithJunk(a, b, true, d.Charjunk)
716 eqi := -1 // 1st indices of equal lines (if any)
717 eqj := -1
718 out = [][]byte{}
719
720 // search for the pair that matches best without being identical
721 // (identical lines must be junk lines, & we don't want to synch up
722 // on junk -- unless we have to)
723 var best_i, best_j int
724 for j := blo; j < bhi; j++ {
725 bj := b[j]
726 cruncher.SetSeq2(listifyString(bj))
727 for i := alo; i < ahi; i++ {
728 ai := a[i]
729 if bytes.Equal(ai, bj) {
730 if eqi == -1 {
731 eqi = i
732 eqj = j
733 }
734 continue
735 }
736 cruncher.SetSeq1(listifyString(ai))
737 // computing similarity is expensive, so use the quick
738 // upper bounds first -- have seen this speed up messy
739 // compares by a factor of 3.
740 // note that ratio() is only expensive to compute the first
741 // time it's called on a sequence pair; the expensive part
742 // of the computation is cached by cruncher
743 if cruncher.RealQuickRatio() > best_ratio &&
744 cruncher.QuickRatio() > best_ratio &&
745 cruncher.Ratio() > best_ratio {
746 best_ratio = cruncher.Ratio()
747 best_i = i
748 best_j = j
749 }
750 }
751 }
752 if best_ratio < cutoff {
753 // no non-identical "pretty close" pair
754 if eqi == -1 {
755 // no identical pair either -- treat it as a straight replace
756 out, _ = d.PlainReplace(a, alo, ahi, b, blo, bhi)
757 return out, nil
758 }
759 // no close pair, but an identical pair -- synch up on that
760 best_i = eqi
761 best_j = eqj
762 best_ratio = 1.0
763 } else {
764 // there's a close pair, so forget the identical pair (if any)
765 eqi = -1
766 }
767 // a[best_i] very similar to b[best_j]; eqi is None iff they're not
768 // identical
769
770 // pump out diffs from before the synch point
771 out = append(out, d.fancyHelper(a, alo, best_i, b, blo, best_j)...)
772
773 // do intraline marking on the synch pair
774 aelt, belt := a[best_i], b[best_j]
775 if eqi == -1 {
776 // pump out a '-', '?', '+', '?' quad for the synched lines
777 var atags, btags []byte
778 cruncher.SetSeqs(listifyString(aelt), listifyString(belt))
779 opcodes := cruncher.GetOpCodes()
780 for _, current := range opcodes {
781 ai1 := current.I1
782 ai2 := current.I2
783 bj1 := current.J1
784 bj2 := current.J2
785 la, lb := ai2-ai1, bj2-bj1
786 if current.Tag == 'r' {
787 atags = append(atags, bytes.Repeat(CARET, la)...)
788 btags = append(btags, bytes.Repeat(CARET, lb)...)
789 } else if current.Tag == 'd' {
790 atags = append(atags, bytes.Repeat(MINUS, la)...)
791 } else if current.Tag == 'i' {
792 btags = append(btags, bytes.Repeat(PLUS, lb)...)
793 } else if current.Tag == 'e' {
794 atags = append(atags, bytes.Repeat(SPACE, la)...)
795 btags = append(btags, bytes.Repeat(SPACE, lb)...)
796 } else {
797 return nil, errors.New(fmt.Sprintf("unknown tag %q",
798 current.Tag))
799 }
800 }
801 out = append(out, d.QFormat(aelt, belt, atags, btags)...)
802 } else {
803 // the synch pair is identical
804 out = append(out, append([]byte{' ', ' '}, aelt...))
805 }
806 // pump out diffs from after the synch point
807 out = append(out, d.fancyHelper(a, best_i+1, ahi, b, best_j+1, bhi)...)
808 return out, nil
809 }
810
811 func (d *Differ) fancyHelper(a [][]byte, alo int, ahi int, b [][]byte, blo int, bhi int) (out [][]byte) {
812 if alo < ahi {
813 if blo < bhi {
814 out, _ = d.FancyReplace(a, alo, ahi, b, blo, bhi)
815 } else {
816 out = d.Dump(MINUS, a, alo, ahi)
817 }
818 } else if blo < bhi {
819 out = d.Dump(PLUS, b, blo, bhi)
820 } else {
821 out = [][]byte{}
822 }
823 return out
824 }
825
826 func (d *Differ) QFormat(aline []byte, bline []byte, atags []byte, btags []byte) (out [][]byte) {
827 // Format "?" output and deal with leading tabs.
828
829 // Can hurt, but will probably help most of the time.
830 common := min(count_leading(aline, '\t'), count_leading(bline, '\t'))
831 common = min(common, count_leading(atags[:common], ' '))
832 common = min(common, count_leading(btags[:common], ' '))
833 atags = bytes.TrimRightFunc(atags[common:], unicode.IsSpace)
834 btags = bytes.TrimRightFunc(btags[common:], unicode.IsSpace)
835
836 out = [][]byte{append([]byte("- "), aline...)}
837 if len(atags) > 0 {
838 t := make([]byte, 0, len(atags) + common + 3)
839 t = append(t, []byte("? ")...)
840 for i := 0; i < common; i++ {
841 t = append(t, byte('\t'))
842 }
843 t = append(t, atags...)
844 t = append(t, byte('\n'))
845 out = append(out, t)
846 }
847 out = append(out, append([]byte("+ "), bline...))
848 if len(btags) > 0 {
849 t := make([]byte, 0, len(btags) + common + 3)
850 t = append(t, []byte("? ")...)
851 for i := 0; i < common; i++ {
852 t = append(t, byte('\t'))
853 }
854 t = append(t, btags...)
855 t = append(t, byte('\n'))
856 out = append(out, t)
857 }
858 return out
859 }
860
861 // Convert range to the "ed" format
862 func formatRangeUnified(start, stop int) []byte {
863 // Per the diff spec at http://www.unix.org/single_unix_specification/
864 beginning := start + 1 // lines start numbering with one
865 length := stop - start
866 if length == 1 {
867 return []byte(fmt.Sprintf("%d", beginning))
868 }
869 if length == 0 {
870 beginning -= 1 // empty ranges begin at line just before the range
871 }
872 return []byte(fmt.Sprintf("%d,%d", beginning, length))
873 }
874
875 // Unified diff parameters
876 type UnifiedDiff struct {
877 A [][]byte // First sequence lines
878 FromFile string // First file name
879 FromDate string // First file time
880 B [][]byte // Second sequence lines
881 ToFile string // Second file name
882 ToDate string // Second file time
883 Eol []byte // Headers end of line, defaults to LF
884 Context int // Number of context lines
885 }
886
887 // Compare two sequences of lines; generate the delta as a unified diff.
888 //
889 // Unified diffs are a compact way of showing line changes and a few
890 // lines of context. The number of context lines is set by 'n' which
891 // defaults to three.
892 //
893 // By default, the diff control lines (those with ---, +++, or @@) are
894 // created with a trailing newline. This is helpful so that inputs
895 // created from file.readlines() result in diffs that are suitable for
896 // file.writelines() since both the inputs and outputs have trailing
897 // newlines.
898 //
899 // For inputs that do not have trailing newlines, set the lineterm
900 // argument to "" so that the output will be uniformly newline free.
901 //
902 // The unidiff format normally has a header for filenames and modification
903 // times. Any or all of these may be specified using strings for
904 // 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
905 // The modification times are normally expressed in the ISO 8601 format.
906 func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error {
907 //buf := bufio.NewWriter(writer)
908 //defer buf.Flush()
909 var bld strings.Builder
910 bld.Reset()
911 wf := func(format string, args ...interface{}) error {
912 _, err := fmt.Fprintf(&bld, format, args...)
913 return err
914 }
915 ws := func(s []byte) error {
916 _, err := bld.Write(s)
917 return err
918 }
919
920 if len(diff.Eol) == 0 {
921 diff.Eol = []byte("\n")
922 }
923
924 started := false
925 m := NewMatcher(diff.A, diff.B)
926 for _, g := range m.GetGroupedOpCodes(diff.Context) {
927 if !started {
928 started = true
929 fromDate := ""
930 if len(diff.FromDate) > 0 {
931 fromDate = "\t" + diff.FromDate
932 }
933 toDate := ""
934 if len(diff.ToDate) > 0 {
935 toDate = "\t" + diff.ToDate
936 }
937 if diff.FromFile != "" || diff.ToFile != "" {
938 err := wf("--- %s%s%s", diff.FromFile, fromDate, diff.Eol)
939 if err != nil {
940 return err
941 }
942 err = wf("+++ %s%s%s", diff.ToFile, toDate, diff.Eol)
943 if err != nil {
944 return err
945 }
946 }
947 }
948 first, last := g[0], g[len(g)-1]
949 range1 := formatRangeUnified(first.I1, last.I2)
950 range2 := formatRangeUnified(first.J1, last.J2)
951 if err := wf("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil {
952 return err
953 }
954 for _, c := range g {
955 i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
956 if c.Tag == 'e' {
957 for _, line := range diff.A[i1:i2] {
958 if err := ws(SPACE); err != nil {
959 return err
960 }
961 if err := ws(line); err != nil {
962 return err
963 }
964 }
965 continue
966 }
967 if c.Tag == 'r' || c.Tag == 'd' {
968 for _, line := range diff.A[i1:i2] {
969 if err := ws(MINUS); err != nil {
970 return err
971 }
972 if err := ws(line); err != nil {
973 return err
974 }
975 }
976 }
977 if c.Tag == 'r' || c.Tag == 'i' {
978 for _, line := range diff.B[j1:j2] {
979 if err := ws(PLUS); err != nil {
980 return err
981 }
982 if err := ws(line); err != nil {
983 return err
984 }
985 }
986 }
987 }
988 }
989 buf := bufio.NewWriter(writer)
990 buf.WriteString(bld.String())
991 buf.Flush()
992 return nil
993 }
994
995 // Like WriteUnifiedDiff but returns the diff a []byte.
996 func GetUnifiedDiffString(diff UnifiedDiff) ([]byte, error) {
997 w := &bytes.Buffer{}
998 err := WriteUnifiedDiff(w, diff)
999 return []byte(w.Bytes()), err
1000 }
1001
1002 // Convert range to the "ed" format.
1003 func formatRangeContext(start, stop int) []byte {
1004 // Per the diff spec at http://www.unix.org/single_unix_specification/
1005 beginning := start + 1 // lines start numbering with one
1006 length := stop - start
1007 if length == 0 {
1008 beginning -= 1 // empty ranges begin at line just before the range
1009 }
1010 if length <= 1 {
1011 return []byte(fmt.Sprintf("%d", beginning))
1012 }
1013 return []byte(fmt.Sprintf("%d,%d", beginning, beginning+length-1))
1014 }
1015
1016 type ContextDiff UnifiedDiff
1017
1018 // Compare two sequences of lines; generate the delta as a context diff.
1019 //
1020 // Context diffs are a compact way of showing line changes and a few
1021 // lines of context. The number of context lines is set by diff.Context
1022 // which defaults to three.
1023 //
1024 // By default, the diff control lines (those with *** or ---) are
1025 // created with a trailing newline.
1026 //
1027 // For inputs that do not have trailing newlines, set the diff.Eol
1028 // argument to "" so that the output will be uniformly newline free.
1029 //
1030 // The context diff format normally has a header for filenames and
1031 // modification times. Any or all of these may be specified using
1032 // strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate.
1033 // The modification times are normally expressed in the ISO 8601 format.
1034 // If not specified, the strings default to blanks.
1035 func WriteContextDiff(writer io.Writer, diff ContextDiff) error {
1036 buf := bufio.NewWriter(writer)
1037 defer buf.Flush()
1038 var diffErr error
1039 wf := func(format string, args ...interface{}) {
1040 _, err := buf.WriteString(fmt.Sprintf(format, args...))
1041 if diffErr == nil && err != nil {
1042 diffErr = err
1043 }
1044 }
1045 ws := func(s []byte) {
1046 _, err := buf.Write(s)
1047 if diffErr == nil && err != nil {
1048 diffErr = err
1049 }
1050 }
1051
1052 if len(diff.Eol) == 0 {
1053 diff.Eol = []byte("\n")
1054 }
1055
1056 prefix := map[byte][]byte{
1057 'i': []byte("+ "),
1058 'd': []byte("- "),
1059 'r': []byte("! "),
1060 'e': []byte(" "),
1061 }
1062
1063 started := false
1064 m := NewMatcher(diff.A, diff.B)
1065 for _, g := range m.GetGroupedOpCodes(diff.Context) {
1066 if !started {
1067 started = true
1068 fromDate := ""
1069 if len(diff.FromDate) > 0 {
1070 fromDate = "\t" + diff.FromDate
1071 }
1072 toDate := ""
1073 if len(diff.ToDate) > 0 {
1074 toDate = "\t" + diff.ToDate
1075 }
1076 if diff.FromFile != "" || diff.ToFile != "" {
1077 wf("*** %s%s%s", diff.FromFile, fromDate, diff.Eol)
1078 wf("--- %s%s%s", diff.ToFile, toDate, diff.Eol)
1079 }
1080 }
1081
1082 first, last := g[0], g[len(g)-1]
1083 ws([]byte("***************"))
1084 ws(diff.Eol)
1085
1086 range1 := formatRangeContext(first.I1, last.I2)
1087 wf("*** %s ****%s", range1, diff.Eol)
1088 for _, c := range g {
1089 if c.Tag == 'r' || c.Tag == 'd' {
1090 for _, cc := range g {
1091 if cc.Tag == 'i' {
1092 continue
1093 }
1094 for _, line := range diff.A[cc.I1:cc.I2] {
1095 ws(prefix[cc.Tag])
1096 ws(line)
1097 }
1098 }
1099 break
1100 }
1101 }
1102
1103 range2 := formatRangeContext(first.J1, last.J2)
1104 wf("--- %s ----%s", range2, diff.Eol)
1105 for _, c := range g {
1106 if c.Tag == 'r' || c.Tag == 'i' {
1107 for _, cc := range g {
1108 if cc.Tag == 'd' {
1109 continue
1110 }
1111 for _, line := range diff.B[cc.J1:cc.J2] {
1112 ws(prefix[cc.Tag])
1113 ws(line)
1114 }
1115 }
1116 break
1117 }
1118 }
1119 }
1120 return diffErr
1121 }
1122
1123 // Like WriteContextDiff but returns the diff a []byte.
1124 func GetContextDiffString(diff ContextDiff) ([]byte, error) {
1125 w := &bytes.Buffer{}
1126 err := WriteContextDiff(w, diff)
1127 return []byte(w.Bytes()), err
1128 }
1129
1130 // Split a []byte on "\n" while preserving them. The output can be used
1131 // as input for UnifiedDiff and ContextDiff structures.
1132 func SplitLines(s []byte) [][]byte {
1133 lines := bytes.SplitAfter(s, []byte("\n"))
1134 lines[len(lines)-1] = append(lines[len(lines)-1], '\n')
1135 return lines
1136 }