PageRenderTime 59ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/difflib.py

https://bitbucket.org/varialus/jyjy
Python | 2059 lines | 1940 code | 15 blank | 104 comment | 44 complexity | acb708524ab9a21b7be5869bb5284585 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. #! /usr/bin/env python
  2. """
  3. Module difflib -- helpers for computing deltas between objects.
  4. Function get_close_matches(word, possibilities, n=3, cutoff=0.6):
  5. Use SequenceMatcher to return list of the best "good enough" matches.
  6. Function context_diff(a, b):
  7. For two lists of strings, return a delta in context diff format.
  8. Function ndiff(a, b):
  9. Return a delta: the difference between `a` and `b` (lists of strings).
  10. Function restore(delta, which):
  11. Return one of the two sequences that generated an ndiff delta.
  12. Function unified_diff(a, b):
  13. For two lists of strings, return a delta in unified diff format.
  14. Class SequenceMatcher:
  15. A flexible class for comparing pairs of sequences of any type.
  16. Class Differ:
  17. For producing human-readable deltas from sequences of lines of text.
  18. Class HtmlDiff:
  19. For producing HTML side by side comparison with change highlights.
  20. """
  21. __all__ = ['get_close_matches', 'ndiff', 'restore', 'SequenceMatcher',
  22. 'Differ','IS_CHARACTER_JUNK', 'IS_LINE_JUNK', 'context_diff',
  23. 'unified_diff', 'HtmlDiff', 'Match']
  24. import heapq
  25. from collections import namedtuple as _namedtuple
  26. from functools import reduce
  27. Match = _namedtuple('Match', 'a b size')
  28. def _calculate_ratio(matches, length):
  29. if length:
  30. return 2.0 * matches / length
  31. return 1.0
  32. class SequenceMatcher:
  33. """
  34. SequenceMatcher is a flexible class for comparing pairs of sequences of
  35. any type, so long as the sequence elements are hashable. The basic
  36. algorithm predates, and is a little fancier than, an algorithm
  37. published in the late 1980's by Ratcliff and Obershelp under the
  38. hyperbolic name "gestalt pattern matching". The basic idea is to find
  39. the longest contiguous matching subsequence that contains no "junk"
  40. elements (R-O doesn't address junk). The same idea is then applied
  41. recursively to the pieces of the sequences to the left and to the right
  42. of the matching subsequence. This does not yield minimal edit
  43. sequences, but does tend to yield matches that "look right" to people.
  44. SequenceMatcher tries to compute a "human-friendly diff" between two
  45. sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
  46. longest *contiguous* & junk-free matching subsequence. That's what
  47. catches peoples' eyes. The Windows(tm) windiff has another interesting
  48. notion, pairing up elements that appear uniquely in each sequence.
  49. That, and the method here, appear to yield more intuitive difference
  50. reports than does diff. This method appears to be the least vulnerable
  51. to synching up on blocks of "junk lines", though (like blank lines in
  52. ordinary text files, or maybe "<P>" lines in HTML files). That may be
  53. because this is the only method of the 3 that has a *concept* of
  54. "junk" <wink>.
  55. Example, comparing two strings, and considering blanks to be "junk":
  56. >>> s = SequenceMatcher(lambda x: x == " ",
  57. ... "private Thread currentThread;",
  58. ... "private volatile Thread currentThread;")
  59. >>>
  60. .ratio() returns a float in [0, 1], measuring the "similarity" of the
  61. sequences. As a rule of thumb, a .ratio() value over 0.6 means the
  62. sequences are close matches:
  63. >>> print round(s.ratio(), 3)
  64. 0.866
  65. >>>
  66. If you're only interested in where the sequences match,
  67. .get_matching_blocks() is handy:
  68. >>> for block in s.get_matching_blocks():
  69. ... print "a[%d] and b[%d] match for %d elements" % block
  70. a[0] and b[0] match for 8 elements
  71. a[8] and b[17] match for 21 elements
  72. a[29] and b[38] match for 0 elements
  73. Note that the last tuple returned by .get_matching_blocks() is always a
  74. dummy, (len(a), len(b), 0), and this is the only case in which the last
  75. tuple element (number of elements matched) is 0.
  76. If you want to know how to change the first sequence into the second,
  77. use .get_opcodes():
  78. >>> for opcode in s.get_opcodes():
  79. ... print "%6s a[%d:%d] b[%d:%d]" % opcode
  80. equal a[0:8] b[0:8]
  81. insert a[8:8] b[8:17]
  82. equal a[8:29] b[17:38]
  83. See the Differ class for a fancy human-friendly file differencer, which
  84. uses SequenceMatcher both to compare sequences of lines, and to compare
  85. sequences of characters within similar (near-matching) lines.
  86. See also function get_close_matches() in this module, which shows how
  87. simple code building on SequenceMatcher can be used to do useful work.
  88. Timing: Basic R-O is cubic time worst case and quadratic time expected
  89. case. SequenceMatcher is quadratic time for the worst case and has
  90. expected-case behavior dependent in a complicated way on how many
  91. elements the sequences have in common; best case time is linear.
  92. Methods:
  93. __init__(isjunk=None, a='', b='')
  94. Construct a SequenceMatcher.
  95. set_seqs(a, b)
  96. Set the two sequences to be compared.
  97. set_seq1(a)
  98. Set the first sequence to be compared.
  99. set_seq2(b)
  100. Set the second sequence to be compared.
  101. find_longest_match(alo, ahi, blo, bhi)
  102. Find longest matching block in a[alo:ahi] and b[blo:bhi].
  103. get_matching_blocks()
  104. Return list of triples describing matching subsequences.
  105. get_opcodes()
  106. Return list of 5-tuples describing how to turn a into b.
  107. ratio()
  108. Return a measure of the sequences' similarity (float in [0,1]).
  109. quick_ratio()
  110. Return an upper bound on .ratio() relatively quickly.
  111. real_quick_ratio()
  112. Return an upper bound on ratio() very quickly.
  113. """
  114. def __init__(self, isjunk=None, a='', b='', autojunk=True):
  115. """Construct a SequenceMatcher.
  116. Optional arg isjunk is None (the default), or a one-argument
  117. function that takes a sequence element and returns true iff the
  118. element is junk. None is equivalent to passing "lambda x: 0", i.e.
  119. no elements are considered to be junk. For example, pass
  120. lambda x: x in " \\t"
  121. if you're comparing lines as sequences of characters, and don't
  122. want to synch up on blanks or hard tabs.
  123. Optional arg a is the first of two sequences to be compared. By
  124. default, an empty string. The elements of a must be hashable. See
  125. also .set_seqs() and .set_seq1().
  126. Optional arg b is the second of two sequences to be compared. By
  127. default, an empty string. The elements of b must be hashable. See
  128. also .set_seqs() and .set_seq2().
  129. Optional arg autojunk should be set to False to disable the
  130. "automatic junk heuristic" that treats popular elements as junk
  131. (see module documentation for more information).
  132. """
  133. # Members:
  134. # a
  135. # first sequence
  136. # b
  137. # second sequence; differences are computed as "what do
  138. # we need to do to 'a' to change it into 'b'?"
  139. # b2j
  140. # for x in b, b2j[x] is a list of the indices (into b)
  141. # at which x appears; junk elements do not appear
  142. # fullbcount
  143. # for x in b, fullbcount[x] == the number of times x
  144. # appears in b; only materialized if really needed (used
  145. # only for computing quick_ratio())
  146. # matching_blocks
  147. # a list of (i, j, k) triples, where a[i:i+k] == b[j:j+k];
  148. # ascending & non-overlapping in i and in j; terminated by
  149. # a dummy (len(a), len(b), 0) sentinel
  150. # opcodes
  151. # a list of (tag, i1, i2, j1, j2) tuples, where tag is
  152. # one of
  153. # 'replace' a[i1:i2] should be replaced by b[j1:j2]
  154. # 'delete' a[i1:i2] should be deleted
  155. # 'insert' b[j1:j2] should be inserted
  156. # 'equal' a[i1:i2] == b[j1:j2]
  157. # isjunk
  158. # a user-supplied function taking a sequence element and
  159. # returning true iff the element is "junk" -- this has
  160. # subtle but helpful effects on the algorithm, which I'll
  161. # get around to writing up someday <0.9 wink>.
  162. # DON'T USE! Only __chain_b uses this. Use isbjunk.
  163. # isbjunk
  164. # for x in b, isbjunk(x) == isjunk(x) but much faster;
  165. # it's really the __contains__ method of a hidden dict.
  166. # DOES NOT WORK for x in a!
  167. # isbpopular
  168. # for x in b, isbpopular(x) is true iff b is reasonably long
  169. # (at least 200 elements) and x accounts for more than 1 + 1% of
  170. # its elements (when autojunk is enabled).
  171. # DOES NOT WORK for x in a!
  172. self.isjunk = isjunk
  173. self.a = self.b = None
  174. self.autojunk = autojunk
  175. self.set_seqs(a, b)
  176. def set_seqs(self, a, b):
  177. """Set the two sequences to be compared.
  178. >>> s = SequenceMatcher()
  179. >>> s.set_seqs("abcd", "bcde")
  180. >>> s.ratio()
  181. 0.75
  182. """
  183. self.set_seq1(a)
  184. self.set_seq2(b)
  185. def set_seq1(self, a):
  186. """Set the first sequence to be compared.
  187. The second sequence to be compared is not changed.
  188. >>> s = SequenceMatcher(None, "abcd", "bcde")
  189. >>> s.ratio()
  190. 0.75
  191. >>> s.set_seq1("bcde")
  192. >>> s.ratio()
  193. 1.0
  194. >>>
  195. SequenceMatcher computes and caches detailed information about the
  196. second sequence, so if you want to compare one sequence S against
  197. many sequences, use .set_seq2(S) once and call .set_seq1(x)
  198. repeatedly for each of the other sequences.
  199. See also set_seqs() and set_seq2().
  200. """
  201. if a is self.a:
  202. return
  203. self.a = a
  204. self.matching_blocks = self.opcodes = None
  205. def set_seq2(self, b):
  206. """Set the second sequence to be compared.
  207. The first sequence to be compared is not changed.
  208. >>> s = SequenceMatcher(None, "abcd", "bcde")
  209. >>> s.ratio()
  210. 0.75
  211. >>> s.set_seq2("abcd")
  212. >>> s.ratio()
  213. 1.0
  214. >>>
  215. SequenceMatcher computes and caches detailed information about the
  216. second sequence, so if you want to compare one sequence S against
  217. many sequences, use .set_seq2(S) once and call .set_seq1(x)
  218. repeatedly for each of the other sequences.
  219. See also set_seqs() and set_seq1().
  220. """
  221. if b is self.b:
  222. return
  223. self.b = b
  224. self.matching_blocks = self.opcodes = None
  225. self.fullbcount = None
  226. self.__chain_b()
  227. # For each element x in b, set b2j[x] to a list of the indices in
  228. # b where x appears; the indices are in increasing order; note that
  229. # the number of times x appears in b is len(b2j[x]) ...
  230. # when self.isjunk is defined, junk elements don't show up in this
  231. # map at all, which stops the central find_longest_match method
  232. # from starting any matching block at a junk element ...
  233. # also creates the fast isbjunk function ...
  234. # b2j also does not contain entries for "popular" elements, meaning
  235. # elements that account for more than 1 + 1% of the total elements, and
  236. # when the sequence is reasonably large (>= 200 elements); this can
  237. # be viewed as an adaptive notion of semi-junk, and yields an enormous
  238. # speedup when, e.g., comparing program files with hundreds of
  239. # instances of "return NULL;" ...
  240. # note that this is only called when b changes; so for cross-product
  241. # kinds of matches, it's best to call set_seq2 once, then set_seq1
  242. # repeatedly
  243. def __chain_b(self):
  244. # Because isjunk is a user-defined (not C) function, and we test
  245. # for junk a LOT, it's important to minimize the number of calls.
  246. # Before the tricks described here, __chain_b was by far the most
  247. # time-consuming routine in the whole module! If anyone sees
  248. # Jim Roskind, thank him again for profile.py -- I never would
  249. # have guessed that.
  250. # The first trick is to build b2j ignoring the possibility
  251. # of junk. I.e., we don't call isjunk at all yet. Throwing
  252. # out the junk later is much cheaper than building b2j "right"
  253. # from the start.
  254. b = self.b
  255. self.b2j = b2j = {}
  256. for i, elt in enumerate(b):
  257. indices = b2j.setdefault(elt, [])
  258. indices.append(i)
  259. # Purge junk elements
  260. junk = set()
  261. isjunk = self.isjunk
  262. if isjunk:
  263. for elt in list(b2j.keys()): # using list() since b2j is modified
  264. if isjunk(elt):
  265. junk.add(elt)
  266. del b2j[elt]
  267. # Purge popular elements that are not junk
  268. popular = set()
  269. n = len(b)
  270. if self.autojunk and n >= 200:
  271. ntest = n // 100 + 1
  272. for elt, idxs in list(b2j.items()):
  273. if len(idxs) > ntest:
  274. popular.add(elt)
  275. del b2j[elt]
  276. # Now for x in b, isjunk(x) == x in junk, but the latter is much faster.
  277. # Sicne the number of *unique* junk elements is probably small, the
  278. # memory burden of keeping this set alive is likely trivial compared to
  279. # the size of b2j.
  280. self.isbjunk = junk.__contains__
  281. self.isbpopular = popular.__contains__
  282. def find_longest_match(self, alo, ahi, blo, bhi):
  283. """Find longest matching block in a[alo:ahi] and b[blo:bhi].
  284. If isjunk is not defined:
  285. Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
  286. alo <= i <= i+k <= ahi
  287. blo <= j <= j+k <= bhi
  288. and for all (i',j',k') meeting those conditions,
  289. k >= k'
  290. i <= i'
  291. and if i == i', j <= j'
  292. In other words, of all maximal matching blocks, return one that
  293. starts earliest in a, and of all those maximal matching blocks that
  294. start earliest in a, return the one that starts earliest in b.
  295. >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
  296. >>> s.find_longest_match(0, 5, 0, 9)
  297. Match(a=0, b=4, size=5)
  298. If isjunk is defined, first the longest matching block is
  299. determined as above, but with the additional restriction that no
  300. junk element appears in the block. Then that block is extended as
  301. far as possible by matching (only) junk elements on both sides. So
  302. the resulting block never matches on junk except as identical junk
  303. happens to be adjacent to an "interesting" match.
  304. Here's the same example as before, but considering blanks to be
  305. junk. That prevents " abcd" from matching the " abcd" at the tail
  306. end of the second sequence directly. Instead only the "abcd" can
  307. match, and matches the leftmost "abcd" in the second sequence:
  308. >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
  309. >>> s.find_longest_match(0, 5, 0, 9)
  310. Match(a=1, b=0, size=4)
  311. If no blocks match, return (alo, blo, 0).
  312. >>> s = SequenceMatcher(None, "ab", "c")
  313. >>> s.find_longest_match(0, 2, 0, 1)
  314. Match(a=0, b=0, size=0)
  315. """
  316. # CAUTION: stripping common prefix or suffix would be incorrect.
  317. # E.g.,
  318. # ab
  319. # acab
  320. # Longest matching block is "ab", but if common prefix is
  321. # stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
  322. # strip, so ends up claiming that ab is changed to acab by
  323. # inserting "ca" in the middle. That's minimal but unintuitive:
  324. # "it's obvious" that someone inserted "ac" at the front.
  325. # Windiff ends up at the same place as diff, but by pairing up
  326. # the unique 'b's and then matching the first two 'a's.
  327. a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.isbjunk
  328. besti, bestj, bestsize = alo, blo, 0
  329. # find longest junk-free match
  330. # during an iteration of the loop, j2len[j] = length of longest
  331. # junk-free match ending with a[i-1] and b[j]
  332. j2len = {}
  333. nothing = []
  334. for i in xrange(alo, ahi):
  335. # look at all instances of a[i] in b; note that because
  336. # b2j has no junk keys, the loop is skipped if a[i] is junk
  337. j2lenget = j2len.get
  338. newj2len = {}
  339. for j in b2j.get(a[i], nothing):
  340. # a[i] matches b[j]
  341. if j < blo:
  342. continue
  343. if j >= bhi:
  344. break
  345. k = newj2len[j] = j2lenget(j-1, 0) + 1
  346. if k > bestsize:
  347. besti, bestj, bestsize = i-k+1, j-k+1, k
  348. j2len = newj2len
  349. # Extend the best by non-junk elements on each end. In particular,
  350. # "popular" non-junk elements aren't in b2j, which greatly speeds
  351. # the inner loop above, but also means "the best" match so far
  352. # doesn't contain any junk *or* popular non-junk elements.
  353. while besti > alo and bestj > blo and \
  354. not isbjunk(b[bestj-1]) 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. not isbjunk(b[bestj+bestsize]) and \
  359. a[besti+bestsize] == b[bestj+bestsize]:
  360. bestsize += 1
  361. # Now that we have a wholly interesting match (albeit possibly
  362. # empty!), we may as well suck up the matching junk on each
  363. # side of it too. Can't think of a good reason not to, and it
  364. # saves post-processing the (possibly considerable) expense of
  365. # figuring out what to do with it. In the case of an empty
  366. # interesting match, this is clearly the right thing to do,
  367. # because no other kind of match is possible in the regions.
  368. while besti > alo and bestj > blo and \
  369. isbjunk(b[bestj-1]) and \
  370. a[besti-1] == b[bestj-1]:
  371. besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
  372. while besti+bestsize < ahi and bestj+bestsize < bhi and \
  373. isbjunk(b[bestj+bestsize]) and \
  374. a[besti+bestsize] == b[bestj+bestsize]:
  375. bestsize = bestsize + 1
  376. return Match(besti, bestj, bestsize)
  377. def get_matching_blocks(self):
  378. """Return list of triples describing matching subsequences.
  379. Each triple is of the form (i, j, n), and means that
  380. a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
  381. i and in j. New in Python 2.5, it's also guaranteed that if
  382. (i, j, n) and (i', j', n') are adjacent triples in the list, and
  383. the second is not the last triple in the list, then i+n != i' or
  384. j+n != j'. IOW, adjacent triples never describe adjacent equal
  385. blocks.
  386. The last triple is a dummy, (len(a), len(b), 0), and is the only
  387. triple with n==0.
  388. >>> s = SequenceMatcher(None, "abxcd", "abcd")
  389. >>> s.get_matching_blocks()
  390. [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
  391. """
  392. if self.matching_blocks is not None:
  393. return self.matching_blocks
  394. la, lb = len(self.a), len(self.b)
  395. # This is most naturally expressed as a recursive algorithm, but
  396. # at least one user bumped into extreme use cases that exceeded
  397. # the recursion limit on their box. So, now we maintain a list
  398. # ('queue`) of blocks we still need to look at, and append partial
  399. # results to `matching_blocks` in a loop; the matches are sorted
  400. # at the end.
  401. queue = [(0, la, 0, lb)]
  402. matching_blocks = []
  403. while queue:
  404. alo, ahi, blo, bhi = queue.pop()
  405. i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)
  406. # a[alo:i] vs b[blo:j] unknown
  407. # a[i:i+k] same as b[j:j+k]
  408. # a[i+k:ahi] vs b[j+k:bhi] unknown
  409. if k: # if k is 0, there was no matching block
  410. matching_blocks.append(x)
  411. if alo < i and blo < j:
  412. queue.append((alo, i, blo, j))
  413. if i+k < ahi and j+k < bhi:
  414. queue.append((i+k, ahi, j+k, bhi))
  415. matching_blocks.sort()
  416. # It's possible that we have adjacent equal blocks in the
  417. # matching_blocks list now. Starting with 2.5, this code was added
  418. # to collapse them.
  419. i1 = j1 = k1 = 0
  420. non_adjacent = []
  421. for i2, j2, k2 in matching_blocks:
  422. # Is this block adjacent to i1, j1, k1?
  423. if i1 + k1 == i2 and j1 + k1 == j2:
  424. # Yes, so collapse them -- this just increases the length of
  425. # the first block by the length of the second, and the first
  426. # block so lengthened remains the block to compare against.
  427. k1 += k2
  428. else:
  429. # Not adjacent. Remember the first block (k1==0 means it's
  430. # the dummy we started with), and make the second block the
  431. # new block to compare against.
  432. if k1:
  433. non_adjacent.append((i1, j1, k1))
  434. i1, j1, k1 = i2, j2, k2
  435. if k1:
  436. non_adjacent.append((i1, j1, k1))
  437. non_adjacent.append( (la, lb, 0) )
  438. self.matching_blocks = non_adjacent
  439. return map(Match._make, self.matching_blocks)
  440. def get_opcodes(self):
  441. """Return list of 5-tuples describing how to turn a into b.
  442. Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
  443. has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
  444. tuple preceding it, and likewise for j1 == the previous j2.
  445. The tags are strings, with these meanings:
  446. 'replace': a[i1:i2] should be replaced by b[j1:j2]
  447. 'delete': a[i1:i2] should be deleted.
  448. Note that j1==j2 in this case.
  449. 'insert': b[j1:j2] should be inserted at a[i1:i1].
  450. Note that i1==i2 in this case.
  451. 'equal': a[i1:i2] == b[j1:j2]
  452. >>> a = "qabxcd"
  453. >>> b = "abycdf"
  454. >>> s = SequenceMatcher(None, a, b)
  455. >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
  456. ... print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
  457. ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))
  458. delete a[0:1] (q) b[0:0] ()
  459. equal a[1:3] (ab) b[0:2] (ab)
  460. replace a[3:4] (x) b[2:3] (y)
  461. equal a[4:6] (cd) b[3:5] (cd)
  462. insert a[6:6] () b[5:6] (f)
  463. """
  464. if self.opcodes is not None:
  465. return self.opcodes
  466. i = j = 0
  467. self.opcodes = answer = []
  468. for ai, bj, size in self.get_matching_blocks():
  469. # invariant: we've pumped out correct diffs to change
  470. # a[:i] into b[:j], and the next matching block is
  471. # a[ai:ai+size] == b[bj:bj+size]. So we need to pump
  472. # out a diff to change a[i:ai] into b[j:bj], pump out
  473. # the matching block, and move (i,j) beyond the match
  474. tag = ''
  475. if i < ai and j < bj:
  476. tag = 'replace'
  477. elif i < ai:
  478. tag = 'delete'
  479. elif j < bj:
  480. tag = 'insert'
  481. if tag:
  482. answer.append( (tag, i, ai, j, bj) )
  483. i, j = ai+size, bj+size
  484. # the list of matching blocks is terminated by a
  485. # sentinel with size 0
  486. if size:
  487. answer.append( ('equal', ai, i, bj, j) )
  488. return answer
  489. def get_grouped_opcodes(self, n=3):
  490. """ Isolate change clusters by eliminating ranges with no changes.
  491. Return a generator of groups with upto n lines of context.
  492. Each group is in the same format as returned by get_opcodes().
  493. >>> from pprint import pprint
  494. >>> a = map(str, range(1,40))
  495. >>> b = a[:]
  496. >>> b[8:8] = ['i'] # Make an insertion
  497. >>> b[20] += 'x' # Make a replacement
  498. >>> b[23:28] = [] # Make a deletion
  499. >>> b[30] += 'y' # Make another replacement
  500. >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
  501. [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
  502. [('equal', 16, 19, 17, 20),
  503. ('replace', 19, 20, 20, 21),
  504. ('equal', 20, 22, 21, 23),
  505. ('delete', 22, 27, 23, 23),
  506. ('equal', 27, 30, 23, 26)],
  507. [('equal', 31, 34, 27, 30),
  508. ('replace', 34, 35, 30, 31),
  509. ('equal', 35, 38, 31, 34)]]
  510. """
  511. codes = self.get_opcodes()
  512. if not codes:
  513. codes = [("equal", 0, 1, 0, 1)]
  514. # Fixup leading and trailing groups if they show no changes.
  515. if codes[0][0] == 'equal':
  516. tag, i1, i2, j1, j2 = codes[0]
  517. codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2
  518. if codes[-1][0] == 'equal':
  519. tag, i1, i2, j1, j2 = codes[-1]
  520. codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)
  521. nn = n + n
  522. group = []
  523. for tag, i1, i2, j1, j2 in codes:
  524. # End the current group and start a new one whenever
  525. # there is a large range with no changes.
  526. if tag == 'equal' and i2-i1 > nn:
  527. group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))
  528. yield group
  529. group = []
  530. i1, j1 = max(i1, i2-n), max(j1, j2-n)
  531. group.append((tag, i1, i2, j1 ,j2))
  532. if group and not (len(group)==1 and group[0][0] == 'equal'):
  533. yield group
  534. def ratio(self):
  535. """Return a measure of the sequences' similarity (float in [0,1]).
  536. Where T is the total number of elements in both sequences, and
  537. M is the number of matches, this is 2.0*M / T.
  538. Note that this is 1 if the sequences are identical, and 0 if
  539. they have nothing in common.
  540. .ratio() is expensive to compute if you haven't already computed
  541. .get_matching_blocks() or .get_opcodes(), in which case you may
  542. want to try .quick_ratio() or .real_quick_ratio() first to get an
  543. upper bound.
  544. >>> s = SequenceMatcher(None, "abcd", "bcde")
  545. >>> s.ratio()
  546. 0.75
  547. >>> s.quick_ratio()
  548. 0.75
  549. >>> s.real_quick_ratio()
  550. 1.0
  551. """
  552. matches = reduce(lambda sum, triple: sum + triple[-1],
  553. self.get_matching_blocks(), 0)
  554. return _calculate_ratio(matches, len(self.a) + len(self.b))
  555. def quick_ratio(self):
  556. """Return an upper bound on ratio() relatively quickly.
  557. This isn't defined beyond that it is an upper bound on .ratio(), and
  558. is faster to compute.
  559. """
  560. # viewing a and b as multisets, set matches to the cardinality
  561. # of their intersection; this counts the number of matches
  562. # without regard to order, so is clearly an upper bound
  563. if self.fullbcount is None:
  564. self.fullbcount = fullbcount = {}
  565. for elt in self.b:
  566. fullbcount[elt] = fullbcount.get(elt, 0) + 1
  567. fullbcount = self.fullbcount
  568. # avail[x] is the number of times x appears in 'b' less the
  569. # number of times we've seen it in 'a' so far ... kinda
  570. avail = {}
  571. availhas, matches = avail.__contains__, 0
  572. for elt in self.a:
  573. if availhas(elt):
  574. numb = avail[elt]
  575. else:
  576. numb = fullbcount.get(elt, 0)
  577. avail[elt] = numb - 1
  578. if numb > 0:
  579. matches = matches + 1
  580. return _calculate_ratio(matches, len(self.a) + len(self.b))
  581. def real_quick_ratio(self):
  582. """Return an upper bound on ratio() very quickly.
  583. This isn't defined beyond that it is an upper bound on .ratio(), and
  584. is faster to compute than either .ratio() or .quick_ratio().
  585. """
  586. la, lb = len(self.a), len(self.b)
  587. # can't have more matches than the number of elements in the
  588. # shorter sequence
  589. return _calculate_ratio(min(la, lb), la + lb)
  590. def get_close_matches(word, possibilities, n=3, cutoff=0.6):
  591. """Use SequenceMatcher to return list of the best "good enough" matches.
  592. word is a sequence for which close matches are desired (typically a
  593. string).
  594. possibilities is a list of sequences against which to match word
  595. (typically a list of strings).
  596. Optional arg n (default 3) is the maximum number of close matches to
  597. return. n must be > 0.
  598. Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
  599. that don't score at least that similar to word are ignored.
  600. The best (no more than n) matches among the possibilities are returned
  601. in a list, sorted by similarity score, most similar first.
  602. >>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
  603. ['apple', 'ape']
  604. >>> import keyword as _keyword
  605. >>> get_close_matches("wheel", _keyword.kwlist)
  606. ['while']
  607. >>> get_close_matches("apple", _keyword.kwlist)
  608. []
  609. >>> get_close_matches("accept", _keyword.kwlist)
  610. ['except']
  611. """
  612. if not n > 0:
  613. raise ValueError("n must be > 0: %r" % (n,))
  614. if not 0.0 <= cutoff <= 1.0:
  615. raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
  616. result = []
  617. s = SequenceMatcher()
  618. s.set_seq2(word)
  619. for x in possibilities:
  620. s.set_seq1(x)
  621. if s.real_quick_ratio() >= cutoff and \
  622. s.quick_ratio() >= cutoff and \
  623. s.ratio() >= cutoff:
  624. result.append((s.ratio(), x))
  625. # Move the best scorers to head of list
  626. result = heapq.nlargest(n, result)
  627. # Strip scores for the best n matches
  628. return [x for score, x in result]
  629. def _count_leading(line, ch):
  630. """
  631. Return number of `ch` characters at the start of `line`.
  632. Example:
  633. >>> _count_leading(' abc', ' ')
  634. 3
  635. """
  636. i, n = 0, len(line)
  637. while i < n and line[i] == ch:
  638. i += 1
  639. return i
  640. class Differ:
  641. r"""
  642. Differ is a class for comparing sequences of lines of text, and
  643. producing human-readable differences or deltas. Differ uses
  644. SequenceMatcher both to compare sequences of lines, and to compare
  645. sequences of characters within similar (near-matching) lines.
  646. Each line of a Differ delta begins with a two-letter code:
  647. '- ' line unique to sequence 1
  648. '+ ' line unique to sequence 2
  649. ' ' line common to both sequences
  650. '? ' line not present in either input sequence
  651. Lines beginning with '? ' attempt to guide the eye to intraline
  652. differences, and were not present in either input sequence. These lines
  653. can be confusing if the sequences contain tab characters.
  654. Note that Differ makes no claim to produce a *minimal* diff. To the
  655. contrary, minimal diffs are often counter-intuitive, because they synch
  656. up anywhere possible, sometimes accidental matches 100 pages apart.
  657. Restricting synch points to contiguous matches preserves some notion of
  658. locality, at the occasional cost of producing a longer diff.
  659. Example: Comparing two texts.
  660. First we set up the texts, sequences of individual single-line strings
  661. ending with newlines (such sequences can also be obtained from the
  662. `readlines()` method of file-like objects):
  663. >>> text1 = ''' 1. Beautiful is better than ugly.
  664. ... 2. Explicit is better than implicit.
  665. ... 3. Simple is better than complex.
  666. ... 4. Complex is better than complicated.
  667. ... '''.splitlines(1)
  668. >>> len(text1)
  669. 4
  670. >>> text1[0][-1]
  671. '\n'
  672. >>> text2 = ''' 1. Beautiful is better than ugly.
  673. ... 3. Simple is better than complex.
  674. ... 4. Complicated is better than complex.
  675. ... 5. Flat is better than nested.
  676. ... '''.splitlines(1)
  677. Next we instantiate a Differ object:
  678. >>> d = Differ()
  679. Note that when instantiating a Differ object we may pass functions to
  680. filter out line and character 'junk'. See Differ.__init__ for details.
  681. Finally, we compare the two:
  682. >>> result = list(d.compare(text1, text2))
  683. 'result' is a list of strings, so let's pretty-print it:
  684. >>> from pprint import pprint as _pprint
  685. >>> _pprint(result)
  686. [' 1. Beautiful is better than ugly.\n',
  687. '- 2. Explicit is better than implicit.\n',
  688. '- 3. Simple is better than complex.\n',
  689. '+ 3. Simple is better than complex.\n',
  690. '? ++\n',
  691. '- 4. Complex is better than complicated.\n',
  692. '? ^ ---- ^\n',
  693. '+ 4. Complicated is better than complex.\n',
  694. '? ++++ ^ ^\n',
  695. '+ 5. Flat is better than nested.\n']
  696. As a single multi-line string it looks like this:
  697. >>> print ''.join(result),
  698. 1. Beautiful is better than ugly.
  699. - 2. Explicit is better than implicit.
  700. - 3. Simple is better than complex.
  701. + 3. Simple is better than complex.
  702. ? ++
  703. - 4. Complex is better than complicated.
  704. ? ^ ---- ^
  705. + 4. Complicated is better than complex.
  706. ? ++++ ^ ^
  707. + 5. Flat is better than nested.
  708. Methods:
  709. __init__(linejunk=None, charjunk=None)
  710. Construct a text differencer, with optional filters.
  711. compare(a, b)
  712. Compare two sequences of lines; generate the resulting delta.
  713. """
  714. def __init__(self, linejunk=None, charjunk=None):
  715. """
  716. Construct a text differencer, with optional filters.
  717. The two optional keyword parameters are for filter functions:
  718. - `linejunk`: A function that should accept a single string argument,
  719. and return true iff the string is junk. The module-level function
  720. `IS_LINE_JUNK` may be used to filter out lines without visible
  721. characters, except for at most one splat ('#'). It is recommended
  722. to leave linejunk None; as of Python 2.3, the underlying
  723. SequenceMatcher class has grown an adaptive notion of "noise" lines
  724. that's better than any static definition the author has ever been
  725. able to craft.
  726. - `charjunk`: A function that should accept a string of length 1. The
  727. module-level function `IS_CHARACTER_JUNK` may be used to filter out
  728. whitespace characters (a blank or tab; **note**: bad idea to include
  729. newline in this!). Use of IS_CHARACTER_JUNK is recommended.
  730. """
  731. self.linejunk = linejunk
  732. self.charjunk = charjunk
  733. def compare(self, a, b):
  734. r"""
  735. Compare two sequences of lines; generate the resulting delta.
  736. Each sequence must contain individual single-line strings ending with
  737. newlines. Such sequences can be obtained from the `readlines()` method
  738. of file-like objects. The delta generated also consists of newline-
  739. terminated strings, ready to be printed as-is via the writeline()
  740. method of a file-like object.
  741. Example:
  742. >>> print ''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1),
  743. ... 'ore\ntree\nemu\n'.splitlines(1))),
  744. - one
  745. ? ^
  746. + ore
  747. ? ^
  748. - two
  749. - three
  750. ? -
  751. + tree
  752. + emu
  753. """
  754. cruncher = SequenceMatcher(self.linejunk, a, b)
  755. for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
  756. if tag == 'replace':
  757. g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
  758. elif tag == 'delete':
  759. g = self._dump('-', a, alo, ahi)
  760. elif tag == 'insert':
  761. g = self._dump('+', b, blo, bhi)
  762. elif tag == 'equal':
  763. g = self._dump(' ', a, alo, ahi)
  764. else:
  765. raise ValueError, 'unknown tag %r' % (tag,)
  766. for line in g:
  767. yield line
  768. def _dump(self, tag, x, lo, hi):
  769. """Generate comparison results for a same-tagged range."""
  770. for i in xrange(lo, hi):
  771. yield '%s %s' % (tag, x[i])
  772. def _plain_replace(self, a, alo, ahi, b, blo, bhi):
  773. assert alo < ahi and blo < bhi
  774. # dump the shorter block first -- reduces the burden on short-term
  775. # memory if the blocks are of very different sizes
  776. if bhi - blo < ahi - alo:
  777. first = self._dump('+', b, blo, bhi)
  778. second = self._dump('-', a, alo, ahi)
  779. else:
  780. first = self._dump('-', a, alo, ahi)
  781. second = self._dump('+', b, blo, bhi)
  782. for g in first, second:
  783. for line in g:
  784. yield line
  785. def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
  786. r"""
  787. When replacing one block of lines with another, search the blocks
  788. for *similar* lines; the best-matching pair (if any) is used as a
  789. synch point, and intraline difference marking is done on the
  790. similar pair. Lots of work, but often worth it.
  791. Example:
  792. >>> d = Differ()
  793. >>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
  794. ... ['abcdefGhijkl\n'], 0, 1)
  795. >>> print ''.join(results),
  796. - abcDefghiJkl
  797. ? ^ ^ ^
  798. + abcdefGhijkl
  799. ? ^ ^ ^
  800. """
  801. # don't synch up unless the lines have a similarity score of at
  802. # least cutoff; best_ratio tracks the best score seen so far
  803. best_ratio, cutoff = 0.74, 0.75
  804. cruncher = SequenceMatcher(self.charjunk)
  805. eqi, eqj = None, None # 1st indices of equal lines (if any)
  806. # search for the pair that matches best without being identical
  807. # (identical lines must be junk lines, & we don't want to synch up
  808. # on junk -- unless we have to)
  809. for j in xrange(blo, bhi):
  810. bj = b[j]
  811. cruncher.set_seq2(bj)
  812. for i in xrange(alo, ahi):
  813. ai = a[i]
  814. if ai == bj:
  815. if eqi is None:
  816. eqi, eqj = i, j
  817. continue
  818. cruncher.set_seq1(ai)
  819. # computing similarity is expensive, so use the quick
  820. # upper bounds first -- have seen this speed up messy
  821. # compares by a factor of 3.
  822. # note that ratio() is only expensive to compute the first
  823. # time it's called on a sequence pair; the expensive part
  824. # of the computation is cached by cruncher
  825. if cruncher.real_quick_ratio() > best_ratio and \
  826. cruncher.quick_ratio() > best_ratio and \
  827. cruncher.ratio() > best_ratio:
  828. best_ratio, best_i, best_j = cruncher.ratio(), i, j
  829. if best_ratio < cutoff:
  830. # no non-identical "pretty close" pair
  831. if eqi is None:
  832. # no identical pair either -- treat it as a straight replace
  833. for line in self._plain_replace(a, alo, ahi, b, blo, bhi):
  834. yield line
  835. return
  836. # no close pair, but an identical pair -- synch up on that
  837. best_i, best_j, best_ratio = eqi, eqj, 1.0
  838. else:
  839. # there's a close pair, so forget the identical pair (if any)
  840. eqi = None
  841. # a[best_i] very similar to b[best_j]; eqi is None iff they're not
  842. # identical
  843. # pump out diffs from before the synch point
  844. for line in self._fancy_helper(a, alo, best_i, b, blo, best_j):
  845. yield line
  846. # do intraline marking on the synch pair
  847. aelt, belt = a[best_i], b[best_j]
  848. if eqi is None:
  849. # pump out a '-', '?', '+', '?' quad for the synched lines
  850. atags = btags = ""
  851. cruncher.set_seqs(aelt, belt)
  852. for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
  853. la, lb = ai2 - ai1, bj2 - bj1
  854. if tag == 'replace':
  855. atags += '^' * la
  856. btags += '^' * lb
  857. elif tag == 'delete':
  858. atags += '-' * la
  859. elif tag == 'insert':
  860. btags += '+' * lb
  861. elif tag == 'equal':
  862. atags += ' ' * la
  863. btags += ' ' * lb
  864. else:
  865. raise ValueError, 'unknown tag %r' % (tag,)
  866. for line in self._qformat(aelt, belt, atags, btags):
  867. yield line
  868. else:
  869. # the synch pair is identical
  870. yield ' ' + aelt
  871. # pump out diffs from after the synch point
  872. for line in self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi):
  873. yield line
  874. def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
  875. g = []
  876. if alo < ahi:
  877. if blo < bhi:
  878. g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
  879. else:
  880. g = self._dump('-', a, alo, ahi)
  881. elif blo < bhi:
  882. g = self._dump('+', b, blo, bhi)
  883. for line in g:
  884. yield line
  885. def _qformat(self, aline, bline, atags, btags):
  886. r"""
  887. Format "?" output and deal with leading tabs.
  888. Example:
  889. >>> d = Differ()
  890. >>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n',
  891. ... ' ^ ^ ^ ', ' ^ ^ ^ ')
  892. >>> for line in results: print repr(line)
  893. ...
  894. '- \tabcDefghiJkl\n'
  895. '? \t ^ ^ ^\n'
  896. '+ \tabcdefGhijkl\n'
  897. '? \t ^ ^ ^\n'
  898. """
  899. # Can hurt, but will probably help most of the time.
  900. common = min(_count_leading(aline, "\t"),
  901. _count_leading(bline, "\t"))
  902. common = min(common, _count_leading(atags[:common], " "))
  903. common = min(common, _count_leading(btags[:common], " "))
  904. atags = atags[common:].rstrip()
  905. btags = btags[common:].rstrip()
  906. yield "- " + aline
  907. if atags:
  908. yield "? %s%s\n" % ("\t" * common, atags)
  909. yield "+ " + bline
  910. if btags:
  911. yield "? %s%s\n" % ("\t" * common, btags)
  912. # With respect to junk, an earlier version of ndiff simply refused to
  913. # *start* a match with a junk element. The result was cases like this:
  914. # before: private Thread currentThread;
  915. # after: private volatile Thread currentThread;
  916. # If you consider whitespace to be junk, the longest contiguous match
  917. # not starting with junk is "e Thread currentThread". So ndiff reported
  918. # that "e volatil" was inserted between the 't' and the 'e' in "private".
  919. # While an accurate view, to people that's absurd. The current version
  920. # looks for matching blocks that are entirely junk-free, then extends the
  921. # longest one of those as far as possible but only with matching junk.
  922. # So now "currentThread" is matched, then extended to suck up the
  923. # preceding blank; then "private" is matched, and extended to suck up the
  924. # following blank; then "Thread" is matched; and finally ndiff reports
  925. # that "volatile " was inserted before "Thread". The only quibble
  926. # remaining is that perhaps it was really the case that " volatile"
  927. # was inserted after "private". I can live with that <wink>.
  928. import re
  929. def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match):
  930. r"""
  931. Return 1 for ignorable line: iff `line` is blank or contains a single '#'.
  932. Examples:
  933. >>> IS_LINE_JUNK('\n')
  934. True
  935. >>> IS_LINE_JUNK(' # \n')
  936. True
  937. >>> IS_LINE_JUNK('hello\n')
  938. False
  939. """
  940. return pat(line) is not None
  941. def IS_CHARACTER_JUNK(ch, ws=" \t"):
  942. r"""
  943. Return 1 for ignorable character: iff `ch` is a space or tab.
  944. Examples:
  945. >>> IS_CHARACTER_JUNK(' ')
  946. True
  947. >>> IS_CHARACTER_JUNK('\t')
  948. True
  949. >>> IS_CHARACTER_JUNK('\n')
  950. False
  951. >>> IS_CHARACTER_JUNK('x')
  952. False
  953. """
  954. return ch in ws
  955. ########################################################################
  956. ### Unified Diff
  957. ########################################################################
  958. def _format_range_unified(start, stop):
  959. 'Convert range to the "ed" format'
  960. # Per the diff spec at http://www.unix.org/single_unix_specification/
  961. beginning = start + 1 # lines start numbering with one
  962. length = stop - start
  963. if length == 1:
  964. return '{}'.format(beginning)
  965. if not length:
  966. beginning -= 1 # empty ranges begin at line just before the range
  967. return '{},{}'.format(beginning, length)
  968. def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
  969. tofiledate='', n=3, lineterm='\n'):
  970. r"""
  971. Compare two sequences of lines; generate the delta as a unified diff.
  972. Unified diffs are a compact way of showing line changes and a few
  973. lines of context. The number of context lines is set by 'n' which
  974. defaults to three.
  975. By default, the diff control lines (those with ---, +++, or @@) are
  976. created with a trailing newline. This is helpful so that inputs
  977. created from file.readlines() result in diffs that are suitable for
  978. file.writelines() since both the inputs and outputs have trailing
  979. newlines.
  980. For inputs that do not have trailing newlines, set the lineterm
  981. argument to "" so that the output will be uniformly newline free.
  982. The unidiff format normally has a header for filenames and modification
  983. times. Any or all of these may be specified using strings for
  984. 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
  985. The modification times are normally expressed in the ISO 8601 format.
  986. Example:
  987. >>> for line in unified_diff('one two three four'.split(),
  988. ... 'zero one tree four'.split(), 'Original', 'Current',
  989. ... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
  990. ... lineterm=''):
  991. ... print line # doctest: +NORMALIZE_WHITESPACE
  992. --- Original 2005-01-26 23:30:50
  993. +++ Current 2010-04-02 10:20:52
  994. @@ -1,4 +1,4 @@
  995. +zero
  996. one
  997. -two
  998. -three
  999. +tree
  1000. four
  1001. """
  1002. started = False
  1003. for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
  1004. if not started:
  1005. started = True
  1006. fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
  1007. todate = '\t{}'.format(tofiledate) if tofiledate else ''
  1008. yield '--- {}{}{}'.format(fromfile, fromdate, lineterm)
  1009. yield '+++ {}{}{}'.format(tofile, todate, lineterm)
  1010. first, last = group[0], group[-1]
  1011. file1_range = _format_range_unified(first[1], last[2])
  1012. file2_range = _format_range_unified(first[3], last[4])
  1013. yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm)
  1014. for tag, i1, i2, j1, j2 in group:
  1015. if tag == 'equal':
  1016. for line in a[i1:i2]:
  1017. yield ' ' + line
  1018. continue
  1019. if tag in ('replace', 'delete'):
  1020. for line in a[i1:i2]:
  1021. yield '-' + line
  1022. if tag in ('replace', 'insert'):
  1023. for line in b[j1:j2]:
  1024. yield '+' + line
  1025. ########################################################################
  1026. ### Context Diff
  1027. ########################################################################
  1028. def _format_range_context(start, stop):
  1029. 'Convert range to the "ed" format'
  1030. # Per the diff spec at http://www.unix.org/single_unix_specification/
  1031. beginning = start + 1 # lines start numbering with one
  1032. length = stop - start
  1033. if not length:
  1034. beginning -= 1 # empty ranges begin at line just before the range
  1035. if length <= 1:
  1036. return '{}'.format(beginning)
  1037. return '{},{}'.format(beginning, beginning + length - 1)
  1038. # See http://www.unix.org/single_unix_specification/
  1039. def context_diff(a, b, fromfile='', tofile='',
  1040. fromfiledate='', tofiledate='', n=3, lineterm='\n'):
  1041. r"""
  1042. Compare two sequences of lines; generate the delta as a context diff.
  1043. Context diffs are a compact way of showing line changes and a few
  1044. lines of context. The number of context lines is set by 'n' which
  1045. defaults to three.
  1046. By default, the diff control lines (those with *** or ---) are
  1047. created with a trailing newline. This is helpful so that inputs
  1048. created from file.readlines() result in diffs that are suitable for
  1049. file.writelines() since both the inputs and outputs have trailing
  1050. newlines.
  1051. For inputs that do not have trailing newlines, set the lineterm
  1052. argument to "" so that the output will be uniformly newline free.
  1053. The context diff format normally has a header for filenames and
  1054. modification times. Any or all of these may be specified using
  1055. strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
  1056. The modification times are normally expressed in the ISO 8601 format.
  1057. If not specified, the strings default to blanks.
  1058. Example:
  1059. >>> print ''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1),
  1060. ... 'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current')),
  1061. *** Original
  1062. --- Current
  1063. ***************
  1064. *** 1,4 ****
  1065. one
  1066. ! two
  1067. ! three
  1068. four
  1069. --- 1,4 ----
  1070. + zero
  1071. one
  1072. ! tree
  1073. four
  1074. """
  1075. prefix = dict(insert='+ ', delete='- ', replace='! ', equal=' ')
  1076. started = False
  1077. for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
  1078. if not started:
  1079. started = True
  1080. fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
  1081. todate = '\t{}'.format(tofiledate) if tofiledate else ''
  1082. yie

Large files files are truncated, but you can click here to view the full file