_difflib.py 83 KB

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