difflib.py 82 KB

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