lxml 5.3.2__cp39-cp39-macosx_10_9_universal2.whl → 6.0.0__cp39-cp39-macosx_10_9_universal2.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. lxml/__init__.py +1 -1
  2. lxml/_elementpath.cpython-39-darwin.so +0 -0
  3. lxml/_elementpath.py +3 -1
  4. lxml/apihelpers.pxi +25 -17
  5. lxml/builder.cpython-39-darwin.so +0 -0
  6. lxml/builder.py +11 -0
  7. lxml/debug.pxi +0 -54
  8. lxml/etree.cpython-39-darwin.so +0 -0
  9. lxml/etree.h +24 -28
  10. lxml/etree.pyx +154 -33
  11. lxml/etree_api.h +59 -50
  12. lxml/extensions.pxi +3 -6
  13. lxml/html/__init__.py +7 -3
  14. lxml/html/_difflib.cpython-39-darwin.so +0 -0
  15. lxml/html/_difflib.py +2106 -0
  16. lxml/html/builder.py +40 -0
  17. lxml/html/defs.py +3 -3
  18. lxml/html/diff.cpython-39-darwin.so +0 -0
  19. lxml/html/diff.py +406 -312
  20. lxml/includes/etree_defs.h +6 -6
  21. lxml/includes/libexslt/exsltconfig.h +3 -3
  22. lxml/includes/libxml/HTMLparser.h +41 -45
  23. lxml/includes/libxml/HTMLtree.h +1 -0
  24. lxml/includes/libxml/SAX.h +2 -186
  25. lxml/includes/libxml/SAX2.h +2 -3
  26. lxml/includes/libxml/c14n.h +1 -12
  27. lxml/includes/libxml/catalog.h +1 -0
  28. lxml/includes/libxml/debugXML.h +0 -138
  29. lxml/includes/libxml/encoding.h +131 -59
  30. lxml/includes/libxml/entities.h +12 -20
  31. lxml/includes/libxml/globals.h +0 -16
  32. lxml/includes/libxml/hash.h +19 -0
  33. lxml/includes/libxml/list.h +2 -2
  34. lxml/includes/libxml/nanoftp.h +3 -173
  35. lxml/includes/libxml/nanohttp.h +17 -0
  36. lxml/includes/libxml/parser.h +505 -256
  37. lxml/includes/libxml/parserInternals.h +26 -98
  38. lxml/includes/libxml/relaxng.h +7 -2
  39. lxml/includes/libxml/threads.h +0 -6
  40. lxml/includes/libxml/tree.h +61 -97
  41. lxml/includes/libxml/uri.h +11 -0
  42. lxml/includes/libxml/valid.h +49 -14
  43. lxml/includes/libxml/xinclude.h +12 -0
  44. lxml/includes/libxml/xlink.h +4 -0
  45. lxml/includes/libxml/xmlIO.h +33 -35
  46. lxml/includes/libxml/xmlautomata.h +19 -2
  47. lxml/includes/libxml/xmlerror.h +32 -18
  48. lxml/includes/libxml/xmlexports.h +61 -15
  49. lxml/includes/libxml/xmlmemory.h +27 -64
  50. lxml/includes/libxml/xmlmodule.h +4 -0
  51. lxml/includes/libxml/xmlreader.h +13 -3
  52. lxml/includes/libxml/xmlregexp.h +7 -106
  53. lxml/includes/libxml/xmlsave.h +15 -1
  54. lxml/includes/libxml/xmlschemas.h +10 -5
  55. lxml/includes/libxml/xmlunicode.h +3 -190
  56. lxml/includes/libxml/xmlversion.h +15 -194
  57. lxml/includes/libxml/xmlwriter.h +1 -0
  58. lxml/includes/libxml/xpath.h +9 -15
  59. lxml/includes/libxml/xpathInternals.h +9 -3
  60. lxml/includes/libxml/xpointer.h +1 -91
  61. lxml/includes/libxslt/xsltconfig.h +6 -6
  62. lxml/includes/lxml-version.h +1 -1
  63. lxml/includes/tree.pxd +10 -12
  64. lxml/includes/xmlparser.pxd +46 -8
  65. lxml/lxml.etree.h +24 -28
  66. lxml/lxml.etree_api.h +59 -50
  67. lxml/objectify.cpython-39-darwin.so +0 -0
  68. lxml/objectify.pyx +11 -7
  69. lxml/parser.pxi +106 -47
  70. lxml/sax.cpython-39-darwin.so +0 -0
  71. lxml/sax.py +11 -0
  72. lxml/saxparser.pxi +14 -14
  73. lxml/schematron.pxi +8 -3
  74. lxml/serializer.pxi +71 -3
  75. lxml/xslt.pxi +10 -3
  76. lxml-6.0.0.dist-info/METADATA +163 -0
  77. {lxml-5.3.2.dist-info → lxml-6.0.0.dist-info}/RECORD +81 -79
  78. {lxml-5.3.2.dist-info → lxml-6.0.0.dist-info}/WHEEL +2 -1
  79. {lxml-5.3.2.dist-info → lxml-6.0.0.dist-info}/licenses/LICENSE.txt +3 -1
  80. lxml-5.3.2.dist-info/METADATA +0 -100
  81. {lxml-5.3.2.dist-info → lxml-6.0.0.dist-info}/licenses/LICENSES.txt +0 -0
  82. {lxml-5.3.2.dist-info → lxml-6.0.0.dist-info}/top_level.txt +0 -0
