blob: c074b190658b0dacbb107b0e63ca092aedc3147c [file] [log] [blame]
Tim Peters9ae21482001-02-10 08:00:53 +00001#! /usr/bin/env python
2
3"""
4Module difflib -- helpers for computing deltas between objects.
5
6Function get_close_matches(word, possibilities, n=3, cutoff=0.6):
Tim Peters9ae21482001-02-10 08:00:53 +00007 Use SequenceMatcher to return list of the best "good enough" matches.
8
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00009Function context_diff(a, b):
10 For two lists of strings, return a delta in context diff format.
11
Tim Peters5e824c32001-08-12 22:25:01 +000012Function ndiff(a, b):
13 Return a delta: the difference between `a` and `b` (lists of strings).
Tim Peters9ae21482001-02-10 08:00:53 +000014
Tim Peters5e824c32001-08-12 22:25:01 +000015Function restore(delta, which):
16 Return one of the two sequences that generated an ndiff delta.
Tim Peters9ae21482001-02-10 08:00:53 +000017
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +000018Function unified_diff(a, b):
19 For two lists of strings, return a delta in unified diff format.
20
Tim Peters5e824c32001-08-12 22:25:01 +000021Class SequenceMatcher:
22 A flexible class for comparing pairs of sequences of any type.
Tim Peters9ae21482001-02-10 08:00:53 +000023
Tim Peters5e824c32001-08-12 22:25:01 +000024Class Differ:
25 For producing human-readable deltas from sequences of lines of text.
Tim Peters9ae21482001-02-10 08:00:53 +000026"""
27
Tim Peters5e824c32001-08-12 22:25:01 +000028__all__ = ['get_close_matches', 'ndiff', 'restore', 'SequenceMatcher',
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +000029 'Differ','IS_CHARACTER_JUNK', 'IS_LINE_JUNK', 'context_diff',
30 'unified_diff']
Tim Peters5e824c32001-08-12 22:25:01 +000031
Neal Norwitze7dfe212003-07-01 14:59:46 +000032def _calculate_ratio(matches, length):
33 if length:
34 return 2.0 * matches / length
35 return 1.0
36
Tim Peters9ae21482001-02-10 08:00:53 +000037class SequenceMatcher:
Tim Peters5e824c32001-08-12 22:25:01 +000038
39 """
40 SequenceMatcher is a flexible class for comparing pairs of sequences of
41 any type, so long as the sequence elements are hashable. The basic
42 algorithm predates, and is a little fancier than, an algorithm
43 published in the late 1980's by Ratcliff and Obershelp under the
44 hyperbolic name "gestalt pattern matching". The basic idea is to find
45 the longest contiguous matching subsequence that contains no "junk"
46 elements (R-O doesn't address junk). The same idea is then applied
47 recursively to the pieces of the sequences to the left and to the right
48 of the matching subsequence. This does not yield minimal edit
49 sequences, but does tend to yield matches that "look right" to people.
50
51 SequenceMatcher tries to compute a "human-friendly diff" between two
52 sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
53 longest *contiguous* & junk-free matching subsequence. That's what
54 catches peoples' eyes. The Windows(tm) windiff has another interesting
55 notion, pairing up elements that appear uniquely in each sequence.
56 That, and the method here, appear to yield more intuitive difference
57 reports than does diff. This method appears to be the least vulnerable
58 to synching up on blocks of "junk lines", though (like blank lines in
59 ordinary text files, or maybe "<P>" lines in HTML files). That may be
60 because this is the only method of the 3 that has a *concept* of
61 "junk" <wink>.
62
63 Example, comparing two strings, and considering blanks to be "junk":
64
65 >>> s = SequenceMatcher(lambda x: x == " ",
66 ... "private Thread currentThread;",
67 ... "private volatile Thread currentThread;")
68 >>>
69
70 .ratio() returns a float in [0, 1], measuring the "similarity" of the
71 sequences. As a rule of thumb, a .ratio() value over 0.6 means the
72 sequences are close matches:
73
74 >>> print round(s.ratio(), 3)
75 0.866
76 >>>
77
78 If you're only interested in where the sequences match,
79 .get_matching_blocks() is handy:
80
81 >>> for block in s.get_matching_blocks():
82 ... print "a[%d] and b[%d] match for %d elements" % block
83 a[0] and b[0] match for 8 elements
84 a[8] and b[17] match for 6 elements
85 a[14] and b[23] match for 15 elements
86 a[29] and b[38] match for 0 elements
87
88 Note that the last tuple returned by .get_matching_blocks() is always a
89 dummy, (len(a), len(b), 0), and this is the only case in which the last
90 tuple element (number of elements matched) is 0.
91
92 If you want to know how to change the first sequence into the second,
93 use .get_opcodes():
94
95 >>> for opcode in s.get_opcodes():
96 ... print "%6s a[%d:%d] b[%d:%d]" % opcode
97 equal a[0:8] b[0:8]
98 insert a[8:8] b[8:17]
99 equal a[8:14] b[17:23]
100 equal a[14:29] b[23:38]
101
102 See the Differ class for a fancy human-friendly file differencer, which
103 uses SequenceMatcher both to compare sequences of lines, and to compare
104 sequences of characters within similar (near-matching) lines.
105
106 See also function get_close_matches() in this module, which shows how
107 simple code building on SequenceMatcher can be used to do useful work.
108
109 Timing: Basic R-O is cubic time worst case and quadratic time expected
110 case. SequenceMatcher is quadratic time for the worst case and has
111 expected-case behavior dependent in a complicated way on how many
112 elements the sequences have in common; best case time is linear.
113
114 Methods:
115
116 __init__(isjunk=None, a='', b='')
117 Construct a SequenceMatcher.
118
119 set_seqs(a, b)
120 Set the two sequences to be compared.
121
122 set_seq1(a)
123 Set the first sequence to be compared.
124
125 set_seq2(b)
126 Set the second sequence to be compared.
127
128 find_longest_match(alo, ahi, blo, bhi)
129 Find longest matching block in a[alo:ahi] and b[blo:bhi].
130
131 get_matching_blocks()
132 Return list of triples describing matching subsequences.
133
134 get_opcodes()
135 Return list of 5-tuples describing how to turn a into b.
136
137 ratio()
138 Return a measure of the sequences' similarity (float in [0,1]).
139
140 quick_ratio()
141 Return an upper bound on .ratio() relatively quickly.
142
143 real_quick_ratio()
144 Return an upper bound on ratio() very quickly.
145 """
146
Tim Peters9ae21482001-02-10 08:00:53 +0000147 def __init__(self, isjunk=None, a='', b=''):
148 """Construct a SequenceMatcher.
149
150 Optional arg isjunk is None (the default), or a one-argument
151 function that takes a sequence element and returns true iff the
Tim Peters5e824c32001-08-12 22:25:01 +0000152 element is junk. None is equivalent to passing "lambda x: 0", i.e.
Fred Drakef1da6282001-02-19 19:30:05 +0000153 no elements are considered to be junk. For example, pass
Tim Peters9ae21482001-02-10 08:00:53 +0000154 lambda x: x in " \\t"
155 if you're comparing lines as sequences of characters, and don't
156 want to synch up on blanks or hard tabs.
157
158 Optional arg a is the first of two sequences to be compared. By
159 default, an empty string. The elements of a must be hashable. See
160 also .set_seqs() and .set_seq1().
161
162 Optional arg b is the second of two sequences to be compared. By
Fred Drakef1da6282001-02-19 19:30:05 +0000163 default, an empty string. The elements of b must be hashable. See
Tim Peters9ae21482001-02-10 08:00:53 +0000164 also .set_seqs() and .set_seq2().
165 """
166
167 # Members:
168 # a
169 # first sequence
170 # b
171 # second sequence; differences are computed as "what do
172 # we need to do to 'a' to change it into 'b'?"
173 # b2j
174 # for x in b, b2j[x] is a list of the indices (into b)
175 # at which x appears; junk elements do not appear
Tim Peters9ae21482001-02-10 08:00:53 +0000176 # fullbcount
177 # for x in b, fullbcount[x] == the number of times x
178 # appears in b; only materialized if really needed (used
179 # only for computing quick_ratio())
180 # matching_blocks
181 # a list of (i, j, k) triples, where a[i:i+k] == b[j:j+k];
182 # ascending & non-overlapping in i and in j; terminated by
183 # a dummy (len(a), len(b), 0) sentinel
184 # opcodes
185 # a list of (tag, i1, i2, j1, j2) tuples, where tag is
186 # one of
187 # 'replace' a[i1:i2] should be replaced by b[j1:j2]
188 # 'delete' a[i1:i2] should be deleted
189 # 'insert' b[j1:j2] should be inserted
190 # 'equal' a[i1:i2] == b[j1:j2]
191 # isjunk
192 # a user-supplied function taking a sequence element and
193 # returning true iff the element is "junk" -- this has
194 # subtle but helpful effects on the algorithm, which I'll
195 # get around to writing up someday <0.9 wink>.
196 # DON'T USE! Only __chain_b uses this. Use isbjunk.
197 # isbjunk
198 # for x in b, isbjunk(x) == isjunk(x) but much faster;
199 # it's really the has_key method of a hidden dict.
200 # DOES NOT WORK for x in a!
Tim Peters81b92512002-04-29 01:37:32 +0000201 # isbpopular
202 # for x in b, isbpopular(x) is true iff b is reasonably long
203 # (at least 200 elements) and x accounts for more than 1% of
204 # its elements. DOES NOT WORK for x in a!
Tim Peters9ae21482001-02-10 08:00:53 +0000205
206 self.isjunk = isjunk
207 self.a = self.b = None
208 self.set_seqs(a, b)
209
210 def set_seqs(self, a, b):
211 """Set the two sequences to be compared.
212
213 >>> s = SequenceMatcher()
214 >>> s.set_seqs("abcd", "bcde")
215 >>> s.ratio()
216 0.75
217 """
218
219 self.set_seq1(a)
220 self.set_seq2(b)
221
222 def set_seq1(self, a):
223 """Set the first sequence to be compared.
224
225 The second sequence to be compared is not changed.
226
227 >>> s = SequenceMatcher(None, "abcd", "bcde")
228 >>> s.ratio()
229 0.75
230 >>> s.set_seq1("bcde")
231 >>> s.ratio()
232 1.0
233 >>>
234
235 SequenceMatcher computes and caches detailed information about the
236 second sequence, so if you want to compare one sequence S against
237 many sequences, use .set_seq2(S) once and call .set_seq1(x)
238 repeatedly for each of the other sequences.
239
240 See also set_seqs() and set_seq2().
241 """
242
243 if a is self.a:
244 return
245 self.a = a
246 self.matching_blocks = self.opcodes = None
247
248 def set_seq2(self, b):
249 """Set the second sequence to be compared.
250
251 The first sequence to be compared is not changed.
252
253 >>> s = SequenceMatcher(None, "abcd", "bcde")
254 >>> s.ratio()
255 0.75
256 >>> s.set_seq2("abcd")
257 >>> s.ratio()
258 1.0
259 >>>
260
261 SequenceMatcher computes and caches detailed information about the
262 second sequence, so if you want to compare one sequence S against
263 many sequences, use .set_seq2(S) once and call .set_seq1(x)
264 repeatedly for each of the other sequences.
265
266 See also set_seqs() and set_seq1().
267 """
268
269 if b is self.b:
270 return
271 self.b = b
272 self.matching_blocks = self.opcodes = None
273 self.fullbcount = None
274 self.__chain_b()
275
276 # For each element x in b, set b2j[x] to a list of the indices in
277 # b where x appears; the indices are in increasing order; note that
278 # the number of times x appears in b is len(b2j[x]) ...
279 # when self.isjunk is defined, junk elements don't show up in this
280 # map at all, which stops the central find_longest_match method
281 # from starting any matching block at a junk element ...
282 # also creates the fast isbjunk function ...
Tim Peters81b92512002-04-29 01:37:32 +0000283 # b2j also does not contain entries for "popular" elements, meaning
284 # elements that account for more than 1% of the total elements, and
285 # when the sequence is reasonably large (>= 200 elements); this can
286 # be viewed as an adaptive notion of semi-junk, and yields an enormous
287 # speedup when, e.g., comparing program files with hundreds of
288 # instances of "return NULL;" ...
Tim Peters9ae21482001-02-10 08:00:53 +0000289 # note that this is only called when b changes; so for cross-product
290 # kinds of matches, it's best to call set_seq2 once, then set_seq1
291 # repeatedly
292
293 def __chain_b(self):
294 # Because isjunk is a user-defined (not C) function, and we test
295 # for junk a LOT, it's important to minimize the number of calls.
296 # Before the tricks described here, __chain_b was by far the most
297 # time-consuming routine in the whole module! If anyone sees
298 # Jim Roskind, thank him again for profile.py -- I never would
299 # have guessed that.
300 # The first trick is to build b2j ignoring the possibility
301 # of junk. I.e., we don't call isjunk at all yet. Throwing
302 # out the junk later is much cheaper than building b2j "right"
303 # from the start.
304 b = self.b
Tim Peters81b92512002-04-29 01:37:32 +0000305 n = len(b)
Tim Peters9ae21482001-02-10 08:00:53 +0000306 self.b2j = b2j = {}
Tim Peters81b92512002-04-29 01:37:32 +0000307 populardict = {}
308 for i, elt in enumerate(b):
309 if elt in b2j:
310 indices = b2j[elt]
311 if n >= 200 and len(indices) * 100 > n:
312 populardict[elt] = 1
313 del indices[:]
314 else:
315 indices.append(i)
Tim Peters9ae21482001-02-10 08:00:53 +0000316 else:
317 b2j[elt] = [i]
318
Tim Peters81b92512002-04-29 01:37:32 +0000319 # Purge leftover indices for popular elements.
320 for elt in populardict:
321 del b2j[elt]
322
Tim Peters9ae21482001-02-10 08:00:53 +0000323 # Now b2j.keys() contains elements uniquely, and especially when
324 # the sequence is a string, that's usually a good deal smaller
325 # than len(string). The difference is the number of isjunk calls
326 # saved.
Tim Peters81b92512002-04-29 01:37:32 +0000327 isjunk = self.isjunk
328 junkdict = {}
Tim Peters9ae21482001-02-10 08:00:53 +0000329 if isjunk:
Tim Peters81b92512002-04-29 01:37:32 +0000330 for d in populardict, b2j:
331 for elt in d.keys():
332 if isjunk(elt):
333 junkdict[elt] = 1
334 del d[elt]
Tim Peters9ae21482001-02-10 08:00:53 +0000335
Raymond Hettinger54f02222002-06-01 14:18:47 +0000336 # Now for x in b, isjunk(x) == x in junkdict, but the
Tim Peters9ae21482001-02-10 08:00:53 +0000337 # latter is much faster. Note too that while there may be a
338 # lot of junk in the sequence, the number of *unique* junk
339 # elements is probably small. So the memory burden of keeping
340 # this dict alive is likely trivial compared to the size of b2j.
341 self.isbjunk = junkdict.has_key
Tim Peters81b92512002-04-29 01:37:32 +0000342 self.isbpopular = populardict.has_key
Tim Peters9ae21482001-02-10 08:00:53 +0000343
344 def find_longest_match(self, alo, ahi, blo, bhi):
345 """Find longest matching block in a[alo:ahi] and b[blo:bhi].
346
347 If isjunk is not defined:
348
349 Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
350 alo <= i <= i+k <= ahi
351 blo <= j <= j+k <= bhi
352 and for all (i',j',k') meeting those conditions,
353 k >= k'
354 i <= i'
355 and if i == i', j <= j'
356
357 In other words, of all maximal matching blocks, return one that
358 starts earliest in a, and of all those maximal matching blocks that
359 start earliest in a, return the one that starts earliest in b.
360
361 >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
362 >>> s.find_longest_match(0, 5, 0, 9)
363 (0, 4, 5)
364
365 If isjunk is defined, first the longest matching block is
366 determined as above, but with the additional restriction that no
367 junk element appears in the block. Then that block is extended as
368 far as possible by matching (only) junk elements on both sides. So
369 the resulting block never matches on junk except as identical junk
370 happens to be adjacent to an "interesting" match.
371
372 Here's the same example as before, but considering blanks to be
373 junk. That prevents " abcd" from matching the " abcd" at the tail
374 end of the second sequence directly. Instead only the "abcd" can
375 match, and matches the leftmost "abcd" in the second sequence:
376
377 >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
378 >>> s.find_longest_match(0, 5, 0, 9)
379 (1, 0, 4)
380
381 If no blocks match, return (alo, blo, 0).
382
383 >>> s = SequenceMatcher(None, "ab", "c")
384 >>> s.find_longest_match(0, 2, 0, 1)
385 (0, 0, 0)
386 """
387
388 # CAUTION: stripping common prefix or suffix would be incorrect.
389 # E.g.,
390 # ab
391 # acab
392 # Longest matching block is "ab", but if common prefix is
393 # stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
394 # strip, so ends up claiming that ab is changed to acab by
395 # inserting "ca" in the middle. That's minimal but unintuitive:
396 # "it's obvious" that someone inserted "ac" at the front.
397 # Windiff ends up at the same place as diff, but by pairing up
398 # the unique 'b's and then matching the first two 'a's.
399
400 a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.isbjunk
401 besti, bestj, bestsize = alo, blo, 0
402 # find longest junk-free match
403 # during an iteration of the loop, j2len[j] = length of longest
404 # junk-free match ending with a[i-1] and b[j]
405 j2len = {}
406 nothing = []
407 for i in xrange(alo, ahi):
408 # look at all instances of a[i] in b; note that because
409 # b2j has no junk keys, the loop is skipped if a[i] is junk
410 j2lenget = j2len.get
411 newj2len = {}
412 for j in b2j.get(a[i], nothing):
413 # a[i] matches b[j]
414 if j < blo:
415 continue
416 if j >= bhi:
417 break
418 k = newj2len[j] = j2lenget(j-1, 0) + 1
419 if k > bestsize:
420 besti, bestj, bestsize = i-k+1, j-k+1, k
421 j2len = newj2len
422
Tim Peters81b92512002-04-29 01:37:32 +0000423 # Extend the best by non-junk elements on each end. In particular,
424 # "popular" non-junk elements aren't in b2j, which greatly speeds
425 # the inner loop above, but also means "the best" match so far
426 # doesn't contain any junk *or* popular non-junk elements.
427 while besti > alo and bestj > blo and \
428 not isbjunk(b[bestj-1]) and \
429 a[besti-1] == b[bestj-1]:
430 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
431 while besti+bestsize < ahi and bestj+bestsize < bhi and \
432 not isbjunk(b[bestj+bestsize]) and \
433 a[besti+bestsize] == b[bestj+bestsize]:
434 bestsize += 1
435
Tim Peters9ae21482001-02-10 08:00:53 +0000436 # Now that we have a wholly interesting match (albeit possibly
437 # empty!), we may as well suck up the matching junk on each
438 # side of it too. Can't think of a good reason not to, and it
439 # saves post-processing the (possibly considerable) expense of
440 # figuring out what to do with it. In the case of an empty
441 # interesting match, this is clearly the right thing to do,
442 # because no other kind of match is possible in the regions.
443 while besti > alo and bestj > blo and \
444 isbjunk(b[bestj-1]) and \
445 a[besti-1] == b[bestj-1]:
446 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
447 while besti+bestsize < ahi and bestj+bestsize < bhi and \
448 isbjunk(b[bestj+bestsize]) and \
449 a[besti+bestsize] == b[bestj+bestsize]:
450 bestsize = bestsize + 1
451
Tim Peters9ae21482001-02-10 08:00:53 +0000452 return besti, bestj, bestsize
453
454 def get_matching_blocks(self):
455 """Return list of triples describing matching subsequences.
456
457 Each triple is of the form (i, j, n), and means that
458 a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
459 i and in j.
460
461 The last triple is a dummy, (len(a), len(b), 0), and is the only
462 triple with n==0.
463
464 >>> s = SequenceMatcher(None, "abxcd", "abcd")
465 >>> s.get_matching_blocks()
466 [(0, 0, 2), (3, 2, 2), (5, 4, 0)]
467 """
468
469 if self.matching_blocks is not None:
470 return self.matching_blocks
471 self.matching_blocks = []
472 la, lb = len(self.a), len(self.b)
473 self.__helper(0, la, 0, lb, self.matching_blocks)
474 self.matching_blocks.append( (la, lb, 0) )
Tim Peters9ae21482001-02-10 08:00:53 +0000475 return self.matching_blocks
476
477 # builds list of matching blocks covering a[alo:ahi] and
478 # b[blo:bhi], appending them in increasing order to answer
479
480 def __helper(self, alo, ahi, blo, bhi, answer):
481 i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)
482 # a[alo:i] vs b[blo:j] unknown
483 # a[i:i+k] same as b[j:j+k]
484 # a[i+k:ahi] vs b[j+k:bhi] unknown
485 if k:
486 if alo < i and blo < j:
487 self.__helper(alo, i, blo, j, answer)
488 answer.append(x)
489 if i+k < ahi and j+k < bhi:
490 self.__helper(i+k, ahi, j+k, bhi, answer)
491
492 def get_opcodes(self):
493 """Return list of 5-tuples describing how to turn a into b.
494
495 Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
496 has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
497 tuple preceding it, and likewise for j1 == the previous j2.
498
499 The tags are strings, with these meanings:
500
501 'replace': a[i1:i2] should be replaced by b[j1:j2]
502 'delete': a[i1:i2] should be deleted.
503 Note that j1==j2 in this case.
504 'insert': b[j1:j2] should be inserted at a[i1:i1].
505 Note that i1==i2 in this case.
506 'equal': a[i1:i2] == b[j1:j2]
507
508 >>> a = "qabxcd"
509 >>> b = "abycdf"
510 >>> s = SequenceMatcher(None, a, b)
511 >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
512 ... print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
513 ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))
514 delete a[0:1] (q) b[0:0] ()
515 equal a[1:3] (ab) b[0:2] (ab)
516 replace a[3:4] (x) b[2:3] (y)
517 equal a[4:6] (cd) b[3:5] (cd)
518 insert a[6:6] () b[5:6] (f)
519 """
520
521 if self.opcodes is not None:
522 return self.opcodes
523 i = j = 0
524 self.opcodes = answer = []
525 for ai, bj, size in self.get_matching_blocks():
526 # invariant: we've pumped out correct diffs to change
527 # a[:i] into b[:j], and the next matching block is
528 # a[ai:ai+size] == b[bj:bj+size]. So we need to pump
529 # out a diff to change a[i:ai] into b[j:bj], pump out
530 # the matching block, and move (i,j) beyond the match
531 tag = ''
532 if i < ai and j < bj:
533 tag = 'replace'
534 elif i < ai:
535 tag = 'delete'
536 elif j < bj:
537 tag = 'insert'
538 if tag:
539 answer.append( (tag, i, ai, j, bj) )
540 i, j = ai+size, bj+size
541 # the list of matching blocks is terminated by a
542 # sentinel with size 0
543 if size:
544 answer.append( ('equal', ai, i, bj, j) )
545 return answer
546
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000547 def get_grouped_opcodes(self, n=3):
548 """ Isolate change clusters by eliminating ranges with no changes.
549
550 Return a generator of groups with upto n lines of context.
551 Each group is in the same format as returned by get_opcodes().
552
553 >>> from pprint import pprint
554 >>> a = map(str, range(1,40))
555 >>> b = a[:]
556 >>> b[8:8] = ['i'] # Make an insertion
557 >>> b[20] += 'x' # Make a replacement
558 >>> b[23:28] = [] # Make a deletion
559 >>> b[30] += 'y' # Make another replacement
560 >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
561 [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
562 [('equal', 16, 19, 17, 20),
563 ('replace', 19, 20, 20, 21),
564 ('equal', 20, 22, 21, 23),
565 ('delete', 22, 27, 23, 23),
566 ('equal', 27, 30, 23, 26)],
567 [('equal', 31, 34, 27, 30),
568 ('replace', 34, 35, 30, 31),
569 ('equal', 35, 38, 31, 34)]]
570 """
571
572 codes = self.get_opcodes()
573 # Fixup leading and trailing groups if they show no changes.
574 if codes[0][0] == 'equal':
575 tag, i1, i2, j1, j2 = codes[0]
576 codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2
577 if codes[-1][0] == 'equal':
578 tag, i1, i2, j1, j2 = codes[-1]
579 codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)
580
581 nn = n + n
582 group = []
583 for tag, i1, i2, j1, j2 in codes:
584 # End the current group and start a new one whenever
585 # there is a large range with no changes.
586 if tag == 'equal' and i2-i1 > nn:
587 group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))
588 yield group
589 group = []
590 i1, j1 = max(i1, i2-n), max(j1, j2-n)
591 group.append((tag, i1, i2, j1 ,j2))
592 if group and not (len(group)==1 and group[0][0] == 'equal'):
593 yield group
594
Tim Peters9ae21482001-02-10 08:00:53 +0000595 def ratio(self):
596 """Return a measure of the sequences' similarity (float in [0,1]).
597
598 Where T is the total number of elements in both sequences, and
599 M is the number of matches, this is 2,0*M / T.
600 Note that this is 1 if the sequences are identical, and 0 if
601 they have nothing in common.
602
603 .ratio() is expensive to compute if you haven't already computed
604 .get_matching_blocks() or .get_opcodes(), in which case you may
605 want to try .quick_ratio() or .real_quick_ratio() first to get an
606 upper bound.
607
608 >>> s = SequenceMatcher(None, "abcd", "bcde")
609 >>> s.ratio()
610 0.75
611 >>> s.quick_ratio()
612 0.75
613 >>> s.real_quick_ratio()
614 1.0
615 """
616
617 matches = reduce(lambda sum, triple: sum + triple[-1],
618 self.get_matching_blocks(), 0)
Neal Norwitze7dfe212003-07-01 14:59:46 +0000619 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000620
621 def quick_ratio(self):
622 """Return an upper bound on ratio() relatively quickly.
623
624 This isn't defined beyond that it is an upper bound on .ratio(), and
625 is faster to compute.
626 """
627
628 # viewing a and b as multisets, set matches to the cardinality
629 # of their intersection; this counts the number of matches
630 # without regard to order, so is clearly an upper bound
631 if self.fullbcount is None:
632 self.fullbcount = fullbcount = {}
633 for elt in self.b:
634 fullbcount[elt] = fullbcount.get(elt, 0) + 1
635 fullbcount = self.fullbcount
636 # avail[x] is the number of times x appears in 'b' less the
637 # number of times we've seen it in 'a' so far ... kinda
638 avail = {}
639 availhas, matches = avail.has_key, 0
640 for elt in self.a:
641 if availhas(elt):
642 numb = avail[elt]
643 else:
644 numb = fullbcount.get(elt, 0)
645 avail[elt] = numb - 1
646 if numb > 0:
647 matches = matches + 1
Neal Norwitze7dfe212003-07-01 14:59:46 +0000648 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000649
650 def real_quick_ratio(self):
651 """Return an upper bound on ratio() very quickly.
652
653 This isn't defined beyond that it is an upper bound on .ratio(), and
654 is faster to compute than either .ratio() or .quick_ratio().
655 """
656
657 la, lb = len(self.a), len(self.b)
658 # can't have more matches than the number of elements in the
659 # shorter sequence
Neal Norwitze7dfe212003-07-01 14:59:46 +0000660 return _calculate_ratio(min(la, lb), la + lb)
Tim Peters9ae21482001-02-10 08:00:53 +0000661
662def get_close_matches(word, possibilities, n=3, cutoff=0.6):
663 """Use SequenceMatcher to return list of the best "good enough" matches.
664
665 word is a sequence for which close matches are desired (typically a
666 string).
667
668 possibilities is a list of sequences against which to match word
669 (typically a list of strings).
670
671 Optional arg n (default 3) is the maximum number of close matches to
672 return. n must be > 0.
673
674 Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
675 that don't score at least that similar to word are ignored.
676
677 The best (no more than n) matches among the possibilities are returned
678 in a list, sorted by similarity score, most similar first.
679
680 >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
681 ['apple', 'ape']
Tim Peters5e824c32001-08-12 22:25:01 +0000682 >>> import keyword as _keyword
683 >>> get_close_matches("wheel", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000684 ['while']
Tim Peters5e824c32001-08-12 22:25:01 +0000685 >>> get_close_matches("apple", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000686 []
Tim Peters5e824c32001-08-12 22:25:01 +0000687 >>> get_close_matches("accept", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000688 ['except']
689 """
690
691 if not n > 0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000692 raise ValueError("n must be > 0: %r" % (n,))
Tim Peters9ae21482001-02-10 08:00:53 +0000693 if not 0.0 <= cutoff <= 1.0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000694 raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
Tim Peters9ae21482001-02-10 08:00:53 +0000695 result = []
696 s = SequenceMatcher()
697 s.set_seq2(word)
698 for x in possibilities:
699 s.set_seq1(x)
700 if s.real_quick_ratio() >= cutoff and \
701 s.quick_ratio() >= cutoff and \
702 s.ratio() >= cutoff:
703 result.append((s.ratio(), x))
Tim Peters9ae21482001-02-10 08:00:53 +0000704
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000705 # Move the best scorers to head of list
706 result.sort(reverse=True)
707 # Strip scores for the best n matches
708 return [x for score, x in result[:n]]
Tim Peters5e824c32001-08-12 22:25:01 +0000709
710def _count_leading(line, ch):
711 """
712 Return number of `ch` characters at the start of `line`.
713
714 Example:
715
716 >>> _count_leading(' abc', ' ')
717 3
718 """
719
720 i, n = 0, len(line)
721 while i < n and line[i] == ch:
722 i += 1
723 return i
724
725class Differ:
726 r"""
727 Differ is a class for comparing sequences of lines of text, and
728 producing human-readable differences or deltas. Differ uses
729 SequenceMatcher both to compare sequences of lines, and to compare
730 sequences of characters within similar (near-matching) lines.
731
732 Each line of a Differ delta begins with a two-letter code:
733
734 '- ' line unique to sequence 1
735 '+ ' line unique to sequence 2
736 ' ' line common to both sequences
737 '? ' line not present in either input sequence
738
739 Lines beginning with '? ' attempt to guide the eye to intraline
740 differences, and were not present in either input sequence. These lines
741 can be confusing if the sequences contain tab characters.
742
743 Note that Differ makes no claim to produce a *minimal* diff. To the
744 contrary, minimal diffs are often counter-intuitive, because they synch
745 up anywhere possible, sometimes accidental matches 100 pages apart.
746 Restricting synch points to contiguous matches preserves some notion of
747 locality, at the occasional cost of producing a longer diff.
748
749 Example: Comparing two texts.
750
751 First we set up the texts, sequences of individual single-line strings
752 ending with newlines (such sequences can also be obtained from the
753 `readlines()` method of file-like objects):
754
755 >>> text1 = ''' 1. Beautiful is better than ugly.
756 ... 2. Explicit is better than implicit.
757 ... 3. Simple is better than complex.
758 ... 4. Complex is better than complicated.
759 ... '''.splitlines(1)
760 >>> len(text1)
761 4
762 >>> text1[0][-1]
763 '\n'
764 >>> text2 = ''' 1. Beautiful is better than ugly.
765 ... 3. Simple is better than complex.
766 ... 4. Complicated is better than complex.
767 ... 5. Flat is better than nested.
768 ... '''.splitlines(1)
769
770 Next we instantiate a Differ object:
771
772 >>> d = Differ()
773
774 Note that when instantiating a Differ object we may pass functions to
775 filter out line and character 'junk'. See Differ.__init__ for details.
776
777 Finally, we compare the two:
778
Tim Peters8a9c2842001-09-22 21:30:22 +0000779 >>> result = list(d.compare(text1, text2))
Tim Peters5e824c32001-08-12 22:25:01 +0000780
781 'result' is a list of strings, so let's pretty-print it:
782
783 >>> from pprint import pprint as _pprint
784 >>> _pprint(result)
785 [' 1. Beautiful is better than ugly.\n',
786 '- 2. Explicit is better than implicit.\n',
787 '- 3. Simple is better than complex.\n',
788 '+ 3. Simple is better than complex.\n',
789 '? ++\n',
790 '- 4. Complex is better than complicated.\n',
791 '? ^ ---- ^\n',
792 '+ 4. Complicated is better than complex.\n',
793 '? ++++ ^ ^\n',
794 '+ 5. Flat is better than nested.\n']
795
796 As a single multi-line string it looks like this:
797
798 >>> print ''.join(result),
799 1. Beautiful is better than ugly.
800 - 2. Explicit is better than implicit.
801 - 3. Simple is better than complex.
802 + 3. Simple is better than complex.
803 ? ++
804 - 4. Complex is better than complicated.
805 ? ^ ---- ^
806 + 4. Complicated is better than complex.
807 ? ++++ ^ ^
808 + 5. Flat is better than nested.
809
810 Methods:
811
812 __init__(linejunk=None, charjunk=None)
813 Construct a text differencer, with optional filters.
814
815 compare(a, b)
Tim Peters8a9c2842001-09-22 21:30:22 +0000816 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000817 """
818
819 def __init__(self, linejunk=None, charjunk=None):
820 """
821 Construct a text differencer, with optional filters.
822
823 The two optional keyword parameters are for filter functions:
824
825 - `linejunk`: A function that should accept a single string argument,
826 and return true iff the string is junk. The module-level function
827 `IS_LINE_JUNK` may be used to filter out lines without visible
Tim Peters81b92512002-04-29 01:37:32 +0000828 characters, except for at most one splat ('#'). It is recommended
829 to leave linejunk None; as of Python 2.3, the underlying
830 SequenceMatcher class has grown an adaptive notion of "noise" lines
831 that's better than any static definition the author has ever been
832 able to craft.
Tim Peters5e824c32001-08-12 22:25:01 +0000833
834 - `charjunk`: A function that should accept a string of length 1. The
835 module-level function `IS_CHARACTER_JUNK` may be used to filter out
836 whitespace characters (a blank or tab; **note**: bad idea to include
Tim Peters81b92512002-04-29 01:37:32 +0000837 newline in this!). Use of IS_CHARACTER_JUNK is recommended.
Tim Peters5e824c32001-08-12 22:25:01 +0000838 """
839
840 self.linejunk = linejunk
841 self.charjunk = charjunk
Tim Peters5e824c32001-08-12 22:25:01 +0000842
843 def compare(self, a, b):
844 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +0000845 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000846
847 Each sequence must contain individual single-line strings ending with
848 newlines. Such sequences can be obtained from the `readlines()` method
Tim Peters8a9c2842001-09-22 21:30:22 +0000849 of file-like objects. The delta generated also consists of newline-
850 terminated strings, ready to be printed as-is via the writeline()
Tim Peters5e824c32001-08-12 22:25:01 +0000851 method of a file-like object.
852
853 Example:
854
855 >>> print ''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1),
856 ... 'ore\ntree\nemu\n'.splitlines(1))),
857 - one
858 ? ^
859 + ore
860 ? ^
861 - two
862 - three
863 ? -
864 + tree
865 + emu
866 """
867
868 cruncher = SequenceMatcher(self.linejunk, a, b)
869 for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
870 if tag == 'replace':
Tim Peters8a9c2842001-09-22 21:30:22 +0000871 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000872 elif tag == 'delete':
Tim Peters8a9c2842001-09-22 21:30:22 +0000873 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000874 elif tag == 'insert':
Tim Peters8a9c2842001-09-22 21:30:22 +0000875 g = self._dump('+', b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000876 elif tag == 'equal':
Tim Peters8a9c2842001-09-22 21:30:22 +0000877 g = self._dump(' ', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000878 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000879 raise ValueError, 'unknown tag %r' % (tag,)
Tim Peters8a9c2842001-09-22 21:30:22 +0000880
881 for line in g:
882 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000883
884 def _dump(self, tag, x, lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000885 """Generate comparison results for a same-tagged range."""
Tim Peters5e824c32001-08-12 22:25:01 +0000886 for i in xrange(lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000887 yield '%s %s' % (tag, x[i])
Tim Peters5e824c32001-08-12 22:25:01 +0000888
889 def _plain_replace(self, a, alo, ahi, b, blo, bhi):
890 assert alo < ahi and blo < bhi
891 # dump the shorter block first -- reduces the burden on short-term
892 # memory if the blocks are of very different sizes
893 if bhi - blo < ahi - alo:
Tim Peters8a9c2842001-09-22 21:30:22 +0000894 first = self._dump('+', b, blo, bhi)
895 second = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000896 else:
Tim Peters8a9c2842001-09-22 21:30:22 +0000897 first = self._dump('-', a, alo, ahi)
898 second = self._dump('+', b, blo, bhi)
899
900 for g in first, second:
901 for line in g:
902 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000903
904 def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
905 r"""
906 When replacing one block of lines with another, search the blocks
907 for *similar* lines; the best-matching pair (if any) is used as a
908 synch point, and intraline difference marking is done on the
909 similar pair. Lots of work, but often worth it.
910
911 Example:
912
913 >>> d = Differ()
Raymond Hettinger83325e92003-07-16 04:32:32 +0000914 >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
915 ... ['abcdefGhijkl\n'], 0, 1)
916 >>> print ''.join(results),
Tim Peters5e824c32001-08-12 22:25:01 +0000917 - abcDefghiJkl
918 ? ^ ^ ^
919 + abcdefGhijkl
920 ? ^ ^ ^
921 """
922
Tim Peters5e824c32001-08-12 22:25:01 +0000923 # don't synch up unless the lines have a similarity score of at
924 # least cutoff; best_ratio tracks the best score seen so far
925 best_ratio, cutoff = 0.74, 0.75
926 cruncher = SequenceMatcher(self.charjunk)
927 eqi, eqj = None, None # 1st indices of equal lines (if any)
928
929 # search for the pair that matches best without being identical
930 # (identical lines must be junk lines, & we don't want to synch up
931 # on junk -- unless we have to)
932 for j in xrange(blo, bhi):
933 bj = b[j]
934 cruncher.set_seq2(bj)
935 for i in xrange(alo, ahi):
936 ai = a[i]
937 if ai == bj:
938 if eqi is None:
939 eqi, eqj = i, j
940 continue
941 cruncher.set_seq1(ai)
942 # computing similarity is expensive, so use the quick
943 # upper bounds first -- have seen this speed up messy
944 # compares by a factor of 3.
945 # note that ratio() is only expensive to compute the first
946 # time it's called on a sequence pair; the expensive part
947 # of the computation is cached by cruncher
948 if cruncher.real_quick_ratio() > best_ratio and \
949 cruncher.quick_ratio() > best_ratio and \
950 cruncher.ratio() > best_ratio:
951 best_ratio, best_i, best_j = cruncher.ratio(), i, j
952 if best_ratio < cutoff:
953 # no non-identical "pretty close" pair
954 if eqi is None:
955 # no identical pair either -- treat it as a straight replace
Tim Peters8a9c2842001-09-22 21:30:22 +0000956 for line in self._plain_replace(a, alo, ahi, b, blo, bhi):
957 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000958 return
959 # no close pair, but an identical pair -- synch up on that
960 best_i, best_j, best_ratio = eqi, eqj, 1.0
961 else:
962 # there's a close pair, so forget the identical pair (if any)
963 eqi = None
964
965 # a[best_i] very similar to b[best_j]; eqi is None iff they're not
966 # identical
Tim Peters5e824c32001-08-12 22:25:01 +0000967
968 # pump out diffs from before the synch point
Tim Peters8a9c2842001-09-22 21:30:22 +0000969 for line in self._fancy_helper(a, alo, best_i, b, blo, best_j):
970 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000971
972 # do intraline marking on the synch pair
973 aelt, belt = a[best_i], b[best_j]
974 if eqi is None:
975 # pump out a '-', '?', '+', '?' quad for the synched lines
976 atags = btags = ""
977 cruncher.set_seqs(aelt, belt)
978 for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
979 la, lb = ai2 - ai1, bj2 - bj1
980 if tag == 'replace':
981 atags += '^' * la
982 btags += '^' * lb
983 elif tag == 'delete':
984 atags += '-' * la
985 elif tag == 'insert':
986 btags += '+' * lb
987 elif tag == 'equal':
988 atags += ' ' * la
989 btags += ' ' * lb
990 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000991 raise ValueError, 'unknown tag %r' % (tag,)
Tim Peters8a9c2842001-09-22 21:30:22 +0000992 for line in self._qformat(aelt, belt, atags, btags):
993 yield line
Tim Peters5e824c32001-08-12 22:25:01 +0000994 else:
995 # the synch pair is identical
Tim Peters8a9c2842001-09-22 21:30:22 +0000996 yield ' ' + aelt
Tim Peters5e824c32001-08-12 22:25:01 +0000997
998 # pump out diffs from after the synch point
Tim Peters8a9c2842001-09-22 21:30:22 +0000999 for line in self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi):
1000 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001001
1002 def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
Tim Peters8a9c2842001-09-22 21:30:22 +00001003 g = []
Tim Peters5e824c32001-08-12 22:25:01 +00001004 if alo < ahi:
1005 if blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001006 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +00001007 else:
Tim Peters8a9c2842001-09-22 21:30:22 +00001008 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +00001009 elif blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001010 g = self._dump('+', b, blo, bhi)
1011
1012 for line in g:
1013 yield line
Tim Peters5e824c32001-08-12 22:25:01 +00001014
1015 def _qformat(self, aline, bline, atags, btags):
1016 r"""
1017 Format "?" output and deal with leading tabs.
1018
1019 Example:
1020
1021 >>> d = Differ()
Raymond Hettinger83325e92003-07-16 04:32:32 +00001022 >>> results = d._qformat('\tabcDefghiJkl\n', '\t\tabcdefGhijkl\n',
1023 ... ' ^ ^ ^ ', '+ ^ ^ ^ ')
1024 >>> for line in results: print repr(line)
Tim Peters5e824c32001-08-12 22:25:01 +00001025 ...
1026 '- \tabcDefghiJkl\n'
1027 '? \t ^ ^ ^\n'
1028 '+ \t\tabcdefGhijkl\n'
1029 '? \t ^ ^ ^\n'
1030 """
1031
1032 # Can hurt, but will probably help most of the time.
1033 common = min(_count_leading(aline, "\t"),
1034 _count_leading(bline, "\t"))
1035 common = min(common, _count_leading(atags[:common], " "))
1036 atags = atags[common:].rstrip()
1037 btags = btags[common:].rstrip()
1038
Tim Peters8a9c2842001-09-22 21:30:22 +00001039 yield "- " + aline
Tim Peters5e824c32001-08-12 22:25:01 +00001040 if atags:
Tim Peters527e64f2001-10-04 05:36:56 +00001041 yield "? %s%s\n" % ("\t" * common, atags)
Tim Peters5e824c32001-08-12 22:25:01 +00001042
Tim Peters8a9c2842001-09-22 21:30:22 +00001043 yield "+ " + bline
Tim Peters5e824c32001-08-12 22:25:01 +00001044 if btags:
Tim Peters8a9c2842001-09-22 21:30:22 +00001045 yield "? %s%s\n" % ("\t" * common, btags)
Tim Peters5e824c32001-08-12 22:25:01 +00001046
1047# With respect to junk, an earlier version of ndiff simply refused to
1048# *start* a match with a junk element. The result was cases like this:
1049# before: private Thread currentThread;
1050# after: private volatile Thread currentThread;
1051# If you consider whitespace to be junk, the longest contiguous match
1052# not starting with junk is "e Thread currentThread". So ndiff reported
1053# that "e volatil" was inserted between the 't' and the 'e' in "private".
1054# While an accurate view, to people that's absurd. The current version
1055# looks for matching blocks that are entirely junk-free, then extends the
1056# longest one of those as far as possible but only with matching junk.
1057# So now "currentThread" is matched, then extended to suck up the
1058# preceding blank; then "private" is matched, and extended to suck up the
1059# following blank; then "Thread" is matched; and finally ndiff reports
1060# that "volatile " was inserted before "Thread". The only quibble
1061# remaining is that perhaps it was really the case that " volatile"
1062# was inserted after "private". I can live with that <wink>.
1063
1064import re
1065
1066def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match):
1067 r"""
1068 Return 1 for ignorable line: iff `line` is blank or contains a single '#'.
1069
1070 Examples:
1071
1072 >>> IS_LINE_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001073 True
Tim Peters5e824c32001-08-12 22:25:01 +00001074 >>> IS_LINE_JUNK(' # \n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001075 True
Tim Peters5e824c32001-08-12 22:25:01 +00001076 >>> IS_LINE_JUNK('hello\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001077 False
Tim Peters5e824c32001-08-12 22:25:01 +00001078 """
1079
1080 return pat(line) is not None
1081
1082def IS_CHARACTER_JUNK(ch, ws=" \t"):
1083 r"""
1084 Return 1 for ignorable character: iff `ch` is a space or tab.
1085
1086 Examples:
1087
1088 >>> IS_CHARACTER_JUNK(' ')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001089 True
Tim Peters5e824c32001-08-12 22:25:01 +00001090 >>> IS_CHARACTER_JUNK('\t')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001091 True
Tim Peters5e824c32001-08-12 22:25:01 +00001092 >>> IS_CHARACTER_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001093 False
Tim Peters5e824c32001-08-12 22:25:01 +00001094 >>> IS_CHARACTER_JUNK('x')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001095 False
Tim Peters5e824c32001-08-12 22:25:01 +00001096 """
1097
1098 return ch in ws
1099
1100del re
1101
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001102
1103def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
1104 tofiledate='', n=3, lineterm='\n'):
1105 r"""
1106 Compare two sequences of lines; generate the delta as a unified diff.
1107
1108 Unified diffs are a compact way of showing line changes and a few
1109 lines of context. The number of context lines is set by 'n' which
1110 defaults to three.
1111
Raymond Hettinger0887c732003-06-17 16:53:25 +00001112 By default, the diff control lines (those with ---, +++, or @@) are
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001113 created with a trailing newline. This is helpful so that inputs
1114 created from file.readlines() result in diffs that are suitable for
1115 file.writelines() since both the inputs and outputs have trailing
1116 newlines.
1117
1118 For inputs that do not have trailing newlines, set the lineterm
1119 argument to "" so that the output will be uniformly newline free.
1120
1121 The unidiff format normally has a header for filenames and modification
1122 times. Any or all of these may be specified using strings for
1123 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. The modification
1124 times are normally expressed in the format returned by time.ctime().
1125
1126 Example:
1127
1128 >>> for line in unified_diff('one two three four'.split(),
1129 ... 'zero one tree four'.split(), 'Original', 'Current',
1130 ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:20:52 2003',
1131 ... lineterm=''):
1132 ... print line
1133 --- Original Sat Jan 26 23:30:50 1991
1134 +++ Current Fri Jun 06 10:20:52 2003
1135 @@ -1,4 +1,4 @@
1136 +zero
1137 one
1138 -two
1139 -three
1140 +tree
1141 four
1142 """
1143
1144 started = False
1145 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1146 if not started:
1147 yield '--- %s %s%s' % (fromfile, fromfiledate, lineterm)
1148 yield '+++ %s %s%s' % (tofile, tofiledate, lineterm)
1149 started = True
1150 i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4]
1151 yield "@@ -%d,%d +%d,%d @@%s" % (i1+1, i2-i1, j1+1, j2-j1, lineterm)
1152 for tag, i1, i2, j1, j2 in group:
1153 if tag == 'equal':
1154 for line in a[i1:i2]:
1155 yield ' ' + line
1156 continue
1157 if tag == 'replace' or tag == 'delete':
1158 for line in a[i1:i2]:
1159 yield '-' + line
1160 if tag == 'replace' or tag == 'insert':
1161 for line in b[j1:j2]:
1162 yield '+' + line
1163
1164# See http://www.unix.org/single_unix_specification/
1165def context_diff(a, b, fromfile='', tofile='',
1166 fromfiledate='', tofiledate='', n=3, lineterm='\n'):
1167 r"""
1168 Compare two sequences of lines; generate the delta as a context diff.
1169
1170 Context diffs are a compact way of showing line changes and a few
1171 lines of context. The number of context lines is set by 'n' which
1172 defaults to three.
1173
1174 By default, the diff control lines (those with *** or ---) are
1175 created with a trailing newline. This is helpful so that inputs
1176 created from file.readlines() result in diffs that are suitable for
1177 file.writelines() since both the inputs and outputs have trailing
1178 newlines.
1179
1180 For inputs that do not have trailing newlines, set the lineterm
1181 argument to "" so that the output will be uniformly newline free.
1182
1183 The context diff format normally has a header for filenames and
1184 modification times. Any or all of these may be specified using
1185 strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
1186 The modification times are normally expressed in the format returned
1187 by time.ctime(). If not specified, the strings default to blanks.
1188
1189 Example:
1190
1191 >>> print ''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1),
1192 ... 'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current',
1193 ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:22:46 2003')),
1194 *** Original Sat Jan 26 23:30:50 1991
1195 --- Current Fri Jun 06 10:22:46 2003
1196 ***************
1197 *** 1,4 ****
1198 one
1199 ! two
1200 ! three
1201 four
1202 --- 1,4 ----
1203 + zero
1204 one
1205 ! tree
1206 four
1207 """
1208
1209 started = False
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001210 prefixmap = {'insert':'+ ', 'delete':'- ', 'replace':'! ', 'equal':' '}
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001211 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1212 if not started:
1213 yield '*** %s %s%s' % (fromfile, fromfiledate, lineterm)
1214 yield '--- %s %s%s' % (tofile, tofiledate, lineterm)
1215 started = True
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001216
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001217 yield '***************%s' % (lineterm,)
1218 if group[-1][2] - group[0][1] >= 2:
1219 yield '*** %d,%d ****%s' % (group[0][1]+1, group[-1][2], lineterm)
1220 else:
1221 yield '*** %d ****%s' % (group[-1][2], lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001222 visiblechanges = [e for e in group if e[0] in ('replace', 'delete')]
1223 if visiblechanges:
1224 for tag, i1, i2, _, _ in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001225 if tag != 'insert':
1226 for line in a[i1:i2]:
1227 yield prefixmap[tag] + line
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001228
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001229 if group[-1][4] - group[0][3] >= 2:
1230 yield '--- %d,%d ----%s' % (group[0][3]+1, group[-1][4], lineterm)
1231 else:
1232 yield '--- %d ----%s' % (group[-1][4], lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001233 visiblechanges = [e for e in group if e[0] in ('replace', 'insert')]
1234 if visiblechanges:
1235 for tag, _, _, j1, j2 in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001236 if tag != 'delete':
1237 for line in b[j1:j2]:
1238 yield prefixmap[tag] + line
1239
Tim Peters81b92512002-04-29 01:37:32 +00001240def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
Tim Peters5e824c32001-08-12 22:25:01 +00001241 r"""
1242 Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
1243
1244 Optional keyword parameters `linejunk` and `charjunk` are for filter
1245 functions (or None):
1246
1247 - linejunk: A function that should accept a single string argument, and
Tim Peters81b92512002-04-29 01:37:32 +00001248 return true iff the string is junk. The default is None, and is
1249 recommended; as of Python 2.3, an adaptive notion of "noise" lines is
1250 used that does a good job on its own.
Tim Peters5e824c32001-08-12 22:25:01 +00001251
1252 - charjunk: A function that should accept a string of length 1. The
1253 default is module-level function IS_CHARACTER_JUNK, which filters out
1254 whitespace characters (a blank or tab; note: bad idea to include newline
1255 in this!).
1256
1257 Tools/scripts/ndiff.py is a command-line front-end to this function.
1258
1259 Example:
1260
1261 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
1262 ... 'ore\ntree\nemu\n'.splitlines(1))
1263 >>> print ''.join(diff),
1264 - one
1265 ? ^
1266 + ore
1267 ? ^
1268 - two
1269 - three
1270 ? -
1271 + tree
1272 + emu
1273 """
1274 return Differ(linejunk, charjunk).compare(a, b)
1275
1276def restore(delta, which):
1277 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +00001278 Generate one of the two sequences that generated a delta.
Tim Peters5e824c32001-08-12 22:25:01 +00001279
1280 Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
1281 lines originating from file 1 or 2 (parameter `which`), stripping off line
1282 prefixes.
1283
1284 Examples:
1285
1286 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
1287 ... 'ore\ntree\nemu\n'.splitlines(1))
Tim Peters8a9c2842001-09-22 21:30:22 +00001288 >>> diff = list(diff)
Tim Peters5e824c32001-08-12 22:25:01 +00001289 >>> print ''.join(restore(diff, 1)),
1290 one
1291 two
1292 three
1293 >>> print ''.join(restore(diff, 2)),
1294 ore
1295 tree
1296 emu
1297 """
1298 try:
1299 tag = {1: "- ", 2: "+ "}[int(which)]
1300 except KeyError:
1301 raise ValueError, ('unknown delta choice (must be 1 or 2): %r'
1302 % which)
1303 prefixes = (" ", tag)
Tim Peters5e824c32001-08-12 22:25:01 +00001304 for line in delta:
1305 if line[:2] in prefixes:
Tim Peters8a9c2842001-09-22 21:30:22 +00001306 yield line[2:]
Tim Peters5e824c32001-08-12 22:25:01 +00001307
Tim Peters9ae21482001-02-10 08:00:53 +00001308def _test():
1309 import doctest, difflib
1310 return doctest.testmod(difflib)
1311
1312if __name__ == "__main__":
1313 _test()