difflib.coffee 45 KB

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