difflib.js 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486
  1. // Generated by CoffeeScript 1.3.1
  2. /*
  3. Module difflib -- helpers for computing deltas between objects.
  4. Function getCloseMatches(word, possibilities, n=3, cutoff=0.6):
  5. Use SequenceMatcher to return list of the best "good enough" matches.
  6. Function contextDiff(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 unifiedDiff(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. */
  19. (function() {
  20. var Differ, Heap, IS_CHARACTER_JUNK, IS_LINE_JUNK, SequenceMatcher, assert, contextDiff, floor, getCloseMatches, max, min, ndiff, restore, unifiedDiff, _any, _arrayCmp, _calculateRatio, _countLeading, _formatRangeContext, _formatRangeUnified, _has,
  21. __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
  22. floor = Math.floor, max = Math.max, min = Math.min;
  23. Heap = require('heap');
  24. assert = require('assert');
  25. _calculateRatio = function(matches, length) {
  26. if (length) {
  27. return 2.0 * matches / length;
  28. } else {
  29. return 1.0;
  30. }
  31. };
  32. _arrayCmp = function(a, b) {
  33. var i, la, lb, _i, _ref, _ref1;
  34. _ref = [a.length, b.length], la = _ref[0], lb = _ref[1];
  35. for (i = _i = 0, _ref1 = min(la, lb); 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) {
  36. if (a[i] < b[i]) {
  37. return -1;
  38. }
  39. if (a[i] > b[i]) {
  40. return 1;
  41. }
  42. }
  43. return la - lb;
  44. };
  45. _has = function(obj, key) {
  46. return Object.prototype.hasOwnProperty.call(obj, key);
  47. };
  48. _any = function(items) {
  49. var item, _i, _len;
  50. for (_i = 0, _len = items.length; _i < _len; _i++) {
  51. item = items[_i];
  52. if (item) {
  53. return true;
  54. }
  55. }
  56. return false;
  57. };
  58. SequenceMatcher = (function() {
  59. SequenceMatcher.name = 'SequenceMatcher';
  60. /*
  61. SequenceMatcher is a flexible class for comparing pairs of sequences of
  62. any type, so long as the sequence elements are hashable. The basic
  63. algorithm predates, and is a little fancier than, an algorithm
  64. published in the late 1980's by Ratcliff and Obershelp under the
  65. hyperbolic name "gestalt pattern matching". The basic idea is to find
  66. the longest contiguous matching subsequence that contains no "junk"
  67. elements (R-O doesn't address junk). The same idea is then applied
  68. recursively to the pieces of the sequences to the left and to the right
  69. of the matching subsequence. This does not yield minimal edit
  70. sequences, but does tend to yield matches that "look right" to people.
  71. SequenceMatcher tries to compute a "human-friendly diff" between two
  72. sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
  73. longest *contiguous* & junk-free matching subsequence. That's what
  74. catches peoples' eyes. The Windows(tm) windiff has another interesting
  75. notion, pairing up elements that appear uniquely in each sequence.
  76. That, and the method here, appear to yield more intuitive difference
  77. reports than does diff. This method appears to be the least vulnerable
  78. to synching up on blocks of "junk lines", though (like blank lines in
  79. ordinary text files, or maybe "<P>" lines in HTML files). That may be
  80. because this is the only method of the 3 that has a *concept* of
  81. "junk" <wink>.
  82. Example, comparing two strings, and considering blanks to be "junk":
  83. >>> isjunk = (c) -> c is ' '
  84. >>> s = new SequenceMatcher(isjunk,
  85. 'private Thread currentThread;',
  86. 'private volatile Thread currentThread;')
  87. .ratio() returns a float in [0, 1], measuring the "similarity" of the
  88. sequences. As a rule of thumb, a .ratio() value over 0.6 means the
  89. sequences are close matches:
  90. >>> s.ratio().toPrecision(3)
  91. '0.866'
  92. If you're only interested in where the sequences match,
  93. .getMatchingBlocks() is handy:
  94. >>> for [a, b, size] in s.getMatchingBlocks()
  95. ... console.log("a[#{a}] and b[#{b}] match for #{size} elements");
  96. a[0] and b[0] match for 8 elements
  97. a[8] and b[17] match for 21 elements
  98. a[29] and b[38] match for 0 elements
  99. Note that the last tuple returned by .get_matching_blocks() is always a
  100. dummy, (len(a), len(b), 0), and this is the only case in which the last
  101. tuple element (number of elements matched) is 0.
  102. If you want to know how to change the first sequence into the second,
  103. use .get_opcodes():
  104. >>> for [op, a1, a2, b1, b2] in s.getOpcodes()
  105. ... console.log "#{op} a[#{a1}:#{a2}] b[#{b1}:#{b2}]"
  106. equal a[0:8] b[0:8]
  107. insert a[8:8] b[8:17]
  108. equal a[8:29] b[17:38]
  109. See the Differ class for a fancy human-friendly file differencer, which
  110. uses SequenceMatcher both to compare sequences of lines, and to compare
  111. sequences of characters within similar (near-matching) lines.
  112. See also function getCloseMatches() in this module, which shows how
  113. simple code building on SequenceMatcher can be used to do useful work.
  114. Timing: Basic R-O is cubic time worst case and quadratic time expected
  115. case. SequenceMatcher is quadratic time for the worst case and has
  116. expected-case behavior dependent in a complicated way on how many
  117. elements the sequences have in common; best case time is linear.
  118. Methods:
  119. constructor(isjunk=null, a='', b='')
  120. Construct a SequenceMatcher.
  121. setSeqs(a, b)
  122. Set the two sequences to be compared.
  123. setSeq1(a)
  124. Set the first sequence to be compared.
  125. setSeq2(b)
  126. Set the second sequence to be compared.
  127. findLongestMatch(alo, ahi, blo, bhi)
  128. Find longest matching block in a[alo:ahi] and b[blo:bhi].
  129. getMatchingBlocks()
  130. Return list of triples describing matching subsequences.
  131. getOpcodes()
  132. Return list of 5-tuples describing how to turn a into b.
  133. ratio()
  134. Return a measure of the sequences' similarity (float in [0,1]).
  135. quickRatio()
  136. Return an upper bound on .ratio() relatively quickly.
  137. realQuickRatio()
  138. Return an upper bound on ratio() very quickly.
  139. */
  140. function SequenceMatcher(isjunk, a, b, autojunk) {
  141. this.isjunk = isjunk;
  142. if (a == null) {
  143. a = '';
  144. }
  145. if (b == null) {
  146. b = '';
  147. }
  148. this.autojunk = autojunk != null ? autojunk : true;
  149. /*
  150. Construct a SequenceMatcher.
  151. Optional arg isjunk is null (the default), or a one-argument
  152. function that takes a sequence element and returns true iff the
  153. element is junk. Null is equivalent to passing "(x) -> 0", i.e.
  154. no elements are considered to be junk. For example, pass
  155. (x) -> x in ' \t'
  156. if you're comparing lines as sequences of characters, and don't
  157. want to synch up on blanks or hard tabs.
  158. Optional arg a is the first of two sequences to be compared. By
  159. default, an empty string. The elements of a must be hashable. See
  160. also .setSeqs() and .setSeq1().
  161. Optional arg b is the second of two sequences to be compared. By
  162. default, an empty string. The elements of b must be hashable. See
  163. also .setSeqs() and .setSeq2().
  164. Optional arg autojunk should be set to false to disable the
  165. "automatic junk heuristic" that treats popular elements as junk
  166. (see module documentation for more information).
  167. */
  168. this.a = this.b = null;
  169. this.setSeqs(a, b);
  170. }
  171. SequenceMatcher.prototype.setSeqs = function(a, b) {
  172. /*
  173. Set the two sequences to be compared.
  174. >>> s = new SequenceMatcher()
  175. >>> s.setSeqs('abcd', 'bcde')
  176. >>> s.ratio()
  177. 0.75
  178. */
  179. this.setSeq1(a);
  180. return this.setSeq2(b);
  181. };
  182. SequenceMatcher.prototype.setSeq1 = function(a) {
  183. /*
  184. Set the first sequence to be compared.
  185. The second sequence to be compared is not changed.
  186. >>> s = new SequenceMatcher(null, 'abcd', 'bcde')
  187. >>> s.ratio()
  188. 0.75
  189. >>> s.setSeq1('bcde')
  190. >>> s.ratio()
  191. 1.0
  192. SequenceMatcher computes and caches detailed information about the
  193. second sequence, so if you want to compare one sequence S against
  194. many sequences, use .setSeq2(S) once and call .setSeq1(x)
  195. repeatedly for each of the other sequences.
  196. See also setSeqs() and setSeq2().
  197. */
  198. if (a === this.a) {
  199. return;
  200. }
  201. this.a = a;
  202. return this.matchingBlocks = this.opcodes = null;
  203. };
  204. SequenceMatcher.prototype.setSeq2 = function(b) {
  205. /*
  206. Set the second sequence to be compared.
  207. The first sequence to be compared is not changed.
  208. >>> s = new SequenceMatcher(null, 'abcd', 'bcde')
  209. >>> s.ratio()
  210. 0.75
  211. >>> s.setSeq2('abcd')
  212. >>> s.ratio()
  213. 1.0
  214. SequenceMatcher computes and caches detailed information about the
  215. second sequence, so if you want to compare one sequence S against
  216. many sequences, use .setSeq2(S) once and call .setSeq1(x)
  217. repeatedly for each of the other sequences.
  218. See also setSeqs() and setSeq1().
  219. */
  220. if (b === this.b) {
  221. return;
  222. }
  223. this.b = b;
  224. this.matchingBlocks = this.opcodes = null;
  225. this.fullbcount = null;
  226. return this._chainB();
  227. };
  228. SequenceMatcher.prototype._chainB = function() {
  229. var b, b2j, elt, i, idxs, indices, isjunk, junk, n, ntest, popular, _i, _j, _len, _len1, _ref;
  230. b = this.b;
  231. this.b2j = b2j = {};
  232. for (i = _i = 0, _len = b.length; _i < _len; i = ++_i) {
  233. elt = b[i];
  234. indices = _has(b2j, elt) ? b2j[elt] : b2j[elt] = [];
  235. indices.push(i);
  236. }
  237. junk = {};
  238. isjunk = this.isjunk;
  239. if (isjunk) {
  240. _ref = Object.keys(b2j);
  241. for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
  242. elt = _ref[_j];
  243. if (isjunk(elt)) {
  244. junk[elt] = true;
  245. delete b2j[elt];
  246. }
  247. }
  248. }
  249. popular = {};
  250. n = b.length;
  251. if (this.autojunk && n >= 200) {
  252. ntest = floor(n / 100) + 1;
  253. for (elt in b2j) {
  254. idxs = b2j[elt];
  255. if (idxs.length > ntest) {
  256. popular[elt] = true;
  257. delete b2j[elt];
  258. }
  259. }
  260. }
  261. this.isbjunk = function(b) {
  262. return _has(junk, b);
  263. };
  264. return this.isbpopular = function(b) {
  265. return _has(popular, b);
  266. };
  267. };
  268. SequenceMatcher.prototype.findLongestMatch = function(alo, ahi, blo, bhi) {
  269. /*
  270. Find longest matching block in a[alo...ahi] and b[blo...bhi].
  271. If isjunk is not defined:
  272. Return [i,j,k] such that a[i...i+k] is equal to b[j...j+k], where
  273. alo <= i <= i+k <= ahi
  274. blo <= j <= j+k <= bhi
  275. and for all [i',j',k'] meeting those conditions,
  276. k >= k'
  277. i <= i'
  278. and if i == i', j <= j'
  279. In other words, of all maximal matching blocks, return one that
  280. starts earliest in a, and of all those maximal matching blocks that
  281. start earliest in a, return the one that starts earliest in b.
  282. >>> isjunk = (x) -> x is ' '
  283. >>> s = new SequenceMatcher(isjunk, ' abcd', 'abcd abcd')
  284. >>> s.findLongestMatch(0, 5, 0, 9)
  285. [1, 0, 4]
  286. >>> s = new SequenceMatcher(null, 'ab', 'c')
  287. >>> s.findLongestMatch(0, 2, 0, 1)
  288. [0, 0, 0]
  289. */
  290. var a, b, b2j, besti, bestj, bestsize, i, isbjunk, j, j2len, k, newj2len, _i, _j, _len, _ref, _ref1, _ref2, _ref3, _ref4, _ref5;
  291. _ref = [this.a, this.b, this.b2j, this.isbjunk], a = _ref[0], b = _ref[1], b2j = _ref[2], isbjunk = _ref[3];
  292. _ref1 = [alo, blo, 0], besti = _ref1[0], bestj = _ref1[1], bestsize = _ref1[2];
  293. j2len = {};
  294. for (i = _i = alo; alo <= ahi ? _i < ahi : _i > ahi; i = alo <= ahi ? ++_i : --_i) {
  295. newj2len = {};
  296. _ref2 = (_has(b2j, a[i]) ? b2j[a[i]] : []);
  297. for (_j = 0, _len = _ref2.length; _j < _len; _j++) {
  298. j = _ref2[_j];
  299. if (j < blo) {
  300. continue;
  301. }
  302. if (j >= bhi) {
  303. break;
  304. }
  305. k = newj2len[j] = (j2len[j - 1] || 0) + 1;
  306. if (k > bestsize) {
  307. _ref3 = [i - k + 1, j - k + 1, k], besti = _ref3[0], bestj = _ref3[1], bestsize = _ref3[2];
  308. }
  309. }
  310. j2len = newj2len;
  311. }
  312. while (besti > alo && bestj > blo && !isbjunk(b[bestj - 1]) && a[besti - 1] === b[bestj - 1]) {
  313. _ref4 = [besti - 1, bestj - 1, bestsize + 1], besti = _ref4[0], bestj = _ref4[1], bestsize = _ref4[2];
  314. }
  315. while (besti + bestsize < ahi && bestj + bestsize < bhi && !isbjunk(b[bestj + bestsize]) && a[besti + bestsize] === b[bestj + bestsize]) {
  316. bestsize++;
  317. }
  318. while (besti > alo && bestj > blo && isbjunk(b[bestj - 1]) && a[besti - 1] === b[bestj - 1]) {
  319. _ref5 = [besti - 1, bestj - 1, bestsize + 1], besti = _ref5[0], bestj = _ref5[1], bestsize = _ref5[2];
  320. }
  321. while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b[bestj + bestsize]) && a[besti + bestsize] === b[bestj + bestsize]) {
  322. bestsize++;
  323. }
  324. return [besti, bestj, bestsize];
  325. };
  326. SequenceMatcher.prototype.getMatchingBlocks = function() {
  327. /*
  328. Return list of triples describing matching subsequences.
  329. Each triple is of the form [i, j, n], and means that
  330. a[i...i+n] == b[j...j+n]. The triples are monotonically increasing in
  331. i and in j. it's also guaranteed that if
  332. [i, j, n] and [i', j', n'] are adjacent triples in the list, and
  333. the second is not the last triple in the list, then i+n != i' or
  334. j+n != j'. IOW, adjacent triples never describe adjacent equal
  335. blocks.
  336. The last triple is a dummy, [a.length, b.length, 0], and is the only
  337. triple with n==0.
  338. >>> s = new SequenceMatcher(null, 'abxcd', 'abcd')
  339. >>> s.getMatchingBlocks()
  340. [[0, 0, 2], [3, 2, 2], [5, 4, 0]]
  341. */
  342. var ahi, alo, bhi, blo, i, i1, i2, j, j1, j2, k, k1, k2, la, lb, matchingBlocks, nonAdjacent, queue, x, _i, _len, _ref, _ref1, _ref2, _ref3, _ref4;
  343. if (this.matchingBlocks) {
  344. return this.matchingBlocks;
  345. }
  346. _ref = [this.a.length, this.b.length], la = _ref[0], lb = _ref[1];
  347. queue = [[0, la, 0, lb]];
  348. matchingBlocks = [];
  349. while (queue.length) {
  350. _ref1 = queue.pop(), alo = _ref1[0], ahi = _ref1[1], blo = _ref1[2], bhi = _ref1[3];
  351. _ref2 = x = this.findLongestMatch(alo, ahi, blo, bhi), i = _ref2[0], j = _ref2[1], k = _ref2[2];
  352. if (k) {
  353. matchingBlocks.push(x);
  354. if (alo < i && blo < j) {
  355. queue.push([alo, i, blo, j]);
  356. }
  357. if (i + k < ahi && j + k < bhi) {
  358. queue.push([i + k, ahi, j + k, bhi]);
  359. }
  360. }
  361. }
  362. matchingBlocks.sort(_arrayCmp);
  363. i1 = j1 = k1 = 0;
  364. nonAdjacent = [];
  365. for (_i = 0, _len = matchingBlocks.length; _i < _len; _i++) {
  366. _ref3 = matchingBlocks[_i], i2 = _ref3[0], j2 = _ref3[1], k2 = _ref3[2];
  367. if (i1 + k1 === i2 && j1 + k1 === j2) {
  368. k1 += k2;
  369. } else {
  370. if (k1) {
  371. nonAdjacent.push([i1, j1, k1]);
  372. }
  373. _ref4 = [i2, j2, k2], i1 = _ref4[0], j1 = _ref4[1], k1 = _ref4[2];
  374. }
  375. }
  376. if (k1) {
  377. nonAdjacent.push([i1, j1, k1]);
  378. }
  379. nonAdjacent.push([la, lb, 0]);
  380. return this.matchingBlocks = nonAdjacent;
  381. };
  382. SequenceMatcher.prototype.getOpcodes = function() {
  383. /*
  384. Return list of 5-tuples describing how to turn a into b.
  385. Each tuple is of the form [tag, i1, i2, j1, j2]. The first tuple
  386. has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
  387. tuple preceding it, and likewise for j1 == the previous j2.
  388. The tags are strings, with these meanings:
  389. 'replace': a[i1...i2] should be replaced by b[j1...j2]
  390. 'delete': a[i1...i2] should be deleted.
  391. Note that j1==j2 in this case.
  392. 'insert': b[j1...j2] should be inserted at a[i1...i1].
  393. Note that i1==i2 in this case.
  394. 'equal': a[i1...i2] == b[j1...j2]
  395. >>> s = new SequenceMatcher(null, 'qabxcd', 'abycdf')
  396. >>> s.getOpcodes()
  397. [ [ 'delete' , 0 , 1 , 0 , 0 ] ,
  398. [ 'equal' , 1 , 3 , 0 , 2 ] ,
  399. [ 'replace' , 3 , 4 , 2 , 3 ] ,
  400. [ 'equal' , 4 , 6 , 3 , 5 ] ,
  401. [ 'insert' , 6 , 6 , 5 , 6 ] ]
  402. */
  403. var ai, answer, bj, i, j, size, tag, _i, _len, _ref, _ref1, _ref2;
  404. if (this.opcodes) {
  405. return this.opcodes;
  406. }
  407. i = j = 0;
  408. this.opcodes = answer = [];
  409. _ref = this.getMatchingBlocks();
  410. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  411. _ref1 = _ref[_i], ai = _ref1[0], bj = _ref1[1], size = _ref1[2];
  412. tag = '';
  413. if (i < ai && j < bj) {
  414. tag = 'replace';
  415. } else if (i < ai) {
  416. tag = 'delete';
  417. } else if (j < bj) {
  418. tag = 'insert';
  419. }
  420. if (tag) {
  421. answer.push([tag, i, ai, j, bj]);
  422. }
  423. _ref2 = [ai + size, bj + size], i = _ref2[0], j = _ref2[1];
  424. if (size) {
  425. answer.push(['equal', ai, i, bj, j]);
  426. }
  427. }
  428. return answer;
  429. };
  430. SequenceMatcher.prototype.getGroupedOpcodes = function(n) {
  431. var codes, group, groups, i1, i2, j1, j2, nn, tag, _i, _len, _ref, _ref1, _ref2, _ref3;
  432. if (n == null) {
  433. n = 3;
  434. }
  435. /*
  436. Isolate change clusters by eliminating ranges with no changes.
  437. Return a list groups with upto n lines of context.
  438. Each group is in the same format as returned by get_opcodes().
  439. >>> a = [1...40].map(String)
  440. >>> b = a.slice()
  441. >>> b[8...8] = 'i'
  442. >>> b[20] += 'x'
  443. >>> b[23...28] = []
  444. >>> b[30] += 'y'
  445. >>> s = new SequenceMatcher(null, a, b)
  446. >>> s.getGroupedOpcodes()
  447. [ [ [ 'equal' , 5 , 8 , 5 , 8 ],
  448. [ 'insert' , 8 , 8 , 8 , 9 ],
  449. [ 'equal' , 8 , 11 , 9 , 12 ] ],
  450. [ [ 'equal' , 16 , 19 , 17 , 20 ],
  451. [ 'replace' , 19 , 20 , 20 , 21 ],
  452. [ 'equal' , 20 , 22 , 21 , 23 ],
  453. [ 'delete' , 22 , 27 , 23 , 23 ],
  454. [ 'equal' , 27 , 30 , 23 , 26 ] ],
  455. [ [ 'equal' , 31 , 34 , 27 , 30 ],
  456. [ 'replace' , 34 , 35 , 30 , 31 ],
  457. [ 'equal' , 35 , 38 , 31 , 34 ] ] ]
  458. */
  459. codes = this.getOpcodes();
  460. if (!codes.length) {
  461. codes = [['equal', 0, 1, 0, 1]];
  462. }
  463. if (codes[0][0] === 'equal') {
  464. _ref = codes[0], tag = _ref[0], i1 = _ref[1], i2 = _ref[2], j1 = _ref[3], j2 = _ref[4];
  465. codes[0] = [tag, max(i1, i2 - n), i2, max(j1, j2 - n), j2];
  466. }
  467. if (codes[codes.length - 1][0] === 'equal') {
  468. _ref1 = codes[codes.length - 1], tag = _ref1[0], i1 = _ref1[1], i2 = _ref1[2], j1 = _ref1[3], j2 = _ref1[4];
  469. codes[codes.length - 1] = [tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n)];
  470. }
  471. nn = n + n;
  472. groups = [];
  473. group = [];
  474. for (_i = 0, _len = codes.length; _i < _len; _i++) {
  475. _ref2 = codes[_i], tag = _ref2[0], i1 = _ref2[1], i2 = _ref2[2], j1 = _ref2[3], j2 = _ref2[4];
  476. if (tag === 'equal' && i2 - i1 > nn) {
  477. group.push([tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n)]);
  478. groups.push(group);
  479. group = [];
  480. _ref3 = [max(i1, i2 - n), max(j1, j2 - n)], i1 = _ref3[0], j1 = _ref3[1];
  481. }
  482. group.push([tag, i1, i2, j1, j2]);
  483. }
  484. if (group.length && !(group.length === 1 && group[0][0] === 'equal')) {
  485. groups.push(group);
  486. }
  487. return groups;
  488. };
  489. SequenceMatcher.prototype.ratio = function() {
  490. /*
  491. Return a measure of the sequences' similarity (float in [0,1]).
  492. Where T is the total number of elements in both sequences, and
  493. M is the number of matches, this is 2.0*M / T.
  494. Note that this is 1 if the sequences are identical, and 0 if
  495. they have nothing in common.
  496. .ratio() is expensive to compute if you haven't already computed
  497. .getMatchingBlocks() or .getOpcodes(), in which case you may
  498. want to try .quickRatio() or .realQuickRatio() first to get an
  499. upper bound.
  500. >>> s = new SequenceMatcher(null, 'abcd', 'bcde')
  501. >>> s.ratio()
  502. 0.75
  503. >>> s.quickRatio()
  504. 0.75
  505. >>> s.realQuickRatio()
  506. 1.0
  507. */
  508. var match, matches, _i, _len, _ref;
  509. matches = 0;
  510. _ref = this.getMatchingBlocks();
  511. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  512. match = _ref[_i];
  513. matches += match[2];
  514. }
  515. return _calculateRatio(matches, this.a.length + this.b.length);
  516. };
  517. SequenceMatcher.prototype.quickRatio = function() {
  518. /*
  519. Return an upper bound on ratio() relatively quickly.
  520. This isn't defined beyond that it is an upper bound on .ratio(), and
  521. is faster to compute.
  522. */
  523. var avail, elt, fullbcount, matches, numb, _i, _j, _len, _len1, _ref, _ref1;
  524. if (!this.fullbcount) {
  525. this.fullbcount = fullbcount = {};
  526. _ref = this.b;
  527. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  528. elt = _ref[_i];
  529. fullbcount[elt] = (fullbcount[elt] || 0) + 1;
  530. }
  531. }
  532. fullbcount = this.fullbcount;
  533. avail = {};
  534. matches = 0;
  535. _ref1 = this.a;
  536. for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
  537. elt = _ref1[_j];
  538. if (_has(avail, elt)) {
  539. numb = avail[elt];
  540. } else {
  541. numb = fullbcount[elt] || 0;
  542. }
  543. avail[elt] = numb - 1;
  544. if (numb > 0) {
  545. matches++;
  546. }
  547. }
  548. return _calculateRatio(matches, this.a.length + this.b.length);
  549. };
  550. SequenceMatcher.prototype.realQuickRatio = function() {
  551. /*
  552. Return an upper bound on ratio() very quickly.
  553. This isn't defined beyond that it is an upper bound on .ratio(), and
  554. is faster to compute than either .ratio() or .quickRatio().
  555. */
  556. var la, lb, _ref;
  557. _ref = [this.a.length, this.b.length], la = _ref[0], lb = _ref[1];
  558. return _calculateRatio(min(la, lb), la + lb);
  559. };
  560. return SequenceMatcher;
  561. })();
  562. getCloseMatches = function(word, possibilities, n, cutoff) {
  563. var result, s, score, x, _i, _j, _len, _len1, _ref, _results;
  564. if (n == null) {
  565. n = 3;
  566. }
  567. if (cutoff == null) {
  568. cutoff = 0.6;
  569. }
  570. /*
  571. Use SequenceMatcher to return list of the best "good enough" matches.
  572. word is a sequence for which close matches are desired (typically a
  573. string).
  574. possibilities is a list of sequences against which to match word
  575. (typically a list of strings).
  576. Optional arg n (default 3) is the maximum number of close matches to
  577. return. n must be > 0.
  578. Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
  579. that don't score at least that similar to word are ignored.
  580. The best (no more than n) matches among the possibilities are returned
  581. in a list, sorted by similarity score, most similar first.
  582. >>> getCloseMatches('appel', ['ape', 'apple', 'peach', 'puppy'])
  583. ['apple', 'ape']
  584. >>> KEYWORDS = require('coffee-script').RESERVED
  585. >>> getCloseMatches('wheel', KEYWORDS)
  586. ['when', 'while']
  587. >>> getCloseMatches('accost', KEYWORDS)
  588. ['const']
  589. */
  590. if (!(n > 0)) {
  591. throw new Error("n must be > 0: (" + n + ")");
  592. }
  593. if (!((0.0 <= cutoff && cutoff <= 1.0))) {
  594. throw new Error("cutoff must be in [0.0, 1.0]: (" + cutoff + ")");
  595. }
  596. result = [];
  597. s = new SequenceMatcher();
  598. s.setSeq2(word);
  599. for (_i = 0, _len = possibilities.length; _i < _len; _i++) {
  600. x = possibilities[_i];
  601. s.setSeq1(x);
  602. if (s.realQuickRatio() >= cutoff && s.quickRatio() >= cutoff && s.ratio() >= cutoff) {
  603. result.push([s.ratio(), x]);
  604. }
  605. }
  606. result = Heap.nlargest(result, n, _arrayCmp);
  607. _results = [];
  608. for (_j = 0, _len1 = result.length; _j < _len1; _j++) {
  609. _ref = result[_j], score = _ref[0], x = _ref[1];
  610. _results.push(x);
  611. }
  612. return _results;
  613. };
  614. _countLeading = function(line, ch) {
  615. /*
  616. Return number of `ch` characters at the start of `line`.
  617. >>> _countLeading(' abc', ' ')
  618. 3
  619. */
  620. var i, n, _ref;
  621. _ref = [0, line.length], i = _ref[0], n = _ref[1];
  622. while (i < n && line[i] === ch) {
  623. i++;
  624. }
  625. return i;
  626. };
  627. Differ = (function() {
  628. Differ.name = 'Differ';
  629. /*
  630. Differ is a class for comparing sequences of lines of text, and
  631. producing human-readable differences or deltas. Differ uses
  632. SequenceMatcher both to compare sequences of lines, and to compare
  633. sequences of characters within similar (near-matching) lines.
  634. Each line of a Differ delta begins with a two-letter code:
  635. '- ' line unique to sequence 1
  636. '+ ' line unique to sequence 2
  637. ' ' line common to both sequences
  638. '? ' line not present in either input sequence
  639. Lines beginning with '? ' attempt to guide the eye to intraline
  640. differences, and were not present in either input sequence. These lines
  641. can be confusing if the sequences contain tab characters.
  642. Note that Differ makes no claim to produce a *minimal* diff. To the
  643. contrary, minimal diffs are often counter-intuitive, because they synch
  644. up anywhere possible, sometimes accidental matches 100 pages apart.
  645. Restricting synch points to contiguous matches preserves some notion of
  646. locality, at the occasional cost of producing a longer diff.
  647. Example: Comparing two texts.
  648. >>> text1 = ['1. Beautiful is better than ugly.\n',
  649. ... '2. Explicit is better than implicit.\n',
  650. ... '3. Simple is better than complex.\n',
  651. ... '4. Complex is better than complicated.\n']
  652. >>> text1.length
  653. 4
  654. >>> text2 = ['1. Beautiful is better than ugly.\n',
  655. ... '3. Simple is better than complex.\n',
  656. ... '4. Complicated is better than complex.\n',
  657. ... '5. Flat is better than nested.\n']
  658. Next we instantiate a Differ object:
  659. >>> d = new Differ()
  660. Note that when instantiating a Differ object we may pass functions to
  661. filter out line and character 'junk'.
  662. Finally, we compare the two:
  663. >>> result = d.compare(text1, text2)
  664. [ ' 1. Beautiful is better than ugly.\n',
  665. '- 2. Explicit is better than implicit.\n',
  666. '- 3. Simple is better than complex.\n',
  667. '+ 3. Simple is better than complex.\n',
  668. '? ++\n',
  669. '- 4. Complex is better than complicated.\n',
  670. '? ^ ---- ^\n',
  671. '+ 4. Complicated is better than complex.\n',
  672. '? ++++ ^ ^\n',
  673. '+ 5. Flat is better than nested.\n' ]
  674. Methods:
  675. constructor(linejunk=null, charjunk=null)
  676. Construct a text differencer, with optional filters.
  677. compare(a, b)
  678. Compare two sequences of lines; generate the resulting delta.
  679. */
  680. function Differ(linejunk, charjunk) {
  681. this.linejunk = linejunk;
  682. this.charjunk = charjunk;
  683. /*
  684. Construct a text differencer, with optional filters.
  685. The two optional keyword parameters are for filter functions:
  686. - `linejunk`: A function that should accept a single string argument,
  687. and return true iff the string is junk. The module-level function
  688. `IS_LINE_JUNK` may be used to filter out lines without visible
  689. characters, except for at most one splat ('#'). It is recommended
  690. to leave linejunk null.
  691. - `charjunk`: A function that should accept a string of length 1. The
  692. module-level function `IS_CHARACTER_JUNK` may be used to filter out
  693. whitespace characters (a blank or tab; **note**: bad idea to include
  694. newline in this!). Use of IS_CHARACTER_JUNK is recommended.
  695. */
  696. }
  697. Differ.prototype.compare = function(a, b) {
  698. /*
  699. Compare two sequences of lines; generate the resulting delta.
  700. Each sequence must contain individual single-line strings ending with
  701. newlines. Such sequences can be obtained from the `readlines()` method
  702. of file-like objects. The delta generated also consists of newline-
  703. terminated strings, ready to be printed as-is via the writeline()
  704. method of a file-like object.
  705. Example:
  706. >>> d = new Differ
  707. >>> d.compare(['one\n', 'two\n', 'three\n'],
  708. ... ['ore\n', 'tree\n', 'emu\n'])
  709. [ '- one\n',
  710. '? ^\n',
  711. '+ ore\n',
  712. '? ^\n',
  713. '- two\n',
  714. '- three\n',
  715. '? -\n',
  716. '+ tree\n',
  717. '+ emu\n' ]
  718. */
  719. var ahi, alo, bhi, blo, cruncher, g, line, lines, tag, _i, _j, _len, _len1, _ref, _ref1;
  720. cruncher = new SequenceMatcher(this.linejunk, a, b);
  721. lines = [];
  722. _ref = cruncher.getOpcodes();
  723. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  724. _ref1 = _ref[_i], tag = _ref1[0], alo = _ref1[1], ahi = _ref1[2], blo = _ref1[3], bhi = _ref1[4];
  725. switch (tag) {
  726. case 'replace':
  727. g = this._fancyReplace(a, alo, ahi, b, blo, bhi);
  728. break;
  729. case 'delete':
  730. g = this._dump('-', a, alo, ahi);
  731. break;
  732. case 'insert':
  733. g = this._dump('+', b, blo, bhi);
  734. break;
  735. case 'equal':
  736. g = this._dump(' ', a, alo, ahi);
  737. break;
  738. default:
  739. throw new Error("unknow tag (" + tag + ")");
  740. }
  741. for (_j = 0, _len1 = g.length; _j < _len1; _j++) {
  742. line = g[_j];
  743. lines.push(line);
  744. }
  745. }
  746. return lines;
  747. };
  748. Differ.prototype._dump = function(tag, x, lo, hi) {
  749. /*
  750. Generate comparison results for a same-tagged range.
  751. */
  752. var i, _i, _results;
  753. _results = [];
  754. for (i = _i = lo; lo <= hi ? _i < hi : _i > hi; i = lo <= hi ? ++_i : --_i) {
  755. _results.push("" + tag + " " + x[i]);
  756. }
  757. return _results;
  758. };
  759. Differ.prototype._plainReplace = function(a, alo, ahi, b, blo, bhi) {
  760. var first, g, line, lines, second, _i, _j, _len, _len1, _ref;
  761. assert(alo < ahi && blo < bhi);
  762. if (bhi - blo < ahi - alo) {
  763. first = this._dump('+', b, blo, bhi);
  764. second = this._dump('-', a, alo, ahi);
  765. } else {
  766. first = this._dump('-', a, alo, ahi);
  767. second = this._dump('+', b, blo, bhi);
  768. }
  769. lines = [];
  770. _ref = [first, second];
  771. for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  772. g = _ref[_i];
  773. for (_j = 0, _len1 = g.length; _j < _len1; _j++) {
  774. line = g[_j];
  775. lines.push(line);
  776. }
  777. }
  778. return lines;
  779. };
  780. Differ.prototype._fancyReplace = function(a, alo, ahi, b, blo, bhi) {
  781. /*
  782. When replacing one block of lines with another, search the blocks
  783. for *similar* lines; the best-matching pair (if any) is used as a
  784. synch point, and intraline difference marking is done on the
  785. similar pair. Lots of work, but often worth it.
  786. Example:
  787. >>> d = new Differ
  788. >>> d._fancyReplace(['abcDefghiJkl\n'], 0, 1,
  789. ... ['abcdefGhijkl\n'], 0, 1)
  790. [ '- abcDefghiJkl\n',
  791. '? ^ ^ ^\n',
  792. '+ abcdefGhijkl\n',
  793. '? ^ ^ ^\n' ]
  794. */
  795. var aelt, ai, ai1, ai2, atags, belt, bestRatio, besti, bestj, bj, bj1, bj2, btags, cruncher, cutoff, eqi, eqj, i, j, la, lb, line, lines, tag, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _m, _n, _o, _ref, _ref1, _ref10, _ref11, _ref12, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9;
  796. _ref = [0.74, 0.75], bestRatio = _ref[0], cutoff = _ref[1];
  797. cruncher = new SequenceMatcher(this.charjunk);
  798. _ref1 = [null, null], eqi = _ref1[0], eqj = _ref1[1];
  799. lines = [];
  800. for (j = _i = blo; blo <= bhi ? _i < bhi : _i > bhi; j = blo <= bhi ? ++_i : --_i) {
  801. bj = b[j];
  802. cruncher.setSeq2(bj);
  803. for (i = _j = alo; alo <= ahi ? _j < ahi : _j > ahi; i = alo <= ahi ? ++_j : --_j) {
  804. ai = a[i];
  805. if (ai === bj) {
  806. if (eqi === null) {
  807. _ref2 = [i, j], eqi = _ref2[0], eqj = _ref2[1];
  808. }
  809. continue;
  810. }
  811. cruncher.setSeq1(ai);
  812. if (cruncher.realQuickRatio() > bestRatio && cruncher.quickRatio() > bestRatio && cruncher.ratio() > bestRatio) {
  813. _ref3 = [cruncher.ratio(), i, j], bestRatio = _ref3[0], besti = _ref3[1], bestj = _ref3[2];
  814. }
  815. }
  816. }
  817. if (bestRatio < cutoff) {
  818. if (eqi === null) {
  819. _ref4 = this._plainReplace(a, alo, ahi, b, blo, bhi);
  820. for (_k = 0, _len = _ref4.length; _k < _len; _k++) {
  821. line = _ref4[_k];
  822. lines.push(line);
  823. }
  824. return lines;
  825. }
  826. _ref5 = [eqi, eqj, 1.0], besti = _ref5[0], bestj = _ref5[1], bestRatio = _ref5[2];
  827. } else {
  828. eqi = null;
  829. }
  830. _ref6 = this._fancyHelper(a, alo, besti, b, blo, bestj);
  831. for (_l = 0, _len1 = _ref6.length; _l < _len1; _l++) {
  832. line = _ref6[_l];
  833. lines.push(line);
  834. }
  835. _ref7 = [a[besti], b[bestj]], aelt = _ref7[0], belt = _ref7[1];
  836. if (eqi === null) {
  837. atags = btags = '';
  838. cruncher.setSeqs(aelt, belt);
  839. _ref8 = cruncher.getOpcodes();
  840. for (_m = 0, _len2 = _ref8.length; _m < _len2; _m++) {
  841. _ref9 = _ref8[_m], tag = _ref9[0], ai1 = _ref9[1], ai2 = _ref9[2], bj1 = _ref9[3], bj2 = _ref9[4];
  842. _ref10 = [ai2 - ai1, bj2 - bj1], la = _ref10[0], lb = _ref10[1];
  843. switch (tag) {
  844. case 'replace':
  845. atags += Array(la + 1).join('^');
  846. btags += Array(lb + 1).join('^');
  847. break;
  848. case 'delete':
  849. atags += Array(la + 1).join('-');
  850. break;
  851. case 'insert':
  852. btags += Array(lb + 1).join('+');
  853. break;
  854. case 'equal':
  855. atags += Array(la + 1).join(' ');
  856. btags += Array(lb + 1).join(' ');
  857. break;
  858. default:
  859. throw new Error("unknow tag (" + tag + ")");
  860. }
  861. }
  862. _ref11 = this._qformat(aelt, belt, atags, btags);
  863. for (_n = 0, _len3 = _ref11.length; _n < _len3; _n++) {
  864. line = _ref11[_n];
  865. lines.push(line);
  866. }
  867. } else {
  868. lines.push(' ' + aelt);
  869. }
  870. _ref12 = this._fancyHelper(a, besti + 1, ahi, b, bestj + 1, bhi);
  871. for (_o = 0, _len4 = _ref12.length; _o < _len4; _o++) {
  872. line = _ref12[_o];
  873. lines.push(line);
  874. }
  875. return lines;
  876. };
  877. Differ.prototype._fancyHelper = function(a, alo, ahi, b, blo, bhi) {
  878. var g;
  879. g = [];
  880. if (alo < ahi) {
  881. if (blo < bhi) {
  882. g = this._fancyReplace(a, alo, ahi, b, blo, bhi);
  883. } else {
  884. g = this._dump('-', a, alo, ahi);
  885. }
  886. } else if (blo < bhi) {
  887. g = this._dump('+', b, blo, bhi);
  888. }
  889. return g;
  890. };
  891. Differ.prototype._qformat = function(aline, bline, atags, btags) {
  892. /*
  893. Format "?" output and deal with leading tabs.
  894. Example:
  895. >>> d = new Differ
  896. >>> d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n',
  897. [ '- \tabcDefghiJkl\n',
  898. '? \t ^ ^ ^\n',
  899. '+ \tabcdefGhijkl\n',
  900. '? \t ^ ^ ^\n' ]
  901. */
  902. var common, lines;
  903. lines = [];
  904. common = min(_countLeading(aline, '\t'), _countLeading(bline, '\t'));
  905. common = min(common, _countLeading(atags.slice(0, common), ' '));
  906. common = min(common, _countLeading(btags.slice(0, common), ' '));
  907. atags = atags.slice(common).replace(/\s+$/, '');
  908. btags = btags.slice(common).replace(/\s+$/, '');
  909. lines.push('- ' + aline);
  910. if (atags.length) {
  911. lines.push("? " + (Array(common + 1).join('\t')) + atags + "\n");
  912. }
  913. lines.push('+ ' + bline);
  914. if (btags.length) {
  915. lines.push("? " + (Array(common + 1).join('\t')) + btags + "\n");
  916. }
  917. return lines;
  918. };
  919. return Differ;
  920. })();
  921. IS_LINE_JUNK = function(line, pat) {
  922. if (pat == null) {
  923. pat = /^\s*#?\s*$/;
  924. }
  925. /*
  926. Return 1 for ignorable line: iff `line` is blank or contains a single '#'.
  927. Examples:
  928. >>> IS_LINE_JUNK('\n')
  929. true
  930. >>> IS_LINE_JUNK(' # \n')
  931. true
  932. >>> IS_LINE_JUNK('hello\n')
  933. false
  934. */
  935. return pat.test(line);
  936. };
  937. IS_CHARACTER_JUNK = function(ch, ws) {
  938. if (ws == null) {
  939. ws = ' \t';
  940. }
  941. /*
  942. Return 1 for ignorable character: iff `ch` is a space or tab.
  943. Examples:
  944. >>> IS_CHARACTER_JUNK(' ').should.be.true
  945. true
  946. >>> IS_CHARACTER_JUNK('\t').should.be.true
  947. true
  948. >>> IS_CHARACTER_JUNK('\n').should.be.false
  949. false
  950. >>> IS_CHARACTER_JUNK('x').should.be.false
  951. false
  952. */
  953. return __indexOf.call(ws, ch) >= 0;
  954. };
  955. _formatRangeUnified = function(start, stop) {
  956. /*
  957. Convert range to the "ed" format'
  958. */
  959. var beginning, length;
  960. beginning = start + 1;
  961. length = stop - start;
  962. if (length === 1) {
  963. return "" + beginning;
  964. }
  965. if (!length) {
  966. beginning--;
  967. }
  968. return "" + beginning + "," + length;
  969. };
  970. unifiedDiff = function(a, b, _arg) {
  971. var file1Range, file2Range, first, fromdate, fromfile, fromfiledate, group, i1, i2, j1, j2, last, line, lines, lineterm, n, started, tag, todate, tofile, tofiledate, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _m, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6;
  972. _ref = _arg != null ? _arg : {}, fromfile = _ref.fromfile, tofile = _ref.tofile, fromfiledate = _ref.fromfiledate, tofiledate = _ref.tofiledate, n = _ref.n, lineterm = _ref.lineterm;
  973. /*
  974. Compare two sequences of lines; generate the delta as a unified diff.
  975. Unified diffs are a compact way of showing line changes and a few
  976. lines of context. The number of context lines is set by 'n' which
  977. defaults to three.
  978. By default, the diff control lines (those with ---, +++, or @@) are
  979. created with a trailing newline.
  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. >>> unifiedDiff('one two three four'.split(' '),
  988. ... 'zero one tree four'.split(' '), {
  989. ... fromfile: 'Original'
  990. ... tofile: 'Current',
  991. ... fromfiledate: '2005-01-26 23:30:50',
  992. ... tofiledate: '2010-04-02 10:20:52',
  993. ... lineterm: ''
  994. ... })
  995. [ '--- Original\t2005-01-26 23:30:50',
  996. '+++ Current\t2010-04-02 10:20:52',
  997. '@@ -1,4 +1,4 @@',
  998. '+zero',
  999. ' one',
  1000. '-two',
  1001. '-three',
  1002. '+tree',
  1003. ' four' ]
  1004. */
  1005. if (fromfile == null) {
  1006. fromfile = '';
  1007. }
  1008. if (tofile == null) {
  1009. tofile = '';
  1010. }
  1011. if (fromfiledate == null) {
  1012. fromfiledate = '';
  1013. }
  1014. if (tofiledate == null) {
  1015. tofiledate = '';
  1016. }
  1017. if (n == null) {
  1018. n = 3;
  1019. }
  1020. if (lineterm == null) {
  1021. lineterm = '\n';
  1022. }
  1023. lines = [];
  1024. started = false;
  1025. _ref1 = (new SequenceMatcher(null, a, b)).getGroupedOpcodes();
  1026. for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
  1027. group = _ref1[_i];
  1028. if (!started) {
  1029. started = true;
  1030. fromdate = fromfiledate ? "\t" + fromfiledate : '';
  1031. todate = tofiledate ? "\t" + tofiledate : '';
  1032. lines.push("--- " + fromfile + fromdate + lineterm);
  1033. lines.push("+++ " + tofile + todate + lineterm);
  1034. }
  1035. _ref2 = [group[0], group[group.length - 1]], first = _ref2[0], last = _ref2[1];
  1036. file1Range = _formatRangeUnified(first[1], last[2]);
  1037. file2Range = _formatRangeUnified(first[3], last[4]);
  1038. lines.push("@@ -" + file1Range + " +" + file2Range + " @@" + lineterm);
  1039. for (_j = 0, _len1 = group.length; _j < _len1; _j++) {
  1040. _ref3 = group[_j], tag = _ref3[0], i1 = _ref3[1], i2 = _ref3[2], j1 = _ref3[3], j2 = _ref3[4];
  1041. if (tag === 'equal') {
  1042. _ref4 = a.slice(i1, i2);
  1043. for (_k = 0, _len2 = _ref4.length; _k < _len2; _k++) {
  1044. line = _ref4[_k];
  1045. lines.push(' ' + line);
  1046. }
  1047. continue;
  1048. }
  1049. if (tag === 'replace' || tag === 'delete') {
  1050. _ref5 = a.slice(i1, i2);
  1051. for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) {
  1052. line = _ref5[_l];
  1053. lines.push('-' + line);
  1054. }
  1055. }
  1056. if (tag === 'replace' || tag === 'insert') {
  1057. _ref6 = b.slice(j1, j2);
  1058. for (_m = 0, _len4 = _ref6.length; _m < _len4; _m++) {
  1059. line = _ref6[_m];
  1060. lines.push('+' + line);
  1061. }
  1062. }
  1063. }
  1064. }
  1065. return lines;
  1066. };
  1067. _formatRangeContext = function(start, stop) {
  1068. /*
  1069. Convert range to the "ed" format'
  1070. */
  1071. var beginning, length;
  1072. beginning = start + 1;
  1073. length = stop - start;
  1074. if (!length) {
  1075. beginning--;
  1076. }
  1077. if (length <= 1) {
  1078. return "" + beginning;
  1079. }
  1080. return "" + beginning + "," + (beginning + length - 1);
  1081. };
  1082. contextDiff = function(a, b, _arg) {
  1083. var file1Range, file2Range, first, fromdate, fromfile, fromfiledate, group, i1, i2, j1, j2, last, line, lines, lineterm, n, prefix, started, tag, todate, tofile, tofiledate, _, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _m, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6;
  1084. _ref = _arg != null ? _arg : {}, fromfile = _ref.fromfile, tofile = _ref.tofile, fromfiledate = _ref.fromfiledate, tofiledate = _ref.tofiledate, n = _ref.n, lineterm = _ref.lineterm;
  1085. /*
  1086. Compare two sequences of lines; generate the delta as a context diff.
  1087. Context diffs are a compact way of showing line changes and a few
  1088. lines of context. The number of context lines is set by 'n' which
  1089. defaults to three.
  1090. By default, the diff control lines (those with *** or ---) are
  1091. created with a trailing newline. This is helpful so that inputs
  1092. created from file.readlines() result in diffs that are suitable for
  1093. file.writelines() since both the inputs and outputs have trailing
  1094. newlines.
  1095. For inputs that do not have trailing newlines, set the lineterm
  1096. argument to "" so that the output will be uniformly newline free.
  1097. The context diff format normally has a header for filenames and
  1098. modification times. Any or all of these may be specified using
  1099. strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
  1100. The modification times are normally expressed in the ISO 8601 format.
  1101. If not specified, the strings default to blanks.
  1102. Example:
  1103. >>> a = ['one\n', 'two\n', 'three\n', 'four\n']
  1104. >>> b = ['zero\n', 'one\n', 'tree\n', 'four\n']
  1105. >>> contextDiff(a, b, {fromfile: 'Original', tofile: 'Current'})
  1106. [ '*** Original\n',
  1107. '--- Current\n',
  1108. '***************\n',
  1109. '*** 1,4 ****\n',
  1110. ' one\n',
  1111. '! two\n',
  1112. '! three\n',
  1113. ' four\n',
  1114. '--- 1,4 ----\n',
  1115. '+ zero\n',
  1116. ' one\n',
  1117. '! tree\n',
  1118. ' four\n' ]
  1119. */
  1120. if (fromfile == null) {
  1121. fromfile = '';
  1122. }
  1123. if (tofile == null) {
  1124. tofile = '';
  1125. }
  1126. if (fromfiledate == null) {
  1127. fromfiledate = '';
  1128. }
  1129. if (tofiledate == null) {
  1130. tofiledate = '';
  1131. }
  1132. if (n == null) {
  1133. n = 3;
  1134. }
  1135. if (lineterm == null) {
  1136. lineterm = '\n';
  1137. }
  1138. prefix = {
  1139. insert: '+ ',
  1140. "delete": '- ',
  1141. replace: '! ',
  1142. equal: ' '
  1143. };
  1144. started = false;
  1145. lines = [];
  1146. _ref1 = (new SequenceMatcher(null, a, b)).getGroupedOpcodes();
  1147. for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
  1148. group = _ref1[_i];
  1149. if (!started) {
  1150. started = true;
  1151. fromdate = fromfiledate ? "\t" + fromfiledate : '';
  1152. todate = tofiledate ? "\t" + tofiledate : '';
  1153. lines.push("*** " + fromfile + fromdate + lineterm);
  1154. lines.push("--- " + tofile + todate + lineterm);
  1155. _ref2 = [group[0], group[group.length - 1]], first = _ref2[0], last = _ref2[1];
  1156. lines.push('***************' + lineterm);
  1157. file1Range = _formatRangeContext(first[1], last[2]);
  1158. lines.push("*** " + file1Range + " ****" + lineterm);
  1159. if (_any((function() {
  1160. var _j, _len1, _ref3, _results;
  1161. _results = [];
  1162. for (_j = 0, _len1 = group.length; _j < _len1; _j++) {
  1163. _ref3 = group[_j], tag = _ref3[0], _ = _ref3[1], _ = _ref3[2], _ = _ref3[3], _ = _ref3[4];
  1164. _results.push(tag === 'replace' || tag === 'delete');
  1165. }
  1166. return _results;
  1167. })())) {
  1168. for (_j = 0, _len1 = group.length; _j < _len1; _j++) {
  1169. _ref3 = group[_j], tag = _ref3[0], i1 = _ref3[1], i2 = _ref3[2], _ = _ref3[3], _ = _ref3[4];
  1170. if (tag !== 'insert') {
  1171. _ref4 = a.slice(i1, i2);
  1172. for (_k = 0, _len2 = _ref4.length; _k < _len2; _k++) {
  1173. line = _ref4[_k];
  1174. lines.push(prefix[tag] + line);
  1175. }
  1176. }
  1177. }
  1178. }
  1179. file2Range = _formatRangeContext(first[3], last[4]);
  1180. lines.push("--- " + file2Range + " ----" + lineterm);
  1181. if (_any((function() {
  1182. var _l, _len3, _ref5, _results;
  1183. _results = [];
  1184. for (_l = 0, _len3 = group.length; _l < _len3; _l++) {
  1185. _ref5 = group[_l], tag = _ref5[0], _ = _ref5[1], _ = _ref5[2], _ = _ref5[3], _ = _ref5[4];
  1186. _results.push(tag === 'replace' || tag === 'insert');
  1187. }
  1188. return _results;
  1189. })())) {
  1190. for (_l = 0, _len3 = group.length; _l < _len3; _l++) {
  1191. _ref5 = group[_l], tag = _ref5[0], _ = _ref5[1], _ = _ref5[2], j1 = _ref5[3], j2 = _ref5[4];
  1192. if (tag !== 'delete') {
  1193. _ref6 = b.slice(j1, j2);
  1194. for (_m = 0, _len4 = _ref6.length; _m < _len4; _m++) {
  1195. line = _ref6[_m];
  1196. lines.push(prefix[tag] + line);
  1197. }
  1198. }
  1199. }
  1200. }
  1201. }
  1202. }
  1203. return lines;
  1204. };
  1205. ndiff = function(a, b, linejunk, charjunk) {
  1206. if (charjunk == null) {
  1207. charjunk = IS_CHARACTER_JUNK;
  1208. }
  1209. /*
  1210. Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
  1211. Optional keyword parameters `linejunk` and `charjunk` are for filter
  1212. functions (or None):
  1213. - linejunk: A function that should accept a single string argument, and
  1214. return true iff the string is junk. The default is null, and is
  1215. recommended;
  1216. - charjunk: A function that should accept a string of length 1. The
  1217. default is module-level function IS_CHARACTER_JUNK, which filters out
  1218. whitespace characters (a blank or tab; note: bad idea to include newline
  1219. in this!).
  1220. Example:
  1221. >>> a = ['one\n', 'two\n', 'three\n']
  1222. >>> b = ['ore\n', 'tree\n', 'emu\n']
  1223. >>> ndiff(a, b)
  1224. [ '- one\n',
  1225. '? ^\n',
  1226. '+ ore\n',
  1227. '? ^\n',
  1228. '- two\n',
  1229. '- three\n',
  1230. '? -\n',
  1231. '+ tree\n',
  1232. '+ emu\n' ]
  1233. */
  1234. return (new Differ(linejunk, charjunk)).compare(a, b);
  1235. };
  1236. restore = function(delta, which) {
  1237. /*
  1238. Generate one of the two sequences that generated a delta.
  1239. Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
  1240. lines originating from file 1 or 2 (parameter `which`), stripping off line
  1241. prefixes.
  1242. Examples:
  1243. >>> a = ['one\n', 'two\n', 'three\n']
  1244. >>> b = ['ore\n', 'tree\n', 'emu\n']
  1245. >>> diff = ndiff(a, b)
  1246. >>> restore(diff, 1)
  1247. [ 'one\n',
  1248. 'two\n',
  1249. 'three\n' ]
  1250. >>> restore(diff, 2)
  1251. [ 'ore\n',
  1252. 'tree\n',
  1253. 'emu\n' ]
  1254. */
  1255. var line, lines, prefixes, tag, _i, _len, _ref;
  1256. tag = {
  1257. 1: '- ',
  1258. 2: '+ '
  1259. }[which];
  1260. if (!tag) {
  1261. throw new Error("unknow delta choice (must be 1 or 2): " + which);
  1262. }
  1263. prefixes = [' ', tag];
  1264. lines = [];
  1265. for (_i = 0, _len = delta.length; _i < _len; _i++) {
  1266. line = delta[_i];
  1267. if (_ref = line.slice(0, 2), __indexOf.call(prefixes, _ref) >= 0) {
  1268. lines.push(line.slice(2));
  1269. }
  1270. }
  1271. return lines;
  1272. };
  1273. exports._arrayCmp = _arrayCmp;
  1274. exports.SequenceMatcher = SequenceMatcher;
  1275. exports.getCloseMatches = getCloseMatches;
  1276. exports._countLeading = _countLeading;
  1277. exports.Differ = Differ;
  1278. exports.IS_LINE_JUNK = IS_LINE_JUNK;
  1279. exports.IS_CHARACTER_JUNK = IS_CHARACTER_JUNK;
  1280. exports._formatRangeUnified = _formatRangeUnified;
  1281. exports.unifiedDiff = unifiedDiff;
  1282. exports._formatRangeContext = _formatRangeContext;
  1283. exports.contextDiff = contextDiff;
  1284. exports.ndiff = ndiff;
  1285. exports.restore = restore;
  1286. }).call(this);