blob: f2215d8d4561c2ec2a576f4ea2fd6436af2cb2e4 [file] [log] [blame]
Tim Peters9ae21482001-02-10 08:00:53 +00001"""
2Module difflib -- helpers for computing deltas between objects.
3
4Function get_close_matches(word, possibilities, n=3, cutoff=0.6):
Tim Peters9ae21482001-02-10 08:00:53 +00005 Use SequenceMatcher to return list of the best "good enough" matches.
6
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00007Function context_diff(a, b):
8 For two lists of strings, return a delta in context diff format.
9
Tim Peters5e824c32001-08-12 22:25:01 +000010Function ndiff(a, b):
11 Return a delta: the difference between `a` and `b` (lists of strings).
Tim Peters9ae21482001-02-10 08:00:53 +000012
Tim Peters5e824c32001-08-12 22:25:01 +000013Function restore(delta, which):
14 Return one of the two sequences that generated an ndiff delta.
Tim Peters9ae21482001-02-10 08:00:53 +000015
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +000016Function unified_diff(a, b):
17 For two lists of strings, return a delta in unified diff format.
18
Tim Peters5e824c32001-08-12 22:25:01 +000019Class SequenceMatcher:
20 A flexible class for comparing pairs of sequences of any type.
Tim Peters9ae21482001-02-10 08:00:53 +000021
Tim Peters5e824c32001-08-12 22:25:01 +000022Class Differ:
23 For producing human-readable deltas from sequences of lines of text.
Martin v. Löwise064b412004-08-29 16:34:40 +000024
25Class HtmlDiff:
26 For producing HTML side by side comparison with change highlights.
Tim Peters9ae21482001-02-10 08:00:53 +000027"""
28
Tim Peters5e824c32001-08-12 22:25:01 +000029__all__ = ['get_close_matches', 'ndiff', 'restore', 'SequenceMatcher',
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +000030 'Differ','IS_CHARACTER_JUNK', 'IS_LINE_JUNK', 'context_diff',
Greg Ward4d9d2562015-04-20 20:21:21 -040031 'unified_diff', 'diff_bytes', 'HtmlDiff', 'Match']
Tim Peters5e824c32001-08-12 22:25:01 +000032
Raymond Hettingerae39fbd2014-08-03 22:40:59 -070033from heapq import nlargest as _nlargest
Christian Heimes25bb7832008-01-11 16:17:00 +000034from collections import namedtuple as _namedtuple
Ethan Smithe3ec44d2020-04-09 21:47:31 -070035from types import GenericAlias
Christian Heimes25bb7832008-01-11 16:17:00 +000036
37Match = _namedtuple('Match', 'a b size')
Raymond Hettingerbb6b7342004-06-13 09:57:33 +000038
Neal Norwitze7dfe212003-07-01 14:59:46 +000039def _calculate_ratio(matches, length):
40 if length:
41 return 2.0 * matches / length
42 return 1.0
43
Tim Peters9ae21482001-02-10 08:00:53 +000044class SequenceMatcher:
Tim Peters5e824c32001-08-12 22:25:01 +000045
46 """
47 SequenceMatcher is a flexible class for comparing pairs of sequences of
48 any type, so long as the sequence elements are hashable. The basic
49 algorithm predates, and is a little fancier than, an algorithm
50 published in the late 1980's by Ratcliff and Obershelp under the
51 hyperbolic name "gestalt pattern matching". The basic idea is to find
52 the longest contiguous matching subsequence that contains no "junk"
53 elements (R-O doesn't address junk). The same idea is then applied
54 recursively to the pieces of the sequences to the left and to the right
55 of the matching subsequence. This does not yield minimal edit
56 sequences, but does tend to yield matches that "look right" to people.
57
58 SequenceMatcher tries to compute a "human-friendly diff" between two
59 sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
60 longest *contiguous* & junk-free matching subsequence. That's what
61 catches peoples' eyes. The Windows(tm) windiff has another interesting
62 notion, pairing up elements that appear uniquely in each sequence.
63 That, and the method here, appear to yield more intuitive difference
64 reports than does diff. This method appears to be the least vulnerable
65 to synching up on blocks of "junk lines", though (like blank lines in
66 ordinary text files, or maybe "<P>" lines in HTML files). That may be
67 because this is the only method of the 3 that has a *concept* of
68 "junk" <wink>.
69
70 Example, comparing two strings, and considering blanks to be "junk":
71
72 >>> s = SequenceMatcher(lambda x: x == " ",
73 ... "private Thread currentThread;",
74 ... "private volatile Thread currentThread;")
75 >>>
76
77 .ratio() returns a float in [0, 1], measuring the "similarity" of the
78 sequences. As a rule of thumb, a .ratio() value over 0.6 means the
79 sequences are close matches:
80
Guido van Rossumfff80df2007-02-09 20:33:44 +000081 >>> print(round(s.ratio(), 3))
Tim Peters5e824c32001-08-12 22:25:01 +000082 0.866
83 >>>
84
85 If you're only interested in where the sequences match,
86 .get_matching_blocks() is handy:
87
88 >>> for block in s.get_matching_blocks():
Guido van Rossumfff80df2007-02-09 20:33:44 +000089 ... print("a[%d] and b[%d] match for %d elements" % block)
Tim Peters5e824c32001-08-12 22:25:01 +000090 a[0] and b[0] match for 8 elements
Thomas Wouters0e3f5912006-08-11 14:57:12 +000091 a[8] and b[17] match for 21 elements
Tim Peters5e824c32001-08-12 22:25:01 +000092 a[29] and b[38] match for 0 elements
93
94 Note that the last tuple returned by .get_matching_blocks() is always a
95 dummy, (len(a), len(b), 0), and this is the only case in which the last
96 tuple element (number of elements matched) is 0.
97
98 If you want to know how to change the first sequence into the second,
99 use .get_opcodes():
100
101 >>> for opcode in s.get_opcodes():
Guido van Rossumfff80df2007-02-09 20:33:44 +0000102 ... print("%6s a[%d:%d] b[%d:%d]" % opcode)
Tim Peters5e824c32001-08-12 22:25:01 +0000103 equal a[0:8] b[0:8]
104 insert a[8:8] b[8:17]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000105 equal a[8:29] b[17:38]
Tim Peters5e824c32001-08-12 22:25:01 +0000106
107 See the Differ class for a fancy human-friendly file differencer, which
108 uses SequenceMatcher both to compare sequences of lines, and to compare
109 sequences of characters within similar (near-matching) lines.
110
111 See also function get_close_matches() in this module, which shows how
112 simple code building on SequenceMatcher can be used to do useful work.
113
114 Timing: Basic R-O is cubic time worst case and quadratic time expected
115 case. SequenceMatcher is quadratic time for the worst case and has
116 expected-case behavior dependent in a complicated way on how many
117 elements the sequences have in common; best case time is linear.
118
119 Methods:
120
121 __init__(isjunk=None, a='', b='')
122 Construct a SequenceMatcher.
123
124 set_seqs(a, b)
125 Set the two sequences to be compared.
126
127 set_seq1(a)
128 Set the first sequence to be compared.
129
130 set_seq2(b)
131 Set the second sequence to be compared.
132
133 find_longest_match(alo, ahi, blo, bhi)
134 Find longest matching block in a[alo:ahi] and b[blo:bhi].
135
136 get_matching_blocks()
137 Return list of triples describing matching subsequences.
138
139 get_opcodes()
140 Return list of 5-tuples describing how to turn a into b.
141
142 ratio()
143 Return a measure of the sequences' similarity (float in [0,1]).
144
145 quick_ratio()
146 Return an upper bound on .ratio() relatively quickly.
147
148 real_quick_ratio()
149 Return an upper bound on ratio() very quickly.
150 """
151
Terry Reedy99f96372010-11-25 06:12:34 +0000152 def __init__(self, isjunk=None, a='', b='', autojunk=True):
Tim Peters9ae21482001-02-10 08:00:53 +0000153 """Construct a SequenceMatcher.
154
155 Optional arg isjunk is None (the default), or a one-argument
156 function that takes a sequence element and returns true iff the
Tim Peters5e824c32001-08-12 22:25:01 +0000157 element is junk. None is equivalent to passing "lambda x: 0", i.e.
Fred Drakef1da6282001-02-19 19:30:05 +0000158 no elements are considered to be junk. For example, pass
Tim Peters9ae21482001-02-10 08:00:53 +0000159 lambda x: x in " \\t"
160 if you're comparing lines as sequences of characters, and don't
161 want to synch up on blanks or hard tabs.
162
163 Optional arg a is the first of two sequences to be compared. By
164 default, an empty string. The elements of a must be hashable. See
165 also .set_seqs() and .set_seq1().
166
167 Optional arg b is the second of two sequences to be compared. By
Fred Drakef1da6282001-02-19 19:30:05 +0000168 default, an empty string. The elements of b must be hashable. See
Tim Peters9ae21482001-02-10 08:00:53 +0000169 also .set_seqs() and .set_seq2().
Terry Reedy99f96372010-11-25 06:12:34 +0000170
171 Optional arg autojunk should be set to False to disable the
172 "automatic junk heuristic" that treats popular elements as junk
173 (see module documentation for more information).
Tim Peters9ae21482001-02-10 08:00:53 +0000174 """
175
176 # Members:
177 # a
178 # first sequence
179 # b
180 # second sequence; differences are computed as "what do
181 # we need to do to 'a' to change it into 'b'?"
182 # b2j
183 # for x in b, b2j[x] is a list of the indices (into b)
Terry Reedybcd89882010-12-03 22:29:40 +0000184 # at which x appears; junk and popular elements do not appear
Tim Peters9ae21482001-02-10 08:00:53 +0000185 # fullbcount
186 # for x in b, fullbcount[x] == the number of times x
187 # appears in b; only materialized if really needed (used
188 # only for computing quick_ratio())
189 # matching_blocks
190 # a list of (i, j, k) triples, where a[i:i+k] == b[j:j+k];
191 # ascending & non-overlapping in i and in j; terminated by
192 # a dummy (len(a), len(b), 0) sentinel
193 # opcodes
194 # a list of (tag, i1, i2, j1, j2) tuples, where tag is
195 # one of
196 # 'replace' a[i1:i2] should be replaced by b[j1:j2]
197 # 'delete' a[i1:i2] should be deleted
198 # 'insert' b[j1:j2] should be inserted
199 # 'equal' a[i1:i2] == b[j1:j2]
200 # isjunk
201 # a user-supplied function taking a sequence element and
202 # returning true iff the element is "junk" -- this has
203 # subtle but helpful effects on the algorithm, which I'll
204 # get around to writing up someday <0.9 wink>.
Florent Xicluna7f1c15b2011-12-10 13:02:17 +0100205 # DON'T USE! Only __chain_b uses this. Use "in self.bjunk".
Terry Reedy74a7c672010-12-03 18:57:42 +0000206 # bjunk
207 # the items in b for which isjunk is True.
208 # bpopular
209 # nonjunk items in b treated as junk by the heuristic (if used).
Tim Peters9ae21482001-02-10 08:00:53 +0000210
211 self.isjunk = isjunk
212 self.a = self.b = None
Terry Reedy99f96372010-11-25 06:12:34 +0000213 self.autojunk = autojunk
Tim Peters9ae21482001-02-10 08:00:53 +0000214 self.set_seqs(a, b)
215
216 def set_seqs(self, a, b):
217 """Set the two sequences to be compared.
218
219 >>> s = SequenceMatcher()
220 >>> s.set_seqs("abcd", "bcde")
221 >>> s.ratio()
222 0.75
223 """
224
225 self.set_seq1(a)
226 self.set_seq2(b)
227
228 def set_seq1(self, a):
229 """Set the first sequence to be compared.
230
231 The second sequence to be compared is not changed.
232
233 >>> s = SequenceMatcher(None, "abcd", "bcde")
234 >>> s.ratio()
235 0.75
236 >>> s.set_seq1("bcde")
237 >>> s.ratio()
238 1.0
239 >>>
240
241 SequenceMatcher computes and caches detailed information about the
242 second sequence, so if you want to compare one sequence S against
243 many sequences, use .set_seq2(S) once and call .set_seq1(x)
244 repeatedly for each of the other sequences.
245
246 See also set_seqs() and set_seq2().
247 """
248
249 if a is self.a:
250 return
251 self.a = a
252 self.matching_blocks = self.opcodes = None
253
254 def set_seq2(self, b):
255 """Set the second sequence to be compared.
256
257 The first sequence to be compared is not changed.
258
259 >>> s = SequenceMatcher(None, "abcd", "bcde")
260 >>> s.ratio()
261 0.75
262 >>> s.set_seq2("abcd")
263 >>> s.ratio()
264 1.0
265 >>>
266
267 SequenceMatcher computes and caches detailed information about the
268 second sequence, so if you want to compare one sequence S against
269 many sequences, use .set_seq2(S) once and call .set_seq1(x)
270 repeatedly for each of the other sequences.
271
272 See also set_seqs() and set_seq1().
273 """
274
275 if b is self.b:
276 return
277 self.b = b
278 self.matching_blocks = self.opcodes = None
279 self.fullbcount = None
280 self.__chain_b()
281
282 # For each element x in b, set b2j[x] to a list of the indices in
283 # b where x appears; the indices are in increasing order; note that
284 # the number of times x appears in b is len(b2j[x]) ...
285 # when self.isjunk is defined, junk elements don't show up in this
286 # map at all, which stops the central find_longest_match method
287 # from starting any matching block at a junk element ...
Tim Peters81b92512002-04-29 01:37:32 +0000288 # b2j also does not contain entries for "popular" elements, meaning
Terry Reedy99f96372010-11-25 06:12:34 +0000289 # elements that account for more than 1 + 1% of the total elements, and
Tim Peters81b92512002-04-29 01:37:32 +0000290 # when the sequence is reasonably large (>= 200 elements); this can
291 # be viewed as an adaptive notion of semi-junk, and yields an enormous
292 # speedup when, e.g., comparing program files with hundreds of
293 # instances of "return NULL;" ...
Tim Peters9ae21482001-02-10 08:00:53 +0000294 # note that this is only called when b changes; so for cross-product
295 # kinds of matches, it's best to call set_seq2 once, then set_seq1
296 # repeatedly
297
298 def __chain_b(self):
299 # Because isjunk is a user-defined (not C) function, and we test
300 # for junk a LOT, it's important to minimize the number of calls.
301 # Before the tricks described here, __chain_b was by far the most
302 # time-consuming routine in the whole module! If anyone sees
303 # Jim Roskind, thank him again for profile.py -- I never would
304 # have guessed that.
305 # The first trick is to build b2j ignoring the possibility
306 # of junk. I.e., we don't call isjunk at all yet. Throwing
307 # out the junk later is much cheaper than building b2j "right"
308 # from the start.
309 b = self.b
310 self.b2j = b2j = {}
Terry Reedy99f96372010-11-25 06:12:34 +0000311
Tim Peters81b92512002-04-29 01:37:32 +0000312 for i, elt in enumerate(b):
Terry Reedy99f96372010-11-25 06:12:34 +0000313 indices = b2j.setdefault(elt, [])
314 indices.append(i)
Tim Peters9ae21482001-02-10 08:00:53 +0000315
Terry Reedy99f96372010-11-25 06:12:34 +0000316 # Purge junk elements
Terry Reedy74a7c672010-12-03 18:57:42 +0000317 self.bjunk = junk = set()
Tim Peters81b92512002-04-29 01:37:32 +0000318 isjunk = self.isjunk
Tim Peters9ae21482001-02-10 08:00:53 +0000319 if isjunk:
Terry Reedy17a59252010-12-15 20:18:10 +0000320 for elt in b2j.keys():
Terry Reedy99f96372010-11-25 06:12:34 +0000321 if isjunk(elt):
322 junk.add(elt)
Terry Reedy17a59252010-12-15 20:18:10 +0000323 for elt in junk: # separate loop avoids separate list of keys
324 del b2j[elt]
Tim Peters9ae21482001-02-10 08:00:53 +0000325
Terry Reedy99f96372010-11-25 06:12:34 +0000326 # Purge popular elements that are not junk
Terry Reedy74a7c672010-12-03 18:57:42 +0000327 self.bpopular = popular = set()
Terry Reedy99f96372010-11-25 06:12:34 +0000328 n = len(b)
329 if self.autojunk and n >= 200:
330 ntest = n // 100 + 1
Terry Reedy17a59252010-12-15 20:18:10 +0000331 for elt, idxs in b2j.items():
Terry Reedy99f96372010-11-25 06:12:34 +0000332 if len(idxs) > ntest:
333 popular.add(elt)
Terry Reedy17a59252010-12-15 20:18:10 +0000334 for elt in popular: # ditto; as fast for 1% deletion
335 del b2j[elt]
Terry Reedy99f96372010-11-25 06:12:34 +0000336
Tim Peters9ae21482001-02-10 08:00:53 +0000337 def find_longest_match(self, alo, ahi, blo, bhi):
338 """Find longest matching block in a[alo:ahi] and b[blo:bhi].
339
340 If isjunk is not defined:
341
342 Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
343 alo <= i <= i+k <= ahi
344 blo <= j <= j+k <= bhi
345 and for all (i',j',k') meeting those conditions,
346 k >= k'
347 i <= i'
348 and if i == i', j <= j'
349
350 In other words, of all maximal matching blocks, return one that
351 starts earliest in a, and of all those maximal matching blocks that
352 start earliest in a, return the one that starts earliest in b.
353
354 >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
355 >>> s.find_longest_match(0, 5, 0, 9)
Christian Heimes25bb7832008-01-11 16:17:00 +0000356 Match(a=0, b=4, size=5)
Tim Peters9ae21482001-02-10 08:00:53 +0000357
358 If isjunk is defined, first the longest matching block is
359 determined as above, but with the additional restriction that no
360 junk element appears in the block. Then that block is extended as
361 far as possible by matching (only) junk elements on both sides. So
362 the resulting block never matches on junk except as identical junk
363 happens to be adjacent to an "interesting" match.
364
365 Here's the same example as before, but considering blanks to be
366 junk. That prevents " abcd" from matching the " abcd" at the tail
367 end of the second sequence directly. Instead only the "abcd" can
368 match, and matches the leftmost "abcd" in the second sequence:
369
370 >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
371 >>> s.find_longest_match(0, 5, 0, 9)
Christian Heimes25bb7832008-01-11 16:17:00 +0000372 Match(a=1, b=0, size=4)
Tim Peters9ae21482001-02-10 08:00:53 +0000373
374 If no blocks match, return (alo, blo, 0).
375
376 >>> s = SequenceMatcher(None, "ab", "c")
377 >>> s.find_longest_match(0, 2, 0, 1)
Christian Heimes25bb7832008-01-11 16:17:00 +0000378 Match(a=0, b=0, size=0)
Tim Peters9ae21482001-02-10 08:00:53 +0000379 """
380
381 # CAUTION: stripping common prefix or suffix would be incorrect.
382 # E.g.,
383 # ab
384 # acab
385 # Longest matching block is "ab", but if common prefix is
386 # stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
387 # strip, so ends up claiming that ab is changed to acab by
388 # inserting "ca" in the middle. That's minimal but unintuitive:
389 # "it's obvious" that someone inserted "ac" at the front.
390 # Windiff ends up at the same place as diff, but by pairing up
391 # the unique 'b's and then matching the first two 'a's.
392
Terry Reedybcd89882010-12-03 22:29:40 +0000393 a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.bjunk.__contains__
Tim Peters9ae21482001-02-10 08:00:53 +0000394 besti, bestj, bestsize = alo, blo, 0
395 # find longest junk-free match
396 # during an iteration of the loop, j2len[j] = length of longest
397 # junk-free match ending with a[i-1] and b[j]
398 j2len = {}
399 nothing = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000400 for i in range(alo, ahi):
Tim Peters9ae21482001-02-10 08:00:53 +0000401 # look at all instances of a[i] in b; note that because
402 # b2j has no junk keys, the loop is skipped if a[i] is junk
403 j2lenget = j2len.get
404 newj2len = {}
405 for j in b2j.get(a[i], nothing):
406 # a[i] matches b[j]
407 if j < blo:
408 continue
409 if j >= bhi:
410 break
411 k = newj2len[j] = j2lenget(j-1, 0) + 1
412 if k > bestsize:
413 besti, bestj, bestsize = i-k+1, j-k+1, k
414 j2len = newj2len
415
Tim Peters81b92512002-04-29 01:37:32 +0000416 # Extend the best by non-junk elements on each end. In particular,
417 # "popular" non-junk elements aren't in b2j, which greatly speeds
418 # the inner loop above, but also means "the best" match so far
419 # doesn't contain any junk *or* popular non-junk elements.
420 while besti > alo and bestj > blo and \
421 not isbjunk(b[bestj-1]) and \
422 a[besti-1] == b[bestj-1]:
423 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
424 while besti+bestsize < ahi and bestj+bestsize < bhi and \
425 not isbjunk(b[bestj+bestsize]) and \
426 a[besti+bestsize] == b[bestj+bestsize]:
427 bestsize += 1
428
Tim Peters9ae21482001-02-10 08:00:53 +0000429 # Now that we have a wholly interesting match (albeit possibly
430 # empty!), we may as well suck up the matching junk on each
431 # side of it too. Can't think of a good reason not to, and it
432 # saves post-processing the (possibly considerable) expense of
433 # figuring out what to do with it. In the case of an empty
434 # interesting match, this is clearly the right thing to do,
435 # because no other kind of match is possible in the regions.
436 while besti > alo and bestj > blo and \
437 isbjunk(b[bestj-1]) and \
438 a[besti-1] == b[bestj-1]:
439 besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
440 while besti+bestsize < ahi and bestj+bestsize < bhi and \
441 isbjunk(b[bestj+bestsize]) and \
442 a[besti+bestsize] == b[bestj+bestsize]:
443 bestsize = bestsize + 1
444
Christian Heimes25bb7832008-01-11 16:17:00 +0000445 return Match(besti, bestj, bestsize)
Tim Peters9ae21482001-02-10 08:00:53 +0000446
447 def get_matching_blocks(self):
448 """Return list of triples describing matching subsequences.
449
450 Each triple is of the form (i, j, n), and means that
451 a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000452 i and in j. New in Python 2.5, it's also guaranteed that if
453 (i, j, n) and (i', j', n') are adjacent triples in the list, and
454 the second is not the last triple in the list, then i+n != i' or
455 j+n != j'. IOW, adjacent triples never describe adjacent equal
456 blocks.
Tim Peters9ae21482001-02-10 08:00:53 +0000457
458 The last triple is a dummy, (len(a), len(b), 0), and is the only
459 triple with n==0.
460
461 >>> s = SequenceMatcher(None, "abxcd", "abcd")
Christian Heimes25bb7832008-01-11 16:17:00 +0000462 >>> list(s.get_matching_blocks())
463 [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
Tim Peters9ae21482001-02-10 08:00:53 +0000464 """
465
466 if self.matching_blocks is not None:
467 return self.matching_blocks
Tim Peters9ae21482001-02-10 08:00:53 +0000468 la, lb = len(self.a), len(self.b)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000469
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000470 # This is most naturally expressed as a recursive algorithm, but
471 # at least one user bumped into extreme use cases that exceeded
472 # the recursion limit on their box. So, now we maintain a list
473 # ('queue`) of blocks we still need to look at, and append partial
474 # results to `matching_blocks` in a loop; the matches are sorted
475 # at the end.
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000476 queue = [(0, la, 0, lb)]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000477 matching_blocks = []
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000478 while queue:
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000479 alo, ahi, blo, bhi = queue.pop()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000480 i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000481 # a[alo:i] vs b[blo:j] unknown
482 # a[i:i+k] same as b[j:j+k]
483 # a[i+k:ahi] vs b[j+k:bhi] unknown
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000484 if k: # if k is 0, there was no matching block
485 matching_blocks.append(x)
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000486 if alo < i and blo < j:
487 queue.append((alo, i, blo, j))
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000488 if i+k < ahi and j+k < bhi:
489 queue.append((i+k, ahi, j+k, bhi))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000490 matching_blocks.sort()
Gustavo Niemeyer548148812006-01-31 18:34:13 +0000491
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000492 # It's possible that we have adjacent equal blocks in the
493 # matching_blocks list now. Starting with 2.5, this code was added
494 # to collapse them.
495 i1 = j1 = k1 = 0
496 non_adjacent = []
497 for i2, j2, k2 in matching_blocks:
498 # Is this block adjacent to i1, j1, k1?
499 if i1 + k1 == i2 and j1 + k1 == j2:
500 # Yes, so collapse them -- this just increases the length of
501 # the first block by the length of the second, and the first
502 # block so lengthened remains the block to compare against.
503 k1 += k2
504 else:
505 # Not adjacent. Remember the first block (k1==0 means it's
506 # the dummy we started with), and make the second block the
507 # new block to compare against.
508 if k1:
509 non_adjacent.append((i1, j1, k1))
510 i1, j1, k1 = i2, j2, k2
511 if k1:
512 non_adjacent.append((i1, j1, k1))
513
514 non_adjacent.append( (la, lb, 0) )
Raymond Hettingerfabefc32014-06-21 11:57:36 -0700515 self.matching_blocks = list(map(Match._make, non_adjacent))
516 return self.matching_blocks
Tim Peters9ae21482001-02-10 08:00:53 +0000517
Tim Peters9ae21482001-02-10 08:00:53 +0000518 def get_opcodes(self):
519 """Return list of 5-tuples describing how to turn a into b.
520
521 Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
522 has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
523 tuple preceding it, and likewise for j1 == the previous j2.
524
525 The tags are strings, with these meanings:
526
527 'replace': a[i1:i2] should be replaced by b[j1:j2]
528 'delete': a[i1:i2] should be deleted.
529 Note that j1==j2 in this case.
530 'insert': b[j1:j2] should be inserted at a[i1:i1].
531 Note that i1==i2 in this case.
532 'equal': a[i1:i2] == b[j1:j2]
533
534 >>> a = "qabxcd"
535 >>> b = "abycdf"
536 >>> s = SequenceMatcher(None, a, b)
537 >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
Guido van Rossumfff80df2007-02-09 20:33:44 +0000538 ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
539 ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
Tim Peters9ae21482001-02-10 08:00:53 +0000540 delete a[0:1] (q) b[0:0] ()
541 equal a[1:3] (ab) b[0:2] (ab)
542 replace a[3:4] (x) b[2:3] (y)
543 equal a[4:6] (cd) b[3:5] (cd)
544 insert a[6:6] () b[5:6] (f)
545 """
546
547 if self.opcodes is not None:
548 return self.opcodes
549 i = j = 0
550 self.opcodes = answer = []
551 for ai, bj, size in self.get_matching_blocks():
552 # invariant: we've pumped out correct diffs to change
553 # a[:i] into b[:j], and the next matching block is
554 # a[ai:ai+size] == b[bj:bj+size]. So we need to pump
555 # out a diff to change a[i:ai] into b[j:bj], pump out
556 # the matching block, and move (i,j) beyond the match
557 tag = ''
558 if i < ai and j < bj:
559 tag = 'replace'
560 elif i < ai:
561 tag = 'delete'
562 elif j < bj:
563 tag = 'insert'
564 if tag:
565 answer.append( (tag, i, ai, j, bj) )
566 i, j = ai+size, bj+size
567 # the list of matching blocks is terminated by a
568 # sentinel with size 0
569 if size:
570 answer.append( ('equal', ai, i, bj, j) )
571 return answer
572
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000573 def get_grouped_opcodes(self, n=3):
574 """ Isolate change clusters by eliminating ranges with no changes.
575
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300576 Return a generator of groups with up to n lines of context.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000577 Each group is in the same format as returned by get_opcodes().
578
579 >>> from pprint import pprint
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000580 >>> a = list(map(str, range(1,40)))
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000581 >>> b = a[:]
582 >>> b[8:8] = ['i'] # Make an insertion
583 >>> b[20] += 'x' # Make a replacement
584 >>> b[23:28] = [] # Make a deletion
585 >>> b[30] += 'y' # Make another replacement
586 >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
587 [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
588 [('equal', 16, 19, 17, 20),
589 ('replace', 19, 20, 20, 21),
590 ('equal', 20, 22, 21, 23),
591 ('delete', 22, 27, 23, 23),
592 ('equal', 27, 30, 23, 26)],
593 [('equal', 31, 34, 27, 30),
594 ('replace', 34, 35, 30, 31),
595 ('equal', 35, 38, 31, 34)]]
596 """
597
598 codes = self.get_opcodes()
Brett Cannond2c5b4b2004-07-10 23:54:07 +0000599 if not codes:
600 codes = [("equal", 0, 1, 0, 1)]
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +0000601 # Fixup leading and trailing groups if they show no changes.
602 if codes[0][0] == 'equal':
603 tag, i1, i2, j1, j2 = codes[0]
604 codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2
605 if codes[-1][0] == 'equal':
606 tag, i1, i2, j1, j2 = codes[-1]
607 codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)
608
609 nn = n + n
610 group = []
611 for tag, i1, i2, j1, j2 in codes:
612 # End the current group and start a new one whenever
613 # there is a large range with no changes.
614 if tag == 'equal' and i2-i1 > nn:
615 group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))
616 yield group
617 group = []
618 i1, j1 = max(i1, i2-n), max(j1, j2-n)
619 group.append((tag, i1, i2, j1 ,j2))
620 if group and not (len(group)==1 and group[0][0] == 'equal'):
621 yield group
622
Tim Peters9ae21482001-02-10 08:00:53 +0000623 def ratio(self):
624 """Return a measure of the sequences' similarity (float in [0,1]).
625
626 Where T is the total number of elements in both sequences, and
Tim Petersbcc95cb2004-07-31 00:19:43 +0000627 M is the number of matches, this is 2.0*M / T.
Tim Peters9ae21482001-02-10 08:00:53 +0000628 Note that this is 1 if the sequences are identical, and 0 if
629 they have nothing in common.
630
631 .ratio() is expensive to compute if you haven't already computed
632 .get_matching_blocks() or .get_opcodes(), in which case you may
633 want to try .quick_ratio() or .real_quick_ratio() first to get an
634 upper bound.
635
636 >>> s = SequenceMatcher(None, "abcd", "bcde")
637 >>> s.ratio()
638 0.75
639 >>> s.quick_ratio()
640 0.75
641 >>> s.real_quick_ratio()
642 1.0
643 """
644
Guido van Rossum89da5d72006-08-22 00:21:25 +0000645 matches = sum(triple[-1] for triple in self.get_matching_blocks())
Neal Norwitze7dfe212003-07-01 14:59:46 +0000646 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000647
648 def quick_ratio(self):
649 """Return an upper bound on ratio() relatively quickly.
650
651 This isn't defined beyond that it is an upper bound on .ratio(), and
652 is faster to compute.
653 """
654
655 # viewing a and b as multisets, set matches to the cardinality
656 # of their intersection; this counts the number of matches
657 # without regard to order, so is clearly an upper bound
658 if self.fullbcount is None:
659 self.fullbcount = fullbcount = {}
660 for elt in self.b:
661 fullbcount[elt] = fullbcount.get(elt, 0) + 1
662 fullbcount = self.fullbcount
663 # avail[x] is the number of times x appears in 'b' less the
664 # number of times we've seen it in 'a' so far ... kinda
665 avail = {}
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000666 availhas, matches = avail.__contains__, 0
Tim Peters9ae21482001-02-10 08:00:53 +0000667 for elt in self.a:
668 if availhas(elt):
669 numb = avail[elt]
670 else:
671 numb = fullbcount.get(elt, 0)
672 avail[elt] = numb - 1
673 if numb > 0:
674 matches = matches + 1
Neal Norwitze7dfe212003-07-01 14:59:46 +0000675 return _calculate_ratio(matches, len(self.a) + len(self.b))
Tim Peters9ae21482001-02-10 08:00:53 +0000676
677 def real_quick_ratio(self):
678 """Return an upper bound on ratio() very quickly.
679
680 This isn't defined beyond that it is an upper bound on .ratio(), and
681 is faster to compute than either .ratio() or .quick_ratio().
682 """
683
684 la, lb = len(self.a), len(self.b)
685 # can't have more matches than the number of elements in the
686 # shorter sequence
Neal Norwitze7dfe212003-07-01 14:59:46 +0000687 return _calculate_ratio(min(la, lb), la + lb)
Tim Peters9ae21482001-02-10 08:00:53 +0000688
Ethan Smithe3ec44d2020-04-09 21:47:31 -0700689 __class_getitem__ = classmethod(GenericAlias)
690
691
Tim Peters9ae21482001-02-10 08:00:53 +0000692def get_close_matches(word, possibilities, n=3, cutoff=0.6):
693 """Use SequenceMatcher to return list of the best "good enough" matches.
694
695 word is a sequence for which close matches are desired (typically a
696 string).
697
698 possibilities is a list of sequences against which to match word
699 (typically a list of strings).
700
701 Optional arg n (default 3) is the maximum number of close matches to
702 return. n must be > 0.
703
704 Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
705 that don't score at least that similar to word are ignored.
706
707 The best (no more than n) matches among the possibilities are returned
708 in a list, sorted by similarity score, most similar first.
709
710 >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
711 ['apple', 'ape']
Tim Peters5e824c32001-08-12 22:25:01 +0000712 >>> import keyword as _keyword
713 >>> get_close_matches("wheel", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000714 ['while']
Guido van Rossum486364b2007-06-30 05:01:58 +0000715 >>> get_close_matches("Apple", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000716 []
Tim Peters5e824c32001-08-12 22:25:01 +0000717 >>> get_close_matches("accept", _keyword.kwlist)
Tim Peters9ae21482001-02-10 08:00:53 +0000718 ['except']
719 """
720
721 if not n > 0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000722 raise ValueError("n must be > 0: %r" % (n,))
Tim Peters9ae21482001-02-10 08:00:53 +0000723 if not 0.0 <= cutoff <= 1.0:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000724 raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
Tim Peters9ae21482001-02-10 08:00:53 +0000725 result = []
726 s = SequenceMatcher()
727 s.set_seq2(word)
728 for x in possibilities:
729 s.set_seq1(x)
730 if s.real_quick_ratio() >= cutoff and \
731 s.quick_ratio() >= cutoff and \
732 s.ratio() >= cutoff:
733 result.append((s.ratio(), x))
Tim Peters9ae21482001-02-10 08:00:53 +0000734
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000735 # Move the best scorers to head of list
Raymond Hettingerae39fbd2014-08-03 22:40:59 -0700736 result = _nlargest(n, result)
Raymond Hettinger6b59f5f2003-10-16 05:53:16 +0000737 # Strip scores for the best n matches
Raymond Hettingerbb6b7342004-06-13 09:57:33 +0000738 return [x for score, x in result]
Tim Peters5e824c32001-08-12 22:25:01 +0000739
Tim Peters5e824c32001-08-12 22:25:01 +0000740
Anthony Sottilee1c638d2019-08-21 11:59:26 -0700741def _keep_original_ws(s, tag_s):
742 """Replace whitespace with the original whitespace characters in `s`"""
743 return ''.join(
744 c if tag_c == " " and c.isspace() else tag_c
745 for c, tag_c in zip(s, tag_s)
746 )
Tim Peters5e824c32001-08-12 22:25:01 +0000747
Tim Peters5e824c32001-08-12 22:25:01 +0000748
Tim Peters5e824c32001-08-12 22:25:01 +0000749
750class Differ:
751 r"""
752 Differ is a class for comparing sequences of lines of text, and
753 producing human-readable differences or deltas. Differ uses
754 SequenceMatcher both to compare sequences of lines, and to compare
755 sequences of characters within similar (near-matching) lines.
756
757 Each line of a Differ delta begins with a two-letter code:
758
759 '- ' line unique to sequence 1
760 '+ ' line unique to sequence 2
761 ' ' line common to both sequences
762 '? ' line not present in either input sequence
763
764 Lines beginning with '? ' attempt to guide the eye to intraline
765 differences, and were not present in either input sequence. These lines
766 can be confusing if the sequences contain tab characters.
767
768 Note that Differ makes no claim to produce a *minimal* diff. To the
769 contrary, minimal diffs are often counter-intuitive, because they synch
770 up anywhere possible, sometimes accidental matches 100 pages apart.
771 Restricting synch points to contiguous matches preserves some notion of
772 locality, at the occasional cost of producing a longer diff.
773
774 Example: Comparing two texts.
775
776 First we set up the texts, sequences of individual single-line strings
777 ending with newlines (such sequences can also be obtained from the
778 `readlines()` method of file-like objects):
779
780 >>> text1 = ''' 1. Beautiful is better than ugly.
781 ... 2. Explicit is better than implicit.
782 ... 3. Simple is better than complex.
783 ... 4. Complex is better than complicated.
Ezio Melottid8b509b2011-09-28 17:37:55 +0300784 ... '''.splitlines(keepends=True)
Tim Peters5e824c32001-08-12 22:25:01 +0000785 >>> len(text1)
786 4
787 >>> text1[0][-1]
788 '\n'
789 >>> text2 = ''' 1. Beautiful is better than ugly.
790 ... 3. Simple is better than complex.
791 ... 4. Complicated is better than complex.
792 ... 5. Flat is better than nested.
Ezio Melottid8b509b2011-09-28 17:37:55 +0300793 ... '''.splitlines(keepends=True)
Tim Peters5e824c32001-08-12 22:25:01 +0000794
795 Next we instantiate a Differ object:
796
797 >>> d = Differ()
798
799 Note that when instantiating a Differ object we may pass functions to
800 filter out line and character 'junk'. See Differ.__init__ for details.
801
802 Finally, we compare the two:
803
Tim Peters8a9c2842001-09-22 21:30:22 +0000804 >>> result = list(d.compare(text1, text2))
Tim Peters5e824c32001-08-12 22:25:01 +0000805
806 'result' is a list of strings, so let's pretty-print it:
807
808 >>> from pprint import pprint as _pprint
809 >>> _pprint(result)
810 [' 1. Beautiful is better than ugly.\n',
811 '- 2. Explicit is better than implicit.\n',
812 '- 3. Simple is better than complex.\n',
813 '+ 3. Simple is better than complex.\n',
814 '? ++\n',
815 '- 4. Complex is better than complicated.\n',
816 '? ^ ---- ^\n',
817 '+ 4. Complicated is better than complex.\n',
818 '? ++++ ^ ^\n',
819 '+ 5. Flat is better than nested.\n']
820
821 As a single multi-line string it looks like this:
822
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000823 >>> print(''.join(result), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000824 1. Beautiful is better than ugly.
825 - 2. Explicit is better than implicit.
826 - 3. Simple is better than complex.
827 + 3. Simple is better than complex.
828 ? ++
829 - 4. Complex is better than complicated.
830 ? ^ ---- ^
831 + 4. Complicated is better than complex.
832 ? ++++ ^ ^
833 + 5. Flat is better than nested.
834
835 Methods:
836
837 __init__(linejunk=None, charjunk=None)
838 Construct a text differencer, with optional filters.
839
840 compare(a, b)
Tim Peters8a9c2842001-09-22 21:30:22 +0000841 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000842 """
843
844 def __init__(self, linejunk=None, charjunk=None):
845 """
846 Construct a text differencer, with optional filters.
847
848 The two optional keyword parameters are for filter functions:
849
850 - `linejunk`: A function that should accept a single string argument,
851 and return true iff the string is junk. The module-level function
852 `IS_LINE_JUNK` may be used to filter out lines without visible
Tim Peters81b92512002-04-29 01:37:32 +0000853 characters, except for at most one splat ('#'). It is recommended
Andrew Kuchlingc51da2b2014-03-19 16:43:06 -0400854 to leave linejunk None; the underlying SequenceMatcher class has
855 an adaptive notion of "noise" lines that's better than any static
856 definition the author has ever been able to craft.
Tim Peters5e824c32001-08-12 22:25:01 +0000857
858 - `charjunk`: A function that should accept a string of length 1. The
859 module-level function `IS_CHARACTER_JUNK` may be used to filter out
860 whitespace characters (a blank or tab; **note**: bad idea to include
Tim Peters81b92512002-04-29 01:37:32 +0000861 newline in this!). Use of IS_CHARACTER_JUNK is recommended.
Tim Peters5e824c32001-08-12 22:25:01 +0000862 """
863
864 self.linejunk = linejunk
865 self.charjunk = charjunk
Tim Peters5e824c32001-08-12 22:25:01 +0000866
867 def compare(self, a, b):
868 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +0000869 Compare two sequences of lines; generate the resulting delta.
Tim Peters5e824c32001-08-12 22:25:01 +0000870
871 Each sequence must contain individual single-line strings ending with
872 newlines. Such sequences can be obtained from the `readlines()` method
Tim Peters8a9c2842001-09-22 21:30:22 +0000873 of file-like objects. The delta generated also consists of newline-
874 terminated strings, ready to be printed as-is via the writeline()
Tim Peters5e824c32001-08-12 22:25:01 +0000875 method of a file-like object.
876
877 Example:
878
Ezio Melottid8b509b2011-09-28 17:37:55 +0300879 >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(True),
880 ... 'ore\ntree\nemu\n'.splitlines(True))),
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000881 ... end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000882 - one
883 ? ^
884 + ore
885 ? ^
886 - two
887 - three
888 ? -
889 + tree
890 + emu
891 """
892
893 cruncher = SequenceMatcher(self.linejunk, a, b)
894 for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
895 if tag == 'replace':
Tim Peters8a9c2842001-09-22 21:30:22 +0000896 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000897 elif tag == 'delete':
Tim Peters8a9c2842001-09-22 21:30:22 +0000898 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000899 elif tag == 'insert':
Tim Peters8a9c2842001-09-22 21:30:22 +0000900 g = self._dump('+', b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000901 elif tag == 'equal':
Tim Peters8a9c2842001-09-22 21:30:22 +0000902 g = self._dump(' ', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000903 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000904 raise ValueError('unknown tag %r' % (tag,))
Tim Peters8a9c2842001-09-22 21:30:22 +0000905
Philip Jenvey4993cc02012-10-01 12:53:43 -0700906 yield from g
Tim Peters5e824c32001-08-12 22:25:01 +0000907
908 def _dump(self, tag, x, lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000909 """Generate comparison results for a same-tagged range."""
Guido van Rossum805365e2007-05-07 22:24:25 +0000910 for i in range(lo, hi):
Tim Peters8a9c2842001-09-22 21:30:22 +0000911 yield '%s %s' % (tag, x[i])
Tim Peters5e824c32001-08-12 22:25:01 +0000912
913 def _plain_replace(self, a, alo, ahi, b, blo, bhi):
914 assert alo < ahi and blo < bhi
915 # dump the shorter block first -- reduces the burden on short-term
916 # memory if the blocks are of very different sizes
917 if bhi - blo < ahi - alo:
Tim Peters8a9c2842001-09-22 21:30:22 +0000918 first = self._dump('+', b, blo, bhi)
919 second = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +0000920 else:
Tim Peters8a9c2842001-09-22 21:30:22 +0000921 first = self._dump('-', a, alo, ahi)
922 second = self._dump('+', b, blo, bhi)
923
924 for g in first, second:
Philip Jenvey4993cc02012-10-01 12:53:43 -0700925 yield from g
Tim Peters5e824c32001-08-12 22:25:01 +0000926
927 def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
928 r"""
929 When replacing one block of lines with another, search the blocks
930 for *similar* lines; the best-matching pair (if any) is used as a
931 synch point, and intraline difference marking is done on the
932 similar pair. Lots of work, but often worth it.
933
934 Example:
935
936 >>> d = Differ()
Raymond Hettinger83325e92003-07-16 04:32:32 +0000937 >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
938 ... ['abcdefGhijkl\n'], 0, 1)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000939 >>> print(''.join(results), end="")
Tim Peters5e824c32001-08-12 22:25:01 +0000940 - abcDefghiJkl
941 ? ^ ^ ^
942 + abcdefGhijkl
943 ? ^ ^ ^
944 """
945
Tim Peters5e824c32001-08-12 22:25:01 +0000946 # don't synch up unless the lines have a similarity score of at
947 # least cutoff; best_ratio tracks the best score seen so far
948 best_ratio, cutoff = 0.74, 0.75
949 cruncher = SequenceMatcher(self.charjunk)
950 eqi, eqj = None, None # 1st indices of equal lines (if any)
951
952 # search for the pair that matches best without being identical
953 # (identical lines must be junk lines, & we don't want to synch up
954 # on junk -- unless we have to)
Guido van Rossum805365e2007-05-07 22:24:25 +0000955 for j in range(blo, bhi):
Tim Peters5e824c32001-08-12 22:25:01 +0000956 bj = b[j]
957 cruncher.set_seq2(bj)
Guido van Rossum805365e2007-05-07 22:24:25 +0000958 for i in range(alo, ahi):
Tim Peters5e824c32001-08-12 22:25:01 +0000959 ai = a[i]
960 if ai == bj:
961 if eqi is None:
962 eqi, eqj = i, j
963 continue
964 cruncher.set_seq1(ai)
965 # computing similarity is expensive, so use the quick
966 # upper bounds first -- have seen this speed up messy
967 # compares by a factor of 3.
968 # note that ratio() is only expensive to compute the first
969 # time it's called on a sequence pair; the expensive part
970 # of the computation is cached by cruncher
971 if cruncher.real_quick_ratio() > best_ratio and \
972 cruncher.quick_ratio() > best_ratio and \
973 cruncher.ratio() > best_ratio:
974 best_ratio, best_i, best_j = cruncher.ratio(), i, j
975 if best_ratio < cutoff:
976 # no non-identical "pretty close" pair
977 if eqi is None:
978 # no identical pair either -- treat it as a straight replace
Philip Jenvey4993cc02012-10-01 12:53:43 -0700979 yield from self._plain_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +0000980 return
981 # no close pair, but an identical pair -- synch up on that
982 best_i, best_j, best_ratio = eqi, eqj, 1.0
983 else:
984 # there's a close pair, so forget the identical pair (if any)
985 eqi = None
986
987 # a[best_i] very similar to b[best_j]; eqi is None iff they're not
988 # identical
Tim Peters5e824c32001-08-12 22:25:01 +0000989
990 # pump out diffs from before the synch point
Philip Jenvey4993cc02012-10-01 12:53:43 -0700991 yield from self._fancy_helper(a, alo, best_i, b, blo, best_j)
Tim Peters5e824c32001-08-12 22:25:01 +0000992
993 # do intraline marking on the synch pair
994 aelt, belt = a[best_i], b[best_j]
995 if eqi is None:
996 # pump out a '-', '?', '+', '?' quad for the synched lines
997 atags = btags = ""
998 cruncher.set_seqs(aelt, belt)
999 for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
1000 la, lb = ai2 - ai1, bj2 - bj1
1001 if tag == 'replace':
1002 atags += '^' * la
1003 btags += '^' * lb
1004 elif tag == 'delete':
1005 atags += '-' * la
1006 elif tag == 'insert':
1007 btags += '+' * lb
1008 elif tag == 'equal':
1009 atags += ' ' * la
1010 btags += ' ' * lb
1011 else:
Collin Winterce36ad82007-08-30 01:19:48 +00001012 raise ValueError('unknown tag %r' % (tag,))
Philip Jenvey4993cc02012-10-01 12:53:43 -07001013 yield from self._qformat(aelt, belt, atags, btags)
Tim Peters5e824c32001-08-12 22:25:01 +00001014 else:
1015 # the synch pair is identical
Tim Peters8a9c2842001-09-22 21:30:22 +00001016 yield ' ' + aelt
Tim Peters5e824c32001-08-12 22:25:01 +00001017
1018 # pump out diffs from after the synch point
Philip Jenvey4993cc02012-10-01 12:53:43 -07001019 yield from self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +00001020
1021 def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
Tim Peters8a9c2842001-09-22 21:30:22 +00001022 g = []
Tim Peters5e824c32001-08-12 22:25:01 +00001023 if alo < ahi:
1024 if blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001025 g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
Tim Peters5e824c32001-08-12 22:25:01 +00001026 else:
Tim Peters8a9c2842001-09-22 21:30:22 +00001027 g = self._dump('-', a, alo, ahi)
Tim Peters5e824c32001-08-12 22:25:01 +00001028 elif blo < bhi:
Tim Peters8a9c2842001-09-22 21:30:22 +00001029 g = self._dump('+', b, blo, bhi)
1030
Philip Jenvey4993cc02012-10-01 12:53:43 -07001031 yield from g
Tim Peters5e824c32001-08-12 22:25:01 +00001032
1033 def _qformat(self, aline, bline, atags, btags):
1034 r"""
Anthony Sottilee1c638d2019-08-21 11:59:26 -07001035 Format "?" output and deal with tabs.
Tim Peters5e824c32001-08-12 22:25:01 +00001036
1037 Example:
1038
1039 >>> d = Differ()
Senthil Kumaran758025c2009-11-23 19:02:52 +00001040 >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n',
1041 ... ' ^ ^ ^ ', ' ^ ^ ^ ')
Guido van Rossumfff80df2007-02-09 20:33:44 +00001042 >>> for line in results: print(repr(line))
1043 ...
Tim Peters5e824c32001-08-12 22:25:01 +00001044 '- \tabcDefghiJkl\n'
1045 '? \t ^ ^ ^\n'
Senthil Kumaran758025c2009-11-23 19:02:52 +00001046 '+ \tabcdefGhijkl\n'
1047 '? \t ^ ^ ^\n'
Tim Peters5e824c32001-08-12 22:25:01 +00001048 """
Anthony Sottilee1c638d2019-08-21 11:59:26 -07001049 atags = _keep_original_ws(aline, atags).rstrip()
1050 btags = _keep_original_ws(bline, btags).rstrip()
Tim Peters5e824c32001-08-12 22:25:01 +00001051
Tim Peters8a9c2842001-09-22 21:30:22 +00001052 yield "- " + aline
Tim Peters5e824c32001-08-12 22:25:01 +00001053 if atags:
Anthony Sottilee1c638d2019-08-21 11:59:26 -07001054 yield f"? {atags}\n"
Tim Peters5e824c32001-08-12 22:25:01 +00001055
Tim Peters8a9c2842001-09-22 21:30:22 +00001056 yield "+ " + bline
Tim Peters5e824c32001-08-12 22:25:01 +00001057 if btags:
Anthony Sottilee1c638d2019-08-21 11:59:26 -07001058 yield f"? {btags}\n"
Tim Peters5e824c32001-08-12 22:25:01 +00001059
1060# With respect to junk, an earlier version of ndiff simply refused to
1061# *start* a match with a junk element. The result was cases like this:
1062# before: private Thread currentThread;
1063# after: private volatile Thread currentThread;
1064# If you consider whitespace to be junk, the longest contiguous match
1065# not starting with junk is "e Thread currentThread". So ndiff reported
1066# that "e volatil" was inserted between the 't' and the 'e' in "private".
1067# While an accurate view, to people that's absurd. The current version
1068# looks for matching blocks that are entirely junk-free, then extends the
1069# longest one of those as far as possible but only with matching junk.
1070# So now "currentThread" is matched, then extended to suck up the
1071# preceding blank; then "private" is matched, and extended to suck up the
1072# following blank; then "Thread" is matched; and finally ndiff reports
1073# that "volatile " was inserted before "Thread". The only quibble
1074# remaining is that perhaps it was really the case that " volatile"
1075# was inserted after "private". I can live with that <wink>.
1076
1077import re
1078
Jamie Davis0e6c8ee2018-03-04 00:33:32 -05001079def IS_LINE_JUNK(line, pat=re.compile(r"\s*(?:#\s*)?$").match):
Tim Peters5e824c32001-08-12 22:25:01 +00001080 r"""
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +02001081 Return True for ignorable line: iff `line` is blank or contains a single '#'.
Tim Peters5e824c32001-08-12 22:25:01 +00001082
1083 Examples:
1084
1085 >>> IS_LINE_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001086 True
Tim Peters5e824c32001-08-12 22:25:01 +00001087 >>> IS_LINE_JUNK(' # \n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001088 True
Tim Peters5e824c32001-08-12 22:25:01 +00001089 >>> IS_LINE_JUNK('hello\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001090 False
Tim Peters5e824c32001-08-12 22:25:01 +00001091 """
1092
1093 return pat(line) is not None
1094
1095def IS_CHARACTER_JUNK(ch, ws=" \t"):
1096 r"""
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +02001097 Return True for ignorable character: iff `ch` is a space or tab.
Tim Peters5e824c32001-08-12 22:25:01 +00001098
1099 Examples:
1100
1101 >>> IS_CHARACTER_JUNK(' ')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001102 True
Tim Peters5e824c32001-08-12 22:25:01 +00001103 >>> IS_CHARACTER_JUNK('\t')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001104 True
Tim Peters5e824c32001-08-12 22:25:01 +00001105 >>> IS_CHARACTER_JUNK('\n')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001106 False
Tim Peters5e824c32001-08-12 22:25:01 +00001107 >>> IS_CHARACTER_JUNK('x')
Guido van Rossum77f6a652002-04-03 22:41:51 +00001108 False
Tim Peters5e824c32001-08-12 22:25:01 +00001109 """
1110
1111 return ch in ws
1112
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001113
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001114########################################################################
1115### Unified Diff
1116########################################################################
1117
1118def _format_range_unified(start, stop):
Raymond Hettinger49353d02011-04-11 12:40:58 -07001119 'Convert range to the "ed" format'
1120 # Per the diff spec at http://www.unix.org/single_unix_specification/
1121 beginning = start + 1 # lines start numbering with one
1122 length = stop - start
1123 if length == 1:
1124 return '{}'.format(beginning)
1125 if not length:
1126 beginning -= 1 # empty ranges begin at line just before the range
1127 return '{},{}'.format(beginning, length)
1128
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001129def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
1130 tofiledate='', n=3, lineterm='\n'):
1131 r"""
1132 Compare two sequences of lines; generate the delta as a unified diff.
1133
1134 Unified diffs are a compact way of showing line changes and a few
1135 lines of context. The number of context lines is set by 'n' which
1136 defaults to three.
1137
Raymond Hettinger0887c732003-06-17 16:53:25 +00001138 By default, the diff control lines (those with ---, +++, or @@) are
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001139 created with a trailing newline. This is helpful so that inputs
1140 created from file.readlines() result in diffs that are suitable for
1141 file.writelines() since both the inputs and outputs have trailing
1142 newlines.
1143
1144 For inputs that do not have trailing newlines, set the lineterm
1145 argument to "" so that the output will be uniformly newline free.
1146
1147 The unidiff format normally has a header for filenames and modification
1148 times. Any or all of these may be specified using strings for
R. David Murrayb2416e52010-04-12 16:58:02 +00001149 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
1150 The modification times are normally expressed in the ISO 8601 format.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001151
1152 Example:
1153
1154 >>> for line in unified_diff('one two three four'.split(),
1155 ... 'zero one tree four'.split(), 'Original', 'Current',
R. David Murrayb2416e52010-04-12 16:58:02 +00001156 ... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001157 ... lineterm=''):
R. David Murrayb2416e52010-04-12 16:58:02 +00001158 ... print(line) # doctest: +NORMALIZE_WHITESPACE
1159 --- Original 2005-01-26 23:30:50
1160 +++ Current 2010-04-02 10:20:52
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001161 @@ -1,4 +1,4 @@
1162 +zero
1163 one
1164 -two
1165 -three
1166 +tree
1167 four
1168 """
1169
Greg Ward4d9d2562015-04-20 20:21:21 -04001170 _check_types(a, b, fromfile, tofile, fromfiledate, tofiledate, lineterm)
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001171 started = False
1172 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1173 if not started:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001174 started = True
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001175 fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
1176 todate = '\t{}'.format(tofiledate) if tofiledate else ''
1177 yield '--- {}{}{}'.format(fromfile, fromdate, lineterm)
1178 yield '+++ {}{}{}'.format(tofile, todate, lineterm)
Raymond Hettinger49353d02011-04-11 12:40:58 -07001179
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001180 first, last = group[0], group[-1]
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001181 file1_range = _format_range_unified(first[1], last[2])
1182 file2_range = _format_range_unified(first[3], last[4])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001183 yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm)
1184
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001185 for tag, i1, i2, j1, j2 in group:
1186 if tag == 'equal':
1187 for line in a[i1:i2]:
1188 yield ' ' + line
1189 continue
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001190 if tag in {'replace', 'delete'}:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001191 for line in a[i1:i2]:
1192 yield '-' + line
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001193 if tag in {'replace', 'insert'}:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001194 for line in b[j1:j2]:
1195 yield '+' + line
1196
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001197
1198########################################################################
1199### Context Diff
1200########################################################################
1201
1202def _format_range_context(start, stop):
1203 'Convert range to the "ed" format'
1204 # Per the diff spec at http://www.unix.org/single_unix_specification/
1205 beginning = start + 1 # lines start numbering with one
1206 length = stop - start
1207 if not length:
1208 beginning -= 1 # empty ranges begin at line just before the range
1209 if length <= 1:
1210 return '{}'.format(beginning)
1211 return '{},{}'.format(beginning, beginning + length - 1)
1212
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001213# See http://www.unix.org/single_unix_specification/
1214def context_diff(a, b, fromfile='', tofile='',
1215 fromfiledate='', tofiledate='', n=3, lineterm='\n'):
1216 r"""
1217 Compare two sequences of lines; generate the delta as a context diff.
1218
1219 Context diffs are a compact way of showing line changes and a few
1220 lines of context. The number of context lines is set by 'n' which
1221 defaults to three.
1222
1223 By default, the diff control lines (those with *** or ---) are
1224 created with a trailing newline. This is helpful so that inputs
1225 created from file.readlines() result in diffs that are suitable for
1226 file.writelines() since both the inputs and outputs have trailing
1227 newlines.
1228
1229 For inputs that do not have trailing newlines, set the lineterm
1230 argument to "" so that the output will be uniformly newline free.
1231
1232 The context diff format normally has a header for filenames and
1233 modification times. Any or all of these may be specified using
1234 strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
R. David Murrayb2416e52010-04-12 16:58:02 +00001235 The modification times are normally expressed in the ISO 8601 format.
1236 If not specified, the strings default to blanks.
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001237
1238 Example:
1239
Ezio Melottid8b509b2011-09-28 17:37:55 +03001240 >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(True),
1241 ... 'zero\none\ntree\nfour\n'.splitlines(True), 'Original', 'Current')),
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001242 ... end="")
R. David Murrayb2416e52010-04-12 16:58:02 +00001243 *** Original
1244 --- Current
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001245 ***************
1246 *** 1,4 ****
1247 one
1248 ! two
1249 ! three
1250 four
1251 --- 1,4 ----
1252 + zero
1253 one
1254 ! tree
1255 four
1256 """
1257
Greg Ward4d9d2562015-04-20 20:21:21 -04001258 _check_types(a, b, fromfile, tofile, fromfiledate, tofiledate, lineterm)
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001259 prefix = dict(insert='+ ', delete='- ', replace='! ', equal=' ')
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001260 started = False
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001261 for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1262 if not started:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001263 started = True
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001264 fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
1265 todate = '\t{}'.format(tofiledate) if tofiledate else ''
1266 yield '*** {}{}{}'.format(fromfile, fromdate, lineterm)
1267 yield '--- {}{}{}'.format(tofile, todate, lineterm)
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001268
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001269 first, last = group[0], group[-1]
Raymond Hettinger49353d02011-04-11 12:40:58 -07001270 yield '***************' + lineterm
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001271
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001272 file1_range = _format_range_context(first[1], last[2])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001273 yield '*** {} ****{}'.format(file1_range, lineterm)
1274
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001275 if any(tag in {'replace', 'delete'} for tag, _, _, _, _ in group):
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001276 for tag, i1, i2, _, _ in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001277 if tag != 'insert':
1278 for line in a[i1:i2]:
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001279 yield prefix[tag] + line
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001280
Raymond Hettinger9180deb2011-04-12 15:25:30 -07001281 file2_range = _format_range_context(first[3], last[4])
Raymond Hettinger49353d02011-04-11 12:40:58 -07001282 yield '--- {} ----{}'.format(file2_range, lineterm)
1283
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001284 if any(tag in {'replace', 'insert'} for tag, _, _, _, _ in group):
Raymond Hettinger7f2d3022003-06-08 19:38:42 +00001285 for tag, _, _, j1, j2 in group:
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001286 if tag != 'delete':
1287 for line in b[j1:j2]:
Raymond Hettinger47e120e2011-04-10 17:14:56 -07001288 yield prefix[tag] + line
Raymond Hettingerf0b1a1f2003-06-08 11:07:08 +00001289
Greg Ward4d9d2562015-04-20 20:21:21 -04001290def _check_types(a, b, *args):
1291 # Checking types is weird, but the alternative is garbled output when
1292 # someone passes mixed bytes and str to {unified,context}_diff(). E.g.
1293 # without this check, passing filenames as bytes results in output like
1294 # --- b'oldfile.txt'
1295 # +++ b'newfile.txt'
1296 # because of how str.format() incorporates bytes objects.
1297 if a and not isinstance(a[0], str):
1298 raise TypeError('lines to compare must be str, not %s (%r)' %
1299 (type(a[0]).__name__, a[0]))
1300 if b and not isinstance(b[0], str):
1301 raise TypeError('lines to compare must be str, not %s (%r)' %
1302 (type(b[0]).__name__, b[0]))
1303 for arg in args:
1304 if not isinstance(arg, str):
1305 raise TypeError('all arguments must be str, not: %r' % (arg,))
1306
1307def diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'',
1308 fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n'):
1309 r"""
1310 Compare `a` and `b`, two sequences of lines represented as bytes rather
1311 than str. This is a wrapper for `dfunc`, which is typically either
1312 unified_diff() or context_diff(). Inputs are losslessly converted to
1313 strings so that `dfunc` only has to worry about strings, and encoded
1314 back to bytes on return. This is necessary to compare files with
1315 unknown or inconsistent encoding. All other inputs (except `n`) must be
1316 bytes rather than str.
1317 """
1318 def decode(s):
1319 try:
1320 return s.decode('ascii', 'surrogateescape')
1321 except AttributeError as err:
1322 msg = ('all arguments must be bytes, not %s (%r)' %
1323 (type(s).__name__, s))
1324 raise TypeError(msg) from err
1325 a = list(map(decode, a))
1326 b = list(map(decode, b))
1327 fromfile = decode(fromfile)
1328 tofile = decode(tofile)
1329 fromfiledate = decode(fromfiledate)
1330 tofiledate = decode(tofiledate)
1331 lineterm = decode(lineterm)
1332
1333 lines = dfunc(a, b, fromfile, tofile, fromfiledate, tofiledate, n, lineterm)
1334 for line in lines:
1335 yield line.encode('ascii', 'surrogateescape')
1336
Tim Peters81b92512002-04-29 01:37:32 +00001337def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
Tim Peters5e824c32001-08-12 22:25:01 +00001338 r"""
1339 Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
1340
1341 Optional keyword parameters `linejunk` and `charjunk` are for filter
Andrew Kuchlingc51da2b2014-03-19 16:43:06 -04001342 functions, or can be None:
Tim Peters5e824c32001-08-12 22:25:01 +00001343
Andrew Kuchlingc51da2b2014-03-19 16:43:06 -04001344 - linejunk: A function that should accept a single string argument and
Tim Peters81b92512002-04-29 01:37:32 +00001345 return true iff the string is junk. The default is None, and is
Andrew Kuchlingc51da2b2014-03-19 16:43:06 -04001346 recommended; the underlying SequenceMatcher class has an adaptive
1347 notion of "noise" lines.
Tim Peters5e824c32001-08-12 22:25:01 +00001348
Andrew Kuchlingc51da2b2014-03-19 16:43:06 -04001349 - charjunk: A function that accepts a character (string of length
1350 1), and returns true iff the character is junk. The default is
1351 the module-level function IS_CHARACTER_JUNK, which filters out
1352 whitespace characters (a blank or tab; note: it's a bad idea to
1353 include newline in this!).
Tim Peters5e824c32001-08-12 22:25:01 +00001354
1355 Tools/scripts/ndiff.py is a command-line front-end to this function.
1356
1357 Example:
1358
Ezio Melottid8b509b2011-09-28 17:37:55 +03001359 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
1360 ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001361 >>> print(''.join(diff), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00001362 - one
1363 ? ^
1364 + ore
1365 ? ^
1366 - two
1367 - three
1368 ? -
1369 + tree
1370 + emu
1371 """
1372 return Differ(linejunk, charjunk).compare(a, b)
1373
Martin v. Löwise064b412004-08-29 16:34:40 +00001374def _mdiff(fromlines, tolines, context=None, linejunk=None,
1375 charjunk=IS_CHARACTER_JUNK):
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001376 r"""Returns generator yielding marked up from/to side by side differences.
Martin v. Löwise064b412004-08-29 16:34:40 +00001377
1378 Arguments:
1379 fromlines -- list of text lines to compared to tolines
1380 tolines -- list of text lines to be compared to fromlines
1381 context -- number of context lines to display on each side of difference,
1382 if None, all from/to text lines will be generated.
1383 linejunk -- passed on to ndiff (see ndiff documentation)
1384 charjunk -- passed on to ndiff (see ndiff documentation)
Tim Peters48bd7f32004-08-29 22:38:38 +00001385
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001386 This function returns an iterator which returns a tuple:
Martin v. Löwise064b412004-08-29 16:34:40 +00001387 (from line tuple, to line tuple, boolean flag)
1388
1389 from/to line tuple -- (line num, line text)
Mark Dickinson934896d2009-02-21 20:59:32 +00001390 line num -- integer or None (to indicate a context separation)
Martin v. Löwise064b412004-08-29 16:34:40 +00001391 line text -- original line text with following markers inserted:
1392 '\0+' -- marks start of added text
1393 '\0-' -- marks start of deleted text
1394 '\0^' -- marks start of changed text
1395 '\1' -- marks end of added/deleted/changed text
Tim Peters48bd7f32004-08-29 22:38:38 +00001396
Martin v. Löwise064b412004-08-29 16:34:40 +00001397 boolean flag -- None indicates context separation, True indicates
1398 either "from" or "to" line contains a change, otherwise False.
1399
1400 This function/iterator was originally developed to generate side by side
1401 file difference for making HTML pages (see HtmlDiff class for example
1402 usage).
1403
1404 Note, this function utilizes the ndiff function to generate the side by
1405 side difference markup. Optional ndiff arguments may be passed to this
Tim Peters48bd7f32004-08-29 22:38:38 +00001406 function and they in turn will be passed to ndiff.
Martin v. Löwise064b412004-08-29 16:34:40 +00001407 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001408 import re
Martin v. Löwise064b412004-08-29 16:34:40 +00001409
1410 # regular expression for finding intraline change indices
R David Murray44b548d2016-09-08 13:59:53 -04001411 change_re = re.compile(r'(\++|\-+|\^+)')
Tim Peters48bd7f32004-08-29 22:38:38 +00001412
Martin v. Löwise064b412004-08-29 16:34:40 +00001413 # create the difference iterator to generate the differences
1414 diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk)
1415
1416 def _make_line(lines, format_key, side, num_lines=[0,0]):
1417 """Returns line of text with user's change markup and line formatting.
1418
1419 lines -- list of lines from the ndiff generator to produce a line of
1420 text from. When producing the line of text to return, the
1421 lines used are removed from this list.
1422 format_key -- '+' return first line in list with "add" markup around
1423 the entire line.
1424 '-' return first line in list with "delete" markup around
1425 the entire line.
1426 '?' return first line in list with add/delete/change
1427 intraline markup (indices obtained from second line)
1428 None return first line in list with no markup
1429 side -- indice into the num_lines list (0=from,1=to)
1430 num_lines -- from/to current line number. This is NOT intended to be a
1431 passed parameter. It is present as a keyword argument to
1432 maintain memory of the current line numbers between calls
1433 of this function.
1434
1435 Note, this function is purposefully not defined at the module scope so
1436 that data it needs from its parent function (within whose context it
1437 is defined) does not need to be of module scope.
1438 """
1439 num_lines[side] += 1
1440 # Handle case where no user markup is to be added, just return line of
1441 # text with user's line format to allow for usage of the line number.
1442 if format_key is None:
1443 return (num_lines[side],lines.pop(0)[2:])
1444 # Handle case of intraline changes
1445 if format_key == '?':
1446 text, markers = lines.pop(0), lines.pop(0)
1447 # find intraline changes (store change type and indices in tuples)
1448 sub_info = []
1449 def record_sub_info(match_object,sub_info=sub_info):
1450 sub_info.append([match_object.group(1)[0],match_object.span()])
1451 return match_object.group(1)
1452 change_re.sub(record_sub_info,markers)
1453 # process each tuple inserting our special marks that won't be
1454 # noticed by an xml/html escaper.
Raymond Hettingerf25a38e2014-08-03 22:36:32 -07001455 for key,(begin,end) in reversed(sub_info):
Martin v. Löwise064b412004-08-29 16:34:40 +00001456 text = text[0:begin]+'\0'+key+text[begin:end]+'\1'+text[end:]
1457 text = text[2:]
1458 # Handle case of add/delete entire line
1459 else:
1460 text = lines.pop(0)[2:]
1461 # if line of text is just a newline, insert a space so there is
1462 # something for the user to highlight and see.
Tim Peters0ca0c642004-11-12 16:12:15 +00001463 if not text:
1464 text = ' '
Martin v. Löwise064b412004-08-29 16:34:40 +00001465 # insert marks that won't be noticed by an xml/html escaper.
1466 text = '\0' + format_key + text + '\1'
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001467 # Return line of text, first allow user's line formatter to do its
Martin v. Löwise064b412004-08-29 16:34:40 +00001468 # thing (such as adding the line number) then replace the special
1469 # marks with what the user's change markup.
1470 return (num_lines[side],text)
Tim Peters48bd7f32004-08-29 22:38:38 +00001471
Martin v. Löwise064b412004-08-29 16:34:40 +00001472 def _line_iterator():
1473 """Yields from/to lines of text with a change indication.
1474
1475 This function is an iterator. It itself pulls lines from a
1476 differencing iterator, processes them and yields them. When it can
1477 it yields both a "from" and a "to" line, otherwise it will yield one
1478 or the other. In addition to yielding the lines of from/to text, a
1479 boolean flag is yielded to indicate if the text line(s) have
1480 differences in them.
1481
1482 Note, this function is purposefully not defined at the module scope so
1483 that data it needs from its parent function (within whose context it
1484 is defined) does not need to be of module scope.
1485 """
1486 lines = []
1487 num_blanks_pending, num_blanks_to_yield = 0, 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001488 while True:
Martin v. Löwise064b412004-08-29 16:34:40 +00001489 # Load up next 4 lines so we can look ahead, create strings which
1490 # are a concatenation of the first character of each of the 4 lines
1491 # so we can do some very readable comparisons.
1492 while len(lines) < 4:
Raymond Hettingerbbeac6e2014-08-03 22:49:07 -07001493 lines.append(next(diff_lines_iterator, 'X'))
Martin v. Löwise064b412004-08-29 16:34:40 +00001494 s = ''.join([line[0] for line in lines])
1495 if s.startswith('X'):
1496 # When no more lines, pump out any remaining blank lines so the
1497 # corresponding add/delete lines get a matching blank line so
1498 # all line pairs get yielded at the next level.
1499 num_blanks_to_yield = num_blanks_pending
1500 elif s.startswith('-?+?'):
1501 # simple intraline change
1502 yield _make_line(lines,'?',0), _make_line(lines,'?',1), True
1503 continue
1504 elif s.startswith('--++'):
1505 # in delete block, add block coming: we do NOT want to get
1506 # caught up on blank lines yet, just process the delete line
1507 num_blanks_pending -= 1
1508 yield _make_line(lines,'-',0), None, True
1509 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001510 elif s.startswith(('--?+', '--+', '- ')):
Martin Panter7462b6492015-11-02 03:37:02 +00001511 # in delete block and see an intraline change or unchanged line
Martin v. Löwise064b412004-08-29 16:34:40 +00001512 # coming: yield the delete line and then blanks
1513 from_line,to_line = _make_line(lines,'-',0), None
1514 num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0
1515 elif s.startswith('-+?'):
1516 # intraline change
1517 yield _make_line(lines,None,0), _make_line(lines,'?',1), True
1518 continue
1519 elif s.startswith('-?+'):
1520 # intraline change
1521 yield _make_line(lines,'?',0), _make_line(lines,None,1), True
1522 continue
1523 elif s.startswith('-'):
1524 # delete FROM line
1525 num_blanks_pending -= 1
1526 yield _make_line(lines,'-',0), None, True
1527 continue
1528 elif s.startswith('+--'):
1529 # in add block, delete block coming: we do NOT want to get
1530 # caught up on blank lines yet, just process the add line
1531 num_blanks_pending += 1
1532 yield None, _make_line(lines,'+',1), True
1533 continue
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001534 elif s.startswith(('+ ', '+-')):
Martin v. Löwise064b412004-08-29 16:34:40 +00001535 # will be leaving an add block: yield blanks then add line
1536 from_line, to_line = None, _make_line(lines,'+',1)
1537 num_blanks_to_yield,num_blanks_pending = num_blanks_pending+1,0
1538 elif s.startswith('+'):
1539 # inside an add block, yield the add line
1540 num_blanks_pending += 1
1541 yield None, _make_line(lines,'+',1), True
1542 continue
1543 elif s.startswith(' '):
1544 # unchanged text, yield it to both sides
1545 yield _make_line(lines[:],None,0),_make_line(lines,None,1),False
1546 continue
1547 # Catch up on the blank lines so when we yield the next from/to
1548 # pair, they are lined up.
1549 while(num_blanks_to_yield < 0):
1550 num_blanks_to_yield += 1
1551 yield None,('','\n'),True
1552 while(num_blanks_to_yield > 0):
1553 num_blanks_to_yield -= 1
1554 yield ('','\n'),None,True
1555 if s.startswith('X'):
Raymond Hettingerbbeac6e2014-08-03 22:49:07 -07001556 return
Martin v. Löwise064b412004-08-29 16:34:40 +00001557 else:
1558 yield from_line,to_line,True
1559
1560 def _line_pair_iterator():
1561 """Yields from/to lines of text with a change indication.
1562
1563 This function is an iterator. It itself pulls lines from the line
Georg Brandl7eb4b7d2005-07-22 21:49:32 +00001564 iterator. Its difference from that iterator is that this function
Martin v. Löwise064b412004-08-29 16:34:40 +00001565 always yields a pair of from/to text lines (with the change
1566 indication). If necessary it will collect single from/to lines
1567 until it has a matching pair from/to pair to yield.
1568
1569 Note, this function is purposefully not defined at the module scope so
1570 that data it needs from its parent function (within whose context it
1571 is defined) does not need to be of module scope.
1572 """
1573 line_iterator = _line_iterator()
1574 fromlines,tolines=[],[]
1575 while True:
1576 # Collecting lines of text until we have a from/to pair
1577 while (len(fromlines)==0 or len(tolines)==0):
Yury Selivanov68333392015-05-22 11:16:47 -04001578 try:
1579 from_line, to_line, found_diff = next(line_iterator)
1580 except StopIteration:
1581 return
Martin v. Löwise064b412004-08-29 16:34:40 +00001582 if from_line is not None:
1583 fromlines.append((from_line,found_diff))
1584 if to_line is not None:
1585 tolines.append((to_line,found_diff))
1586 # Once we have a pair, remove them from the collection and yield it
1587 from_line, fromDiff = fromlines.pop(0)
1588 to_line, to_diff = tolines.pop(0)
1589 yield (from_line,to_line,fromDiff or to_diff)
1590
1591 # Handle case where user does not want context differencing, just yield
1592 # them up without doing anything else with them.
1593 line_pair_iterator = _line_pair_iterator()
1594 if context is None:
Yury Selivanov8170e8c2015-05-09 11:44:30 -04001595 yield from line_pair_iterator
Martin v. Löwise064b412004-08-29 16:34:40 +00001596 # Handle case where user wants context differencing. We must do some
1597 # storage of lines until we know for sure that they are to be yielded.
1598 else:
1599 context += 1
1600 lines_to_write = 0
1601 while True:
1602 # Store lines up until we find a difference, note use of a
1603 # circular queue because we only need to keep around what
1604 # we need for context.
1605 index, contextLines = 0, [None]*(context)
1606 found_diff = False
1607 while(found_diff is False):
Yury Selivanov68333392015-05-22 11:16:47 -04001608 try:
1609 from_line, to_line, found_diff = next(line_pair_iterator)
1610 except StopIteration:
1611 return
Martin v. Löwise064b412004-08-29 16:34:40 +00001612 i = index % context
1613 contextLines[i] = (from_line, to_line, found_diff)
1614 index += 1
1615 # Yield lines that we have collected so far, but first yield
1616 # the user's separator.
1617 if index > context:
1618 yield None, None, None
1619 lines_to_write = context
1620 else:
1621 lines_to_write = index
1622 index = 0
1623 while(lines_to_write):
1624 i = index % context
1625 index += 1
1626 yield contextLines[i]
1627 lines_to_write -= 1
1628 # Now yield the context lines after the change
1629 lines_to_write = context-1
Raymond Hettinger01b731f2018-04-05 11:19:57 -07001630 try:
1631 while(lines_to_write):
1632 from_line, to_line, found_diff = next(line_pair_iterator)
1633 # If another change within the context, extend the context
1634 if found_diff:
1635 lines_to_write = context-1
1636 else:
1637 lines_to_write -= 1
1638 yield from_line, to_line, found_diff
1639 except StopIteration:
1640 # Catch exception from next() and return normally
1641 return
Martin v. Löwise064b412004-08-29 16:34:40 +00001642
1643
1644_file_template = """
1645<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1646 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1647
1648<html>
1649
1650<head>
Tim Peters48bd7f32004-08-29 22:38:38 +00001651 <meta http-equiv="Content-Type"
Berker Peksag102029d2015-03-15 01:18:47 +02001652 content="text/html; charset=%(charset)s" />
Martin v. Löwise064b412004-08-29 16:34:40 +00001653 <title></title>
1654 <style type="text/css">%(styles)s
1655 </style>
1656</head>
1657
1658<body>
1659 %(table)s%(legend)s
1660</body>
1661
1662</html>"""
1663
1664_styles = """
1665 table.diff {font-family:Courier; border:medium;}
1666 .diff_header {background-color:#e0e0e0}
1667 td.diff_header {text-align:right}
1668 .diff_next {background-color:#c0c0c0}
1669 .diff_add {background-color:#aaffaa}
1670 .diff_chg {background-color:#ffff77}
1671 .diff_sub {background-color:#ffaaaa}"""
1672
1673_table_template = """
Tim Peters48bd7f32004-08-29 22:38:38 +00001674 <table class="diff" id="difflib_chg_%(prefix)s_top"
1675 cellspacing="0" cellpadding="0" rules="groups" >
1676 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
Martin v. Löwise064b412004-08-29 16:34:40 +00001677 <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
1678 %(header_row)s
1679 <tbody>
1680%(data_rows)s </tbody>
1681 </table>"""
1682
1683_legend = """
1684 <table class="diff" summary="Legends">
1685 <tr> <th colspan="2"> Legends </th> </tr>
1686 <tr> <td> <table border="" summary="Colors">
1687 <tr><th> Colors </th> </tr>
1688 <tr><td class="diff_add">&nbsp;Added&nbsp;</td></tr>
1689 <tr><td class="diff_chg">Changed</td> </tr>
1690 <tr><td class="diff_sub">Deleted</td> </tr>
1691 </table></td>
1692 <td> <table border="" summary="Links">
1693 <tr><th colspan="2"> Links </th> </tr>
1694 <tr><td>(f)irst change</td> </tr>
1695 <tr><td>(n)ext change</td> </tr>
1696 <tr><td>(t)op</td> </tr>
1697 </table></td> </tr>
1698 </table>"""
1699
1700class HtmlDiff(object):
1701 """For producing HTML side by side comparison with change highlights.
1702
1703 This class can be used to create an HTML table (or a complete HTML file
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001704 containing the table) showing a side by side, line by line comparison
Tim Peters48bd7f32004-08-29 22:38:38 +00001705 of text with inter-line and intra-line change highlights. The table can
Martin v. Löwise064b412004-08-29 16:34:40 +00001706 be generated in either full or contextual difference mode.
Tim Peters48bd7f32004-08-29 22:38:38 +00001707
Martin v. Löwise064b412004-08-29 16:34:40 +00001708 The following methods are provided for HTML generation:
1709
1710 make_table -- generates HTML for a single side by side table
1711 make_file -- generates complete HTML file with a single side by side table
1712
Tim Peters48bd7f32004-08-29 22:38:38 +00001713 See tools/scripts/diff.py for an example usage of this class.
Martin v. Löwise064b412004-08-29 16:34:40 +00001714 """
1715
1716 _file_template = _file_template
1717 _styles = _styles
1718 _table_template = _table_template
1719 _legend = _legend
1720 _default_prefix = 0
Tim Peters48bd7f32004-08-29 22:38:38 +00001721
Martin v. Löwise064b412004-08-29 16:34:40 +00001722 def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None,
1723 charjunk=IS_CHARACTER_JUNK):
1724 """HtmlDiff instance initializer
1725
1726 Arguments:
1727 tabsize -- tab stop spacing, defaults to 8.
1728 wrapcolumn -- column number where lines are broken and wrapped,
1729 defaults to None where lines are not wrapped.
Andrew Kuchlingc51da2b2014-03-19 16:43:06 -04001730 linejunk,charjunk -- keyword arguments passed into ndiff() (used by
Tim Peters48bd7f32004-08-29 22:38:38 +00001731 HtmlDiff() to generate the side by side HTML differences). See
Martin v. Löwise064b412004-08-29 16:34:40 +00001732 ndiff() documentation for argument default values and descriptions.
1733 """
1734 self._tabsize = tabsize
1735 self._wrapcolumn = wrapcolumn
1736 self._linejunk = linejunk
1737 self._charjunk = charjunk
1738
Berker Peksag102029d2015-03-15 01:18:47 +02001739 def make_file(self, fromlines, tolines, fromdesc='', todesc='',
1740 context=False, numlines=5, *, charset='utf-8'):
Martin v. Löwise064b412004-08-29 16:34:40 +00001741 """Returns HTML file of side by side comparison with change highlights
1742
1743 Arguments:
1744 fromlines -- list of "from" lines
1745 tolines -- list of "to" lines
1746 fromdesc -- "from" file column header string
1747 todesc -- "to" file column header string
1748 context -- set to True for contextual differences (defaults to False
1749 which shows full differences).
1750 numlines -- number of context lines. When context is set True,
1751 controls number of lines displayed before and after the change.
1752 When context is False, controls the number of lines to place
1753 the "next" link anchors before the next change (so click of
1754 "next" link jumps to just before the change).
Berker Peksag102029d2015-03-15 01:18:47 +02001755 charset -- charset of the HTML document
Martin v. Löwise064b412004-08-29 16:34:40 +00001756 """
Tim Peters48bd7f32004-08-29 22:38:38 +00001757
Berker Peksag102029d2015-03-15 01:18:47 +02001758 return (self._file_template % dict(
1759 styles=self._styles,
1760 legend=self._legend,
1761 table=self.make_table(fromlines, tolines, fromdesc, todesc,
1762 context=context, numlines=numlines),
1763 charset=charset
1764 )).encode(charset, 'xmlcharrefreplace').decode(charset)
Tim Peters48bd7f32004-08-29 22:38:38 +00001765
Martin v. Löwise064b412004-08-29 16:34:40 +00001766 def _tab_newline_replace(self,fromlines,tolines):
1767 """Returns from/to line lists with tabs expanded and newlines removed.
1768
1769 Instead of tab characters being replaced by the number of spaces
1770 needed to fill in to the next tab stop, this function will fill
1771 the space with tab characters. This is done so that the difference
1772 algorithms can identify changes in a file when tabs are replaced by
1773 spaces and vice versa. At the end of the HTML generation, the tab
1774 characters will be replaced with a nonbreakable space.
1775 """
1776 def expand_tabs(line):
1777 # hide real spaces
1778 line = line.replace(' ','\0')
1779 # expand tabs into spaces
1780 line = line.expandtabs(self._tabsize)
Ezio Melotti13925002011-03-16 11:05:33 +02001781 # replace spaces from expanded tabs back into tab characters
Martin v. Löwise064b412004-08-29 16:34:40 +00001782 # (we'll replace them with markup after we do differencing)
1783 line = line.replace(' ','\t')
1784 return line.replace('\0',' ').rstrip('\n')
1785 fromlines = [expand_tabs(line) for line in fromlines]
1786 tolines = [expand_tabs(line) for line in tolines]
1787 return fromlines,tolines
1788
1789 def _split_line(self,data_list,line_num,text):
1790 """Builds list of text lines by splitting text lines at wrap point
1791
1792 This function will determine if the input text line needs to be
1793 wrapped (split) into separate lines. If so, the first wrap point
1794 will be determined and the first line appended to the output
1795 text line list. This function is used recursively to handle
1796 the second part of the split line to further split it.
1797 """
1798 # if blank line or context separator, just add it to the output list
1799 if not line_num:
1800 data_list.append((line_num,text))
1801 return
1802
1803 # if line text doesn't need wrapping, just add it to the output list
1804 size = len(text)
1805 max = self._wrapcolumn
1806 if (size <= max) or ((size -(text.count('\0')*3)) <= max):
1807 data_list.append((line_num,text))
1808 return
1809
1810 # scan text looking for the wrap point, keeping track if the wrap
1811 # point is inside markers
1812 i = 0
1813 n = 0
1814 mark = ''
1815 while n < max and i < size:
1816 if text[i] == '\0':
1817 i += 1
1818 mark = text[i]
1819 i += 1
1820 elif text[i] == '\1':
1821 i += 1
1822 mark = ''
1823 else:
1824 i += 1
1825 n += 1
1826
1827 # wrap point is inside text, break it up into separate lines
1828 line1 = text[:i]
1829 line2 = text[i:]
1830
1831 # if wrap point is inside markers, place end marker at end of first
1832 # line and start marker at beginning of second line because each
1833 # line will have its own table tag markup around it.
1834 if mark:
1835 line1 = line1 + '\1'
1836 line2 = '\0' + mark + line2
1837
Tim Peters48bd7f32004-08-29 22:38:38 +00001838 # tack on first line onto the output list
Martin v. Löwise064b412004-08-29 16:34:40 +00001839 data_list.append((line_num,line1))
1840
Tim Peters48bd7f32004-08-29 22:38:38 +00001841 # use this routine again to wrap the remaining text
Martin v. Löwise064b412004-08-29 16:34:40 +00001842 self._split_line(data_list,'>',line2)
1843
1844 def _line_wrapper(self,diffs):
1845 """Returns iterator that splits (wraps) mdiff text lines"""
1846
1847 # pull from/to data and flags from mdiff iterator
1848 for fromdata,todata,flag in diffs:
1849 # check for context separators and pass them through
1850 if flag is None:
1851 yield fromdata,todata,flag
1852 continue
1853 (fromline,fromtext),(toline,totext) = fromdata,todata
1854 # for each from/to line split it at the wrap column to form
1855 # list of text lines.
1856 fromlist,tolist = [],[]
1857 self._split_line(fromlist,fromline,fromtext)
1858 self._split_line(tolist,toline,totext)
1859 # yield from/to line in pairs inserting blank lines as
1860 # necessary when one side has more wrapped lines
1861 while fromlist or tolist:
1862 if fromlist:
1863 fromdata = fromlist.pop(0)
1864 else:
1865 fromdata = ('',' ')
1866 if tolist:
1867 todata = tolist.pop(0)
1868 else:
1869 todata = ('',' ')
1870 yield fromdata,todata,flag
1871
1872 def _collect_lines(self,diffs):
1873 """Collects mdiff output into separate lists
1874
1875 Before storing the mdiff from/to data into a list, it is converted
1876 into a single line of text with HTML markup.
1877 """
1878
1879 fromlist,tolist,flaglist = [],[],[]
Tim Peters48bd7f32004-08-29 22:38:38 +00001880 # pull from/to data and flags from mdiff style iterator
Martin v. Löwise064b412004-08-29 16:34:40 +00001881 for fromdata,todata,flag in diffs:
1882 try:
1883 # store HTML markup of the lines into the lists
1884 fromlist.append(self._format_line(0,flag,*fromdata))
1885 tolist.append(self._format_line(1,flag,*todata))
1886 except TypeError:
1887 # exceptions occur for lines where context separators go
1888 fromlist.append(None)
1889 tolist.append(None)
1890 flaglist.append(flag)
1891 return fromlist,tolist,flaglist
Tim Peters48bd7f32004-08-29 22:38:38 +00001892
Martin v. Löwise064b412004-08-29 16:34:40 +00001893 def _format_line(self,side,flag,linenum,text):
1894 """Returns HTML markup of "from" / "to" text lines
1895
1896 side -- 0 or 1 indicating "from" or "to" text
1897 flag -- indicates if difference on line
1898 linenum -- line number (used for line number column)
1899 text -- line text to be marked up
1900 """
1901 try:
1902 linenum = '%d' % linenum
1903 id = ' id="%s%s"' % (self._prefix[side],linenum)
1904 except TypeError:
1905 # handle blank lines where linenum is '>' or ''
Tim Peters48bd7f32004-08-29 22:38:38 +00001906 id = ''
Martin v. Löwise064b412004-08-29 16:34:40 +00001907 # replace those things that would get confused with HTML symbols
1908 text=text.replace("&","&amp;").replace(">","&gt;").replace("<","&lt;")
1909
1910 # make space non-breakable so they don't get compressed or line wrapped
1911 text = text.replace(' ','&nbsp;').rstrip()
1912
1913 return '<td class="diff_header"%s>%s</td><td nowrap="nowrap">%s</td>' \
1914 % (id,linenum,text)
1915
1916 def _make_prefix(self):
1917 """Create unique anchor prefixes"""
1918
1919 # Generate a unique anchor prefix so multiple tables
1920 # can exist on the same HTML page without conflicts.
1921 fromprefix = "from%d_" % HtmlDiff._default_prefix
1922 toprefix = "to%d_" % HtmlDiff._default_prefix
1923 HtmlDiff._default_prefix += 1
1924 # store prefixes so line format method has access
1925 self._prefix = [fromprefix,toprefix]
1926
1927 def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):
1928 """Makes list of "next" links"""
Tim Peters48bd7f32004-08-29 22:38:38 +00001929
Martin v. Löwise064b412004-08-29 16:34:40 +00001930 # all anchor names will be generated using the unique "to" prefix
1931 toprefix = self._prefix[1]
Tim Peters48bd7f32004-08-29 22:38:38 +00001932
Martin v. Löwise064b412004-08-29 16:34:40 +00001933 # process change flags, generating middle column of next anchors/links
1934 next_id = ['']*len(flaglist)
1935 next_href = ['']*len(flaglist)
1936 num_chg, in_change = 0, False
1937 last = 0
1938 for i,flag in enumerate(flaglist):
1939 if flag:
1940 if not in_change:
1941 in_change = True
1942 last = i
1943 # at the beginning of a change, drop an anchor a few lines
Tim Peters48bd7f32004-08-29 22:38:38 +00001944 # (the context lines) before the change for the previous
Martin v. Löwise064b412004-08-29 16:34:40 +00001945 # link
1946 i = max([0,i-numlines])
1947 next_id[i] = ' id="difflib_chg_%s_%d"' % (toprefix,num_chg)
Tim Peters48bd7f32004-08-29 22:38:38 +00001948 # at the beginning of a change, drop a link to the next
Martin v. Löwise064b412004-08-29 16:34:40 +00001949 # change
1950 num_chg += 1
1951 next_href[last] = '<a href="#difflib_chg_%s_%d">n</a>' % (
1952 toprefix,num_chg)
1953 else:
1954 in_change = False
1955 # check for cases where there is no content to avoid exceptions
1956 if not flaglist:
1957 flaglist = [False]
1958 next_id = ['']
1959 next_href = ['']
1960 last = 0
1961 if context:
1962 fromlist = ['<td></td><td>&nbsp;No Differences Found&nbsp;</td>']
1963 tolist = fromlist
1964 else:
1965 fromlist = tolist = ['<td></td><td>&nbsp;Empty File&nbsp;</td>']
1966 # if not a change on first line, drop a link
1967 if not flaglist[0]:
1968 next_href[0] = '<a href="#difflib_chg_%s_0">f</a>' % toprefix
1969 # redo the last link to link to the top
1970 next_href[last] = '<a href="#difflib_chg_%s_top">t</a>' % (toprefix)
1971
1972 return fromlist,tolist,flaglist,next_href,next_id
1973
1974 def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1975 numlines=5):
1976 """Returns HTML table of side by side comparison with change highlights
1977
1978 Arguments:
1979 fromlines -- list of "from" lines
1980 tolines -- list of "to" lines
1981 fromdesc -- "from" file column header string
1982 todesc -- "to" file column header string
1983 context -- set to True for contextual differences (defaults to False
1984 which shows full differences).
1985 numlines -- number of context lines. When context is set True,
1986 controls number of lines displayed before and after the change.
1987 When context is False, controls the number of lines to place
1988 the "next" link anchors before the next change (so click of
1989 "next" link jumps to just before the change).
1990 """
1991
1992 # make unique anchor prefixes so that multiple tables may exist
1993 # on the same page without conflict.
1994 self._make_prefix()
Tim Peters48bd7f32004-08-29 22:38:38 +00001995
Martin v. Löwise064b412004-08-29 16:34:40 +00001996 # change tabs to spaces before it gets more difficult after we insert
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001997 # markup
Martin v. Löwise064b412004-08-29 16:34:40 +00001998 fromlines,tolines = self._tab_newline_replace(fromlines,tolines)
Tim Peters48bd7f32004-08-29 22:38:38 +00001999
Martin v. Löwise064b412004-08-29 16:34:40 +00002000 # create diffs iterator which generates side by side from/to data
2001 if context:
2002 context_lines = numlines
2003 else:
2004 context_lines = None
2005 diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,
2006 charjunk=self._charjunk)
2007
2008 # set up iterator to wrap lines that exceed desired width
2009 if self._wrapcolumn:
2010 diffs = self._line_wrapper(diffs)
Tim Peters48bd7f32004-08-29 22:38:38 +00002011
Martin v. Löwise064b412004-08-29 16:34:40 +00002012 # collect up from/to lines and flags into lists (also format the lines)
2013 fromlist,tolist,flaglist = self._collect_lines(diffs)
2014
2015 # process change flags, generating middle column of next anchors/links
2016 fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(
2017 fromlist,tolist,flaglist,context,numlines)
2018
Guido van Rossumd8faa362007-04-27 19:54:29 +00002019 s = []
Martin v. Löwise064b412004-08-29 16:34:40 +00002020 fmt = ' <tr><td class="diff_next"%s>%s</td>%s' + \
2021 '<td class="diff_next">%s</td>%s</tr>\n'
2022 for i in range(len(flaglist)):
2023 if flaglist[i] is None:
2024 # mdiff yields None on separator lines skip the bogus ones
2025 # generated for the first line
2026 if i > 0:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002027 s.append(' </tbody> \n <tbody>\n')
Martin v. Löwise064b412004-08-29 16:34:40 +00002028 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +00002029 s.append( fmt % (next_id[i],next_href[i],fromlist[i],
Martin v. Löwise064b412004-08-29 16:34:40 +00002030 next_href[i],tolist[i]))
2031 if fromdesc or todesc:
2032 header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (
2033 '<th class="diff_next"><br /></th>',
2034 '<th colspan="2" class="diff_header">%s</th>' % fromdesc,
2035 '<th class="diff_next"><br /></th>',
2036 '<th colspan="2" class="diff_header">%s</th>' % todesc)
2037 else:
2038 header_row = ''
2039
2040 table = self._table_template % dict(
Guido van Rossumd8faa362007-04-27 19:54:29 +00002041 data_rows=''.join(s),
Martin v. Löwise064b412004-08-29 16:34:40 +00002042 header_row=header_row,
2043 prefix=self._prefix[1])
2044
2045 return table.replace('\0+','<span class="diff_add">'). \
2046 replace('\0-','<span class="diff_sub">'). \
2047 replace('\0^','<span class="diff_chg">'). \
2048 replace('\1','</span>'). \
2049 replace('\t','&nbsp;')
Tim Peters48bd7f32004-08-29 22:38:38 +00002050
Martin v. Löwise064b412004-08-29 16:34:40 +00002051del re
2052
Tim Peters5e824c32001-08-12 22:25:01 +00002053def restore(delta, which):
2054 r"""
Tim Peters8a9c2842001-09-22 21:30:22 +00002055 Generate one of the two sequences that generated a delta.
Tim Peters5e824c32001-08-12 22:25:01 +00002056
2057 Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
2058 lines originating from file 1 or 2 (parameter `which`), stripping off line
2059 prefixes.
2060
2061 Examples:
2062
Ezio Melottid8b509b2011-09-28 17:37:55 +03002063 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
2064 ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
Tim Peters8a9c2842001-09-22 21:30:22 +00002065 >>> diff = list(diff)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002066 >>> print(''.join(restore(diff, 1)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002067 one
2068 two
2069 three
Guido van Rossumbe19ed72007-02-09 05:37:30 +00002070 >>> print(''.join(restore(diff, 2)), end="")
Tim Peters5e824c32001-08-12 22:25:01 +00002071 ore
2072 tree
2073 emu
2074 """
2075 try:
2076 tag = {1: "- ", 2: "+ "}[int(which)]
2077 except KeyError:
Collin Winterce36ad82007-08-30 01:19:48 +00002078 raise ValueError('unknown delta choice (must be 1 or 2): %r'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03002079 % which) from None
Tim Peters5e824c32001-08-12 22:25:01 +00002080 prefixes = (" ", tag)
Tim Peters5e824c32001-08-12 22:25:01 +00002081 for line in delta:
2082 if line[:2] in prefixes:
Tim Peters8a9c2842001-09-22 21:30:22 +00002083 yield line[2:]
Tim Peters5e824c32001-08-12 22:25:01 +00002084
Tim Peters9ae21482001-02-10 08:00:53 +00002085def _test():
2086 import doctest, difflib
2087 return doctest.testmod(difflib)
2088
2089if __name__ == "__main__":
2090 _test()