ยปCore Development>Code coverage>Lib/difflib.py

Python code coverage for Lib/difflib.py

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