lxml/html/_difflib.py ADDED
@@ -0,0 +1,2106 @@
1
+ # Copied from CPython 3.14b2+.
2
+ # cython: infer_types=True
3
+
4
+ """
5
+ Module difflib -- helpers for computing deltas between objects.
6
+
7
+ Function get_close_matches(word, possibilities, n=3, cutoff=0.6):
8
+ Use SequenceMatcher to return list of the best "good enough" matches.
9
+
10
+ Function context_diff(a, b):
11
+ For two lists of strings, return a delta in context diff format.
12
+
13
+ Function ndiff(a, b):
14
+ Return a delta: the difference between `a` and `b` (lists of strings).
15
+
16
+ Function restore(delta, which):
17
+ Return one of the two sequences that generated an ndiff delta.
18
+
19
+ Function unified_diff(a, b):
20
+ For two lists of strings, return a delta in unified diff format.
21
+
22
+ Class SequenceMatcher:
23
+ A flexible class for comparing pairs of sequences of any type.
24
+
25
+ Class Differ:
26
+ For producing human-readable deltas from sequences of lines of text.
27
+
28
+ Class HtmlDiff:
29
+ For producing HTML side by side comparison with change highlights.
30
+ """
31
+
32
+ try:
33
+ import cython
34
+ except ImportError:
35
+ class fake_cython:
36
+ compiled = False
37
+ def cfunc(self, func): return func
38
+ def declare(self, _, value): return value
39
+ def __getattr__(self, type_name): return "object"
40
+
41
+ cython = fake_cython()
42
+
43
+
44
+ __all__ = ['get_close_matches', 'ndiff', 'restore', 'SequenceMatcher',
45
+ 'Differ','IS_CHARACTER_JUNK', 'IS_LINE_JUNK', 'context_diff',
46
+ 'unified_diff', 'diff_bytes', 'HtmlDiff', 'Match']
47
+
48
+ from heapq import nlargest as _nlargest
49
+ from collections import namedtuple as _namedtuple
50
+
51
+ try:
52
+ from types import GenericAlias
53
+ except ImportError:
54
+ GenericAlias = None
55
+
56
+ Match = _namedtuple('Match', 'a b size')
57
+
58
+ def _calculate_ratio(matches, length):
59
+ if length:
60
+ return 2.0 * matches / length
61
+ return 1.0
62
+
63
+ class SequenceMatcher:
64
+
65
+ """
66
+ SequenceMatcher is a flexible class for comparing pairs of sequences of
67
+ any type, so long as the sequence elements are hashable. The basic
68
+ algorithm predates, and is a little fancier than, an algorithm
69
+ published in the late 1980's by Ratcliff and Obershelp under the
70
+ hyperbolic name "gestalt pattern matching". The basic idea is to find
71
+ the longest contiguous matching subsequence that contains no "junk"
72
+ elements (R-O doesn't address junk). The same idea is then applied
73
+ recursively to the pieces of the sequences to the left and to the right
74
+ of the matching subsequence. This does not yield minimal edit
75
+ sequences, but does tend to yield matches that "look right" to people.
76
+
77
+ SequenceMatcher tries to compute a "human-friendly diff" between two
78
+ sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
79
+ longest *contiguous* & junk-free matching subsequence. That's what
80
+ catches peoples' eyes. The Windows(tm) windiff has another interesting
81
+ notion, pairing up elements that appear uniquely in each sequence.
82
+ That, and the method here, appear to yield more intuitive difference
83
+ reports than does diff. This method appears to be the least vulnerable
84
+ to syncing up on blocks of "junk lines", though (like blank lines in
85
+ ordinary text files, or maybe "<P>" lines in HTML files). That may be
86
+ because this is the only method of the 3 that has a *concept* of
87
+ "junk" <wink>.
88
+
89
+ Example, comparing two strings, and considering blanks to be "junk":
90
+
91
+ >>> s = SequenceMatcher(lambda x: x == " ",
92
+ ... "private Thread currentThread;",
93
+ ... "private volatile Thread currentThread;")
94
+ >>>
95
+
96
+ .ratio() returns a float in [0, 1], measuring the "similarity" of the
97
+ sequences. As a rule of thumb, a .ratio() value over 0.6 means the
98
+ sequences are close matches:
99
+
100
+ >>> print(round(s.ratio(), 3))
101
+ 0.866
102
+ >>>
103
+
104
+ If you're only interested in where the sequences match,
105
+ .get_matching_blocks() is handy:
106
+
107
+ >>> for block in s.get_matching_blocks():
108
+ ... print("a[%d] and b[%d] match for %d elements" % block)
109
+ a[0] and b[0] match for 8 elements
110
+ a[8] and b[17] match for 21 elements
111
+ a[29] and b[38] match for 0 elements
112
+
113
+ Note that the last tuple returned by .get_matching_blocks() is always a
114
+ dummy, (len(a), len(b), 0), and this is the only case in which the last
115
+ tuple element (number of elements matched) is 0.
116
+
117
+ If you want to know how to change the first sequence into the second,
118
+ use .get_opcodes():
119
+
120
+ >>> for opcode in s.get_opcodes():
121
+ ... print("%6s a[%d:%d] b[%d:%d]" % opcode)
122
+ equal a[0:8] b[0:8]
123
+ insert a[8:8] b[8:17]
124
+ equal a[8:29] b[17:38]
125
+
126
+ See the Differ class for a fancy human-friendly file differencer, which
127
+ uses SequenceMatcher both to compare sequences of lines, and to compare
128
+ sequences of characters within similar (near-matching) lines.
129
+
130
+ See also function get_close_matches() in this module, which shows how
131
+ simple code building on SequenceMatcher can be used to do useful work.
132
+
133
+ Timing: Basic R-O is cubic time worst case and quadratic time expected
134
+ case. SequenceMatcher is quadratic time for the worst case and has
135
+ expected-case behavior dependent in a complicated way on how many
136
+ elements the sequences have in common; best case time is linear.
137
+ """
138
+
139
+ def __init__(self, isjunk=None, a='', b='', autojunk=True):
140
+ """Construct a SequenceMatcher.
141
+
142
+ Optional arg isjunk is None (the default), or a one-argument
143
+ function that takes a sequence element and returns true iff the
144
+ element is junk. None is equivalent to passing "lambda x: 0", i.e.
145
+ no elements are considered to be junk. For example, pass
146
+ lambda x: x in " \\t"
147
+ if you're comparing lines as sequences of characters, and don't
148
+ want to synch up on blanks or hard tabs.
149
+
150
+ Optional arg a is the first of two sequences to be compared. By
151
+ default, an empty string. The elements of a must be hashable. See
152
+ also .set_seqs() and .set_seq1().
153
+
154
+ Optional arg b is the second of two sequences to be compared. By
155
+ default, an empty string. The elements of b must be hashable. See
156
+ also .set_seqs() and .set_seq2().
157
+
158
+ Optional arg autojunk should be set to False to disable the
159
+ "automatic junk heuristic" that treats popular elements as junk
160
+ (see module documentation for more information).
161
+ """
162
+
163
+ # Members:
164
+ # a
165
+ # first sequence
166
+ # b
167
+ # second sequence; differences are computed as "what do
168
+ # we need to do to 'a' to change it into 'b'?"
169
+ # b2j
170
+ # for x in b, b2j[x] is a list of the indices (into b)
171
+ # at which x appears; junk and popular elements do not appear
172
+ # fullbcount
173
+ # for x in b, fullbcount[x] == the number of times x
174
+ # appears in b; only materialized if really needed (used
175
+ # only for computing quick_ratio())
176
+ # matching_blocks
177
+ # a list of (i, j, k) triples, where a[i:i+k] == b[j:j+k];
178
+ # ascending & non-overlapping in i and in j; terminated by
179
+ # a dummy (len(a), len(b), 0) sentinel
180
+ # opcodes
181
+ # a list of (tag, i1, i2, j1, j2) tuples, where tag is
182
+ # one of
183
+ # 'replace' a[i1:i2] should be replaced by b[j1:j2]
184
+ # 'delete' a[i1:i2] should be deleted
185
+ # 'insert' b[j1:j2] should be inserted
186
+ # 'equal' a[i1:i2] == b[j1:j2]
187
+ # isjunk
188
+ # a user-supplied function taking a sequence element and
189
+ # returning true iff the element is "junk" -- this has
190
+ # subtle but helpful effects on the algorithm, which I'll
191
+ # get around to writing up someday <0.9 wink>.
192
+ # DON'T USE! Only __chain_b uses this. Use "in self.bjunk".
193
+ # bjunk
194
+ # the items in b for which isjunk is True.
195
+ # bpopular
196
+ # nonjunk items in b treated as junk by the heuristic (if used).
197
+
198
+ self.isjunk = isjunk
199
+ self.a = self.b = None
200
+ self.autojunk = autojunk
201
+ self.set_seqs(a, b)
202
+
203
+ def set_seqs(self, a, b):
204
+ """Set the two sequences to be compared.
205
+
206
+ >>> s = SequenceMatcher()
207
+ >>> s.set_seqs("abcd", "bcde")
208
+ >>> s.ratio()
209
+ 0.75
210
+ """
211
+
212
+ self.set_seq1(a)
213
+ self.set_seq2(b)
214
+
215
+ def set_seq1(self, a):
216
+ """Set the first sequence to be compared.
217
+
218
+ The second sequence to be compared is not changed.
219
+
220
+ >>> s = SequenceMatcher(None, "abcd", "bcde")
221
+ >>> s.ratio()
222
+ 0.75
223
+ >>> s.set_seq1("bcde")
224
+ >>> s.ratio()
225
+ 1.0
226
+ >>>
227
+
228
+ SequenceMatcher computes and caches detailed information about the
229
+ second sequence, so if you want to compare one sequence S against
230
+ many sequences, use .set_seq2(S) once and call .set_seq1(x)
231
+ repeatedly for each of the other sequences.
232
+
233
+ See also set_seqs() and set_seq2().
234
+ """
235
+
236
+ if a is self.a:
237
+ return
238
+ self.a = a
239
+ self.matching_blocks = self.opcodes = None
240
+
241
+ def set_seq2(self, b):
242
+ """Set the second sequence to be compared.
243
+
244
+ The first sequence to be compared is not changed.
245
+
246
+ >>> s = SequenceMatcher(None, "abcd", "bcde")
247
+ >>> s.ratio()
248
+ 0.75
249
+ >>> s.set_seq2("abcd")
250
+ >>> s.ratio()
251
+ 1.0
252
+ >>>
253
+
254
+ SequenceMatcher computes and caches detailed information about the
255
+ second sequence, so if you want to compare one sequence S against
256
+ many sequences, use .set_seq2(S) once and call .set_seq1(x)
257
+ repeatedly for each of the other sequences.
258
+
259
+ See also set_seqs() and set_seq1().
260
+ """
261
+
262
+ if b is self.b:
263
+ return
264
+ self.b = b
265
+ self.matching_blocks = self.opcodes = None
266
+ self.fullbcount = None
267
+ self.__chain_b()
268
+
269
+ # For each element x in b, set b2j[x] to a list of the indices in
270
+ # b where x appears; the indices are in increasing order; note that
271
+ # the number of times x appears in b is len(b2j[x]) ...
272
+ # when self.isjunk is defined, junk elements don't show up in this
273
+ # map at all, which stops the central find_longest_match method
274
+ # from starting any matching block at a junk element ...
275
+ # b2j also does not contain entries for "popular" elements, meaning
276
+ # elements that account for more than 1 + 1% of the total elements, and
277
+ # when the sequence is reasonably large (>= 200 elements); this can
278
+ # be viewed as an adaptive notion of semi-junk, and yields an enormous
279
+ # speedup when, e.g., comparing program files with hundreds of
280
+ # instances of "return NULL;" ...
281
+ # note that this is only called when b changes; so for cross-product
282
+ # kinds of matches, it's best to call set_seq2 once, then set_seq1
283
+ # repeatedly
284
+
285
+ def __chain_b(self):
286
+ # Because isjunk is a user-defined (not C) function, and we test
287
+ # for junk a LOT, it's important to minimize the number of calls.
288
+ # Before the tricks described here, __chain_b was by far the most
289
+ # time-consuming routine in the whole module! If anyone sees
290
+ # Jim Roskind, thank him again for profile.py -- I never would
291
+ # have guessed that.
292
+ # The first trick is to build b2j ignoring the possibility
293
+ # of junk. I.e., we don't call isjunk at all yet. Throwing
294
+ # out the junk later is much cheaper than building b2j "right"
295
+ # from the start.
296
+ b = self.b
297
+ self.b2j = b2j = {}
298
+
299
+ for i, elt in enumerate(b):
300
+ indices = b2j.setdefault(elt, [])
301
+ indices.append(i)
302
+
303
+ # Purge junk elements
304
+ self.bjunk = junk = set()
305
+ isjunk = self.isjunk
306
+ if isjunk:
307
+ for elt in b2j.keys():
308
+ if isjunk(elt):
309
+ junk.add(elt)
310
+ for elt in junk: # separate loop avoids separate list of keys
311
+ del b2j[elt]
312
+
313
+ # Purge popular elements that are not junk
314
+ self.bpopular = popular = set()
315
+ n = len(b)
316
+ if self.autojunk and n >= 200:
317
+ ntest = n // 100 + 1
318
+ for elt, idxs in b2j.items():
319
+ if len(idxs) > ntest:
320
+ popular.add(elt)
321
+ for elt in popular: # ditto; as fast for 1% deletion
322
+ del b2j[elt]
323
+
324
+ def find_longest_match(self, alo=0, ahi_=None, blo=0, bhi_=None):
325
+ """Find longest matching block in a[alo:ahi] and b[blo:bhi].
326
+
327
+ By default it will find the longest match in the entirety of a and b.
328
+
329
+ If isjunk is not defined:
330
+
331
+ Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
332
+ alo <= i <= i+k <= ahi
333
+ blo <= j <= j+k <= bhi
334
+ and for all (i',j',k') meeting those conditions,
335
+ k >= k'
336
+ i <= i'
337
+ and if i == i', j <= j'
338
+
339
+ In other words, of all maximal matching blocks, return one that
340
+ starts earliest in a, and of all those maximal matching blocks that
341
+ start earliest in a, return the one that starts earliest in b.
342
+
343
+ >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
344
+ >>> s.find_longest_match(0, 5, 0, 9)
345
+ Match(a=0, b=4, size=5)
346
+
347
+ If isjunk is defined, first the longest matching block is
348
+ determined as above, but with the additional restriction that no
349
+ junk element appears in the block. Then that block is extended as
350
+ far as possible by matching (only) junk elements on both sides. So
351
+ the resulting block never matches on junk except as identical junk
352
+ happens to be adjacent to an "interesting" match.
353
+
354
+ Here's the same example as before, but considering blanks to be
355
+ junk. That prevents " abcd" from matching the " abcd" at the tail
356
+ end of the second sequence directly. Instead only the "abcd" can
357
+ match, and matches the leftmost "abcd" in the second sequence:
358
+
359
+ >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
360
+ >>> s.find_longest_match(0, 5, 0, 9)
361
+ Match(a=1, b=0, size=4)
362
+
363
+ If no blocks match, return (alo, blo, 0).
364
+
365
+ >>> s = SequenceMatcher(None, "ab", "c")
366
+ >>> s.find_longest_match(0, 2, 0, 1)
367
+ Match(a=0, b=0, size=0)
368
+ """
369
+
370
+ # CAUTION: stripping common prefix or suffix would be incorrect.
371
+ # E.g.,
372
+ # ab
373
+ # acab
374
+ # Longest matching block is "ab", but if common prefix is
375
+ # stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
376
+ # strip, so ends up claiming that ab is changed to acab by
377
+ # inserting "ca" in the middle. That's minimal but unintuitive:
378
+ # "it's obvious" that someone inserted "ac" at the front.
379
+ # Windiff ends up at the same place as diff, but by pairing up
380
+ # the unique 'b's and then matching the first two 'a's.
381
+
382
+ bjunk: set = self.bjunk
383
+ a, b, b2j = self.a, self.b, self.b2j
384
+ ahi = len(a) if ahi_ is None else ahi_
385
+ bhi = len(b) if bhi_ is None else bhi_
386
+ besti, bestj, bestsize = alo, blo, 0
387
+ # find longest junk-free match
388
+ # during an iteration of the loop, j2len[j] = length of longest
389
+ # junk-free match ending with a[i-1] and b[j]
390
+ j2len = {}
391
+ nothing = []
392
+ for i in range(alo, ahi):
393
+ # look at all instances of a[i] in b; note that because
394
+ # b2j has no junk keys, the loop is skipped if a[i] is junk
395
+ newj2len = {}
396
+ for j in b2j.get(a[i], nothing):
397
+ # a[i] matches b[j]
398
+ if j < blo:
399
+ continue
400
+ if j >= bhi:
401
+ break
402
+ k = newj2len[j] = j2len.get(j-1, 0) + 1
403
+ if k > bestsize:
404
+ besti, bestj, bestsize = i-k+1, j-k+1, k
405
+ j2len = newj2len
406
+
407
+ # Extend the best by non-junk elements on each end. In particular,
408
+ # "popular" non-junk elements aren't in b2j, which greatly speeds
409
+ # the inner loop above, but also means "the best" match so far
410
+ # doesn't contain any junk *or* popular non-junk elements.
411
+ while besti > alo and bestj > blo and \
412
+ b[bestj-1] not in bjunk and \
413
+ a[besti-1] == b[bestj-1]:
414
+ besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
415
+ while besti+bestsize < ahi and bestj+bestsize < bhi and \
416
+ b[bestj+bestsize] not in bjunk and \
417
+ a[besti+bestsize] == b[bestj+bestsize]:
418
+ bestsize += 1
419
+
420
+ # Now that we have a wholly interesting match (albeit possibly
421
+ # empty!), we may as well suck up the matching junk on each
422
+ # side of it too. Can't think of a good reason not to, and it
423
+ # saves post-processing the (possibly considerable) expense of
424
+ # figuring out what to do with it. In the case of an empty
425
+ # interesting match, this is clearly the right thing to do,
426
+ # because no other kind of match is possible in the regions.
427
+ while besti > alo and bestj > blo and \
428
+ b[bestj-1] in bjunk and \
429
+ a[besti-1] == b[bestj-1]:
430
+ besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
431
+ while besti+bestsize < ahi and bestj+bestsize < bhi and \
432
+ b[bestj+bestsize] in bjunk and \
433
+ a[besti+bestsize] == b[bestj+bestsize]:
434
+ bestsize = bestsize + 1
435
+
436
+ return Match(besti, bestj, bestsize)
437
+
438
+ def get_matching_blocks(self):
439
+ """Return list of triples describing matching subsequences.
440
+
441
+ Each triple is of the form (i, j, n), and means that
442
+ a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
443
+ i and in j. New in Python 2.5, it's also guaranteed that if
444
+ (i, j, n) and (i', j', n') are adjacent triples in the list, and
445
+ the second is not the last triple in the list, then i+n != i' or
446
+ j+n != j'. IOW, adjacent triples never describe adjacent equal
447
+ blocks.
448
+
449
+ The last triple is a dummy, (len(a), len(b), 0), and is the only
450
+ triple with n==0.
451
+
452
+ >>> s = SequenceMatcher(None, "abxcd", "abcd")
453
+ >>> list(s.get_matching_blocks())
454
+ [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
455
+ """
456
+
457
+ if self.matching_blocks is not None:
458
+ return self.matching_blocks
459
+ la, lb = len(self.a), len(self.b)
460
+
461
+ # This is most naturally expressed as a recursive algorithm, but
462
+ # at least one user bumped into extreme use cases that exceeded
463
+ # the recursion limit on their box. So, now we maintain a list
464
+ # ('queue`) of blocks we still need to look at, and append partial
465
+ # results to `matching_blocks` in a loop; the matches are sorted
466
+ # at the end.
467
+ queue = [(0, la, 0, lb)]
468
+ matching_blocks = []
469
+ while queue:
470
+ alo, ahi, blo, bhi = queue.pop()
471
+ i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)
472
+ # a[alo:i] vs b[blo:j] unknown
473
+ # a[i:i+k] same as b[j:j+k]
474
+ # a[i+k:ahi] vs b[j+k:bhi] unknown
475
+ if k: # if k is 0, there was no matching block
476
+ matching_blocks.append(x)
477
+ if alo < i and blo < j:
478
+ queue.append((alo, i, blo, j))
479
+ if i+k < ahi and j+k < bhi:
480
+ queue.append((i+k, ahi, j+k, bhi))
481
+ matching_blocks.sort()
482
+
483
+ # It's possible that we have adjacent equal blocks in the
484
+ # matching_blocks list now. Starting with 2.5, this code was added
485
+ # to collapse them.
486
+ i1 = j1 = k1 = 0
487
+ non_adjacent = []
488
+ for i2, j2, k2 in matching_blocks:
489
+ # Is this block adjacent to i1, j1, k1?
490
+ if i1 + k1 == i2 and j1 + k1 == j2:
491
+ # Yes, so collapse them -- this just increases the length of
492
+ # the first block by the length of the second, and the first
493
+ # block so lengthened remains the block to compare against.
494
+ k1 += k2
495
+ else:
496
+ # Not adjacent. Remember the first block (k1==0 means it's
497
+ # the dummy we started with), and make the second block the
498
+ # new block to compare against.
499
+ if k1:
500
+ non_adjacent.append((i1, j1, k1))
501
+ i1, j1, k1 = i2, j2, k2
502
+ if k1:
503
+ non_adjacent.append((i1, j1, k1))
504
+
505
+ non_adjacent.append( (la, lb, 0) )
506
+ self.matching_blocks = list(map(Match._make, non_adjacent))
507
+ return self.matching_blocks
508
+
509
+ def get_opcodes(self):
510
+ """Return list of 5-tuples describing how to turn a into b.
511
+
512
+ Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
513
+ has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
514
+ tuple preceding it, and likewise for j1 == the previous j2.
515
+
516
+ The tags are strings, with these meanings:
517
+
518
+ 'replace': a[i1:i2] should be replaced by b[j1:j2]
519
+ 'delete': a[i1:i2] should be deleted.
520
+ Note that j1==j2 in this case.
521
+ 'insert': b[j1:j2] should be inserted at a[i1:i1].
522
+ Note that i1==i2 in this case.
523
+ 'equal': a[i1:i2] == b[j1:j2]
524
+
525
+ >>> a = "qabxcd"
526
+ >>> b = "abycdf"
527
+ >>> s = SequenceMatcher(None, a, b)
528
+ >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
529
+ ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
530
+ ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
531
+ delete a[0:1] (q) b[0:0] ()
532
+ equal a[1:3] (ab) b[0:2] (ab)
533
+ replace a[3:4] (x) b[2:3] (y)
534
+ equal a[4:6] (cd) b[3:5] (cd)
535
+ insert a[6:6] () b[5:6] (f)
536
+ """
537
+
538
+ if self.opcodes is not None:
539
+ return self.opcodes
540
+ i = j = 0
541
+ self.opcodes = answer = []
542
+ for ai, bj, size in self.get_matching_blocks():
543
+ # invariant: we've pumped out correct diffs to change
544
+ # a[:i] into b[:j], and the next matching block is
545
+ # a[ai:ai+size] == b[bj:bj+size]. So we need to pump
546
+ # out a diff to change a[i:ai] into b[j:bj], pump out
547
+ # the matching block, and move (i,j) beyond the match
548
+ tag = ''
549
+ if i < ai and j < bj:
550
+ tag = 'replace'
551
+ elif i < ai:
552
+ tag = 'delete'
553
+ elif j < bj:
554
+ tag = 'insert'
555
+ if tag:
556
+ answer.append( (tag, i, ai, j, bj) )
557
+ i, j = ai+size, bj+size
558
+ # the list of matching blocks is terminated by a
559
+ # sentinel with size 0
560
+ if size:
561
+ answer.append( ('equal', ai, i, bj, j) )
562
+ return answer
563
+
564
+ def get_grouped_opcodes(self, n=3):
565
+ """ Isolate change clusters by eliminating ranges with no changes.
566
+
567
+ Return a generator of groups with up to n lines of context.
568
+ Each group is in the same format as returned by get_opcodes().
569
+
570
+ >>> from pprint import pprint
571
+ >>> a = list(map(str, range(1,40)))
572
+ >>> b = a[:]
573
+ >>> b[8:8] = ['i'] # Make an insertion
574
+ >>> b[20] += 'x' # Make a replacement
575
+ >>> b[23:28] = [] # Make a deletion
576
+ >>> b[30] += 'y' # Make another replacement
577
+ >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
578
+ [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
579
+ [('equal', 16, 19, 17, 20),
580
+ ('replace', 19, 20, 20, 21),
581
+ ('equal', 20, 22, 21, 23),
582
+ ('delete', 22, 27, 23, 23),
583
+ ('equal', 27, 30, 23, 26)],
584
+ [('equal', 31, 34, 27, 30),
585
+ ('replace', 34, 35, 30, 31),
586
+ ('equal', 35, 38, 31, 34)]]
587
+ """
588
+
589
+ codes = self.get_opcodes()
590
+ if not codes:
591
+ codes = [("equal", 0, 1, 0, 1)]
592
+ # Fixup leading and trailing groups if they show no changes.
593
+ if codes[0][0] == 'equal':
594
+ tag, i1, i2, j1, j2 = codes[0]
595
+ codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2
596
+ if codes[-1][0] == 'equal':
597
+ tag, i1, i2, j1, j2 = codes[-1]
598
+ codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)
599
+
600
+ nn = n + n
601
+ group = []
602
+ for tag, i1, i2, j1, j2 in codes:
603
+ # End the current group and start a new one whenever
604
+ # there is a large range with no changes.
605
+ if tag == 'equal' and i2-i1 > nn:
606
+ group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))
607
+ yield group
608
+ group = []
609
+ i1, j1 = max(i1, i2-n), max(j1, j2-n)
610
+ group.append((tag, i1, i2, j1 ,j2))
611
+ if group and not (len(group)==1 and group[0][0] == 'equal'):
612
+ yield group
613
+
614
+ def ratio(self):
615
+ """Return a measure of the sequences' similarity (float in [0,1]).
616
+
617
+ Where T is the total number of elements in both sequences, and
618
+ M is the number of matches, this is 2.0*M / T.
619
+ Note that this is 1 if the sequences are identical, and 0 if
620
+ they have nothing in common.
621
+
622
+ .ratio() is expensive to compute if you haven't already computed
623
+ .get_matching_blocks() or .get_opcodes(), in which case you may
624
+ want to try .quick_ratio() or .real_quick_ratio() first to get an
625
+ upper bound.
626
+
627
+ >>> s = SequenceMatcher(None, "abcd", "bcde")
628
+ >>> s.ratio()
629
+ 0.75
630
+ >>> s.quick_ratio()
631
+ 0.75
632
+ >>> s.real_quick_ratio()
633
+ 1.0
634
+ """
635
+
636
+ matches: cython.Py_ssize_t
637
+ matches = sum(triple[-1] for triple in self.get_matching_blocks())
638
+ return _calculate_ratio(matches, len(self.a) + len(self.b))
639
+
640
+ def quick_ratio(self):
641
+ """Return an upper bound on ratio() relatively quickly.
642
+
643
+ This isn't defined beyond that it is an upper bound on .ratio(), and
644
+ is faster to compute.
645
+ """
646
+
647
+ # viewing a and b as multisets, set matches to the cardinality
648
+ # of their intersection; this counts the number of matches
649
+ # without regard to order, so is clearly an upper bound
650
+ if self.fullbcount is None:
651
+ self.fullbcount = fullbcount = {}
652
+ for elt in self.b:
653
+ fullbcount[elt] = fullbcount.get(elt, 0) + 1
654
+ fullbcount = self.fullbcount
655
+ # avail[x] is the number of times x appears in 'b' less the
656
+ # number of times we've seen it in 'a' so far ... kinda
657
+ avail = {}
658
+ matches: cython.Py_ssize_t
659
+ matches = 0
660
+ for elt in self.a:
661
+ if elt in avail:
662
+ numb = avail[elt]
663
+ else:
664
+ numb = fullbcount.get(elt, 0)
665
+ avail[elt] = numb - 1
666
+ if numb > 0:
667
+ matches = matches + 1
668
+ return _calculate_ratio(matches, len(self.a) + len(self.b))
669
+
670
+ def real_quick_ratio(self):
671
+ """Return an upper bound on ratio() very quickly.
672
+
673
+ This isn't defined beyond that it is an upper bound on .ratio(), and
674
+ is faster to compute than either .ratio() or .quick_ratio().
675
+ """
676
+
677
+ la, lb = len(self.a), len(self.b)
678
+ # can't have more matches than the number of elements in the
679
+ # shorter sequence
680
+ return _calculate_ratio(min(la, lb), la + lb)
681
+
682
+ if GenericAlias is not None:
683
+ __class_getitem__ = classmethod(GenericAlias)
684
+
685
+
686
+ def get_close_matches(word, possibilities, n=3, cutoff=0.6):
687
+ """Use SequenceMatcher to return list of the best "good enough" matches.
688
+
689
+ word is a sequence for which close matches are desired (typically a
690
+ string).
691
+
692
+ possibilities is a list of sequences against which to match word
693
+ (typically a list of strings).
694
+
695
+ Optional arg n (default 3) is the maximum number of close matches to
696
+ return. n must be > 0.
697
+
698
+ Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
699
+ that don't score at least that similar to word are ignored.
700
+
701
+ The best (no more than n) matches among the possibilities are returned
702
+ in a list, sorted by similarity score, most similar first.
703
+
704
+ >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
705
+ ['apple', 'ape']
706
+ >>> import keyword as _keyword
707
+ >>> get_close_matches("wheel", _keyword.kwlist)
708
+ ['while']
709
+ >>> get_close_matches("Apple", _keyword.kwlist)
710
+ []
711
+ >>> get_close_matches("accept", _keyword.kwlist)
712
+ ['except']
713
+ """
714
+
715
+ if not n > 0:
716
+ raise ValueError("n must be > 0: %r" % (n,))
717
+ if not 0.0 <= cutoff <= 1.0:
718
+ raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
719
+ result = []
720
+ s = SequenceMatcher()
721
+ s.set_seq2(word)
722
+ for x in possibilities:
723
+ s.set_seq1(x)
724
+ if s.real_quick_ratio() >= cutoff and \
725
+ s.quick_ratio() >= cutoff and \
726
+ s.ratio() >= cutoff:
727
+ result.append((s.ratio(), x))
728
+
729
+ # Move the best scorers to head of list
730
+ result = _nlargest(n, result)
731
+ # Strip scores for the best n matches
732
+ return [x for score, x in result]
733
+
734
+
735
+ def _keep_original_ws(s, tag_s):
736
+ """Replace whitespace with the original whitespace characters in `s`"""
737
+ return ''.join(
738
+ c if tag_c == " " and c.isspace() else tag_c
739
+ for c, tag_c in zip(s, tag_s)
740
+ )
741
+
742
+
743
+
744
+ class Differ:
745
+ r"""
746
+ Differ is a class for comparing sequences of lines of text, and
747
+ producing human-readable differences or deltas. Differ uses
748
+ SequenceMatcher both to compare sequences of lines, and to compare
749
+ sequences of characters within similar (near-matching) lines.
750
+
751
+ Each line of a Differ delta begins with a two-letter code:
752
+
753
+ '- ' line unique to sequence 1
754
+ '+ ' line unique to sequence 2
755
+ ' ' line common to both sequences
756
+ '? ' line not present in either input sequence
757
+
758
+ Lines beginning with '? ' attempt to guide the eye to intraline
759
+ differences, and were not present in either input sequence. These lines
760
+ can be confusing if the sequences contain tab characters.
761
+
762
+ Note that Differ makes no claim to produce a *minimal* diff. To the
763
+ contrary, minimal diffs are often counter-intuitive, because they synch
764
+ up anywhere possible, sometimes accidental matches 100 pages apart.
765
+ Restricting synch points to contiguous matches preserves some notion of
766
+ locality, at the occasional cost of producing a longer diff.
767
+
768
+ Example: Comparing two texts.
769
+
770
+ First we set up the texts, sequences of individual single-line strings
771
+ ending with newlines (such sequences can also be obtained from the
772
+ `readlines()` method of file-like objects):
773
+
774
+ >>> text1 = ''' 1. Beautiful is better than ugly.
775
+ ... 2. Explicit is better than implicit.
776
+ ... 3. Simple is better than complex.
777
+ ... 4. Complex is better than complicated.
778
+ ... '''.splitlines(keepends=True)
779
+ >>> len(text1)
780
+ 4
781
+ >>> text1[0][-1]
782
+ '\n'
783
+ >>> text2 = ''' 1. Beautiful is better than ugly.
784
+ ... 3. Simple is better than complex.
785
+ ... 4. Complicated is better than complex.
786
+ ... 5. Flat is better than nested.
787
+ ... '''.splitlines(keepends=True)
788
+
789
+ Next we instantiate a Differ object:
790
+
791
+ >>> d = Differ()
792
+
793
+ Note that when instantiating a Differ object we may pass functions to
794
+ filter out line and character 'junk'. See Differ.__init__ for details.
795
+
796
+ Finally, we compare the two:
797
+
798
+ >>> result = list(d.compare(text1, text2))
799
+
800
+ 'result' is a list of strings, so let's pretty-print it:
801
+
802
+ >>> from pprint import pprint as _pprint
803
+ >>> _pprint(result)
804
+ [' 1. Beautiful is better than ugly.\n',
805
+ '- 2. Explicit is better than implicit.\n',
806
+ '- 3. Simple is better than complex.\n',
807
+ '+ 3. Simple is better than complex.\n',
808
+ '? ++\n',
809
+ '- 4. Complex is better than complicated.\n',
810
+ '? ^ ---- ^\n',
811
+ '+ 4. Complicated is better than complex.\n',
812
+ '? ++++ ^ ^\n',
813
+ '+ 5. Flat is better than nested.\n']
814
+
815
+ As a single multi-line string it looks like this:
816
+
817
+ >>> print(''.join(result), end="")
818
+ 1. Beautiful is better than ugly.
819
+ - 2. Explicit is better than implicit.
820
+ - 3. Simple is better than complex.
821
+ + 3. Simple is better than complex.
822
+ ? ++
823
+ - 4. Complex is better than complicated.
824
+ ? ^ ---- ^
825
+ + 4. Complicated is better than complex.
826
+ ? ++++ ^ ^
827
+ + 5. Flat is better than nested.
828
+ """
829
+
830
+ def __init__(self, linejunk=None, charjunk=None):
831
+ """
832
+ Construct a text differencer, with optional filters.
833
+
834
+ The two optional keyword parameters are for filter functions:
835
+
836
+ - `linejunk`: A function that should accept a single string argument,
837
+ and return true iff the string is junk. The module-level function
838
+ `IS_LINE_JUNK` may be used to filter out lines without visible
839
+ characters, except for at most one splat ('#'). It is recommended
840
+ to leave linejunk None; the underlying SequenceMatcher class has
841
+ an adaptive notion of "noise" lines that's better than any static
842
+ definition the author has ever been able to craft.
843
+
844
+ - `charjunk`: A function that should accept a string of length 1. The
845
+ module-level function `IS_CHARACTER_JUNK` may be used to filter out
846
+ whitespace characters (a blank or tab; **note**: bad idea to include
847
+ newline in this!). Use of IS_CHARACTER_JUNK is recommended.
848
+ """
849
+
850
+ self.linejunk = linejunk
851
+ self.charjunk = charjunk
852
+
853
+ def compare(self, a, b):
854
+ r"""
855
+ Compare two sequences of lines; generate the resulting delta.
856
+
857
+ Each sequence must contain individual single-line strings ending with
858
+ newlines. Such sequences can be obtained from the `readlines()` method
859
+ of file-like objects. The delta generated also consists of newline-
860
+ terminated strings, ready to be printed as-is via the writelines()
861
+ method of a file-like object.
862
+
863
+ Example:
864
+
865
+ >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(True),
866
+ ... 'ore\ntree\nemu\n'.splitlines(True))),
867
+ ... end="")
868
+ - one
869
+ ? ^
870
+ + ore
871
+ ? ^
872
+ - two
873
+ - three
874
+ ? -
875
+ + tree
876
+ + emu
877
+ """
878
+
879
+ cruncher = SequenceMatcher(self.linejunk, a, b)
880
+ for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
881
+ if tag == 'replace':
882
+ g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
883
+ elif tag == 'delete':
884
+ g = self._dump('-', a, alo, ahi)
885
+ elif tag == 'insert':
886
+ g = self._dump('+', b, blo, bhi)
887
+ elif tag == 'equal':
888
+ g = self._dump(' ', a, alo, ahi)
889
+ else:
890
+ raise ValueError('unknown tag %r' % (tag,))
891
+
892
+ yield from g
893
+
894
+ def _dump(self, tag, x, lo, hi):
895
+ """Generate comparison results for a same-tagged range."""
896
+ for i in range(lo, hi):
897
+ yield '%s %s' % (tag, x[i])
898
+
899
+ def _plain_replace(self, a, alo, ahi, b, blo, bhi):
900
+ assert alo < ahi and blo < bhi
901
+ # dump the shorter block first -- reduces the burden on short-term
902
+ # memory if the blocks are of very different sizes
903
+ if bhi - blo < ahi - alo:
904
+ first = self._dump('+', b, blo, bhi)
905
+ second = self._dump('-', a, alo, ahi)
906
+ else:
907
+ first = self._dump('-', a, alo, ahi)
908
+ second = self._dump('+', b, blo, bhi)
909
+
910
+ for g in first, second:
911
+ yield from g
912
+
913
+ def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
914
+ r"""
915
+ When replacing one block of lines with another, search the blocks
916
+ for *similar* lines; the best-matching pair (if any) is used as a
917
+ synch point, and intraline difference marking is done on the
918
+ similar pair. Lots of work, but often worth it.
919
+
920
+ Example:
921
+
922
+ >>> d = Differ()
923
+ >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
924
+ ... ['abcdefGhijkl\n'], 0, 1)
925
+ >>> print(''.join(results), end="")
926
+ - abcDefghiJkl
927
+ ? ^ ^ ^
928
+ + abcdefGhijkl
929
+ ? ^ ^ ^
930
+ """
931
+ # Don't synch up unless the lines have a similarity score above
932
+ # cutoff. Previously only the smallest pair was handled here,
933
+ # and if there are many pairs with the best ratio, recursion
934
+ # could grow very deep, and runtime cubic. See:
935
+ # https://github.com/python/cpython/issues/119105
936
+ #
937
+ # Later, more pathological cases prompted removing recursion
938
+ # entirely.
939
+ cutoff = 0.74999
940
+ cruncher = SequenceMatcher(self.charjunk)
941
+ crqr = cruncher.real_quick_ratio
942
+ cqr = cruncher.quick_ratio
943
+ cr = cruncher.ratio
944
+
945
+ WINDOW = 10
946
+ best_i = best_j = None
947
+ dump_i, dump_j = alo, blo # smallest indices not yet resolved
948
+ for j in range(blo, bhi):
949
+ cruncher.set_seq2(b[j])
950
+ # Search the corresponding i's within WINDOW for rhe highest
951
+ # ratio greater than `cutoff`.
952
+ aequiv = alo + (j - blo)
953
+ arange = range(max(aequiv - WINDOW, dump_i),
954
+ min(aequiv + WINDOW + 1, ahi))
955
+ if not arange: # likely exit if `a` is shorter than `b`
956
+ break
957
+ best_ratio = cutoff
958
+ for i in arange:
959
+ cruncher.set_seq1(a[i])
960
+ # Ordering by cheapest to most expensive ratio is very
961
+ # valuable, most often getting out early.
962
+ if (crqr() > best_ratio
963
+ and cqr() > best_ratio
964
+ and cr() > best_ratio):
965
+ best_i, best_j, best_ratio = i, j, cr()
966
+
967
+ if best_i is None:
968
+ # found nothing to synch on yet - move to next j
969
+ continue
970
+
971
+ # pump out straight replace from before this synch pair
972
+ yield from self._fancy_helper(a, dump_i, best_i,
973
+ b, dump_j, best_j)
974
+ # do intraline marking on the synch pair
975
+ aelt, belt = a[best_i], b[best_j]
976
+ if aelt != belt:
977
+ # pump out a '-', '?', '+', '?' quad for the synched lines
978
+ atags = btags = ""
979
+ cruncher.set_seqs(aelt, belt)
980
+ for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
981
+ la, lb = ai2 - ai1, bj2 - bj1
982
+ if tag == 'replace':
983
+ atags += '^' * la
984
+ btags += '^' * lb
985
+ elif tag == 'delete':
986
+ atags += '-' * la
987
+ elif tag == 'insert':
988
+ btags += '+' * lb
989
+ elif tag == 'equal':
990
+ atags += ' ' * la
991
+ btags += ' ' * lb
992
+ else:
993
+ raise ValueError('unknown tag %r' % (tag,))
994
+ yield from self._qformat(aelt, belt, atags, btags)
995
+ else:
996
+ # the synch pair is identical
997
+ yield ' ' + aelt
998
+ dump_i, dump_j = best_i + 1, best_j + 1
999
+ best_i = best_j = None
1000
+
1001
+ # pump out straight replace from after the last synch pair
1002
+ yield from self._fancy_helper(a, dump_i, ahi,
1003
+ b, dump_j, bhi)
1004
+
1005
+ def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
1006
+ g = []
1007
+ if alo < ahi:
1008
+ if blo < bhi:
1009
+ g = self._plain_replace(a, alo, ahi, b, blo, bhi)
1010
+ else:
1011
+ g = self._dump('-', a, alo, ahi)
1012
+ elif blo < bhi:
1013
+ g = self._dump('+', b, blo, bhi)
1014
+
1015
+ yield from g
1016
+
1017
+ def _qformat(self, aline, bline, atags, btags):
1018
+ r"""
1019
+ Format "?" output and deal with tabs.
1020
+
1021
+ Example:
1022
+
1023
+ >>> d = Differ()
1024
+ >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n',
1025
+ ... ' ^ ^ ^ ', ' ^ ^ ^ ')
1026
+ >>> for line in results: print(repr(line))
1027
+ ...
1028
+ '- \tabcDefghiJkl\n'
1029
+ '? \t ^ ^ ^\n'
1030
+ '+ \tabcdefGhijkl\n'
1031
+ '? \t ^ ^ ^\n'
1032
+ """
1033
+ atags = _keep_original_ws(aline, atags).rstrip()
1034
+ btags = _keep_original_ws(bline, btags).rstrip()
1035
+
1036
+ yield "- " + aline
1037
+ if atags:
1038
+ yield f"? {atags}\n"
1039
+
1040
+ yield "+ " + bline
1041
+ if btags:
1042
+ yield f"? {btags}\n"
1043
+
1044
+ # With respect to junk, an earlier version of ndiff simply refused to
1045
+ # *start* a match with a junk element. The result was cases like this:
1046
+ # before: private Thread currentThread;
1047
+ # after: private volatile Thread currentThread;
1048
+ # If you consider whitespace to be junk, the longest contiguous match
1049
+ # not starting with junk is "e Thread currentThread". So ndiff reported
1050
+ # that "e volatil" was inserted between the 't' and the 'e' in "private".
1051
+ # While an accurate view, to people that's absurd. The current version
1052
+ # looks for matching blocks that are entirely junk-free, then extends the
1053
+ # longest one of those as far as possible but only with matching junk.
1054
+ # So now "currentThread" is matched, then extended to suck up the
1055
+ # preceding blank; then "private" is matched, and extended to suck up the
1056
+ # following blank; then "Thread" is matched; and finally ndiff reports
1057
+ # that "volatile " was inserted before "Thread". The only quibble
1058
+ # remaining is that perhaps it was really the case that " volatile"
1059
+ # was inserted after "private". I can live with that <wink>.
1060
+
1061
+ def IS_LINE_JUNK(line, pat=None):
1062
+ r"""
1063
+ Return True for ignorable line: if `line` is blank or contains a single '#'.
1064
+
1065
+ Examples:
1066
+
1067
+ >>> IS_LINE_JUNK('\n')
1068
+ True
1069
+ >>> IS_LINE_JUNK(' # \n')
1070
+ True
1071
+ >>> IS_LINE_JUNK('hello\n')
1072
+ False
1073
+ """
1074
+
1075
+ if pat is None:
1076
+ # Default: match '#' or the empty string
1077
+ return line.strip() in '#'
1078
+ # Previous versions used the undocumented parameter 'pat' as a
1079
+ # match function. Retain this behaviour for compatibility.
1080
+ return pat(line) is not None
1081
+
1082
+ def IS_CHARACTER_JUNK(ch, ws=" \t"):
1083
+ r"""
1084
+ Return True for ignorable character: iff `ch` is a space or tab.
1085
+
1086
+ Examples:
1087
+
1088
+ >>> IS_CHARACTER_JUNK(' ')
1089
+ True
1090
+ >>> IS_CHARACTER_JUNK('\t')
1091
+ True
1092
+ >>> IS_CHARACTER_JUNK('\n')
1093
+ False
1094
+ >>> IS_CHARACTER_JUNK('x')
1095
+ False
1096
+ """
1097
+
1098
+ return ch in ws
1099
+
1100
+
1101
+ ########################################################################
1102
+ ### Unified Diff
1103
+ ########################################################################
1104
+
1105
+ def _format_range_unified(start, stop):
1106
+ 'Convert range to the "ed" format'
1107
+ # Per the diff spec at http://www.unix.org/single_unix_specification/
1108
+ beginning = start + 1 # lines start numbering with one
1109
+ length = stop - start
1110
+ if length == 1:
1111
+ return '{}'.format(beginning)
1112
+ if not length:
1113
+ beginning -= 1 # empty ranges begin at line just before the range
1114
+ return '{},{}'.format(beginning, length)
1115
+
1116
+ def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
1117
+ tofiledate='', n=3, lineterm='\n'):
1118
+ r"""
1119
+ Compare two sequences of lines; generate the delta as a unified diff.
1120
+
1121
+ Unified diffs are a compact way of showing line changes and a few
1122
+ lines of context. The number of context lines is set by 'n' which
1123
+ defaults to three.
1124
+
1125
+ By default, the diff control lines (those with ---, +++, or @@) are
1126
+ created with a trailing newline. This is helpful so that inputs
1127
+ created from file.readlines() result in diffs that are suitable for
1128
+ file.writelines() since both the inputs and outputs have trailing
1129
+ newlines.
1130
+
1131
+ For inputs that do not have trailing newlines, set the lineterm
1132
+ argument to "" so that the output will be uniformly newline free.
1133
+
1134
+ The unidiff format normally has a header for filenames and modification
1135
+ times. Any or all of these may be specified using strings for
1136
+ 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
1137
+ The modification times are normally expressed in the ISO 8601 format.
1138
+
1139
+ Example:
1140
+
1141
+ >>> for line in unified_diff('one two three four'.split(),
1142
+ ... 'zero one tree four'.split(), 'Original', 'Current',
1143
+ ... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
1144
+ ... lineterm=''):
1145
+ ... print(line) # doctest: +NORMALIZE_WHITESPACE
1146
+ --- Original 2005-01-26 23:30:50
1147
+ +++ Current 2010-04-02 10:20:52
1148
+ @@ -1,4 +1,4 @@
1149
+ +zero
1150
+ one
1151
+ -two
1152
+ -three
1153
+ +tree
1154
+ four
1155
+ """
1156
+
1157
+ _check_types(a, b, fromfile, tofile, fromfiledate, tofiledate, lineterm)
1158
+ started = False
1159
+ for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1160
+ if not started:
1161
+ started = True
1162
+ fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
1163
+ todate = '\t{}'.format(tofiledate) if tofiledate else ''
1164
+ yield '--- {}{}{}'.format(fromfile, fromdate, lineterm)
1165
+ yield '+++ {}{}{}'.format(tofile, todate, lineterm)
1166
+
1167
+ first, last = group[0], group[-1]
1168
+ file1_range = _format_range_unified(first[1], last[2])
1169
+ file2_range = _format_range_unified(first[3], last[4])
1170
+ yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm)
1171
+
1172
+ for tag, i1, i2, j1, j2 in group:
1173
+ if tag == 'equal':
1174
+ for line in a[i1:i2]:
1175
+ yield ' ' + line
1176
+ continue
1177
+ if tag in {'replace', 'delete'}:
1178
+ for line in a[i1:i2]:
1179
+ yield '-' + line
1180
+ if tag in {'replace', 'insert'}:
1181
+ for line in b[j1:j2]:
1182
+ yield '+' + line
1183
+
1184
+
1185
+ ########################################################################
1186
+ ### Context Diff
1187
+ ########################################################################
1188
+
1189
+ def _format_range_context(start, stop):
1190
+ 'Convert range to the "ed" format'
1191
+ # Per the diff spec at http://www.unix.org/single_unix_specification/
1192
+ beginning = start + 1 # lines start numbering with one
1193
+ length = stop - start
1194
+ if not length:
1195
+ beginning -= 1 # empty ranges begin at line just before the range
1196
+ if length <= 1:
1197
+ return '{}'.format(beginning)
1198
+ return '{},{}'.format(beginning, beginning + length - 1)
1199
+
1200
+ # See http://www.unix.org/single_unix_specification/
1201
+ def context_diff(a, b, fromfile='', tofile='',
1202
+ fromfiledate='', tofiledate='', n=3, lineterm='\n'):
1203
+ r"""
1204
+ Compare two sequences of lines; generate the delta as a context diff.
1205
+
1206
+ Context diffs are a compact way of showing line changes and a few
1207
+ lines of context. The number of context lines is set by 'n' which
1208
+ defaults to three.
1209
+
1210
+ By default, the diff control lines (those with *** or ---) are
1211
+ created with a trailing newline. This is helpful so that inputs
1212
+ created from file.readlines() result in diffs that are suitable for
1213
+ file.writelines() since both the inputs and outputs have trailing
1214
+ newlines.
1215
+
1216
+ For inputs that do not have trailing newlines, set the lineterm
1217
+ argument to "" so that the output will be uniformly newline free.
1218
+
1219
+ The context diff format normally has a header for filenames and
1220
+ modification times. Any or all of these may be specified using
1221
+ strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
1222
+ The modification times are normally expressed in the ISO 8601 format.
1223
+ If not specified, the strings default to blanks.
1224
+
1225
+ Example:
1226
+
1227
+ >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(True),
1228
+ ... 'zero\none\ntree\nfour\n'.splitlines(True), 'Original', 'Current')),
1229
+ ... end="")
1230
+ *** Original
1231
+ --- Current
1232
+ ***************
1233
+ *** 1,4 ****
1234
+ one
1235
+ ! two
1236
+ ! three
1237
+ four
1238
+ --- 1,4 ----
1239
+ + zero
1240
+ one
1241
+ ! tree
1242
+ four
1243
+ """
1244
+
1245
+ _check_types(a, b, fromfile, tofile, fromfiledate, tofiledate, lineterm)
1246
+ prefix = dict(insert='+ ', delete='- ', replace='! ', equal=' ')
1247
+ started = False
1248
+ for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
1249
+ if not started:
1250
+ started = True
1251
+ fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
1252
+ todate = '\t{}'.format(tofiledate) if tofiledate else ''
1253
+ yield '*** {}{}{}'.format(fromfile, fromdate, lineterm)
1254
+ yield '--- {}{}{}'.format(tofile, todate, lineterm)
1255
+
1256
+ first, last = group[0], group[-1]
1257
+ yield '***************' + lineterm
1258
+
1259
+ file1_range = _format_range_context(first[1], last[2])
1260
+ yield '*** {} ****{}'.format(file1_range, lineterm)
1261
+
1262
+ if any(tag in {'replace', 'delete'} for tag, _, _, _, _ in group):
1263
+ for tag, i1, i2, _, _ in group:
1264
+ if tag != 'insert':
1265
+ for line in a[i1:i2]:
1266
+ yield prefix[tag] + line
1267
+
1268
+ file2_range = _format_range_context(first[3], last[4])
1269
+ yield '--- {} ----{}'.format(file2_range, lineterm)
1270
+
1271
+ if any(tag in {'replace', 'insert'} for tag, _, _, _, _ in group):
1272
+ for tag, _, _, j1, j2 in group:
1273
+ if tag != 'delete':
1274
+ for line in b[j1:j2]:
1275
+ yield prefix[tag] + line
1276
+
1277
+ def _check_types(a, b, *args):
1278
+ # Checking types is weird, but the alternative is garbled output when
1279
+ # someone passes mixed bytes and str to {unified,context}_diff(). E.g.
1280
+ # without this check, passing filenames as bytes results in output like
1281
+ # --- b'oldfile.txt'
1282
+ # +++ b'newfile.txt'
1283
+ # because of how str.format() incorporates bytes objects.
1284
+ if a and not isinstance(a[0], str):
1285
+ raise TypeError('lines to compare must be str, not %s (%r)' %
1286
+ (type(a[0]).__name__, a[0]))
1287
+ if b and not isinstance(b[0], str):
1288
+ raise TypeError('lines to compare must be str, not %s (%r)' %
1289
+ (type(b[0]).__name__, b[0]))
1290
+ if isinstance(a, str):
1291
+ raise TypeError('input must be a sequence of strings, not %s' %
1292
+ type(a).__name__)
1293
+ if isinstance(b, str):
1294
+ raise TypeError('input must be a sequence of strings, not %s' %
1295
+ type(b).__name__)
1296
+ for arg in args:
1297
+ if not isinstance(arg, str):
1298
+ raise TypeError('all arguments must be str, not: %r' % (arg,))
1299
+
1300
+ def diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'',
1301
+ fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n'):
1302
+ r"""
1303
+ Compare `a` and `b`, two sequences of lines represented as bytes rather
1304
+ than str. This is a wrapper for `dfunc`, which is typically either
1305
+ unified_diff() or context_diff(). Inputs are losslessly converted to
1306
+ strings so that `dfunc` only has to worry about strings, and encoded
1307
+ back to bytes on return. This is necessary to compare files with
1308
+ unknown or inconsistent encoding. All other inputs (except `n`) must be
1309
+ bytes rather than str.
1310
+ """
1311
+ def decode(s):
1312
+ try:
1313
+ return s.decode('ascii', 'surrogateescape')
1314
+ except AttributeError as err:
1315
+ msg = ('all arguments must be bytes, not %s (%r)' %
1316
+ (type(s).__name__, s))
1317
+ raise TypeError(msg) from err
1318
+ a = list(map(decode, a))
1319
+ b = list(map(decode, b))
1320
+ fromfile = decode(fromfile)
1321
+ tofile = decode(tofile)
1322
+ fromfiledate = decode(fromfiledate)
1323
+ tofiledate = decode(tofiledate)
1324
+ lineterm = decode(lineterm)
1325
+
1326
+ lines = dfunc(a, b, fromfile, tofile, fromfiledate, tofiledate, n, lineterm)
1327
+ for line in lines:
1328
+ yield line.encode('ascii', 'surrogateescape')
1329
+
1330
+ def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
1331
+ r"""
1332
+ Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
1333
+
1334
+ Optional keyword parameters `linejunk` and `charjunk` are for filter
1335
+ functions, or can be None:
1336
+
1337
+ - linejunk: A function that should accept a single string argument and
1338
+ return true iff the string is junk. The default is None, and is
1339
+ recommended; the underlying SequenceMatcher class has an adaptive
1340
+ notion of "noise" lines.
1341
+
1342
+ - charjunk: A function that accepts a character (string of length
1343
+ 1), and returns true iff the character is junk. The default is
1344
+ the module-level function IS_CHARACTER_JUNK, which filters out
1345
+ whitespace characters (a blank or tab; note: it's a bad idea to
1346
+ include newline in this!).
1347
+
1348
+ Tools/scripts/ndiff.py is a command-line front-end to this function.
1349
+
1350
+ Example:
1351
+
1352
+ >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
1353
+ ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
1354
+ >>> print(''.join(diff), end="")
1355
+ - one
1356
+ ? ^
1357
+ + ore
1358
+ ? ^
1359
+ - two
1360
+ - three
1361
+ ? -
1362
+ + tree
1363
+ + emu
1364
+ """
1365
+ return Differ(linejunk, charjunk).compare(a, b)
1366
+
1367
+ def _mdiff(fromlines, tolines, context=None, linejunk=None,
1368
+ charjunk=IS_CHARACTER_JUNK):
1369
+ r"""Returns generator yielding marked up from/to side by side differences.
1370
+
1371
+ Arguments:
1372
+ fromlines -- list of text lines to compared to tolines
1373
+ tolines -- list of text lines to be compared to fromlines
1374
+ context -- number of context lines to display on each side of difference,
1375
+ if None, all from/to text lines will be generated.
1376
+ linejunk -- passed on to ndiff (see ndiff documentation)
1377
+ charjunk -- passed on to ndiff (see ndiff documentation)
1378
+
1379
+ This function returns an iterator which returns a tuple:
1380
+ (from line tuple, to line tuple, boolean flag)
1381
+
1382
+ from/to line tuple -- (line num, line text)
1383
+ line num -- integer or None (to indicate a context separation)
1384
+ line text -- original line text with following markers inserted:
1385
+ '\0+' -- marks start of added text
1386
+ '\0-' -- marks start of deleted text
1387
+ '\0^' -- marks start of changed text
1388
+ '\1' -- marks end of added/deleted/changed text
1389
+
1390
+ boolean flag -- None indicates context separation, True indicates
1391
+ either "from" or "to" line contains a change, otherwise False.
1392
+
1393
+ This function/iterator was originally developed to generate side by side
1394
+ file difference for making HTML pages (see HtmlDiff class for example
1395
+ usage).
1396
+
1397
+ Note, this function utilizes the ndiff function to generate the side by
1398
+ side difference markup. Optional ndiff arguments may be passed to this
1399
+ function and they in turn will be passed to ndiff.
1400
+ """
1401
+ import re
1402
+
1403
+ # regular expression for finding intraline change indices
1404
+ change_re = re.compile(r'(\++|\-+|\^+)')
1405
+
1406
+ # create the difference iterator to generate the differences
1407
+ diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk)
1408
+
1409
+ def _make_line(lines, format_key, side, num_lines=[0,0]):
1410
+ """Returns line of text with user's change markup and line formatting.
1411
+
1412
+ lines -- list of lines from the ndiff generator to produce a line of
1413
+ text from. When producing the line of text to return, the
1414
+ lines used are removed from this list.
1415
+ format_key -- '+' return first line in list with "add" markup around
1416
+ the entire line.
1417
+ '-' return first line in list with "delete" markup around
1418
+ the entire line.
1419
+ '?' return first line in list with add/delete/change
1420
+ intraline markup (indices obtained from second line)
1421
+ None return first line in list with no markup
1422
+ side -- indice into the num_lines list (0=from,1=to)
1423
+ num_lines -- from/to current line number. This is NOT intended to be a
1424
+ passed parameter. It is present as a keyword argument to
1425
+ maintain memory of the current line numbers between calls
1426
+ of this function.
1427
+
1428
+ Note, this function is purposefully not defined at the module scope so
1429
+ that data it needs from its parent function (within whose context it
1430
+ is defined) does not need to be of module scope.
1431
+ """
1432
+ num_lines[side] += 1
1433
+ # Handle case where no user markup is to be added, just return line of
1434
+ # text with user's line format to allow for usage of the line number.
1435
+ if format_key is None:
1436
+ return (num_lines[side],lines.pop(0)[2:])
1437
+ # Handle case of intraline changes
1438
+ if format_key == '?':
1439
+ text, markers = lines.pop(0), lines.pop(0)
1440
+ # find intraline changes (store change type and indices in tuples)
1441
+ sub_info = []
1442
+ def record_sub_info(match_object,sub_info=sub_info):
1443
+ sub_info.append([match_object.group(1)[0],match_object.span()])
1444
+ return match_object.group(1)
1445
+ change_re.sub(record_sub_info,markers)
1446
+ # process each tuple inserting our special marks that won't be
1447
+ # noticed by an xml/html escaper.
1448
+ for key,(begin,end) in reversed(sub_info):
1449
+ text = text[0:begin]+'\0'+key+text[begin:end]+'\1'+text[end:]
1450
+ text = text[2:]
1451
+ # Handle case of add/delete entire line
1452
+ else:
1453
+ text = lines.pop(0)[2:]
1454
+ # if line of text is just a newline, insert a space so there is
1455
+ # something for the user to highlight and see.
1456
+ if not text:
1457
+ text = ' '
1458
+ # insert marks that won't be noticed by an xml/html escaper.
1459
+ text = '\0' + format_key + text + '\1'
1460
+ # Return line of text, first allow user's line formatter to do its
1461
+ # thing (such as adding the line number) then replace the special
1462
+ # marks with what the user's change markup.
1463
+ return (num_lines[side],text)
1464
+
1465
+ def _line_iterator():
1466
+ """Yields from/to lines of text with a change indication.
1467
+
1468
+ This function is an iterator. It itself pulls lines from a
1469
+ differencing iterator, processes them and yields them. When it can
1470
+ it yields both a "from" and a "to" line, otherwise it will yield one
1471
+ or the other. In addition to yielding the lines of from/to text, a
1472
+ boolean flag is yielded to indicate if the text line(s) have
1473
+ differences in them.
1474
+
1475
+ Note, this function is purposefully not defined at the module scope so
1476
+ that data it needs from its parent function (within whose context it
1477
+ is defined) does not need to be of module scope.
1478
+ """
1479
+ lines = []
1480
+ num_blanks_pending, num_blanks_to_yield = 0, 0
1481
+ while True:
1482
+ # Load up next 4 lines so we can look ahead, create strings which
1483
+ # are a concatenation of the first character of each of the 4 lines
1484
+ # so we can do some very readable comparisons.
1485
+ while len(lines) < 4:
1486
+ lines.append(next(diff_lines_iterator, 'X'))
1487
+ s = ''.join([line[0] for line in lines])
1488
+ if s.startswith('X'):
1489
+ # When no more lines, pump out any remaining blank lines so the
1490
+ # corresponding add/delete lines get a matching blank line so
1491
+ # all line pairs get yielded at the next level.
1492
+ num_blanks_to_yield = num_blanks_pending
1493
+ elif s.startswith('-?+?'):
1494
+ # simple intraline change
1495
+ yield _make_line(lines,'?',0), _make_line(lines,'?',1), True
1496
+ continue
1497
+ elif s.startswith('--++'):
1498
+ # in delete block, add block coming: we do NOT want to get
1499
+ # caught up on blank lines yet, just process the delete line
1500
+ num_blanks_pending -= 1
1501
+ yield _make_line(lines,'-',0), None, True
1502
+ continue
1503
+ elif s.startswith(('--?+', '--+', '- ')):
1504
+ # in delete block and see an intraline change or unchanged line
1505
+ # coming: yield the delete line and then blanks
1506
+ from_line,to_line = _make_line(lines,'-',0), None
1507
+ num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0
1508
+ elif s.startswith('-+?'):
1509
+ # intraline change
1510
+ yield _make_line(lines,None,0), _make_line(lines,'?',1), True
1511
+ continue
1512
+ elif s.startswith('-?+'):
1513
+ # intraline change
1514
+ yield _make_line(lines,'?',0), _make_line(lines,None,1), True
1515
+ continue
1516
+ elif s.startswith('-'):
1517
+ # delete FROM line
1518
+ num_blanks_pending -= 1
1519
+ yield _make_line(lines,'-',0), None, True
1520
+ continue
1521
+ elif s.startswith('+--'):
1522
+ # in add block, delete block coming: we do NOT want to get
1523
+ # caught up on blank lines yet, just process the add line
1524
+ num_blanks_pending += 1
1525
+ yield None, _make_line(lines,'+',1), True
1526
+ continue
1527
+ elif s.startswith(('+ ', '+-')):
1528
+ # will be leaving an add block: yield blanks then add line
1529
+ from_line, to_line = None, _make_line(lines,'+',1)
1530
+ num_blanks_to_yield,num_blanks_pending = num_blanks_pending+1,0
1531
+ elif s.startswith('+'):
1532
+ # inside an add block, yield the add line
1533
+ num_blanks_pending += 1
1534
+ yield None, _make_line(lines,'+',1), True
1535
+ continue
1536
+ elif s.startswith(' '):
1537
+ # unchanged text, yield it to both sides
1538
+ yield _make_line(lines[:],None,0),_make_line(lines,None,1),False
1539
+ continue
1540
+ # Catch up on the blank lines so when we yield the next from/to
1541
+ # pair, they are lined up.
1542
+ while(num_blanks_to_yield < 0):
1543
+ num_blanks_to_yield += 1
1544
+ yield None,('','\n'),True
1545
+ while(num_blanks_to_yield > 0):
1546
+ num_blanks_to_yield -= 1
1547
+ yield ('','\n'),None,True
1548
+ if s.startswith('X'):
1549
+ return
1550
+ else:
1551
+ yield from_line,to_line,True
1552
+
1553
+ def _line_pair_iterator():
1554
+ """Yields from/to lines of text with a change indication.
1555
+
1556
+ This function is an iterator. It itself pulls lines from the line
1557
+ iterator. Its difference from that iterator is that this function
1558
+ always yields a pair of from/to text lines (with the change
1559
+ indication). If necessary it will collect single from/to lines
1560
+ until it has a matching pair from/to pair to yield.
1561
+
1562
+ Note, this function is purposefully not defined at the module scope so
1563
+ that data it needs from its parent function (within whose context it
1564
+ is defined) does not need to be of module scope.
1565
+ """
1566
+ line_iterator = _line_iterator()
1567
+ fromlines,tolines=[],[]
1568
+ while True:
1569
+ # Collecting lines of text until we have a from/to pair
1570
+ while (len(fromlines)==0 or len(tolines)==0):
1571
+ try:
1572
+ from_line, to_line, found_diff = next(line_iterator)
1573
+ except StopIteration:
1574
+ return
1575
+ if from_line is not None:
1576
+ fromlines.append((from_line,found_diff))
1577
+ if to_line is not None:
1578
+ tolines.append((to_line,found_diff))
1579
+ # Once we have a pair, remove them from the collection and yield it
1580
+ from_line, fromDiff = fromlines.pop(0)
1581
+ to_line, to_diff = tolines.pop(0)
1582
+ yield (from_line,to_line,fromDiff or to_diff)
1583
+
1584
+ # Handle case where user does not want context differencing, just yield
1585
+ # them up without doing anything else with them.
1586
+ line_pair_iterator = _line_pair_iterator()
1587
+ if context is None:
1588
+ yield from line_pair_iterator
1589
+ # Handle case where user wants context differencing. We must do some
1590
+ # storage of lines until we know for sure that they are to be yielded.
1591
+ else:
1592
+ context += 1
1593
+ lines_to_write = 0
1594
+ while True:
1595
+ # Store lines up until we find a difference, note use of a
1596
+ # circular queue because we only need to keep around what
1597
+ # we need for context.
1598
+ index, contextLines = 0, [None]*(context)
1599
+ found_diff = False
1600
+ while(found_diff is False):
1601
+ try:
1602
+ from_line, to_line, found_diff = next(line_pair_iterator)
1603
+ except StopIteration:
1604
+ return
1605
+ i = index % context
1606
+ contextLines[i] = (from_line, to_line, found_diff)
1607
+ index += 1
1608
+ # Yield lines that we have collected so far, but first yield
1609
+ # the user's separator.
1610
+ if index > context:
1611
+ yield None, None, None
1612
+ lines_to_write = context
1613
+ else:
1614
+ lines_to_write = index
1615
+ index = 0
1616
+ while(lines_to_write):
1617
+ i = index % context
1618
+ index += 1
1619
+ yield contextLines[i]
1620
+ lines_to_write -= 1
1621
+ # Now yield the context lines after the change
1622
+ lines_to_write = context-1
1623
+ try:
1624
+ while(lines_to_write):
1625
+ from_line, to_line, found_diff = next(line_pair_iterator)
1626
+ # If another change within the context, extend the context
1627
+ if found_diff:
1628
+ lines_to_write = context-1
1629
+ else:
1630
+ lines_to_write -= 1
1631
+ yield from_line, to_line, found_diff
1632
+ except StopIteration:
1633
+ # Catch exception from next() and return normally
1634
+ return
1635
+
1636
+
1637
+ _file_template = """
1638
+ <!DOCTYPE html>
1639
+ <html lang="en">
1640
+ <head>
1641
+ <meta charset="%(charset)s">
1642
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1643
+ <title>Diff comparison</title>
1644
+ <style>%(styles)s
1645
+ </style>
1646
+ </head>
1647
+
1648
+ <body>
1649
+ %(table)s%(legend)s
1650
+ </body>
1651
+
1652
+ </html>"""
1653
+
1654
+ _styles = """
1655
+ :root {color-scheme: light dark}
1656
+ table.diff {
1657
+ font-family: Menlo, Consolas, Monaco, Liberation Mono, Lucida Console, monospace;
1658
+ border: medium;
1659
+ }
1660
+ .diff_header {
1661
+ background-color: #e0e0e0;
1662
+ font-weight: bold;
1663
+ }
1664
+ td.diff_header {
1665
+ text-align: right;
1666
+ padding: 0 8px;
1667
+ }
1668
+ .diff_next {
1669
+ background-color: #c0c0c0;
1670
+ padding: 4px 0;
1671
+ }
1672
+ .diff_add {background-color:palegreen}
1673
+ .diff_chg {background-color:#ffff77}
1674
+ .diff_sub {background-color:#ffaaaa}
1675
+ table.diff[summary="Legends"] {
1676
+ margin-top: 20px;
1677
+ border: 1px solid #ccc;
1678
+ }
1679
+ table.diff[summary="Legends"] th {
1680
+ background-color: #e0e0e0;
1681
+ padding: 4px 8px;
1682
+ }
1683
+ table.diff[summary="Legends"] td {
1684
+ padding: 4px 8px;
1685
+ }
1686
+
1687
+ @media (prefers-color-scheme: dark) {
1688
+ .diff_header {background-color:#666}
1689
+ .diff_next {background-color:#393939}
1690
+ .diff_add {background-color:darkgreen}
1691
+ .diff_chg {background-color:#847415}
1692
+ .diff_sub {background-color:darkred}
1693
+ table.diff[summary="Legends"] {border-color:#555}
1694
+ table.diff[summary="Legends"] th{background-color:#666}
1695
+ }"""
1696
+
1697
+ _table_template = """
1698
+ <table class="diff" id="difflib_chg_%(prefix)s_top"
1699
+ cellspacing="0" cellpadding="0" rules="groups" >
1700
+ <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
1701
+ <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
1702
+ %(header_row)s
1703
+ <tbody>
1704
+ %(data_rows)s </tbody>
1705
+ </table>"""
1706
+
1707
+ _legend = """
1708
+ <table class="diff" summary="Legends">
1709
+ <tr> <th colspan="2"> Legends </th> </tr>
1710
+ <tr> <td> <table border="" summary="Colors">
1711
+ <tr><th> Colors </th> </tr>
1712
+ <tr><td class="diff_add">&nbsp;Added&nbsp;</td></tr>
1713
+ <tr><td class="diff_chg">Changed</td> </tr>
1714
+ <tr><td class="diff_sub">Deleted</td> </tr>
1715
+ </table></td>
1716
+ <td> <table border="" summary="Links">
1717
+ <tr><th colspan="2"> Links </th> </tr>
1718
+ <tr><td>(f)irst change</td> </tr>
1719
+ <tr><td>(n)ext change</td> </tr>
1720
+ <tr><td>(t)op</td> </tr>
1721
+ </table></td> </tr>
1722
+ </table>"""
1723
+
1724
+ class HtmlDiff(object):
1725
+ """For producing HTML side by side comparison with change highlights.
1726
+
1727
+ This class can be used to create an HTML table (or a complete HTML file
1728
+ containing the table) showing a side by side, line by line comparison
1729
+ of text with inter-line and intra-line change highlights. The table can
1730
+ be generated in either full or contextual difference mode.
1731
+
1732
+ The following methods are provided for HTML generation:
1733
+
1734
+ make_table -- generates HTML for a single side by side table
1735
+ make_file -- generates complete HTML file with a single side by side table
1736
+
1737
+ See Doc/includes/diff.py for an example usage of this class.
1738
+ """
1739
+
1740
+ _file_template = _file_template
1741
+ _styles = _styles
1742
+ _table_template = _table_template
1743
+ _legend = _legend
1744
+ _default_prefix = 0
1745
+
1746
+ def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None,
1747
+ charjunk=IS_CHARACTER_JUNK):
1748
+ """HtmlDiff instance initializer
1749
+
1750
+ Arguments:
1751
+ tabsize -- tab stop spacing, defaults to 8.
1752
+ wrapcolumn -- column number where lines are broken and wrapped,
1753
+ defaults to None where lines are not wrapped.
1754
+ linejunk,charjunk -- keyword arguments passed into ndiff() (used by
1755
+ HtmlDiff() to generate the side by side HTML differences). See
1756
+ ndiff() documentation for argument default values and descriptions.
1757
+ """
1758
+ self._tabsize = tabsize
1759
+ self._wrapcolumn = wrapcolumn
1760
+ self._linejunk = linejunk
1761
+ self._charjunk = charjunk
1762
+
1763
+ def make_file(self, fromlines, tolines, fromdesc='', todesc='',
1764
+ context=False, numlines=5, *, charset='utf-8'):
1765
+ """Returns HTML file of side by side comparison with change highlights
1766
+
1767
+ Arguments:
1768
+ fromlines -- list of "from" lines
1769
+ tolines -- list of "to" lines
1770
+ fromdesc -- "from" file column header string
1771
+ todesc -- "to" file column header string
1772
+ context -- set to True for contextual differences (defaults to False
1773
+ which shows full differences).
1774
+ numlines -- number of context lines. When context is set True,
1775
+ controls number of lines displayed before and after the change.
1776
+ When context is False, controls the number of lines to place
1777
+ the "next" link anchors before the next change (so click of
1778
+ "next" link jumps to just before the change).
1779
+ charset -- charset of the HTML document
1780
+ """
1781
+
1782
+ return (self._file_template % dict(
1783
+ styles=self._styles,
1784
+ legend=self._legend,
1785
+ table=self.make_table(fromlines, tolines, fromdesc, todesc,
1786
+ context=context, numlines=numlines),
1787
+ charset=charset
1788
+ )).encode(charset, 'xmlcharrefreplace').decode(charset)
1789
+
1790
+ def _tab_newline_replace(self,fromlines,tolines):
1791
+ """Returns from/to line lists with tabs expanded and newlines removed.
1792
+
1793
+ Instead of tab characters being replaced by the number of spaces
1794
+ needed to fill in to the next tab stop, this function will fill
1795
+ the space with tab characters. This is done so that the difference
1796
+ algorithms can identify changes in a file when tabs are replaced by
1797
+ spaces and vice versa. At the end of the HTML generation, the tab
1798
+ characters will be replaced with a nonbreakable space.
1799
+ """
1800
+ def expand_tabs(line):
1801
+ # hide real spaces
1802
+ line = line.replace(' ','\0')
1803
+ # expand tabs into spaces
1804
+ line = line.expandtabs(self._tabsize)
1805
+ # replace spaces from expanded tabs back into tab characters
1806
+ # (we'll replace them with markup after we do differencing)
1807
+ line = line.replace(' ','\t')
1808
+ return line.replace('\0',' ').rstrip('\n')
1809
+ fromlines = [expand_tabs(line) for line in fromlines]
1810
+ tolines = [expand_tabs(line) for line in tolines]
1811
+ return fromlines,tolines
1812
+
1813
+ def _split_line(self,data_list,line_num,text):
1814
+ """Builds list of text lines by splitting text lines at wrap point
1815
+
1816
+ This function will determine if the input text line needs to be
1817
+ wrapped (split) into separate lines. If so, the first wrap point
1818
+ will be determined and the first line appended to the output
1819
+ text line list. This function is used recursively to handle
1820
+ the second part of the split line to further split it.
1821
+ """
1822
+ # if blank line or context separator, just add it to the output list
1823
+ if not line_num:
1824
+ data_list.append((line_num,text))
1825
+ return
1826
+
1827
+ # if line text doesn't need wrapping, just add it to the output list
1828
+ size = len(text)
1829
+ max = self._wrapcolumn
1830
+ if (size <= max) or ((size -(text.count('\0')*3)) <= max):
1831
+ data_list.append((line_num,text))
1832
+ return
1833
+
1834
+ # scan text looking for the wrap point, keeping track if the wrap
1835
+ # point is inside markers
1836
+ i = 0
1837
+ n = 0
1838
+ mark = ''
1839
+ while n < max and i < size:
1840
+ if text[i] == '\0':
1841
+ i += 1
1842
+ mark = text[i]
1843
+ i += 1
1844
+ elif text[i] == '\1':
1845
+ i += 1
1846
+ mark = ''
1847
+ else:
1848
+ i += 1
1849
+ n += 1
1850
+
1851
+ # wrap point is inside text, break it up into separate lines
1852
+ line1 = text[:i]
1853
+ line2 = text[i:]
1854
+
1855
+ # if wrap point is inside markers, place end marker at end of first
1856
+ # line and start marker at beginning of second line because each
1857
+ # line will have its own table tag markup around it.
1858
+ if mark:
1859
+ line1 = line1 + '\1'
1860
+ line2 = '\0' + mark + line2
1861
+
1862
+ # tack on first line onto the output list
1863
+ data_list.append((line_num,line1))
1864
+
1865
+ # use this routine again to wrap the remaining text
1866
+ self._split_line(data_list,'>',line2)
1867
+
1868
+ def _line_wrapper(self,diffs):
1869
+ """Returns iterator that splits (wraps) mdiff text lines"""
1870
+
1871
+ # pull from/to data and flags from mdiff iterator
1872
+ for fromdata,todata,flag in diffs:
1873
+ # check for context separators and pass them through
1874
+ if flag is None:
1875
+ yield fromdata,todata,flag
1876
+ continue
1877
+ (fromline,fromtext),(toline,totext) = fromdata,todata
1878
+ # for each from/to line split it at the wrap column to form
1879
+ # list of text lines.
1880
+ fromlist,tolist = [],[]
1881
+ self._split_line(fromlist,fromline,fromtext)
1882
+ self._split_line(tolist,toline,totext)
1883
+ # yield from/to line in pairs inserting blank lines as
1884
+ # necessary when one side has more wrapped lines
1885
+ while fromlist or tolist:
1886
+ if fromlist:
1887
+ fromdata = fromlist.pop(0)
1888
+ else:
1889
+ fromdata = ('',' ')
1890
+ if tolist:
1891
+ todata = tolist.pop(0)
1892
+ else:
1893
+ todata = ('',' ')
1894
+ yield fromdata,todata,flag
1895
+
1896
+ def _collect_lines(self,diffs):
1897
+ """Collects mdiff output into separate lists
1898
+
1899
+ Before storing the mdiff from/to data into a list, it is converted
1900
+ into a single line of text with HTML markup.
1901
+ """
1902
+
1903
+ fromlist,tolist,flaglist = [],[],[]
1904
+ # pull from/to data and flags from mdiff style iterator
1905
+ for fromdata,todata,flag in diffs:
1906
+ try:
1907
+ # store HTML markup of the lines into the lists
1908
+ fromlist.append(self._format_line(0,flag,*fromdata))
1909
+ tolist.append(self._format_line(1,flag,*todata))
1910
+ except TypeError:
1911
+ # exceptions occur for lines where context separators go
1912
+ fromlist.append(None)
1913
+ tolist.append(None)
1914
+ flaglist.append(flag)
1915
+ return fromlist,tolist,flaglist
1916
+
1917
+ def _format_line(self,side,flag,linenum,text):
1918
+ """Returns HTML markup of "from" / "to" text lines
1919
+
1920
+ side -- 0 or 1 indicating "from" or "to" text
1921
+ flag -- indicates if difference on line
1922
+ linenum -- line number (used for line number column)
1923
+ text -- line text to be marked up
1924
+ """
1925
+ try:
1926
+ linenum = '%d' % linenum
1927
+ id = ' id="%s%s"' % (self._prefix[side],linenum)
1928
+ except TypeError:
1929
+ # handle blank lines where linenum is '>' or ''
1930
+ id = ''
1931
+ # replace those things that would get confused with HTML symbols
1932
+ text=text.replace("&","&amp;").replace(">","&gt;").replace("<","&lt;")
1933
+
1934
+ # make space non-breakable so they don't get compressed or line wrapped
1935
+ text = text.replace(' ','&nbsp;').rstrip()
1936
+
1937
+ return '<td class="diff_header"%s>%s</td><td nowrap="nowrap">%s</td>' \
1938
+ % (id,linenum,text)
1939
+
1940
+ def _make_prefix(self):
1941
+ """Create unique anchor prefixes"""
1942
+
1943
+ # Generate a unique anchor prefix so multiple tables
1944
+ # can exist on the same HTML page without conflicts.
1945
+ fromprefix = "from%d_" % HtmlDiff._default_prefix
1946
+ toprefix = "to%d_" % HtmlDiff._default_prefix
1947
+ HtmlDiff._default_prefix += 1
1948
+ # store prefixes so line format method has access
1949
+ self._prefix = [fromprefix,toprefix]
1950
+
1951
+ def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):
1952
+ """Makes list of "next" links"""
1953
+
1954
+ # all anchor names will be generated using the unique "to" prefix
1955
+ toprefix = self._prefix[1]
1956
+
1957
+ # process change flags, generating middle column of next anchors/links
1958
+ next_id = ['']*len(flaglist)
1959
+ next_href = ['']*len(flaglist)
1960
+ num_chg, in_change = 0, False
1961
+ last = 0
1962
+ for i,flag in enumerate(flaglist):
1963
+ if flag:
1964
+ if not in_change:
1965
+ in_change = True
1966
+ last = i
1967
+ # at the beginning of a change, drop an anchor a few lines
1968
+ # (the context lines) before the change for the previous
1969
+ # link
1970
+ i = max([0,i-numlines])
1971
+ next_id[i] = ' id="difflib_chg_%s_%d"' % (toprefix,num_chg)
1972
+ # at the beginning of a change, drop a link to the next
1973
+ # change
1974
+ num_chg += 1
1975
+ next_href[last] = '<a href="#difflib_chg_%s_%d">n</a>' % (
1976
+ toprefix,num_chg)
1977
+ else:
1978
+ in_change = False
1979
+ # check for cases where there is no content to avoid exceptions
1980
+ if not flaglist:
1981
+ flaglist = [False]
1982
+ next_id = ['']
1983
+ next_href = ['']
1984
+ last = 0
1985
+ if context:
1986
+ fromlist = ['<td></td><td>&nbsp;No Differences Found&nbsp;</td>']
1987
+ tolist = fromlist
1988
+ else:
1989
+ fromlist = tolist = ['<td></td><td>&nbsp;Empty File&nbsp;</td>']
1990
+ # if not a change on first line, drop a link
1991
+ if not flaglist[0]:
1992
+ next_href[0] = '<a href="#difflib_chg_%s_0">f</a>' % toprefix
1993
+ # redo the last link to link to the top
1994
+ next_href[last] = '<a href="#difflib_chg_%s_top">t</a>' % (toprefix)
1995
+
1996
+ return fromlist,tolist,flaglist,next_href,next_id
1997
+
1998
+ def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,
1999
+ numlines=5):
2000
+ """Returns HTML table of side by side comparison with change highlights
2001
+
2002
+ Arguments:
2003
+ fromlines -- list of "from" lines
2004
+ tolines -- list of "to" lines
2005
+ fromdesc -- "from" file column header string
2006
+ todesc -- "to" file column header string
2007
+ context -- set to True for contextual differences (defaults to False
2008
+ which shows full differences).
2009
+ numlines -- number of context lines. When context is set True,
2010
+ controls number of lines displayed before and after the change.
2011
+ When context is False, controls the number of lines to place
2012
+ the "next" link anchors before the next change (so click of
2013
+ "next" link jumps to just before the change).
2014
+ """
2015
+
2016
+ # make unique anchor prefixes so that multiple tables may exist
2017
+ # on the same page without conflict.
2018
+ self._make_prefix()
2019
+
2020
+ # change tabs to spaces before it gets more difficult after we insert
2021
+ # markup
2022
+ fromlines,tolines = self._tab_newline_replace(fromlines,tolines)
2023
+
2024
+ # create diffs iterator which generates side by side from/to data
2025
+ if context:
2026
+ context_lines = numlines
2027
+ else:
2028
+ context_lines = None
2029
+ diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,
2030
+ charjunk=self._charjunk)
2031
+
2032
+ # set up iterator to wrap lines that exceed desired width
2033
+ if self._wrapcolumn:
2034
+ diffs = self._line_wrapper(diffs)
2035
+
2036
+ # collect up from/to lines and flags into lists (also format the lines)
2037
+ fromlist,tolist,flaglist = self._collect_lines(diffs)
2038
+
2039
+ # process change flags, generating middle column of next anchors/links
2040
+ fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(
2041
+ fromlist,tolist,flaglist,context,numlines)
2042
+
2043
+ s = []
2044
+ fmt = ' <tr><td class="diff_next"%s>%s</td>%s' + \
2045
+ '<td class="diff_next">%s</td>%s</tr>\n'
2046
+ for i in range(len(flaglist)):
2047
+ if flaglist[i] is None:
2048
+ # mdiff yields None on separator lines skip the bogus ones
2049
+ # generated for the first line
2050
+ if i > 0:
2051
+ s.append(' </tbody> \n <tbody>\n')
2052
+ else:
2053
+ s.append( fmt % (next_id[i],next_href[i],fromlist[i],
2054
+ next_href[i],tolist[i]))
2055
+ if fromdesc or todesc:
2056
+ header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (
2057
+ '<th class="diff_next"><br /></th>',
2058
+ '<th colspan="2" class="diff_header">%s</th>' % fromdesc,
2059
+ '<th class="diff_next"><br /></th>',
2060
+ '<th colspan="2" class="diff_header">%s</th>' % todesc)
2061
+ else:
2062
+ header_row = ''
2063
+
2064
+ table = self._table_template % dict(
2065
+ data_rows=''.join(s),
2066
+ header_row=header_row,
2067
+ prefix=self._prefix[1])
2068
+
2069
+ return table.replace('\0+','<span class="diff_add">'). \
2070
+ replace('\0-','<span class="diff_sub">'). \
2071
+ replace('\0^','<span class="diff_chg">'). \
2072
+ replace('\1','</span>'). \
2073
+ replace('\t','&nbsp;')
2074
+
2075
+
2076
+ def restore(delta, which):
2077
+ r"""
2078
+ Generate one of the two sequences that generated a delta.
2079
+
2080
+ Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
2081
+ lines originating from file 1 or 2 (parameter `which`), stripping off line
2082
+ prefixes.
2083
+
2084
+ Examples:
2085
+
2086
+ >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
2087
+ ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
2088
+ >>> diff = list(diff)
2089
+ >>> print(''.join(restore(diff, 1)), end="")
2090
+ one
2091
+ two
2092
+ three
2093
+ >>> print(''.join(restore(diff, 2)), end="")
2094
+ ore
2095
+ tree
2096
+ emu
2097
+ """
2098
+ try:
2099
+ tag = {1: "- ", 2: "+ "}[int(which)]
2100
+ except KeyError:
2101
+ raise ValueError('unknown delta choice (must be 1 or 2): %r'
2102
+ % which) from None
2103
+ prefixes = (" ", tag)
2104
+ for line in delta:
2105
+ if line[:2] in prefixes:
2106
+ yield line[2:]