QflEndZgdZddlmZddlmZddlm Z eddZ dZ Gd d Z d$d Z d ZGd dZddlZej"dj$fdZd%dZdZ d&dZdZ d&dZdZ d'dZdefdZddefdZdZdZdZdZ Gdd e!Z"[d!Z#d"Z$e%d#k(re$yy)(ae Module difflib -- helpers for computing deltas between objects. Function get_close_matches(word, possibilities, n=3, cutoff=0.6): Use SequenceMatcher to return list of the best "good enough" matches. Function context_diff(a, b): For two lists of strings, return a delta in context diff format. Function ndiff(a, b): Return a delta: the difference between `a` and `b` (lists of strings). Function restore(delta, which): Return one of the two sequences that generated an ndiff delta. Function unified_diff(a, b): For two lists of strings, return a delta in unified diff format. Class SequenceMatcher: A flexible class for comparing pairs of sequences of any type. Class Differ: For producing human-readable deltas from sequences of lines of text. Class HtmlDiff: For producing HTML side by side comparison with change highlights. ) get_close_matchesndiffrestoreSequenceMatcherDifferIS_CHARACTER_JUNK IS_LINE_JUNK context_diff unified_diff diff_bytesHtmlDiffMatch)nlargest) namedtuple) GenericAliasr za b sizec|rd|z|z Sy)Ng@?)matcheslengths ./opt/alt/python312/lib64/python3.12/difflib.py_calculate_ratior's W}v%% cneZdZdZddZdZdZdZdZddZ d Z d Z dd Z d Z d ZdZeeZy)rao SequenceMatcher is a flexible class for comparing pairs of sequences of any type, so long as the sequence elements are hashable. The basic algorithm predates, and is a little fancier than, an algorithm published in the late 1980's by Ratcliff and Obershelp under the hyperbolic name "gestalt pattern matching". The basic idea is to find the longest contiguous matching subsequence that contains no "junk" elements (R-O doesn't address junk). The same idea is then applied recursively to the pieces of the sequences to the left and to the right of the matching subsequence. This does not yield minimal edit sequences, but does tend to yield matches that "look right" to people. SequenceMatcher tries to compute a "human-friendly diff" between two sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the longest *contiguous* & junk-free matching subsequence. That's what catches peoples' eyes. The Windows(tm) windiff has another interesting notion, pairing up elements that appear uniquely in each sequence. That, and the method here, appear to yield more intuitive difference reports than does diff. This method appears to be the least vulnerable to syncing up on blocks of "junk lines", though (like blank lines in ordinary text files, or maybe "

" lines in HTML files). That may be because this is the only method of the 3 that has a *concept* of "junk" . Example, comparing two strings, and considering blanks to be "junk": >>> s = SequenceMatcher(lambda x: x == " ", ... "private Thread currentThread;", ... "private volatile Thread currentThread;") >>> .ratio() returns a float in [0, 1], measuring the "similarity" of the sequences. As a rule of thumb, a .ratio() value over 0.6 means the sequences are close matches: >>> print(round(s.ratio(), 3)) 0.866 >>> If you're only interested in where the sequences match, .get_matching_blocks() is handy: >>> for block in s.get_matching_blocks(): ... print("a[%d] and b[%d] match for %d elements" % block) a[0] and b[0] match for 8 elements a[8] and b[17] match for 21 elements a[29] and b[38] match for 0 elements Note that the last tuple returned by .get_matching_blocks() is always a dummy, (len(a), len(b), 0), and this is the only case in which the last tuple element (number of elements matched) is 0. If you want to know how to change the first sequence into the second, use .get_opcodes(): >>> for opcode in s.get_opcodes(): ... print("%6s a[%d:%d] b[%d:%d]" % opcode) equal a[0:8] b[0:8] insert a[8:8] b[8:17] equal a[8:29] b[17:38] See the Differ class for a fancy human-friendly file differencer, which uses SequenceMatcher both to compare sequences of lines, and to compare sequences of characters within similar (near-matching) lines. See also function get_close_matches() in this module, which shows how simple code building on SequenceMatcher can be used to do useful work. Timing: Basic R-O is cubic time worst case and quadratic time expected case. SequenceMatcher is quadratic time for the worst case and has expected-case behavior dependent in a complicated way on how many elements the sequences have in common; best case time is linear. Nc`||_dx|_|_||_|j ||y)a!Construct a SequenceMatcher. Optional arg isjunk is None (the default), or a one-argument function that takes a sequence element and returns true iff the element is junk. None is equivalent to passing "lambda x: 0", i.e. no elements are considered to be junk. For example, pass lambda x: x in " \t" if you're comparing lines as sequences of characters, and don't want to synch up on blanks or hard tabs. Optional arg a is the first of two sequences to be compared. By default, an empty string. The elements of a must be hashable. See also .set_seqs() and .set_seq1(). Optional arg b is the second of two sequences to be compared. By default, an empty string. The elements of b must be hashable. See also .set_seqs() and .set_seq2(). Optional arg autojunk should be set to False to disable the "automatic junk heuristic" that treats popular elements as junk (see module documentation for more information). N)isjunkabautojunkset_seqs)selfrrrrs r__init__zSequenceMatcher.__init__xs/v    arcH|j||j|y)zSet the two sequences to be compared. >>> s = SequenceMatcher() >>> s.set_seqs("abcd", "bcde") >>> s.ratio() 0.75 N)set_seq1set_seq2)r!rrs rr zSequenceMatcher.set_seqss a arcL||jury||_dx|_|_y)aMSet the first sequence to be compared. The second sequence to be compared is not changed. >>> s = SequenceMatcher(None, "abcd", "bcde") >>> s.ratio() 0.75 >>> s.set_seq1("bcde") >>> s.ratio() 1.0 >>> SequenceMatcher computes and caches detailed information about the second sequence, so if you want to compare one sequence S against many sequences, use .set_seq2(S) once and call .set_seq1(x) repeatedly for each of the other sequences. See also set_seqs() and set_seq2(). N)rmatching_blocksopcodes)r!rs rr$zSequenceMatcher.set_seq1s(* ; .22t|rcz||jury||_dx|_|_d|_|j y)aMSet the second sequence to be compared. The first sequence to be compared is not changed. >>> s = SequenceMatcher(None, "abcd", "bcde") >>> s.ratio() 0.75 >>> s.set_seq2("abcd") >>> s.ratio() 1.0 >>> SequenceMatcher computes and caches detailed information about the second sequence, so if you want to compare one sequence S against many sequences, use .set_seq2(S) once and call .set_seq1(x) repeatedly for each of the other sequences. See also set_seqs() and set_seq1(). N)rr'r( fullbcount_SequenceMatcher__chain_b)r!rs rr%zSequenceMatcher.set_seq2s9* ; .22t| rc<|j}ix|_}t|D](\}}|j|g}|j |*t x|_}|j}|r9|jD]}||s |j||D]}||=t x|_ }t|} |jrQ| dk\rK| dzdz} |jD]%\}} t| | kDs|j|'|D]}||=yyy)Nd)rb2j enumerate setdefaultappendsetbjunkrkeysaddbpopularlenritems) r!rr0ieltindicesjunkrpopularnntestidxss r __chain_bzSequenceMatcher.__chain_b s FF3lFAsnnS"-G NN1 #  E! T xxz#;HHSM"H#&%'  F ==Q#XHqLE YY[ Tt9u$KK$)H &=rc|j|j|j|jjf\}}}}| t |}| t |}||d} } } i} g} t ||D]e}| j}i}|j||| D];}||kr ||k\rn.||dz ddzx}||<|| kDs*||z dz||z dz|} } } =|} g| |kDr]| |kDrX||| dz sJ|| dz || dz k(r9| dz | dz | dz} } } | |kDr%| |kDr ||| dz s|| dz || dz k(r9| | z|kr\| | z|krT||| | zsF|| | z|| | zk(r5| dz } | | z|kr(| | z|kr ||| | zs|| | z|| | zk(r5| |kDr]| |kDrX||| dz rJ|| dz || dz k(r9| dz | dz | dz} } } | |kDr%| |kDr ||| dz r|| dz || dz k(r9| | z|kr\| | z|krT||| | zrF|| | z|| | zk(r5| dz} | | z|kr(| | z|kr ||| | zr|| | z|| | zk(r5t| | | S)aAFind longest matching block in a[alo:ahi] and b[blo:bhi]. By default it will find the longest match in the entirety of a and b. If isjunk is not defined: Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where alo <= i <= i+k <= ahi blo <= j <= j+k <= bhi and for all (i',j',k') meeting those conditions, k >= k' i <= i' and if i == i', j <= j' In other words, of all maximal matching blocks, return one that starts earliest in a, and of all those maximal matching blocks that start earliest in a, return the one that starts earliest in b. >>> s = SequenceMatcher(None, " abcd", "abcd abcd") >>> s.find_longest_match(0, 5, 0, 9) Match(a=0, b=4, size=5) If isjunk is defined, first the longest matching block is determined as above, but with the additional restriction that no junk element appears in the block. Then that block is extended as far as possible by matching (only) junk elements on both sides. So the resulting block never matches on junk except as identical junk happens to be adjacent to an "interesting" match. Here's the same example as before, but considering blanks to be junk. That prevents " abcd" from matching the " abcd" at the tail end of the second sequence directly. Instead only the "abcd" can match, and matches the leftmost "abcd" in the second sequence: >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") >>> s.find_longest_match(0, 5, 0, 9) Match(a=1, b=0, size=4) If no blocks match, return (alo, blo, 0). >>> s = SequenceMatcher(None, "ab", "c") >>> s.find_longest_match(0, 2, 0, 1) Match(a=0, b=0, size=0) rr/) rrr0r5 __contains__r9rangegetr )r!aloahiblobhirrr0isbjunkbestibestjbestsizej2lennothingr;j2lengetnewj2lenjks rfind_longest_matchz"SequenceMatcher.find_longest_match1s:t"VVTVVTXXtzz7N7NN1c7 ;a&C ;a&C!$c1husCAyyHHWWQqT7+s78"*1Q3"2Q"66HQKx<-.qSUAaCE1(5E,E!(ckeck!E!G*%ajAeAgJ&%*1WeAgxz(5Eckeck!E!G*%ajAeAgJ&Hns"uX~';!E(N+,h1U8^#44 MHHns"uX~';!E(N+,h1U8^#44ckeckaaj!ajAeAgJ&%*1WeAgxz(5Eckeckaaj!ajAeAgJ&Hns"uX~';ah'(h1U8^#44!|HHns"uX~';ah'(h1U8^#44UE8,,rc |j |jSt|jt|j}}d|d|fg}g}|r|j \}}}}|j ||||x\} } } } | r[|j | || kr|| kr|j || || f| | z|kr#| | z|kr|j | | z|| | z|f|r|jdx} x}}g}|D]8\}}}| |z|k(r||z|k(r||z }|r|j | ||f|||}}} :|r|j | ||f|j ||dftttj||_|jS)aReturn list of triples describing matching subsequences. Each triple is of the form (i, j, n), and means that a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in i and in j. New in Python 2.5, it's also guaranteed that if (i, j, n) and (i', j', n') are adjacent triples in the list, and the second is not the last triple in the list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe adjacent equal blocks. The last triple is a dummy, (len(a), len(b), 0), and is the only triple with n==0. >>> s = SequenceMatcher(None, "abxcd", "abcd") >>> list(s.get_matching_blocks()) [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)] r) r'r9rrpoprVr3sortlistmapr _make)r!lalbqueuer'rHrIrJrKr;rTrUxi1j1k1 non_adjacenti2j2k2s rget_matching_blocksz#SequenceMatcher.get_matching_blockss&    +'' 'TVVc$&&kBRB !& Cc311#sCE EGAq!a&&q)7sQwLL#q#q!12Q391sLL!A#sAaC!56  R" )JBBBw"}bBb  ''R 5RB*    R -b"a[*#C \$BC###rc4|j |jSdx}}gx|_}|jD]_\}}}d}||kr||krd}n||krd}n||krd}|r|j|||||f||z||z}}|sJ|jd||||fa|S)a[Return list of 5-tuples describing how to turn a into b. Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the tuple preceding it, and likewise for j1 == the previous j2. The tags are strings, with these meanings: 'replace': a[i1:i2] should be replaced by b[j1:j2] 'delete': a[i1:i2] should be deleted. Note that j1==j2 in this case. 'insert': b[j1:j2] should be inserted at a[i1:i1]. Note that i1==i2 in this case. 'equal': a[i1:i2] == b[j1:j2] >>> a = "qabxcd" >>> b = "abycdf" >>> s = SequenceMatcher(None, a, b) >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))) delete a[0:1] (q) b[0:0] () equal a[1:3] (ab) b[0:2] (ab) replace a[3:4] (x) b[2:3] (y) equal a[4:6] (cd) b[3:5] (cd) insert a[6:6] () b[5:6] (f) rreplacedeleteinsertequal)r(rhr3)r!r;rTansweraibjsizetags r get_opcodeszSequenceMatcher.get_opcodess: << #<<  A "" v 446LBD C2v!b&RR QAr24d7BtGqA QA68'7( rc #vK|j}|sdg}|dddk(r/|d\}}}}}|t|||z |t|||z |f|d<|dddk(r/|d\}}}}}||t|||z|t|||zf|d<||z}g} |D]\}}}}}|dk(r\||z |kDrT| j||t|||z|t|||zf| g} t|||z t|||z }}| j|||||f| rt | dk(r | dddk(s| yyyw)a Isolate change clusters by eliminating ranges with no changes. Return a generator of groups with up to n lines of context. Each group is in the same format as returned by get_opcodes(). >>> from pprint import pprint >>> a = list(map(str, range(1,40))) >>> b = a[:] >>> b[8:8] = ['i'] # Make an insertion >>> b[20] += 'x' # Make a replacement >>> b[23:28] = [] # Make a deletion >>> b[30] += 'y' # Make another replacement >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes())) [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)], [('equal', 16, 19, 17, 20), ('replace', 19, 20, 20, 21), ('equal', 20, 22, 21, 23), ('delete', 22, 27, 23, 23), ('equal', 27, 30, 23, 26)], [('equal', 31, 34, 27, 30), ('replace', 34, 35, 30, 31), ('equal', 35, 38, 31, 34)]] )rnrr/rr/rrnr/N)rtmaxminr3r9) r!r@codesrsrarerbrfnngroups rget_grouped_opcodesz#SequenceMatcher.get_grouped_opcodes#s2  "*+E 8A;' !"'( CRRCBqDM2s2r!t}b@E!H 9Q<7 ""') CRRRRACBqDMAE"I U#( CRRg~"R%"* c2s2r!t}b#b"Q$-HI RAB1 B LL#r2r2. /$) #e*a-E!HQK7,BK-C5sD7D9ctd|jD}t|t|jt|j zS)aReturn a measure of the sequences' similarity (float in [0,1]). Where T is the total number of elements in both sequences, and M is the number of matches, this is 2.0*M / T. Note that this is 1 if the sequences are identical, and 0 if they have nothing in common. .ratio() is expensive to compute if you haven't already computed .get_matching_blocks() or .get_opcodes(), in which case you may want to try .quick_ratio() or .real_quick_ratio() first to get an upper bound. >>> s = SequenceMatcher(None, "abcd", "bcde") >>> s.ratio() 0.75 >>> s.quick_ratio() 0.75 >>> s.real_quick_ratio() 1.0 c3&K|] }|d yw)rvNr).0triples r z(SequenceMatcher.ratio..ksJ/IVfRj/Is)sumrhrr9rr)r!rs rratiozSequenceMatcher.ratioUs?,Jt/G/G/IJJTVVs466{)BCCrc|j2ix|_}|jD]}|j|ddz||<|j}i}|jd}}|jD]5}||r||}n|j|d}|dz ||<|dkDs1|dz}7t |t |jt |jzS)zReturn an upper bound on ratio() relatively quickly. This isn't defined beyond that it is an upper bound on .ratio(), and is faster to compute. rr/)r*rrGrErrr9)r!r*r<availavailhasrnumbs r quick_ratiozSequenceMatcher.quick_rations ?? "+- -DOjvv",..a"81"< 3__ !..'66C}Sz!~~c1-E#Jax!A+ TVVs466{)BCCrct|jt|j}}tt ||||zS)zReturn an upper bound on ratio() very quickly. This isn't defined beyond that it is an upper bound on .ratio(), and is faster to compute than either .ratio() or .quick_ratio(). )r9rrrrx)r!r]r^s rreal_quick_ratioz SequenceMatcher.real_quick_ratios6TVVc$&&kB B R"W55r)NrjrjT)rNrN))__name__ __module__ __qualname____doc__r"r r$r%r+rVrhrtr|rrr classmethodr__class_getitem__rrrrr,s]HT>@ 34X%Nr-hE$N5n0dD2D: 6$L1rrc|dkDstd|d|cxkrdksntd|g}t}|j||D]p}|j||j |k\s(|j |k\s<|j |k\sP|j|j |frt||}|Dcgc]\}}| c}}Scc}}w)aUse SequenceMatcher to return list of the best "good enough" matches. word is a sequence for which close matches are desired (typically a string). possibilities is a list of sequences against which to match word (typically a list of strings). Optional arg n (default 3) is the maximum number of close matches to return. n must be > 0. Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities that don't score at least that similar to word are ignored. The best (no more than n) matches among the possibilities are returned in a list, sorted by similarity score, most similar first. >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"]) ['apple', 'ape'] >>> import keyword as _keyword >>> get_close_matches("wheel", _keyword.kwlist) ['while'] >>> get_close_matches("Apple", _keyword.kwlist) [] >>> get_close_matches("accept", _keyword.kwlist) ['except'] rzn must be > 0: grzcutoff must be in [0.0, 1.0]: ) ValueErrorrr%r$rrrr3 _nlargest)word possibilitiesr@cutoffresultsr`scores rrrs: 6344 & C vGHH FAJJt  1   6 ) ==?f $ 779  MM1779a. ) q& !F$ %f(%Af %% %s C"cFdjdt||DS)zAReplace whitespace with the original whitespace characters in `s`rjc3TK|] \}}|dk(r|jr|n|"yw) N)isspace)rctag_cs rrz$_keep_original_ws..s/%HAuc\aiiku4%s&()joinzip)rtag_ss r_keep_original_wsrs& 77Au  rc<eZdZdZd dZdZdZdZdZdZ d Z y) ra Differ is a class for comparing sequences of lines of text, and producing human-readable differences or deltas. Differ uses SequenceMatcher both to compare sequences of lines, and to compare sequences of characters within similar (near-matching) lines. Each line of a Differ delta begins with a two-letter code: '- ' line unique to sequence 1 '+ ' line unique to sequence 2 ' ' line common to both sequences '? ' line not present in either input sequence Lines beginning with '? ' attempt to guide the eye to intraline differences, and were not present in either input sequence. These lines can be confusing if the sequences contain tab characters. Note that Differ makes no claim to produce a *minimal* diff. To the contrary, minimal diffs are often counter-intuitive, because they synch up anywhere possible, sometimes accidental matches 100 pages apart. Restricting synch points to contiguous matches preserves some notion of locality, at the occasional cost of producing a longer diff. Example: Comparing two texts. First we set up the texts, sequences of individual single-line strings ending with newlines (such sequences can also be obtained from the `readlines()` method of file-like objects): >>> text1 = ''' 1. Beautiful is better than ugly. ... 2. Explicit is better than implicit. ... 3. Simple is better than complex. ... 4. Complex is better than complicated. ... '''.splitlines(keepends=True) >>> len(text1) 4 >>> text1[0][-1] '\n' >>> text2 = ''' 1. Beautiful is better than ugly. ... 3. Simple is better than complex. ... 4. Complicated is better than complex. ... 5. Flat is better than nested. ... '''.splitlines(keepends=True) Next we instantiate a Differ object: >>> d = Differ() Note that when instantiating a Differ object we may pass functions to filter out line and character 'junk'. See Differ.__init__ for details. Finally, we compare the two: >>> result = list(d.compare(text1, text2)) 'result' is a list of strings, so let's pretty-print it: >>> from pprint import pprint as _pprint >>> _pprint(result) [' 1. Beautiful is better than ugly.\n', '- 2. Explicit is better than implicit.\n', '- 3. Simple is better than complex.\n', '+ 3. Simple is better than complex.\n', '? ++\n', '- 4. Complex is better than complicated.\n', '? ^ ---- ^\n', '+ 4. Complicated is better than complex.\n', '? ++++ ^ ^\n', '+ 5. Flat is better than nested.\n'] As a single multi-line string it looks like this: >>> print(''.join(result), end="") 1. Beautiful is better than ugly. - 2. Explicit is better than implicit. - 3. Simple is better than complex. + 3. Simple is better than complex. ? ++ - 4. Complex is better than complicated. ? ^ ---- ^ + 4. Complicated is better than complex. ? ++++ ^ ^ + 5. Flat is better than nested. Nc ||_||_y)a Construct a text differencer, with optional filters. The two optional keyword parameters are for filter functions: - `linejunk`: A function that should accept a single string argument, and return true iff the string is junk. The module-level function `IS_LINE_JUNK` may be used to filter out lines without visible characters, except for at most one splat ('#'). It is recommended to leave linejunk None; the underlying SequenceMatcher class has an adaptive notion of "noise" lines that's better than any static definition the author has ever been able to craft. - `charjunk`: A function that should accept a string of length 1. The module-level function `IS_CHARACTER_JUNK` may be used to filter out whitespace characters (a blank or tab; **note**: bad idea to include newline in this!). Use of IS_CHARACTER_JUNK is recommended. Nlinejunkcharjunk)r!rrs rr"zDiffer.__init__*s(!   rc #xKt|j||}|jD]\}}}}}|dk(r|j||||||} n\|dk(r|j d|||} nB|dk(r|j d|||} n(|dk(r|j d|||} nt d|| Ed {y 7w) a Compare two sequences of lines; generate the resulting delta. Each sequence must contain individual single-line strings ending with newlines. Such sequences can be obtained from the `readlines()` method of file-like objects. The delta generated also consists of newline- terminated strings, ready to be printed as-is via the writelines() method of a file-like object. Example: >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(True), ... 'ore\ntree\nemu\n'.splitlines(True))), ... end="") - one ? ^ + ore ? ^ - two - three ? - + tree + emu rkrl-rm+rnr unknown tag N)rrrt_fancy_replace_dumpr) r!rrcruncherrsrHrIrJrKgs rcomparezDiffer.compareAs4#4==!Q7'/';';'= #Cc3i''3QSAJJsAsC0JJsAsC0JJsAsC0 S!:;;LL(> sB.B:0B81B:c#FKt||D]}|d||yw)z4Generate comparison results for a same-tagged range.rN)rF)r!rsr`lohir;s rrz Differ._dumpjs%r2A !A$' 's!c#K||kr||ksJ||z ||z kr)|jd|||}|jd|||}n(|jd|||}|jd|||}||fD] } | Ed{y7w)Nrr)r) r!rrHrIrrJrKfirstsecondrs r_plain_replacezDiffer._plain_replaceosSyS3Y&& 9sSy ZZQS1EZZQS1FZZQS1EZZQS1FALL sA5B7A?8Bc#Kd\}}t|j} d\} } t||D]} || } | j| t||D]t}||}|| k(r| || } } | j || j |kDs9| j |kDsM| j|kDsa| j|| }}}v||kr(| |j||||||Ed{y| | d}}}nd} |j||||Ed{||||}}| dx}}| j||| jD]g\}}}}}||z ||z }}|dk(r|d|zz }|d|zz })|dk(r |d |zz }7|d k(r |d |zz }E|d k(r|d |zz }|d |zz }[td||j||||Ed{nd|z|j||dz|||dz|Ed{y77767 w)aL When replacing one block of lines with another, search the blocks for *similar* lines; the best-matching pair (if any) is used as a synch point, and intraline difference marking is done on the similar pair. Lots of work, but often worth it. Example: >>> d = Differ() >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1, ... ['abcdefGhijkl\n'], 0, 1) >>> print(''.join(results), end="") - abcDefghiJkl ? ^ ^ ^ + abcdefGhijkl ? ^ ^ ^ )gGz?g?NNNrrjrk^rlrrmrrnrr r/)rrrFr%r$rrrr _fancy_helperr rtr_qformat)r!rrHrIrrJrK best_ratiorreqieqjrTrqr;rpbest_ibest_jaeltbeltatagsbtagsrsai1ai2bj1bj2r]r^s rrzDiffer._fancy_replace}s*( F"4==1S sCA1B   b !3_qT8{#$aS!!"%,,.;**,z9nn&3191A1aJ!%!(  {..q#sAsCHHH),c3JFFC %%afafEEEvY& d ; EE   dD )+3+?+?+A'S#sCsC#IB)#S2X%ES2X%EH_S2X%EH_S2X%EG^S2X%ES2X%E$%>??,B}}T4> > >+ %%a36!8SIIIQI F, ? Js[B H H H48H,G>-'HHB7H H +H8H9HHHHc#Kg}||kr1||kr|j||||||}n.|jd|||}n||kr|jd|||}|Ed{y7w)Nrr)rr)r!rrHrIrrJrKrs rrzDiffer._fancy_helpersi  9Sy''3QSAJJsAsC0 3Y 33,A sAA!AA!c#Kt||j}t||j}d|z|rd|dd|z|r d|dyyw)a Format "?" output and deal with tabs. Example: >>> d = Differ() >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n', ... ' ^ ^ ^ ', ' ^ ^ ^ ') >>> for line in results: print(repr(line)) ... '- \tabcDefghiJkl\n' '? \t ^ ^ ^\n' '+ \tabcdefGhijkl\n' '? \t ^ ^ ^\n' - z?  + N)rrstrip)r!alineblinerrs rrzDiffer._qformatsm "%/668!%/668Ul ugR. Ul ugR.  sAAr) rrrrr"rrrrrrrrrrrs0Sj!.'R( \J| !rrNz \s*(?:#\s*)?$c||duS)z Return True for ignorable line: iff `line` is blank or contains a single '#'. Examples: >>> IS_LINE_JUNK('\n') True >>> IS_LINE_JUNK(' # \n') True >>> IS_LINE_JUNK('hello\n') False Nr)linepats rrrs t9D  rc ||vS)z Return True for ignorable character: iff `ch` is a space or tab. Examples: >>> IS_CHARACTER_JUNK(' ') True >>> IS_CHARACTER_JUNK('\t') True >>> IS_CHARACTER_JUNK('\n') False >>> IS_CHARACTER_JUNK('x') False r)chwss rrr%s 8Orct|dz}||z }|dk(rdj|S|s|dz}dj||Sz Convert range to the "ed" formatr/z{}z{},{}formatstartstop beginningrs r_format_range_unifiedr<sI I E\F {{{9%% Q >>)V ,,rc #HKt|||||||d}td||j|D]} |sVd}|rdj|nd} |rdj|nd} dj|| |dj|| || d| d } } t | d | d }t | d | d }dj|||| D]J\}}}}}|dk(r|||D] }d|z  |dvr|||D] }d|z |dvs:|||D] }d|z Lyw)a Compare two sequences of lines; generate the delta as a unified diff. Unified diffs are a compact way of showing line changes and a few lines of context. The number of context lines is set by 'n' which defaults to three. By default, the diff control lines (those with ---, +++, or @@) are created with a trailing newline. This is helpful so that inputs created from file.readlines() result in diffs that are suitable for file.writelines() since both the inputs and outputs have trailing newlines. For inputs that do not have trailing newlines, set the lineterm argument to "" so that the output will be uniformly newline free. The unidiff format normally has a header for filenames and modification times. Any or all of these may be specified using strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. The modification times are normally expressed in the ISO 8601 format. Example: >>> for line in unified_diff('one two three four'.split(), ... 'zero one tree four'.split(), 'Original', 'Current', ... '2005-01-26 23:30:50', '2010-04-02 10:20:52', ... lineterm=''): ... print(line) # doctest: +NORMALIZE_WHITESPACE --- Original 2005-01-26 23:30:50 +++ Current 2010-04-02 10:20:52 @@ -1,4 +1,4 @@ +zero one -two -three +tree four FNT {}rj --- {}{}{}z +++ {}{}{}rrvr/rz@@ -{} +{} @@{}rnr>rlrkr>rmrkr) _check_typesrr|rr)rrfromfiletofile fromfiledate tofiledater@linetermstartedr{fromdatetodaterlast file1_range file2_rangersrarerbrfrs rr r GsdRAxz8LG a*>>qAG6Bv}}\2H2 +E!Hd1g> &&{KJJ#( CRRg~bHD*$%++bHD*$%++bHD*$%$)Bs D D" D"c|dz}||z }|s|dz}|dkrdj|Sdj|||zdz Srrrs r_format_range_contextrsS I E\F Q  {{{9%% >>)Y%7!%; <>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(True), ... 'zero\none\ntree\nfour\n'.splitlines(True), 'Original', 'Current')), ... end="") *** Original --- Current *************** *** 1,4 **** one ! two ! three four --- 1,4 ---- + zero one ! tree four rrz! r)rmrlrkrnFNTrrjz *** {}{}{}rrrvz***************r/rz *** {} ****{}c30K|]\}}}}}|dvyw)>rlrkNrrrs_s rrzcontext_diff..!I5Q1as++5rmrrz --- {} ----{}c30K|]\}}}}}|dvyw)>rmrkNrrs rrzcontext_diff..rrrl)rdictrr|rrany)rrrrrrr@rprefixrr{rrrrrrsrarerrrrbrfs rr r sXAxz8L dD EFG a*>>qAG6Bv}}\2H2 $$[(;; I5I I%*!RQ(? !"R$SkD00!)&+ ,E!Hd1g> $$[(;; I5I I%*!Q2r(? !"R$SkD00!)&+1BsC4E27AE2E2E2cN|r>t|dts+tdt|djd|dd|r>t|dts+tdt|djd|dd|D] }t|trtd|y)Nrz"lines to compare must be str, not  ()z all arguments must be str, not: ) isinstancestr TypeErrortyper)rrargsargs rrrs AaD#&ad,,ad45 5AaD#&ad,,ad45 5#s#CIJ Jrc # Kd} tt| |}tt| |}| |}| |}| |}| |}| |}|||||||||} | D]} | jddyw)a Compare `a` and `b`, two sequences of lines represented as bytes rather than str. This is a wrapper for `dfunc`, which is typically either unified_diff() or context_diff(). Inputs are losslessly converted to strings so that `dfunc` only has to worry about strings, and encoded back to bytes on return. This is necessary to compare files with unknown or inconsistent encoding. All other inputs (except `n`) must be bytes rather than str. c |jddS#t$r-}dt|jd|d}t ||d}~wwxYw)Nasciisurrogateescapez!all arguments must be bytes, not rr)decodeAttributeErrorrrr)rerrmsgs rrzdiff_bytes..decodesK *88G%67 7 *G$$a)CC.c ) *s A (AA r r N)rZr[encode) dfuncrrrrrrr@rrlinesrs rr r s* S^A S^AhH F^F,'L #JhH !Q&, Ax PEkk'#455sBBc:t||j||S)aJ Compare `a` and `b` (lists of strings); return a `Differ`-style delta. Optional keyword parameters `linejunk` and `charjunk` are for filter functions, or can be None: - linejunk: A function that should accept a single string argument and return true iff the string is junk. The default is None, and is recommended; the underlying SequenceMatcher class has an adaptive notion of "noise" lines. - charjunk: A function that accepts a character (string of length 1), and returns true iff the character is junk. The default is the module-level function IS_CHARACTER_JUNK, which filters out whitespace characters (a blank or tab; note: it's a bad idea to include newline in this!). Tools/scripts/ndiff.py is a command-line front-end to this function. Example: >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True), ... 'ore\ntree\nemu\n'.splitlines(keepends=True)) >>> print(''.join(diff), end="") - one ? ^ + ore ? ^ - two - three ? - + tree + emu )rr)rrrrs rrrsF (H % - -a 33rc#Kddl}|jdt||||ddgffd fdfd}|}| |Ed{y|dz }d} ddg|z} } d} | dur' t|\} } } | |z}| | | f| |<| dz } | dur'| |kDrd |}n| }d} |r| |z}| dz } | ||dz}|r|dz } |r&t|\} } } | r|dz }n|dz}| | | f|r&7#t$rYywxYw#t$rYywxYww) aReturns generator yielding marked up from/to side by side differences. Arguments: fromlines -- list of text lines to compared to tolines tolines -- list of text lines to be compared to fromlines context -- number of context lines to display on each side of difference, if None, all from/to text lines will be generated. linejunk -- passed on to ndiff (see ndiff documentation) charjunk -- passed on to ndiff (see ndiff documentation) This function returns an iterator which returns a tuple: (from line tuple, to line tuple, boolean flag) from/to line tuple -- (line num, line text) line num -- integer or None (to indicate a context separation) line text -- original line text with following markers inserted: '\0+' -- marks start of added text '\0-' -- marks start of deleted text '\0^' -- marks start of changed text '\1' -- marks end of added/deleted/changed text boolean flag -- None indicates context separation, True indicates either "from" or "to" line contains a change, otherwise False. This function/iterator was originally developed to generate side by side file difference for making HTML pages (see HtmlDiff class for example usage). Note, this function utilizes the ndiff function to generate the side by side difference markup. Optional ndiff arguments may be passed to this function and they in turn will be passed to ndiff. rNz (\++|\-+|\^+)c||xxdz cc<||||jdddfS|dk(rq|jd|jd}}g}|fd} j||t|D]"\}\} } |d| dz|z|| | zdz|| dz}$|dd}n#|jddd}|sd }d|z|zdz}|||fS) aReturns line of text with user's change markup and line formatting. lines -- list of lines from the ndiff generator to produce a line of text from. When producing the line of text to return, the lines used are removed from this list. format_key -- '+' return first line in list with "add" markup around the entire line. '-' return first line in list with "delete" markup around the entire line. '?' return first line in list with add/delete/change intraline markup (indices obtained from second line) None return first line in list with no markup side -- indice into the num_lines list (0=from,1=to) num_lines -- from/to current line number. This is NOT intended to be a passed parameter. It is present as a keyword argument to maintain memory of the current line numbers between calls of this function. Note, this function is purposefully not defined at the module scope so that data it needs from its parent function (within whose context it is defined) does not need to be of module scope. r/Nrr?c|j|jdd|jg|jdS)Nr/r)r3r{span) match_objectsub_infos rrecord_sub_infoz3_mdiff.._make_line..record_sub_infos=!3!3A!6q!9,:K:K:M NO#))!,,rr)rXsubreversed) r format_keyside num_linestextmarkersrrkeybeginend change_res r _make_linez_mdiff.._make_linefs. $1  dOEIIaL$45 5  !IIaL%))A,'DH6> - MM/' 2$,H#5KU3Ae}T)#-d5o=dB4:M$68D99Q<#D*$t+d2D$%%rc3Kg}d\}} t|dkr*|jtdt|dkr*dj|Dcgc]}|d c}}|j dr|}n|j dr|dd|dd df|j d r|d z}|d dd df|j d r|d dd }}|d z d}}n|j dr|d d|dd df|j dr|dd|d d df9|j d r|d z}|d dd df`|j dr|d z }d |dd df|j drd |dd }}|d zd}}nT|j dr|d z }d |dd df|j dr|d d d d|d d df|dkr|d z }d|dkr|dkDr|d z}d|dkDr|j dry dfBcc}ww)aYields from/to lines of text with a change indication. This function is an iterator. It itself pulls lines from a differencing iterator, processes them and yields them. When it can it yields both a "from" and a "to" line, otherwise it will yield one or the other. In addition to yielding the lines of from/to text, a boolean flag is yielded to indicate if the text line(s) have differences in them. Note, this function is purposefully not defined at the module scope so that data it needs from its parent function (within whose context it is defined) does not need to be of module scope. )rrTrXrjrz-?+?rr/z--++rN)z--?+z--+rz-+?z-?+z+--r)rz+-rF)NrjrT)r.NT)r9r3nextr startswith) rnum_blanks_pendingnum_blanks_to_yieldrr from_lineto_liner+diff_lines_iterators r_line_iteratorz_mdiff.._line_iterators26//e*q. T"5s;<e*q.U3UTaU34A||C '9#f% s1-z%A/FLLf%#a'" s1-tT9934%/uS$;T' 9KA9Ma$6#e$ tA. 5Q0GMMe$ s1-z%Q/GMMc""a'" s1-tT99e$#a'"JuS3T99l+%):eC+B7 9KA9Ma$6#c""a'"JuS3T99c" q$q1*U42J5PP&)#q(#))&)&)#q(#))&)||C ,,M 4s%AII IF?II3 Ic3K}gg}} t|dk(st|dk(rX t|\}}}||j||f||j||ft|dk(rIt|dk(rX|j d\}}|j d\}}|||xs|f#t$rYywxYww)atYields from/to lines of text with a change indication. This function is an iterator. It itself pulls lines from the line iterator. Its difference from that iterator is that this function always yields a pair of from/to text lines (with the change indication). If necessary it will collect single from/to lines until it has a matching pair from/to pair to yield. Note, this function is purposefully not defined at the module scope so that data it needs from its parent function (within whose context it is defined) does not need to be of module scope. rN)r9r/ StopIterationr3rX) line_iterator fromlinestolinesr3r4 found_difffromDiffto_diffr6s r_line_pair_iteratorz#_mdiff.._line_pair_iterators'( R' y>1$G a59-5H2Iw ($$i %;<&NNGJ#78y>1$G a#,--"2 Ix&{{1~ GWWX%89 9 %s3)CB88C5C4C8 CCCCr/F)NNN)recompilerr/r8)r:r;contextrrr@r?line_pair_iteratorlines_to_writeindex contextLinesr<r3r4r;r6r+r*r5s @@@@r_mdiffrG<sD +,I '(8D78e6&pV-p:B-.%%% 1 #$dVW%5 %(table)s%(legend)s aH table.diff {font-family:Courier; border:medium;} .diff_header {background-color:#e0e0e0} td.diff_header {text-align:right} .diff_next {background-color:#c0c0c0} .diff_add {background-color:#aaffaa} .diff_chg {background-color:#ffff77} .diff_sub {background-color:#ffaaaa}aZ %(header_row)s %(data_rows)s
a
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op
c|eZdZdZeZeZeZeZdZddde fdZ ddddZ d Z d Z d Zd Zd ZdZdZ ddZy)r a{For producing HTML side by side comparison with change highlights. This class can be used to create an HTML table (or a complete HTML file containing the table) showing a side by side, line by line comparison of text with inter-line and intra-line change highlights. The table can be generated in either full or contextual difference mode. The following methods are provided for HTML generation: make_table -- generates HTML for a single side by side table make_file -- generates complete HTML file with a single side by side table See tools/scripts/diff.py for an example usage of this class. rNc<||_||_||_||_y)aHtmlDiff instance initializer Arguments: tabsize -- tab stop spacing, defaults to 8. wrapcolumn -- column number where lines are broken and wrapped, defaults to None where lines are not wrapped. linejunk,charjunk -- keyword arguments passed into ndiff() (used by HtmlDiff() to generate the side by side HTML differences). See ndiff() documentation for argument default values and descriptions. N)_tabsize _wrapcolumn _linejunk _charjunk)r!tabsize wrapcolumnrrs rr"zHtmlDiff.__init__s!  %!!rzutf-8)charsetc |jt|j|j|j |||||||zj |dj |S)aReturns HTML file of side by side comparison with change highlights Arguments: fromlines -- list of "from" lines tolines -- list of "to" lines fromdesc -- "from" file column header string todesc -- "to" file column header string context -- set to True for contextual differences (defaults to False which shows full differences). numlines -- number of context lines. When context is set True, controls number of lines displayed before and after the change. When context is False, controls the number of lines to place the "next" link anchors before the next change (so click of "next" link jumps to just before the change). charset -- charset of the HTML document )rBnumlines)styleslegendtablerQxmlcharrefreplace)_file_templater_styles_legend make_tablerr)r!r:r;fromdesctodescrBrSrQs r make_filezHtmlDiff.make_filesf&##d<<<<//)Wh*1H"F '  6'. /w  @rc~fd}|Dcgc] }|| }}|Dcgc] }|| }}||fScc}wcc}w)aReturns from/to line lists with tabs expanded and newlines removed. Instead of tab characters being replaced by the number of spaces needed to fill in to the next tab stop, this function will fill the space with tab characters. This is done so that the difference algorithms can identify changes in a file when tabs are replaced by spaces and vice versa. At the end of the HTML generation, the tab characters will be replaced with a nonbreakable space. c|jdd}|jj}|jdd}|jddjdS)Nrr r)rk expandtabsrKr)rr!s r expand_tabsz2HtmlDiff._tab_newline_replace..expand_tabssS<<D)D??4==1D<<D)D<<S)006 6rr)r!r:r;rcrs` r_tab_newline_replacezHtmlDiff._tab_newline_replacesO 74==94[&9 =189;t$9  >9s5:c|s|j||fyt|}|j}||ks||jddzz |kr|j||fyd}d}d}||krB||kr=||dk(r|dz }||}|dz }n||dk(r|dz }d}n |dz }|dz }||kr||kr=|d|} ||d} |r | dz} d|z| z} |j|| f|j |d| y) aBuilds list of text lines by splitting text lines at wrap point This function will determine if the input text line needs to be wrapped (split) into separate lines. If so, the first wrap point will be determined and the first line appended to the output text line list. This function is used recursively to handle the second part of the split line to further split it. Nrrrrjr/r>)r3r9rLcount _split_line) r! data_listline_numr%rrrwr;r@markline1line2s rrhzHtmlDiff._split_linesC   ht_ - 4y CKdTZZ%5a%78S@   ht_ -   #g!d(Aw$QAwQaDQQQ#g!d(RaQR DLE4K%'E (5)* 3u-rc#K|D]\}}}||||f||c\}}\}}gg} } |j| |||j| ||| s| sK| r| jd}nd}| r| jd}nd}|||f| r6| r9yw)z5Returns iterator that splits (wraps) mdiff text linesNr)rjr)rhrX) r!diffsfromdatatodataflagfromlinefromtexttolinetotextfromlisttolists r _line_wrapperzHtmlDiff._line_wrappers%* HVD|vd**2:6 / Xh!VH   Xhx 8   VF6 2f'||AH'H#ZZ]F%Fvd**f%*sA B 5B B  B c@ggg}}}|D]^\}}} |j|jd|g||j|jd|g||j|`|||fS#t$r%|jd|jdYEwxYw)zCollects mdiff output into separate lists Before storing the mdiff from/to data into a list, it is converted into a single line of text with HTML markup. rr/N)r3 _format_liner)r!rorwrxflaglistrprqrrs r_collect_lineszHtmlDiff._collect_lines.s$&b$) HVD $ 1 1 1!D C( CD /d//$??@ OOD !%*x''  $% d# $sAA//+BBc d|z}d|j||d}|jddjddjd d }|jd d j}d |d|d|dS#t$rd}YkwxYw)aReturns HTML markup of "from" / "to" text lines side -- 0 or 1 indicating "from" or "to" text flag -- indicates if difference on line linenum -- line number (used for line number column) text -- line text to be marked up z%dz id=""rj&z&rfz>z)_prefixrrkr)r!r#rrlinenumr%ids rr{zHtmlDiff._format_lineCs WnG!%d!3GnFz2 No Differences Found z( Empty File z!fz#t)rr9r1rw)r!rwrxr|rBrSrnext_id next_hrefnum_chg in_changerr;rrs r_convert_flagszHtmlDiff._convert_flagses'<<?$s8}$DX& %)FAd $IDQqzN+A!:hw=O!OGAJqLG&J!'N+'+IdO" !*$wHdGIDPQ!%O$PP6{>IIaL?8L $x '99rc D|j|j||\}}|r|}nd}t||||j|j}|j r|j |}|j|\} } } |j| | | ||\} } } } } g}d}tt| D]G}| ||dkDs|jd |j|| || || || || |fzI|s|rddd|zdd|zd }nd }|jtd j|||jd  z}|j!d dj!ddj!ddj!ddj!ddS)aReturns HTML table of side by side comparison with change highlights Arguments: fromlines -- list of "from" lines tolines -- list of "to" lines fromdesc -- "from" file column header string todesc -- "to" file column header string context -- set to True for contextual differences (defaults to False which shows full differences). numlines -- number of context lines. When context is set True, controls number of lines displayed before and after the change. When context is False, controls the number of lines to place the "next" link anchors before the next change (so click of "next" link jumps to just before the change). NrzV %s%s%s%s rz) z z!
z+%sz rjr/) data_rows header_rowrz+zz-zz^zrzrar)rrdrGrMrNrLryr}rrFr9r3_table_templaterrrrk)r!r:r;r\r]rBrS context_linesrorwrxr|rrrfmtr;rrVs rr[zHtmlDiff.make_tables( !55iH ' $M My#~~/   &&u-E$(#6#6u#= 6:5H5H VHWX6727 7s8}%A{"q5HHJK#IaL!+4Q<q !CCD& v3=H3=F HJ J$$tggaj!<<?($$ }}U#<=WU#<=WU#<=WT),WT(+  ,r)rjrjF)rrrrrXrYrrZrrr"r^rdrhryr}r{rrr[rrrr r s $NG%OGO4+""AC*+@8?@6!.5.n+8(*#. --:^INK,rr c#K dddt|}d|f}|D]}|dd|vs |ddy#t$rtd|zdwxYww)a0 Generate one of the two sequences that generated a delta. Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract lines originating from file 1 or 2 (parameter `which`), stripping off line prefixes. Examples: >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True), ... 'ore\ntree\nemu\n'.splitlines(keepends=True)) >>> diff = list(diff) >>> print(''.join(restore(diff, 1)), end="") one two three >>> print(''.join(restore(diff, 2)), end="") ore tree emu rr)r/rz)unknown delta choice (must be 1 or 2): %rNrr)intKeyErrorr)deltawhichrsprefixesrs rrrsw,.4 U,c{H 8x qr(N .D"#$)- ..sA 0A  A A  A c4ddl}ddl}|j|S)Nr)doctestdifflibtestmod)rrs r_testrs ??7 ##r__main__)rg333333?)z )rjrjrjrjrr)rrrrr )&r__all__heapqrr collectionsr _namedtupletypesrr rrrrrr@rAmatchrrrr rr rr rrGrXrYrrZobjectr rrrrrrrs8 >(1GZ( k 2k 2\.&bl!l!~  %2::&67==! . -=?.2B%R =,.?CJ1XK"25?D6<(9#4J(,d%K\ ( 0 "],v],~ @$ z Gr