difflib.py 80 KB

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