difflib.py 81 KB

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