lJc @scdZddddddddd d g Zd d kZd ZdfdYZdddZdZdfdYZd d kZei di dZ ddZ dddddddZ dddddddZee dZeee dZdZdZd Zd!Zd efd"YZ[d#Zd$Zed%jo end S(&se 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. tget_close_matchestndifftrestoretSequenceMatchertDiffertIS_CHARACTER_JUNKt IS_LINE_JUNKt context_difft unified_difftHtmlDiffiNcCs|od||SndS(Ng@g?((tmatchestlength((s/sys/lib/python/difflib.pyt_calculate_ratio%scBseZdZddddZdZdZdZdZdZ dZ d Z d d Z d Z d ZdZRS(s 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 synching 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. 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. tcCs-||_d|_|_|i||dS(s[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(). N(tisjunktNonetatbtset_seqs(tselfRRR((s/sys/lib/python/difflib.pyt__init__s; cCs|i||i|dS(sSet the two sequences to be compared. >>> s = SequenceMatcher() >>> s.set_seqs("abcd", "bcde") >>> s.ratio() 0.75 N(tset_seq1tset_seq2(RRR((s/sys/lib/python/difflib.pyRs cCs5||ijodSn||_d|_|_dS(sMSet 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(RRtmatching_blockstopcodes(RR((s/sys/lib/python/difflib.pyRs cCsH||ijodSn||_d|_|_d|_|idS(sMSet 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(RRRRt fullbcountt_SequenceMatcher__chain_b(RR((s/sys/lib/python/difflib.pyRs   c CsN|i}t|}h|_}h}xt|D]w\}}||joQ||}|djo)t|d|jod||<|2q|i|q5|g||= 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) (0, 4, 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) (1, 0, 4) If no blocks match, return (alo, blo, 0). >>> s = SequenceMatcher(None, "ab", "c") >>> s.find_longest_match(0, 2, 0, 1) (0, 0, 0) ii(RRRR!txrangetget(RtalotahitblotbhiRRRR!tbestitbestjtbestsizetj2lentnothingR%tj2lengettnewj2lentjtk((s/sys/lib/python/difflib.pytfind_longest_match[sF8*    , %% %%cCs|idj o |iSnt|it|i}}d|d|fg}g}x|o|i\}}}}|i||||\} } } } | o|i| || jo*|| jo|i|| || fn| | |jo6| | |jo%|i| | || | |fq2qXqXW|id} }}g}x||D]t\}}}| ||jo|||jo||7}q\|o|i| ||fn|||} }}q\W|o|i| ||fn|i||df||_|iS(sReturn 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") >>> s.get_matching_blocks() [(0, 0, 2), (3, 2, 2), (5, 4, 0)] iN( RRRRRtpopR:Rtsort(RtlatlbtqueueRR-R.R/R0R%R8R9txti1tj1tk1t non_adjacentti2tj2tk2((s/sys/lib/python/difflib.pytget_matching_blockss:  % ". " cCs|idj o |iSnd}}g|_}x|iD]\}}}d}||jo||jo d}n/||jo d}n||jo d}n|o |i|||||fn||||}}|o |id||||fq?q?W|S(sZReturn 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) iR treplacetdeletetinserttequalN(RRRHR(RR%R8tanswertaitbjtsizettag((s/sys/lib/python/difflib.pyt get_opcodess&          $ic cs|i}|p dg}n|dddjoP|d\}}}}}|t||||t||||f|d>> from pprint import pprint >>> a = 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)]] RLiiiN(sequaliiii(RRtmaxtminRR( RR#tcodesRQRARERBRFtnntgroup((s/sys/lib/python/difflib.pytget_grouped_opcodesGs*  77 6+ 0cCs>td|id}t|t|it|iS(sReturn 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 ||dS(i((tsumttriple((s/sys/lib/python/difflib.pytsi(treduceRHR RRR(RR ((s/sys/lib/python/difflib.pytratioys c Cs|idjo?h|_}x/|iD] }|i|dd||((s/sys/lib/python/difflib.pytreal_quick_ratiosN(t__name__t __module__t__doc__RRRRRRR:RHRRRXR]RaRb(((s/sys/lib/python/difflib.pyR*sj?  - 3 n G 7 2  ig333333?c Cs |djptd|fnd|jo djnptd|fng}t}|i|xq|D]i}|i||i|joC|i|jo0|i|jo|i|i|fq|q|Wti ||}g}|D]\}}||q~S(sUse 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'] isn must be > 0: %rgg?s cutoff must be in [0.0, 1.0]: %r( t ValueErrorRRRRbRaR]Rtheapqtnlargest( twordt possibilitiesR#tcutofftresulttsR@t_[1]tscore((s/sys/lib/python/difflib.pyRs     !cCsGdt|}}x-||jo|||jo|d7}qW|S(s} Return number of `ch` characters at the start of `line`. Example: >>> _count_leading(' abc', ' ') 3 ii(R(tlinetchR%R#((s/sys/lib/python/difflib.pyt_count_leadings !cBsSeZdZdddZdZdZdZdZdZ dZ RS( se 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(1) >>> 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(1) 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), 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. cCs||_||_dS(s 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; as of Python 2.3, the underlying SequenceMatcher class has grown 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(tlinejunktcharjunk(RRsRt((s/sys/lib/python/difflib.pyRYs c cst|i||}x|iD]\}}}}}|djo"|i||||||} n|djo|id|||} nc|djo|id|||} n:|djo|id|||} ntd|fx| D] } | VqWq"Wd S( s 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(1), ... 'ore\ntree\nemu\n'.splitlines(1))), - one ? ^ + ore ? ^ - two - three ? - + tree + emu RIRJt-RKt+RLt sunknown tag %rN(RRsRRt_fancy_replacet_dumpRf( RRRtcruncherRQR-R.R/R0tgRp((s/sys/lib/python/difflib.pytcompareqs  "   ccs1x*t||D]}d|||fVqWdS(s4Generate comparison results for a same-tagged range.s%s %sN(R+(RRQR@tlothiR%((s/sys/lib/python/difflib.pyRysc cs||jo ||jpt||||jo4|id|||}|id|||}n1|id|||}|id|||}x*||fD]} x| D] } | VqWqWdS(NRvRu(tAssertionErrorRy( RRR-R.RR/R0tfirsttsecondR{Rp((s/sys/lib/python/difflib.pyt_plain_replaces! ccs<d\}}t|i} d\} } xt||D]} || } | i| xt||D]}||}|| jo%| djo|| } } qdqdn| i|| i|joD| i|jo1| i|jo| i|| }}}qdqdWq7W||jo[| djo6x+|i ||||||D] }|VqKWdSn| | d}}}nd} x+|i ||||||D] }|VqW||||}}| djo)d}}| i ||x| i D]\}}}}}||||}}|djo |d|7}|d|7}q|djo|d |7}q|d jo|d |7}q|d jo |d |7}|d |7}qt d|fqWx2|i||||D] }|VqWn d|Vx3|i ||d|||d|D] }|Vq)WdS(sD 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), - abcDefghiJkl ? ^ ^ ^ + abcdefGhijkl ? ^ ^ ^ gGz?g?Ng?R RIt^RJRuRKRvRLRwsunknown tag %rs i(gGz?g?(NN(RRtRR+RRRbRaR]Rt _fancy_helperRRRRft_qformat(RRR-R.RR/R0t best_ratioRkRzteqiteqjR8ROR%RNtbest_itbest_jRptaelttbelttatagstbtagsRQtai1tai2tbj1tbj2R=R>((s/sys/lib/python/difflib.pyRxsn        &             'c csg}||joK||jo"|i||||||}q|id|||}n*||jo|id|||}nx|D] }|VqWdS(NRuRv(RxRy( RRR-R.RR/R0R{Rp((s/sys/lib/python/difflib.pyRs  " ccstt|dt|d}t|t|| d}||i}||i}d|V|odd||fVnd|V|odd||fVndS(s Format "?" output and deal with leading tabs. Example: >>> d = Differ() >>> results = d._qformat('\tabcDefghiJkl\n', '\t\tabcdefGhijkl\n', ... ' ^ ^ ^ ', '+ ^ ^ ^ ') >>> for line in results: print repr(line) ... '- \tabcDefghiJkl\n' '? \t ^ ^ ^\n' '+ \t\tabcdefGhijkl\n' '? \t ^ ^ ^\n' s Rws- s? %s%s s+ N(RTRrtrstrip(RtalinetblineRRtcommon((s/sys/lib/python/difflib.pyRs  N( RcRdReRRR|RyRRxRR(((s/sys/lib/python/difflib.pyRs\ )   b s \s*#?\s*$cCs||dj S(s 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 N(R(Rptpat((s/sys/lib/python/difflib.pyRPss cCs ||jS(s 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 ((Rqtws((s/sys/lib/python/difflib.pyR`sR s c cst}xtd||i|D]t} |p.d|||fVd|||fVt}n| dd| dd| dd| ddf\} } } } d | d| | | d| | |fVx| D]\}} } } } |d jo(x|| | !D]}d |VqWqn|d jp |d jo%x"|| | !D]}d|Vq<Wn|d jp |djo%x"|| | !D]}d|Vq{WqqWq"WdS(s 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 format returned by time.ctime(). Example: >>> for line in unified_diff('one two three four'.split(), ... 'zero one tree four'.split(), 'Original', 'Current', ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:20:52 2003', ... lineterm=''): ... print line --- Original Sat Jan 26 23:30:50 1991 +++ Current Fri Jun 06 10:20:52 2003 @@ -1,4 +1,4 @@ +zero one -two -three +tree four s --- %s %s%ss +++ %s %s%siiiiiis@@ -%d,%d +%d,%d @@%sRLRwRIRJRuRKRvN(tFalseRRRXtTrue(RRtfromfilettofilet fromfiledatet tofiledateR#tlinetermtstartedRWRARERBRFRQRp((s/sys/lib/python/difflib.pyRss0) >(  c cst}hdd<dd<dd<dd<} xVtd||i|D]9} |p.d |||fVd |||fVt}nd |fV| d d | ddd jo*d| ddd| d d |fVnd| d d |fVg} | D]"} | ddjo | | qq~ } | oZxW| D]K\}}}}}|djo)x&|||!D]}| ||VqiWq9q9Wn| d d| ddd jo*d| ddd| d d|fVnd| d d|fVg}| D]"} | ddjo || qq~} | oZxW| D]K\}}}}}|djo)x&|||!D]}| ||VqbWq2q2WqLqLWdS(s 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 format returned by time.ctime(). If not specified, the strings default to blanks. Example: >>> print ''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1), ... 'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current', ... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:22:46 2003')), *** Original Sat Jan 26 23:30:50 1991 --- Current Fri Jun 06 10:22:46 2003 *************** *** 1,4 **** one ! two ! three four --- 1,4 ---- + zero one ! tree four s+ RKs- RJs! RIs RLs *** %s %s%ss --- %s %s%ss***************%siiiis*** %d,%d ****%ss *** %d ****%siis--- %d,%d ----%ss --- %d ----%sN(sreplacesdelete(sreplacesinsert(RRRRXR(RRRRRRR#RRt prefixmapRWRntetvisiblechangesRQRAREt_Rpt_[2]RBRF((s/sys/lib/python/difflib.pyRs>,*  !*6 !*6 cCst||i||S(s Compare `a` and `b` (lists of strings); return a `Differ`-style delta. Optional keyword parameters `linejunk` and `charjunk` are for filter functions (or 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; as of Python 2.3, an adaptive notion of "noise" lines is used that does a good job on its own. - charjunk: A function that should accept a string of length 1. The default is module-level function IS_CHARACTER_JUNK, which filters out whitespace characters (a blank or tab; note: 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(1), ... 'ore\ntree\nemu\n'.splitlines(1)) >>> print ''.join(diff), - one ? ^ + ore ? ^ - two - three ? - + tree + emu (RR|(RRRsRt((s/sys/lib/python/difflib.pyRs"c#sddk}|idt||||ddgfdfdfd}|}|djox^to|iVqWnD|d7}d}x0to(ddg|} } t} xN| tjo@|i\} } } | |}| | | f| |<| d7} qW| |jod V|}n | }d} x3|o+| |}| d7} | |V|d8}qMW|d}xN|oF|i\} } } | o|d}n |d8}| | | fVqWqWdS( sReturns 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 interator 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 seperation) 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. iNs (\++|\-+|\^+)ic s2||cd7<|djo|||iddfSn|djo|id|id}}g}|d}i||xS|dddD]>\}\} } |d| !d||| | !d || }qW|d}n7|idd}|p d }nd||d }|||fS( sReturns 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. iiit?cSs3|i|idd|ig|idS(Nii(RRWtspan(t match_objecttsub_info((s/sys/lib/python/difflib.pytrecord_sub_infoks&NitsRw(RR;tsub( tlinest format_keytsidet num_linesttexttmarkersRRtkeytbegintend(t change_re(s/sys/lib/python/difflib.pyt _make_lineJs"   0 c3sg}d\}}xtoxRt|djo>y|iiWqtj o|idqXqWdig}|D]}||dq~}|ido |}n^|ido-|dd|ddtfVqn!|ido+|d8}|d ddtfVqn|ido.|d dd}}|dd}}n|id o-|dd|ddtfVqnk|ido-|dd|ddtfVqn.|id o+|d8}|d ddtfVqn|ido+|d7}d|ddtfVqn|ido.d|dd}}|dd}}nz|ido+|d7}d|ddtfVqn?|ido.|dd|ddtfVqnx*|djo|d7}ddtfVqWx*|djo|d8}ddtfVqFW|ido tq||tfVqWdS(sYields 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. iitXR s-?+?Ris--++Rus--?+s--+s- s-+?s-?+s+--Rvs+ s+-Rws N(ii(s--?+s--+s- (s+ s+-(R s (R s ( RRRtnextt StopIterationtjoint startswithRR(Rtnum_blanks_pendingtnum_blanks_to_yieldRnRpRmt from_linetto_line(Rtdiff_lines_iterator(s/sys/lib/python/difflib.pyt_line_iteratorsl  . & &&   '   c3s}gg}}xtoxt|djpt|djoa|i\}}}|dj o|i||fn|dj o|i||fq#q#W|id\}}|id\}}|||p|fVqWdS(stYields 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. iN(RRRRRR;(t line_iteratort fromlinesttolinesRRt found_difftfromDifftto_diff(R(s/sys/lib/python/difflib.pyt_line_pair_iterators   )  i(NNN(tretcompileRRRRR(RRtcontextRsRtRRtline_pair_iteratortlines_to_writetindext contextLinesRRRR%((RRRRs/sys/lib/python/difflib.pyt_mdiff sJ" 8[               sm %(table)s%(legend)s sH 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}sZ %(header_row)s %(data_rows)s
s
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op
cBseZdZeZeZeZeZdZddde dZ dde ddZ dZ dZd Zd Zd Zd Zd Zdde ddZRS(s{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. iicCs(||_||_||_||_dS(sHtmlDiff 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 to by HtmlDiff() to generate the side by side HTML differences). See ndiff() documentation for argument default values and descriptions. N(t_tabsizet _wrapcolumnt _linejunkt _charjunk(Rttabsizet wrapcolumnRsRt((s/sys/lib/python/difflib.pyRvs   R icCsD|itd|id|id|i||||d|d|S(sReturns 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). tstylestlegendttableRtnumlines(t_file_templatetdictt_stylest_legendt make_table(RRRtfromdescttodescRR((s/sys/lib/python/difflib.pyt make_files    csgfd}g}|D]}|||q~}g}|D]}|||qA~}||fS(sReturns 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. csO|idd}|ii}|idd}|iddidS(NRwRs s (RIt expandtabsRR(Rp(R(s/sys/lib/python/difflib.pyt expand_tabss((RRRRRnRpR((Rs/sys/lib/python/difflib.pyt_tab_newline_replaces  ''c Cs~|p|i||fdSnt|}|i}||jp||idd|jo|i||fdSnd}d}d}x||jo}||jop||djo"|d7}||}|d7}q||djo|d7}d}q|d7}|d7}qW|| } ||} |o| d} d|| } n|i|| f|i|d| dS( sBuilds 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. NRiiR ist>(RRRtcountt _split_line( Rt data_listtline_numRRPRSR%R#tmarktline1tline2((s/sys/lib/python/difflib.pyRs8   +        c csx|D]\}}}|djo|||fVqn||\}}\}}gg} } |i| |||i| ||xa| p| oR| o| id}nd}| o| id}nd}|||fVqWqWdS(s5Returns iterator that splits (wraps) mdiff text linesiR RwN(R Rw(R Rw(RRR;( Rtdiffstfromdatattodatatflagtfromlinetfromtextttolinettotexttfromlistttolist((s/sys/lib/python/difflib.pyt _line_wrappers"  c Csggg}}}x|D]\}}}y<|i|id|||i|id||Wn-tj o!|id|idnX|i|qW|||fS(sCollects 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. iiN(Rt _format_linet TypeErrorR(RRRRtflaglistRRR((s/sys/lib/python/difflib.pyt_collect_lines s  cCsy%d|}d|i||f}Wntj o d}nX|iddiddidd }|id d i}d |||fS( sReturns 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 s%ds id="%s%s"R t&s&Rs>t%s%s(t_prefixRRIR(RRRtlinenumRtid((s/sys/lib/python/difflib.pyRs  *cCs<dti}dti}tid7_||g|_dS(sCreate unique anchor prefixessfrom%d_sto%d_iN(R t_default_prefixR(Rt fromprefixttoprefix((s/sys/lib/python/difflib.pyt _make_prefix5s  cCsd|id}dgt|}dgt|}dt} } d} xt|D]|\} } | oc| pXt} | } td| |g} d|| f|| <| d7} d|| f|| ns2 No Differences Found s( Empty File s!fs#t(RRRRRRS(RRRRRRRtnext_idt next_hreftnum_chgt in_changetlastR%R((s/sys/lib/python/difflib.pyt_convert_flags@s<           c Cs|i|i||\}}|o |}nd}t|||d|id|i}|io|i|}n|i|\} } } |i | | | ||\} } } } } g}dd}xt t | D]m}| |djo"|djo|i dqLq|i || || || || || |fqW|p|o"ddd |dd |f}nd }|i td d i|d |d |id}|iddiddiddiddiddS(sReturns 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). RsRts1 %s%ss%%s%s is) s %s%s%s%ss!
s+%sR t data_rowst header_rowtprefixit+st-st^ssss s N(RRRRRRRRRR trangeRRt_table_templateRRRRI(RRRRRRRt context_linesRRRRRRRmtfmtR%RR((s/sys/lib/python/difflib.pyRosL    $     N(RcRdReRRRRRRRRRRRRRRRRR R(((s/sys/lib/python/difflib.pyR `s&      7    / ccsy&hdd<dd>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) >>> diff = list(diff) >>> print ''.join(restore(diff, 1)), one two three >>> print ''.join(restore(diff, 2)), ore tree emu s- is+ is)unknown delta choice (must be 1 or 2): %rs N(tinttKeyErrorRf(tdeltatwhichRQtprefixesRp((s/sys/lib/python/difflib.pyRs&  cCs%ddk}ddk}|i|S(Ni(tdoctesttdifflibttestmod(RR((s/sys/lib/python/difflib.pyt_testst__main__(Ret__all__RgR RRRrRRRtmatchRRRRRRRRRRRtobjectR RRRc(((s/sys/lib/python/difflib.pyssD     0 T   =J$   ]