grthtrhthjhtyjytjytkergtrhtrjytjerhrfh3 \™Iã @s8dZddddddddd d d d g Zd dlmZd dlmZed dƒZdd„Z Gdd„dƒZ d8dd„Z dd„Z Gdd„dƒZ d dlZejdƒjfdd„Zd9dd„Zdd „Zd:d#d „Zd$d%„Zd;d&d„Zd'd(„Zd" 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. Methods: __init__(isjunk=None, a='', b='') Construct a SequenceMatcher. set_seqs(a, b) Set the two sequences to be compared. set_seq1(a) Set the first sequence to be compared. set_seq2(b) Set the second sequence to be compared. find_longest_match(alo, ahi, blo, bhi) Find longest matching block in a[alo:ahi] and b[blo:bhi]. get_matching_blocks() Return list of triples describing matching subsequences. get_opcodes() Return list of 5-tuples describing how to turn a into b. ratio() Return a measure of the sequences' similarity (float in [0,1]). quick_ratio() Return an upper bound on .ratio() relatively quickly. real_quick_ratio() Return an upper bound on ratio() very quickly. NÚTcCs(||_d|_|_||_|j||ƒdS)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)ÚisjunkÚaÚbÚautojunkÚset_seqs)ÚselfrrrrrrrÚ__init__—s; zSequenceMatcher.__init__cCs|j|ƒ|j|ƒdS)z›Set the two sequences to be compared. >>> s = SequenceMatcher() >>> s.set_seqs("abcd", "bcde") >>> s.ratio() 0.75 N)Úset_seq1Úset_seq2)rrrrrrr×s zSequenceMatcher.set_seqscCs$||jkrdS||_d|_|_dS)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)rÚmatching_blocksÚopcodes)rrrrrrãs zSequenceMatcher.set_seq1cCs2||jkrdS||_d|_|_d|_|jƒdS)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)rrr Ú fullbcountÚ_SequenceMatcher__chain_b)rrrrrrýs   zSequenceMatcher.set_seq2c Csü|j}i|_}x*t|ƒD]\}}|j|gƒ}|j|ƒqWtƒ|_}|j}|rŠx"|jƒD]}||ƒr\|j |ƒq\Wx|D] }||=q|Wtƒ|_ }t |ƒ} |j rø| dkrø| dd} x*|j ƒD]\}} t | ƒ| krÂ|j |ƒqÂWx|D] }||=qêWdS)NéÈédé)rÚb2jÚ enumerateÚ setdefaultÚappendÚsetÚbjunkrÚkeysÚaddZbpopularÚlenrÚitems) rrr&ÚiÚeltÚindicesZjunkrZpopularÚnZntestZidxsrrrZ __chain_b)s,          zSequenceMatcher.__chain_bcCsN|j|j|j|jjf\}}}}||d} } } i} g} x�t||ƒD]‚}| j}i}xn|j||| ƒD]Z}||krpqb||krzP||ddƒd}||<|| krb||d||d|} } } qbW|} qBWxb| |k�r*| |k�r*||| dƒ �r*|| d|| dk�r*| d| d| d} } } qÊWxX| | |k�r„| | |k�r„||| | ƒ �r„|| | || | k�r„| d7} �q.Wxb| |k�rè| |k�rè||| dƒ�rè|| d|| dk�rè| d| d| d} } } �qˆWxV| | |k�r@| | |k�r@||| | ƒ�r@|| | || | k�r@| d} �qìWt| | | ƒS)aòFind longest matching block in a[alo:ahi] and b[blo:bhi]. 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) r r%)rrr&r+Ú __contains__ÚrangeÚgetr )rÚaloÚahiÚbloÚbhirrr&ZisbjunkZbestiZbestjZbestsizeZj2lenZnothingr0Zj2lengetZnewj2lenÚjÚkrrrÚfind_longest_matchPsB8$  "z"SequenceMatcher.find_longest_matchcCs„|jdk r|jSt|jƒt|jƒ}}d|d|fg}g}x”|rÌ|jƒ\}}}}|j||||ƒ\} } } } | r:|j| ƒ|| kr˜|| kr˜|j|| || fƒ| | |kr:| | |kr:|j| | || | |fƒq:W|jƒd} }}g}x^|D]V\}}}| ||k�r|||k�r||7}qì|�r2|j| ||fƒ|||} }}qìW|�r\|j| ||fƒ|j||dfƒtt t j |ƒƒ|_|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)] Nr ) rr.rrÚpopr=r)ÚsortÚlistÚmapr Ú_make)rÚlaÚlbZqueuerr7r8r9r:r0r;r<ÚxÚi1Új1Zk1Z non_adjacentÚi2Új2Zk2rrrÚget_matching_blocks¾s8    z#SequenceMatcher.get_matching_blockscCs´|jdk r|jSd}}g|_}xŒ|jƒD]€\}}}d}||krP||krPd}n||kr^d}n ||krjd}|r‚|j|||||fƒ||||}}|r,|jd||||fƒq,W|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) Nr rÚreplaceÚdeleteÚinsertÚequal)r rJr))rr0r;ZanswerÚaiÚbjÚsizeÚtagrrrÚ get_opcodess$  zSequenceMatcher.get_opcodeséc csr|jƒ}|sdg}|dddkrZ|d\}}}}}|t|||ƒ|t|||ƒ|f|d<|dddkr¢|d\}}}}}||t|||ƒ|t|||ƒf|d<||}g} x�|D]ˆ\}}}}}|dkoÔ|||k�r(| j||t|||ƒ|t|||ƒfƒ| Vg} t|||ƒt|||ƒ}}| j|||||fƒq´W| �rnt| ƒdk�ob| dddk �rn| VdS) 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)]] rNr r%N)rNr r%r r%éÿÿÿÿrUrU)rSÚmaxÚminr)r.) rr3ZcodesrRrFrHrGrIZnnÚgrouprrrÚget_grouped_opcodes<s(&&((z#SequenceMatcher.get_grouped_opcodescCs0tdd„|jƒDƒƒ}t|t|jƒt|jƒƒS)aÒReturn 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 css|]}|dVqdS)r%NrUr)Ú.0Ztriplerrrú „sz(SequenceMatcher.ratio..)ÚsumrJrr.rr)rrrrrÚrationszSequenceMatcher.ratiocCs²|jdkr8i|_}x"|jD]}|j|dƒd||<qW|j}i}|jd}}xH|jD]>}||ƒrl||}n |j|dƒ}|d||<|dkrV|d}qVWt|t|jƒt|jƒƒS)z©Return 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. Nr r%)r!rr6r4rrr.)rr!r1ZavailZavailhasrZnumbrrrÚ quick_ratio‡s         zSequenceMatcher.quick_ratiocCs*t|jƒt|jƒ}}tt||ƒ||ƒS)zÊReturn 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(). )r.rrrrW)rrCrDrrrÚreal_quick_ratio¤sz SequenceMatcher.real_quick_ratio)NrrT)rT)Ú__name__Ú __module__Ú __qualname__Ú__doc__rrrrr"r=rJrSrYr]r^r_rrrrr+sj @ ,'nG7 2rTç333333ã?cCs¶|dkstd|fƒ‚d|ko(dkns 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'] r zn must be > 0: %rggð?z cutoff must be in [0.0, 1.0]: %rcSsg|] \}}|‘qSrr)rZZscorerErrrú Þsz%get_close_matches..) Ú ValueErrorrrrr_r^r]r)Ú _nlargest)ZwordZ possibilitiesr3ÚcutoffÚresultÚsrErrrr°s       cCs4dt|ƒ}}x ||kr.|||kr.|d7}qW|S)z} Return number of `ch` characters at the start of `line`. Example: >>> _count_leading(' abc', ' ') 3 r r%)r.)ÚlineÚchr0r3rrrÚ_count_leadingàs  rmc@sJeZdZdZddd„Zdd„Zdd„Zd d „Zd d „Zd d„Z dd„Z dS)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. Methods: __init__(linejunk=None, charjunk=None) Construct a text differencer, with optional filters. compare(a, b) Compare two sequences of lines; generate the resulting delta. NcCs||_||_dS)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. N)ÚlinejunkÚcharjunk)rrnrorrrrMszDiffer.__init__c cs²t|j||ƒ}xž|jƒD]’\}}}}}|dkrD|j||||||ƒ} n\|dkr^|jd|||ƒ} nB|dkrx|jd|||ƒ} n(|dkr’|jd|||ƒ} ntd|fƒ‚| Ed HqWd S) 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 writeline() 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ú+rNú zunknown tag %rN)rrnrSÚ_fancy_replaceÚ_dumprf) rrrÚcruncherrRr7r8r9r:ÚgrrrÚcomparedszDiffer.compareccs*x$t||ƒD]}d|||fVq WdS)z4Generate comparison results for a same-tagged range.z%s %sN)r5)rrRrEÚloÚhir0rrrrt�sz Differ._dumpc cs†||kr||kst‚||||krF|jd|||ƒ}|jd|||ƒ}n |jd|||ƒ}|jd|||ƒ}x||fD]} | EdHqpWdS)Nrqrp)ÚAssertionErrorrt) rrr7r8rr9r:ÚfirstÚsecondrvrrrÚ_plain_replace’szDiffer._plain_replaceccsHd\}}t|jƒ} d\} } xžt||ƒD]�} || } | j| ƒxxt||ƒD]j}||}|| krp| dkrH|| } } qH| j|ƒ| jƒ|krH| jƒ|krH| jƒ|krH| jƒ|| }}}qHWq&W||k�rü| dkrê|j||||||ƒEdHdS| | d}}}nd} |j ||||||ƒEdH||||}}| dk�rd}}| j ||ƒx´| j ƒD]¨\}}}}}||||}}|dk�r˜|d|7}|d|7}nb|dk�r°|d |7}nJ|d k�rÈ|d |7}n2|d k�rì|d |7}|d |7}nt d|fƒ‚�qTW|j ||||ƒEdHn d|V|j ||d|||d|ƒEdHdS)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 ? ^ ^ ^ ç®Gáz®ç?çè?Ngð?rrKú^rLrprMrqrNrrzunknown tag %rz r%)r~r)NN)rror5rrr_r^r]r}Ú _fancy_helperrrSrfÚ_qformat)rrr7r8rr9r:Z best_ratiorhruZeqiZeqjr;rPr0rOZbest_iZbest_jZaeltZbeltÚatagsÚbtagsrRZai1Zai2Zbj1Zbj2rCrDrrrrs sX                 zDiffer._fancy_replaceccsbg}||kr<||kr*|j||||||ƒ}qT|jd|||ƒ}n||krT|jd|||ƒ}|EdHdS)Nrprq)rsrt)rrr7r8rr9r:rvrrrr�þszDiffer._fancy_helperccsªtt|dƒt|dƒƒ}t|t|d|…dƒƒ}t|t|d|…dƒƒ}||d…jƒ}||d…jƒ}d|V|r†dd||fVd|V|r¦dd||fVdS)a¢ Format "?" output and deal with leading 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' ú Nrrz- z? %s%s z+ )rWrmÚrstrip)rZalineZblinerƒr„Úcommonrrrr‚ s    zDiffer._qformat)NN) r`rarbrcrrwrtr}rsr�r‚rrrrrïs\ )^ Nz \s*(?:#\s*)?$cCs ||ƒdk S)zÜ Return 1 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)rkZpatrrrr>sú cCs||kS)zû Return 1 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)rlZwsrrrrNscCs:|d}||}|dkr"dj|ƒS|s.|d8}dj||ƒS)z Convert range to the "ed" formatr%z{}z{},{})Úformat)ÚstartÚstopÚ beginningrrrrÚ_format_range_unifiedes r�rÚ ccsht|||||||ƒd}�xHtd||ƒj|ƒD�]0} |s€d}|rJdj|ƒnd} |r\dj|ƒnd} dj|| |ƒVdj|| |ƒV| d| d} } t| d | d ƒ}t| d | d ƒ}d j|||ƒVx˜| D]�\}}}}}|dk�rx|||…D]}d|VqòWqÌ|dk�r2x |||…D]}d|V�qW|dkrÌx |||…D]}d|V�qHWqÌWq.WdS)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 FNTz {}rz --- {}{}{}z +++ {}{}{}r r%érTéz@@ -{} +{} @@{}rNrrrKrLrprMrqrU>rLrK>rKrM)Ú _check_typesrrYr‰r�)rrÚfromfileÚtofileÚ fromfiledateÚ tofiledater3ÚlinetermÚstartedrXÚfromdateÚtodater{ÚlastÚ file1_rangeÚ file2_rangerRrFrHrGrIrkrrrr ps0)  cCsB|d}||}|s|d8}|dkr.dj|ƒSdj|||dƒS)z Convert range to the "ed" formatr%z{}z{},{})r‰)rŠr‹rŒrrrrÚ_format_range_context¹s r�ccsªt|||||||ƒtddddd�}d} �xztd||ƒj|ƒD�]b} | s�d} |rZd j|ƒnd } |rld j|ƒnd } d j|| |ƒVd j|| |ƒV| d | d} }d|Vt| d|dƒ}dj||ƒVtdd„| Dƒƒ�r&xD| D]<\}}}}}|dkræx$|||…D]}|||V�q WqæWt| d|dƒ}dj||ƒVtdd„| Dƒƒr>xH| D]@\}}}}}|dk�r^x$|||…D]}|||V�q„W�q^Wq>WdS)ah Compare two sequences of lines; generate the delta as a context diff. Context 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 context diff 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. If not specified, the strings default to blanks. Example: >>> 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 z+ z- z! z )rMrLrKrNFNTz {}rz *** {}{}{}z --- {}{}{}r r%z***************r�z *** {} ****{}css |]\}}}}}|dkVqdS)rKrLN>rLrKr)rZrRÚ_rrrr[szcontext_diff..rMrTr�z --- {} ----{}css |]\}}}}}|dkVqdS)rKrMN>rKrMr)rZrRržrrrr[ srLrU)r‘ÚdictrrYr‰r�Úany)rrr’r“r”r•r3r–Úprefixr—rXr˜r™r{ršr›rRrFrHržrkrœrGrIrrrrÅs4,  cGsŽ|r2t|dtƒ r2tdt|dƒj|dfƒ‚|rdt|dtƒ rdtdt|dƒj|dfƒ‚x$|D]}t|tƒsjtd|fƒ‚qjWdS)Nr z)lines to compare must be str, not %s (%r)z"all arguments must be str, not: %r)Ú isinstanceÚstrÚ TypeErrorÚtyper`)rrÚargsÚargrrrr‘s  r‘óó c cs‚dd„} tt| |ƒƒ}tt| |ƒƒ}| |ƒ}| |ƒ}| |ƒ}| |ƒ}| |ƒ}|||||||||ƒ} x| D]} | jddƒVqhWdS)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. cSsPy |jddƒStk rJ}z"dt|ƒj|f}t|ƒ|‚WYdd}~XnXdS)NÚasciiÚsurrogateescapez(all arguments must be bytes, not %s (%r))ÚdecodeÚAttributeErrorr¥r`r¤)rjÚerrÚmsgrrrr¬-s  zdiff_bytes..decoderªr«N)r@rAÚencode) Zdfuncrrr’r“r”r•r3r–r¬Úlinesrkrrrr "s  cCst||ƒ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 )rrw)rrrnrorrrr@s#c #sœddl}|jdƒ‰t||||ƒ‰ddgf‡fdd„ ‰‡‡fdd„‰‡fdd „}|ƒ}|dkrj|EdH�n.|d 7}d}�xddg|} } d } xR| d kràyt|ƒ\} } } Wntk r¾dSX| |}| | | f| |<| d 7} q�W| |k�rød V|}n| }d} x.|�r.| |}| d 7} | |V|d 8}�qW|d }yDx>|�rxt|ƒ\} } } | �r`|d }n|d 8}| | | fV�q._make_line..record_sub_infoúúrr)r>ÚsubÚreversed) r±Z format_keyÚsideZ num_linesÚtextZmarkersr´rµÚkeyZbeginÚend)Ú change_rerrÚ _make_line�s   4z_mdiff.._make_linec3s€g}d\}}�xlx t|ƒdkr0|jtˆdƒƒqWdjdd„|Dƒƒ}|jdƒrX|}�nÄ|jdƒr„ˆ|ddƒˆ|dd ƒd fVq�n˜|jd ƒr°|d 8}ˆ|d dƒd d fVq�nl|jdƒrÞˆ|d dƒd }}|d d}}�n>|jdƒ�r ˆ|d dƒˆ|dd ƒd fVq�n|jdƒ�r8ˆ|ddƒˆ|d d ƒd fVqnä|jd ƒ�rd|d 8}ˆ|d dƒd d fVqn¸|jdƒ�r�|d 7}d ˆ|dd ƒd fVqnŒ|jdƒ�r¾d ˆ|dd ƒ}}|d d}}n^|jdƒ�rê|d 7}d ˆ|dd ƒd fVqn2|jdƒ�rˆ|d d …d dƒˆ|d d ƒdfVqx|dk�r:|d 7}dV�qWx|dk�rZ|d 8}d V�q>W|jdƒ�rld S||d fVqWd S)!a¡Yields 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. r r�ÚXrcSsg|] }|d‘qS)r r)rZrkrrrreÝsz2_mdiff.._line_iterator..z-?+?r²r%Tz--++rpNú--?+ú--+ú- z-+?z-?+z+--rqú+ ú+-rrFrŽ)r r )rÁrÂrÃ)rÄrÅ©rrŽ)NrÆT©rrŽ)rÇNT)r.r)ÚnextÚjoinÚ startswith)r±Znum_blanks_pendingZnum_blanks_to_yieldrjÚ from_lineÚto_line)r¿Údiff_lines_iteratorrrÚ_line_iteratorÇsf           $     z_mdiff.._line_iteratorc 3s¸ˆƒ}gg}}x¢xpt|ƒdks,t|ƒdkr‚yt|ƒ\}}}Wntk rRdSX|dk rj|j||fƒ|dk r|j||fƒqW|jdƒ\}}|jdƒ\}}|||pª|fVqWdS)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. r N)r.rÈÚ StopIterationr)r>)Z line_iteratorÚ fromlinesÚtolinesrËrÌÚ found_diffZfromDiffZto_diff)rÎrrÚ_line_pair_iterators  z#_mdiff.._line_pair_iteratorr%F)NNN)ÚreÚcompilerrÈrÏ)rÐrÑÚcontextrnrorÔrÓZline_pair_iteratorZlines_to_writeÚindexZ contextLinesrÒrËrÌr0r)rÎr¿r¾rÍrÚ_mdiffesT" 8X !     rØan %(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@sˆeZdZdZeZeZeZeZdZddde fdd„Z dd d œd d „Z dd„Z dd„Z dd„Zdd„Zdd„Zdd„Zdd„Zddd„ZdS) 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. r éNcCs||_||_||_||_dS)aØHtmlDiff 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ÚtabsizeZ wrapcolumnrnrorrrrÁs zHtmlDiff.__init__rFézutf-8)Úcharsetc Cs:|jt|j|j|j||||||d�|d�j|dƒj|ƒ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 )rÖÚnumlines)ZstylesZlegendÚtableràÚxmlcharrefreplace)Ú_file_templaterŸÚ_stylesÚ_legendÚ make_tabler°r¬)rrÐrÑÚfromdescÚtodescrÖráràrrrÚ make_fileÒs  zHtmlDiff.make_filecs8‡fdd„‰‡fdd„|Dƒ}‡fdd„|Dƒ}||fS)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. cs6|jddƒ}|jˆjƒ}|jddƒ}|jddƒjdƒS)Nrrr¶r…rŽ)rKÚ expandtabsrÚr†)rk)rrrÚ expand_tabs÷s   z2HtmlDiff._tab_newline_replace..expand_tabscsg|] }ˆ|ƒ‘qSrr)rZrk)rìrrresz1HtmlDiff._tab_newline_replace..csg|] }ˆ|ƒ‘qSrr)rZrk)rìrrresr)rrÐrÑr)rìrrÚ_tab_newline_replaceís zHtmlDiff._tab_newline_replacec Cs|s|j||fƒdSt|ƒ}|j}||ksB||jdƒd|krT|j||fƒdSd}d}d}xd||krÄ||krÄ||dkr˜|d7}||}|d7}qb||dkr²|d7}d}qb|d7}|d7}qbW|d|…} ||d…} |rö| d} d|| } |j|| fƒ|j|d| ƒdS) a¤Builds 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. Nr¶rTr rr%r·ú>)r)r.rÛÚcountÚ _split_line) rZ data_listZline_numr»rQrVr0r3ZmarkZline1Zline2rrrrðs8        zHtmlDiff._split_linec cs¨x¢|D]š\}}}|dkr&|||fVq||\}}\}}gg} } |j| ||ƒ|j| ||ƒx@| sh| rž| rx| jdƒ}nd}| rŒ| jdƒ}nd}|||fVq`WqWdS)z5Returns iterator that splits (wraps) mdiff text linesNr rrr)rrr)rrr)rðr>) rÚdiffsÚfromdataÚtodataÚflagZfromlineZfromtextZtolineZtotextÚfromlistÚtolistrrrÚ _line_wrapper;s      zHtmlDiff._line_wrapperc Cs–ggg}}}xz|D]r\}}}y4|j|jd|f|žŽƒ|j|jd|f|žŽƒWn(tk r||jdƒ|jdƒYnX|j|ƒqW|||fS)z³Collects 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. r r%N)r)Ú _format_liner¤)rrñrõröÚflaglistròrórôrrrÚ_collect_linesWs zHtmlDiff._collect_linesc Csryd|}d|j||f}Wntk r6d}YnX|jddƒjddƒjdd ƒ}|jd d ƒjƒ}d |||fS) 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="%s%s"rú&z&rîz>ú%s%s)Ú_prefixr¤rKr†)rrºrôZlinenumr»Úidrrrrøls zHtmlDiff._format_linecCs0dtj}dtj}tjd7_||g|_dS)zCreate unique anchor prefixeszfrom%d_zto%d_r%N)r Ú_default_prefixrý)rZ fromprefixÚtoprefixrrrÚ _make_prefixƒs  zHtmlDiff._make_prefixcCsø|jd}dgt|ƒ}dgt|ƒ}d \} } d} xbt|ƒD]V\} } | rŽ| s’d} | } td| |gƒ} d|| f|| <| d7} d|| f|| <qnz2 No Differences Found z( Empty File z!fz#t)r F)rýr.r'rV)rrõrörùrÖrárÚnext_idÚ next_hrefZnum_chgZ in_changeršr0rôrrrÚ_convert_flagsŽs:    zHtmlDiff._convert_flagsc CsV|jƒ|j||ƒ\}}|r"|}nd}t||||j|jd�}|jrL|j|ƒ}|j|ƒ\} } } |j| | | ||ƒ\} } } } } g}d}x`t t | ƒƒD]P}| |dkr²|dkrÞ|j dƒqŽ|j || || || || || |fƒqŽW|sì|�rddd |dd |f}nd }|j t d j|ƒ||jd d �}|jd dƒjddƒjddƒjddƒjddƒS)aîReturns 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). N)rnroz1 %s%sz%%s%s r z) z %s%s%s%sz!
z+%srr%)Z data_rowsÚ header_rowr¡z+zz-zz^zr·zr…z zV %s%s%s%s )rrírØrÜrÝrÛr÷rúrr5r.r)Ú_table_templaterŸrÉrýrK)rrÐrÑrèrérÖráZ context_linesrñrõrörùrrrjZfmtr0rrârrrrç½sJ       zHtmlDiff.make_table)rrFrß)rrFrß)r`rarbrcrärårrærÿrrrêrírðr÷rúrørrrçrrrrr «s& 7 /c cspydddœt|ƒ}Wn tk r6td|ƒ‚YnXd|f}x*|D]"}|dd…|krF|dd…VqFWdS)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 z- z+ )r%r�z)unknown delta choice (must be 1 or 2): %rz Nr�)ÚintÚKeyErrorrf)ZdeltaZwhichrRÚprefixesrkrrrr s cCsddl}ddl}|j|ƒS)Nr )ÚdoctestÚdifflibZtestmod)r r rrrÚ_test,sr Ú__main__)rTrd)rˆ)rrrrrTrŽ)rrrrrTrŽ)r¨r¨r¨r¨rTr©)$rcÚ__all__ÚheapqrrgÚ collectionsrZ _namedtupler rrrrmrrÔrÕÚmatchrrr�r r�rr‘r rrØrärårræÚobjectr rr r`rrrrÚs^     0O   H  K % !  a