Debian Codegraph @

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