diff.js 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  1. /*!
  2. diff v4.0.1
  3. Software License Agreement (BSD License)
  4. Copyright (c) 2009-2015, Kevin Decker <kpdecker@gmail.com>
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms, with or without modification,
  7. are permitted provided that the following conditions are met:
  8. * Redistributions of source code must retain the above
  9. copyright notice, this list of conditions and the
  10. following disclaimer.
  11. * Redistributions in binary form must reproduce the above
  12. copyright notice, this list of conditions and the
  13. following disclaimer in the documentation and/or other
  14. materials provided with the distribution.
  15. * Neither the name of Kevin Decker nor the names of its
  16. contributors may be used to endorse or promote products
  17. derived from this software without specific prior
  18. written permission.
  19. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
  20. IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  21. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  22. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  23. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  25. IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  26. OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. @license
  28. */
  29. (function (global, factory) {
  30. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  31. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  32. (global = global || self, factory(global.Diff = {}));
  33. }(this, function (exports) { 'use strict';
  34. function Diff() {}
  35. Diff.prototype = {
  36. diff: function diff(oldString, newString) {
  37. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  38. var callback = options.callback;
  39. if (typeof options === 'function') {
  40. callback = options;
  41. options = {};
  42. }
  43. this.options = options;
  44. var self = this;
  45. function done(value) {
  46. if (callback) {
  47. setTimeout(function () {
  48. callback(undefined, value);
  49. }, 0);
  50. return true;
  51. } else {
  52. return value;
  53. }
  54. } // Allow subclasses to massage the input prior to running
  55. oldString = this.castInput(oldString);
  56. newString = this.castInput(newString);
  57. oldString = this.removeEmpty(this.tokenize(oldString));
  58. newString = this.removeEmpty(this.tokenize(newString));
  59. var newLen = newString.length,
  60. oldLen = oldString.length;
  61. var editLength = 1;
  62. var maxEditLength = newLen + oldLen;
  63. var bestPath = [{
  64. newPos: -1,
  65. components: []
  66. }]; // Seed editLength = 0, i.e. the content starts with the same values
  67. var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
  68. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  69. // Identity per the equality and tokenizer
  70. return done([{
  71. value: this.join(newString),
  72. count: newString.length
  73. }]);
  74. } // Main worker method. checks all permutations of a given edit length for acceptance.
  75. function execEditLength() {
  76. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  77. var basePath = void 0;
  78. var addPath = bestPath[diagonalPath - 1],
  79. removePath = bestPath[diagonalPath + 1],
  80. _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  81. if (addPath) {
  82. // No one else is going to attempt to use this value, clear it
  83. bestPath[diagonalPath - 1] = undefined;
  84. }
  85. var canAdd = addPath && addPath.newPos + 1 < newLen,
  86. canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
  87. if (!canAdd && !canRemove) {
  88. // If this path is a terminal then prune
  89. bestPath[diagonalPath] = undefined;
  90. continue;
  91. } // Select the diagonal that we want to branch from. We select the prior
  92. // path whose position in the new string is the farthest from the origin
  93. // and does not pass the bounds of the diff graph
  94. if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
  95. basePath = clonePath(removePath);
  96. self.pushComponent(basePath.components, undefined, true);
  97. } else {
  98. basePath = addPath; // No need to clone, we've pulled it from the list
  99. basePath.newPos++;
  100. self.pushComponent(basePath.components, true, undefined);
  101. }
  102. _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
  103. if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
  104. return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
  105. } else {
  106. // Otherwise track this path as a potential candidate and continue.
  107. bestPath[diagonalPath] = basePath;
  108. }
  109. }
  110. editLength++;
  111. } // Performs the length of edit iteration. Is a bit fugly as this has to support the
  112. // sync and async mode which is never fun. Loops over execEditLength until a value
  113. // is produced.
  114. if (callback) {
  115. (function exec() {
  116. setTimeout(function () {
  117. // This should not happen, but we want to be safe.
  118. /* istanbul ignore next */
  119. if (editLength > maxEditLength) {
  120. return callback();
  121. }
  122. if (!execEditLength()) {
  123. exec();
  124. }
  125. }, 0);
  126. })();
  127. } else {
  128. while (editLength <= maxEditLength) {
  129. var ret = execEditLength();
  130. if (ret) {
  131. return ret;
  132. }
  133. }
  134. }
  135. },
  136. pushComponent: function pushComponent(components, added, removed) {
  137. var last = components[components.length - 1];
  138. if (last && last.added === added && last.removed === removed) {
  139. // We need to clone here as the component clone operation is just
  140. // as shallow array clone
  141. components[components.length - 1] = {
  142. count: last.count + 1,
  143. added: added,
  144. removed: removed
  145. };
  146. } else {
  147. components.push({
  148. count: 1,
  149. added: added,
  150. removed: removed
  151. });
  152. }
  153. },
  154. extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
  155. var newLen = newString.length,
  156. oldLen = oldString.length,
  157. newPos = basePath.newPos,
  158. oldPos = newPos - diagonalPath,
  159. commonCount = 0;
  160. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
  161. newPos++;
  162. oldPos++;
  163. commonCount++;
  164. }
  165. if (commonCount) {
  166. basePath.components.push({
  167. count: commonCount
  168. });
  169. }
  170. basePath.newPos = newPos;
  171. return oldPos;
  172. },
  173. equals: function equals(left, right) {
  174. if (this.options.comparator) {
  175. return this.options.comparator(left, right);
  176. } else {
  177. return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
  178. }
  179. },
  180. removeEmpty: function removeEmpty(array) {
  181. var ret = [];
  182. for (var i = 0; i < array.length; i++) {
  183. if (array[i]) {
  184. ret.push(array[i]);
  185. }
  186. }
  187. return ret;
  188. },
  189. castInput: function castInput(value) {
  190. return value;
  191. },
  192. tokenize: function tokenize(value) {
  193. return value.split('');
  194. },
  195. join: function join(chars) {
  196. return chars.join('');
  197. }
  198. };
  199. function buildValues(diff, components, newString, oldString, useLongestToken) {
  200. var componentPos = 0,
  201. componentLen = components.length,
  202. newPos = 0,
  203. oldPos = 0;
  204. for (; componentPos < componentLen; componentPos++) {
  205. var component = components[componentPos];
  206. if (!component.removed) {
  207. if (!component.added && useLongestToken) {
  208. var value = newString.slice(newPos, newPos + component.count);
  209. value = value.map(function (value, i) {
  210. var oldValue = oldString[oldPos + i];
  211. return oldValue.length > value.length ? oldValue : value;
  212. });
  213. component.value = diff.join(value);
  214. } else {
  215. component.value = diff.join(newString.slice(newPos, newPos + component.count));
  216. }
  217. newPos += component.count; // Common case
  218. if (!component.added) {
  219. oldPos += component.count;
  220. }
  221. } else {
  222. component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
  223. oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
  224. // The diffing algorithm is tied to add then remove output and this is the simplest
  225. // route to get the desired output with minimal overhead.
  226. if (componentPos && components[componentPos - 1].added) {
  227. var tmp = components[componentPos - 1];
  228. components[componentPos - 1] = components[componentPos];
  229. components[componentPos] = tmp;
  230. }
  231. }
  232. } // Special case handle for when one terminal is ignored (i.e. whitespace).
  233. // For this case we merge the terminal into the prior string and drop the change.
  234. // This is only available for string mode.
  235. var lastComponent = components[componentLen - 1];
  236. if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
  237. components[componentLen - 2].value += lastComponent.value;
  238. components.pop();
  239. }
  240. return components;
  241. }
  242. function clonePath(path) {
  243. return {
  244. newPos: path.newPos,
  245. components: path.components.slice(0)
  246. };
  247. }
  248. var characterDiff = new Diff();
  249. function diffChars(oldStr, newStr, options) {
  250. return characterDiff.diff(oldStr, newStr, options);
  251. }
  252. function generateOptions(options, defaults) {
  253. if (typeof options === 'function') {
  254. defaults.callback = options;
  255. } else if (options) {
  256. for (var name in options) {
  257. /* istanbul ignore else */
  258. if (options.hasOwnProperty(name)) {
  259. defaults[name] = options[name];
  260. }
  261. }
  262. }
  263. return defaults;
  264. }
  265. //
  266. // Ranges and exceptions:
  267. // Latin-1 Supplement, 0080–00FF
  268. // - U+00D7 × Multiplication sign
  269. // - U+00F7 ÷ Division sign
  270. // Latin Extended-A, 0100–017F
  271. // Latin Extended-B, 0180–024F
  272. // IPA Extensions, 0250–02AF
  273. // Spacing Modifier Letters, 02B0–02FF
  274. // - U+02C7 ˇ &#711; Caron
  275. // - U+02D8 ˘ &#728; Breve
  276. // - U+02D9 ˙ &#729; Dot Above
  277. // - U+02DA ˚ &#730; Ring Above
  278. // - U+02DB ˛ &#731; Ogonek
  279. // - U+02DC ˜ &#732; Small Tilde
  280. // - U+02DD ˝ &#733; Double Acute Accent
  281. // Latin Extended Additional, 1E00–1EFF
  282. var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
  283. var reWhitespace = /\S/;
  284. var wordDiff = new Diff();
  285. wordDiff.equals = function (left, right) {
  286. if (this.options.ignoreCase) {
  287. left = left.toLowerCase();
  288. right = right.toLowerCase();
  289. }
  290. return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
  291. };
  292. wordDiff.tokenize = function (value) {
  293. var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
  294. for (var i = 0; i < tokens.length - 1; i++) {
  295. // If we have an empty string in the next field and we have only word chars before and after, merge
  296. if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
  297. tokens[i] += tokens[i + 2];
  298. tokens.splice(i + 1, 2);
  299. i--;
  300. }
  301. }
  302. return tokens;
  303. };
  304. function diffWords(oldStr, newStr, options) {
  305. options = generateOptions(options, {
  306. ignoreWhitespace: true
  307. });
  308. return wordDiff.diff(oldStr, newStr, options);
  309. }
  310. function diffWordsWithSpace(oldStr, newStr, options) {
  311. return wordDiff.diff(oldStr, newStr, options);
  312. }
  313. var lineDiff = new Diff();
  314. lineDiff.tokenize = function (value) {
  315. var retLines = [],
  316. linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
  317. if (!linesAndNewlines[linesAndNewlines.length - 1]) {
  318. linesAndNewlines.pop();
  319. } // Merge the content and line separators into single tokens
  320. for (var i = 0; i < linesAndNewlines.length; i++) {
  321. var line = linesAndNewlines[i];
  322. if (i % 2 && !this.options.newlineIsToken) {
  323. retLines[retLines.length - 1] += line;
  324. } else {
  325. if (this.options.ignoreWhitespace) {
  326. line = line.trim();
  327. }
  328. retLines.push(line);
  329. }
  330. }
  331. return retLines;
  332. };
  333. function diffLines(oldStr, newStr, callback) {
  334. return lineDiff.diff(oldStr, newStr, callback);
  335. }
  336. function diffTrimmedLines(oldStr, newStr, callback) {
  337. var options = generateOptions(callback, {
  338. ignoreWhitespace: true
  339. });
  340. return lineDiff.diff(oldStr, newStr, options);
  341. }
  342. var sentenceDiff = new Diff();
  343. sentenceDiff.tokenize = function (value) {
  344. return value.split(/(\S.+?[.!?])(?=\s+|$)/);
  345. };
  346. function diffSentences(oldStr, newStr, callback) {
  347. return sentenceDiff.diff(oldStr, newStr, callback);
  348. }
  349. var cssDiff = new Diff();
  350. cssDiff.tokenize = function (value) {
  351. return value.split(/([{}:;,]|\s+)/);
  352. };
  353. function diffCss(oldStr, newStr, callback) {
  354. return cssDiff.diff(oldStr, newStr, callback);
  355. }
  356. function _typeof(obj) {
  357. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  358. _typeof = function (obj) {
  359. return typeof obj;
  360. };
  361. } else {
  362. _typeof = function (obj) {
  363. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  364. };
  365. }
  366. return _typeof(obj);
  367. }
  368. function _toConsumableArray(arr) {
  369. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
  370. }
  371. function _arrayWithoutHoles(arr) {
  372. if (Array.isArray(arr)) {
  373. for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
  374. return arr2;
  375. }
  376. }
  377. function _iterableToArray(iter) {
  378. if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
  379. }
  380. function _nonIterableSpread() {
  381. throw new TypeError("Invalid attempt to spread non-iterable instance");
  382. }
  383. var objectPrototypeToString = Object.prototype.toString;
  384. var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
  385. // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
  386. jsonDiff.useLongestToken = true;
  387. jsonDiff.tokenize = lineDiff.tokenize;
  388. jsonDiff.castInput = function (value) {
  389. var _this$options = this.options,
  390. undefinedReplacement = _this$options.undefinedReplacement,
  391. _this$options$stringi = _this$options.stringifyReplacer,
  392. stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
  393. return typeof v === 'undefined' ? undefinedReplacement : v;
  394. } : _this$options$stringi;
  395. return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
  396. };
  397. jsonDiff.equals = function (left, right) {
  398. return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
  399. };
  400. function diffJson(oldObj, newObj, options) {
  401. return jsonDiff.diff(oldObj, newObj, options);
  402. } // This function handles the presence of circular references by bailing out when encountering an
  403. // object that is already on the "stack" of items being processed. Accepts an optional replacer
  404. function canonicalize(obj, stack, replacementStack, replacer, key) {
  405. stack = stack || [];
  406. replacementStack = replacementStack || [];
  407. if (replacer) {
  408. obj = replacer(key, obj);
  409. }
  410. var i;
  411. for (i = 0; i < stack.length; i += 1) {
  412. if (stack[i] === obj) {
  413. return replacementStack[i];
  414. }
  415. }
  416. var canonicalizedObj;
  417. if ('[object Array]' === objectPrototypeToString.call(obj)) {
  418. stack.push(obj);
  419. canonicalizedObj = new Array(obj.length);
  420. replacementStack.push(canonicalizedObj);
  421. for (i = 0; i < obj.length; i += 1) {
  422. canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
  423. }
  424. stack.pop();
  425. replacementStack.pop();
  426. return canonicalizedObj;
  427. }
  428. if (obj && obj.toJSON) {
  429. obj = obj.toJSON();
  430. }
  431. if (_typeof(obj) === 'object' && obj !== null) {
  432. stack.push(obj);
  433. canonicalizedObj = {};
  434. replacementStack.push(canonicalizedObj);
  435. var sortedKeys = [],
  436. _key;
  437. for (_key in obj) {
  438. /* istanbul ignore else */
  439. if (obj.hasOwnProperty(_key)) {
  440. sortedKeys.push(_key);
  441. }
  442. }
  443. sortedKeys.sort();
  444. for (i = 0; i < sortedKeys.length; i += 1) {
  445. _key = sortedKeys[i];
  446. canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
  447. }
  448. stack.pop();
  449. replacementStack.pop();
  450. } else {
  451. canonicalizedObj = obj;
  452. }
  453. return canonicalizedObj;
  454. }
  455. var arrayDiff = new Diff();
  456. arrayDiff.tokenize = function (value) {
  457. return value.slice();
  458. };
  459. arrayDiff.join = arrayDiff.removeEmpty = function (value) {
  460. return value;
  461. };
  462. function diffArrays(oldArr, newArr, callback) {
  463. return arrayDiff.diff(oldArr, newArr, callback);
  464. }
  465. function parsePatch(uniDiff) {
  466. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  467. var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
  468. delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
  469. list = [],
  470. i = 0;
  471. function parseIndex() {
  472. var index = {};
  473. list.push(index); // Parse diff metadata
  474. while (i < diffstr.length) {
  475. var line = diffstr[i]; // File header found, end parsing diff metadata
  476. if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
  477. break;
  478. } // Diff index
  479. var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
  480. if (header) {
  481. index.index = header[1];
  482. }
  483. i++;
  484. } // Parse file headers if they are defined. Unified diff requires them, but
  485. // there's no technical issues to have an isolated hunk without file header
  486. parseFileHeader(index);
  487. parseFileHeader(index); // Parse hunks
  488. index.hunks = [];
  489. while (i < diffstr.length) {
  490. var _line = diffstr[i];
  491. if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
  492. break;
  493. } else if (/^@@/.test(_line)) {
  494. index.hunks.push(parseHunk());
  495. } else if (_line && options.strict) {
  496. // Ignore unexpected content unless in strict mode
  497. throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
  498. } else {
  499. i++;
  500. }
  501. }
  502. } // Parses the --- and +++ headers, if none are found, no lines
  503. // are consumed.
  504. function parseFileHeader(index) {
  505. var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
  506. if (fileHeader) {
  507. var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
  508. var data = fileHeader[2].split('\t', 2);
  509. var fileName = data[0].replace(/\\\\/g, '\\');
  510. if (/^".*"$/.test(fileName)) {
  511. fileName = fileName.substr(1, fileName.length - 2);
  512. }
  513. index[keyPrefix + 'FileName'] = fileName;
  514. index[keyPrefix + 'Header'] = (data[1] || '').trim();
  515. i++;
  516. }
  517. } // Parses a hunk
  518. // This assumes that we are at the start of a hunk.
  519. function parseHunk() {
  520. var chunkHeaderIndex = i,
  521. chunkHeaderLine = diffstr[i++],
  522. chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
  523. var hunk = {
  524. oldStart: +chunkHeader[1],
  525. oldLines: +chunkHeader[2] || 1,
  526. newStart: +chunkHeader[3],
  527. newLines: +chunkHeader[4] || 1,
  528. lines: [],
  529. linedelimiters: []
  530. };
  531. var addCount = 0,
  532. removeCount = 0;
  533. for (; i < diffstr.length; i++) {
  534. // Lines starting with '---' could be mistaken for the "remove line" operation
  535. // But they could be the header for the next file. Therefore prune such cases out.
  536. if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
  537. break;
  538. }
  539. var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
  540. if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
  541. hunk.lines.push(diffstr[i]);
  542. hunk.linedelimiters.push(delimiters[i] || '\n');
  543. if (operation === '+') {
  544. addCount++;
  545. } else if (operation === '-') {
  546. removeCount++;
  547. } else if (operation === ' ') {
  548. addCount++;
  549. removeCount++;
  550. }
  551. } else {
  552. break;
  553. }
  554. } // Handle the empty block count case
  555. if (!addCount && hunk.newLines === 1) {
  556. hunk.newLines = 0;
  557. }
  558. if (!removeCount && hunk.oldLines === 1) {
  559. hunk.oldLines = 0;
  560. } // Perform optional sanity checking
  561. if (options.strict) {
  562. if (addCount !== hunk.newLines) {
  563. throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
  564. }
  565. if (removeCount !== hunk.oldLines) {
  566. throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
  567. }
  568. }
  569. return hunk;
  570. }
  571. while (i < diffstr.length) {
  572. parseIndex();
  573. }
  574. return list;
  575. }
  576. // Iterator that traverses in the range of [min, max], stepping
  577. // by distance from a given start position. I.e. for [0, 4], with
  578. // start of 2, this will iterate 2, 3, 1, 4, 0.
  579. function distanceIterator (start, minLine, maxLine) {
  580. var wantForward = true,
  581. backwardExhausted = false,
  582. forwardExhausted = false,
  583. localOffset = 1;
  584. return function iterator() {
  585. if (wantForward && !forwardExhausted) {
  586. if (backwardExhausted) {
  587. localOffset++;
  588. } else {
  589. wantForward = false;
  590. } // Check if trying to fit beyond text length, and if not, check it fits
  591. // after offset location (or desired location on first iteration)
  592. if (start + localOffset <= maxLine) {
  593. return localOffset;
  594. }
  595. forwardExhausted = true;
  596. }
  597. if (!backwardExhausted) {
  598. if (!forwardExhausted) {
  599. wantForward = true;
  600. } // Check if trying to fit before text beginning, and if not, check it fits
  601. // before offset location
  602. if (minLine <= start - localOffset) {
  603. return -localOffset++;
  604. }
  605. backwardExhausted = true;
  606. return iterator();
  607. } // We tried to fit hunk before text beginning and beyond text length, then
  608. // hunk can't fit on the text. Return undefined
  609. };
  610. }
  611. function applyPatch(source, uniDiff) {
  612. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  613. if (typeof uniDiff === 'string') {
  614. uniDiff = parsePatch(uniDiff);
  615. }
  616. if (Array.isArray(uniDiff)) {
  617. if (uniDiff.length > 1) {
  618. throw new Error('applyPatch only works with a single input.');
  619. }
  620. uniDiff = uniDiff[0];
  621. } // Apply the diff to the input
  622. var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
  623. delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
  624. hunks = uniDiff.hunks,
  625. compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
  626. return line === patchContent;
  627. },
  628. errorCount = 0,
  629. fuzzFactor = options.fuzzFactor || 0,
  630. minLine = 0,
  631. offset = 0,
  632. removeEOFNL,
  633. addEOFNL;
  634. /**
  635. * Checks if the hunk exactly fits on the provided location
  636. */
  637. function hunkFits(hunk, toPos) {
  638. for (var j = 0; j < hunk.lines.length; j++) {
  639. var line = hunk.lines[j],
  640. operation = line.length > 0 ? line[0] : ' ',
  641. content = line.length > 0 ? line.substr(1) : line;
  642. if (operation === ' ' || operation === '-') {
  643. // Context sanity check
  644. if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
  645. errorCount++;
  646. if (errorCount > fuzzFactor) {
  647. return false;
  648. }
  649. }
  650. toPos++;
  651. }
  652. }
  653. return true;
  654. } // Search best fit offsets for each hunk based on the previous ones
  655. for (var i = 0; i < hunks.length; i++) {
  656. var hunk = hunks[i],
  657. maxLine = lines.length - hunk.oldLines,
  658. localOffset = 0,
  659. toPos = offset + hunk.oldStart - 1;
  660. var iterator = distanceIterator(toPos, minLine, maxLine);
  661. for (; localOffset !== undefined; localOffset = iterator()) {
  662. if (hunkFits(hunk, toPos + localOffset)) {
  663. hunk.offset = offset += localOffset;
  664. break;
  665. }
  666. }
  667. if (localOffset === undefined) {
  668. return false;
  669. } // Set lower text limit to end of the current hunk, so next ones don't try
  670. // to fit over already patched text
  671. minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
  672. } // Apply patch hunks
  673. var diffOffset = 0;
  674. for (var _i = 0; _i < hunks.length; _i++) {
  675. var _hunk = hunks[_i],
  676. _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
  677. diffOffset += _hunk.newLines - _hunk.oldLines;
  678. if (_toPos < 0) {
  679. // Creating a new file
  680. _toPos = 0;
  681. }
  682. for (var j = 0; j < _hunk.lines.length; j++) {
  683. var line = _hunk.lines[j],
  684. operation = line.length > 0 ? line[0] : ' ',
  685. content = line.length > 0 ? line.substr(1) : line,
  686. delimiter = _hunk.linedelimiters[j];
  687. if (operation === ' ') {
  688. _toPos++;
  689. } else if (operation === '-') {
  690. lines.splice(_toPos, 1);
  691. delimiters.splice(_toPos, 1);
  692. /* istanbul ignore else */
  693. } else if (operation === '+') {
  694. lines.splice(_toPos, 0, content);
  695. delimiters.splice(_toPos, 0, delimiter);
  696. _toPos++;
  697. } else if (operation === '\\') {
  698. var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
  699. if (previousOperation === '+') {
  700. removeEOFNL = true;
  701. } else if (previousOperation === '-') {
  702. addEOFNL = true;
  703. }
  704. }
  705. }
  706. } // Handle EOFNL insertion/removal
  707. if (removeEOFNL) {
  708. while (!lines[lines.length - 1]) {
  709. lines.pop();
  710. delimiters.pop();
  711. }
  712. } else if (addEOFNL) {
  713. lines.push('');
  714. delimiters.push('\n');
  715. }
  716. for (var _k = 0; _k < lines.length - 1; _k++) {
  717. lines[_k] = lines[_k] + delimiters[_k];
  718. }
  719. return lines.join('');
  720. } // Wrapper that supports multiple file patches via callbacks.
  721. function applyPatches(uniDiff, options) {
  722. if (typeof uniDiff === 'string') {
  723. uniDiff = parsePatch(uniDiff);
  724. }
  725. var currentIndex = 0;
  726. function processIndex() {
  727. var index = uniDiff[currentIndex++];
  728. if (!index) {
  729. return options.complete();
  730. }
  731. options.loadFile(index, function (err, data) {
  732. if (err) {
  733. return options.complete(err);
  734. }
  735. var updatedContent = applyPatch(data, index, options);
  736. options.patched(index, updatedContent, function (err) {
  737. if (err) {
  738. return options.complete(err);
  739. }
  740. processIndex();
  741. });
  742. });
  743. }
  744. processIndex();
  745. }
  746. function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
  747. if (!options) {
  748. options = {};
  749. }
  750. if (typeof options.context === 'undefined') {
  751. options.context = 4;
  752. }
  753. var diff = diffLines(oldStr, newStr, options);
  754. diff.push({
  755. value: '',
  756. lines: []
  757. }); // Append an empty value to make cleanup easier
  758. function contextLines(lines) {
  759. return lines.map(function (entry) {
  760. return ' ' + entry;
  761. });
  762. }
  763. var hunks = [];
  764. var oldRangeStart = 0,
  765. newRangeStart = 0,
  766. curRange = [],
  767. oldLine = 1,
  768. newLine = 1;
  769. var _loop = function _loop(i) {
  770. var current = diff[i],
  771. lines = current.lines || current.value.replace(/\n$/, '').split('\n');
  772. current.lines = lines;
  773. if (current.added || current.removed) {
  774. var _curRange;
  775. // If we have previous context, start with that
  776. if (!oldRangeStart) {
  777. var prev = diff[i - 1];
  778. oldRangeStart = oldLine;
  779. newRangeStart = newLine;
  780. if (prev) {
  781. curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
  782. oldRangeStart -= curRange.length;
  783. newRangeStart -= curRange.length;
  784. }
  785. } // Output our changes
  786. (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
  787. return (current.added ? '+' : '-') + entry;
  788. }))); // Track the updated file position
  789. if (current.added) {
  790. newLine += lines.length;
  791. } else {
  792. oldLine += lines.length;
  793. }
  794. } else {
  795. // Identical context lines. Track line changes
  796. if (oldRangeStart) {
  797. // Close out any changes that have been output (or join overlapping)
  798. if (lines.length <= options.context * 2 && i < diff.length - 2) {
  799. var _curRange2;
  800. // Overlapping
  801. (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
  802. } else {
  803. var _curRange3;
  804. // end the range and output
  805. var contextSize = Math.min(lines.length, options.context);
  806. (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
  807. var hunk = {
  808. oldStart: oldRangeStart,
  809. oldLines: oldLine - oldRangeStart + contextSize,
  810. newStart: newRangeStart,
  811. newLines: newLine - newRangeStart + contextSize,
  812. lines: curRange
  813. };
  814. if (i >= diff.length - 2 && lines.length <= options.context) {
  815. // EOF is inside this hunk
  816. var oldEOFNewline = /\n$/.test(oldStr);
  817. var newEOFNewline = /\n$/.test(newStr);
  818. var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
  819. if (!oldEOFNewline && noNlBeforeAdds) {
  820. // special case: old has no eol and no trailing context; no-nl can end up before adds
  821. curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
  822. }
  823. if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
  824. curRange.push('\\ No newline at end of file');
  825. }
  826. }
  827. hunks.push(hunk);
  828. oldRangeStart = 0;
  829. newRangeStart = 0;
  830. curRange = [];
  831. }
  832. }
  833. oldLine += lines.length;
  834. newLine += lines.length;
  835. }
  836. };
  837. for (var i = 0; i < diff.length; i++) {
  838. _loop(i);
  839. }
  840. return {
  841. oldFileName: oldFileName,
  842. newFileName: newFileName,
  843. oldHeader: oldHeader,
  844. newHeader: newHeader,
  845. hunks: hunks
  846. };
  847. }
  848. function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
  849. var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
  850. var ret = [];
  851. if (oldFileName == newFileName) {
  852. ret.push('Index: ' + oldFileName);
  853. }
  854. ret.push('===================================================================');
  855. ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
  856. ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
  857. for (var i = 0; i < diff.hunks.length; i++) {
  858. var hunk = diff.hunks[i];
  859. ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
  860. ret.push.apply(ret, hunk.lines);
  861. }
  862. return ret.join('\n') + '\n';
  863. }
  864. function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
  865. return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
  866. }
  867. function arrayEqual(a, b) {
  868. if (a.length !== b.length) {
  869. return false;
  870. }
  871. return arrayStartsWith(a, b);
  872. }
  873. function arrayStartsWith(array, start) {
  874. if (start.length > array.length) {
  875. return false;
  876. }
  877. for (var i = 0; i < start.length; i++) {
  878. if (start[i] !== array[i]) {
  879. return false;
  880. }
  881. }
  882. return true;
  883. }
  884. function calcLineCount(hunk) {
  885. var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
  886. oldLines = _calcOldNewLineCount.oldLines,
  887. newLines = _calcOldNewLineCount.newLines;
  888. if (oldLines !== undefined) {
  889. hunk.oldLines = oldLines;
  890. } else {
  891. delete hunk.oldLines;
  892. }
  893. if (newLines !== undefined) {
  894. hunk.newLines = newLines;
  895. } else {
  896. delete hunk.newLines;
  897. }
  898. }
  899. function merge(mine, theirs, base) {
  900. mine = loadPatch(mine, base);
  901. theirs = loadPatch(theirs, base);
  902. var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
  903. // Leaving sanity checks on this to the API consumer that may know more about the
  904. // meaning in their own context.
  905. if (mine.index || theirs.index) {
  906. ret.index = mine.index || theirs.index;
  907. }
  908. if (mine.newFileName || theirs.newFileName) {
  909. if (!fileNameChanged(mine)) {
  910. // No header or no change in ours, use theirs (and ours if theirs does not exist)
  911. ret.oldFileName = theirs.oldFileName || mine.oldFileName;
  912. ret.newFileName = theirs.newFileName || mine.newFileName;
  913. ret.oldHeader = theirs.oldHeader || mine.oldHeader;
  914. ret.newHeader = theirs.newHeader || mine.newHeader;
  915. } else if (!fileNameChanged(theirs)) {
  916. // No header or no change in theirs, use ours
  917. ret.oldFileName = mine.oldFileName;
  918. ret.newFileName = mine.newFileName;
  919. ret.oldHeader = mine.oldHeader;
  920. ret.newHeader = mine.newHeader;
  921. } else {
  922. // Both changed... figure it out
  923. ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
  924. ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
  925. ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
  926. ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
  927. }
  928. }
  929. ret.hunks = [];
  930. var mineIndex = 0,
  931. theirsIndex = 0,
  932. mineOffset = 0,
  933. theirsOffset = 0;
  934. while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
  935. var mineCurrent = mine.hunks[mineIndex] || {
  936. oldStart: Infinity
  937. },
  938. theirsCurrent = theirs.hunks[theirsIndex] || {
  939. oldStart: Infinity
  940. };
  941. if (hunkBefore(mineCurrent, theirsCurrent)) {
  942. // This patch does not overlap with any of the others, yay.
  943. ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
  944. mineIndex++;
  945. theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
  946. } else if (hunkBefore(theirsCurrent, mineCurrent)) {
  947. // This patch does not overlap with any of the others, yay.
  948. ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
  949. theirsIndex++;
  950. mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
  951. } else {
  952. // Overlap, merge as best we can
  953. var mergedHunk = {
  954. oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
  955. oldLines: 0,
  956. newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
  957. newLines: 0,
  958. lines: []
  959. };
  960. mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
  961. theirsIndex++;
  962. mineIndex++;
  963. ret.hunks.push(mergedHunk);
  964. }
  965. }
  966. return ret;
  967. }
  968. function loadPatch(param, base) {
  969. if (typeof param === 'string') {
  970. if (/^@@/m.test(param) || /^Index:/m.test(param)) {
  971. return parsePatch(param)[0];
  972. }
  973. if (!base) {
  974. throw new Error('Must provide a base reference or pass in a patch');
  975. }
  976. return structuredPatch(undefined, undefined, base, param);
  977. }
  978. return param;
  979. }
  980. function fileNameChanged(patch) {
  981. return patch.newFileName && patch.newFileName !== patch.oldFileName;
  982. }
  983. function selectField(index, mine, theirs) {
  984. if (mine === theirs) {
  985. return mine;
  986. } else {
  987. index.conflict = true;
  988. return {
  989. mine: mine,
  990. theirs: theirs
  991. };
  992. }
  993. }
  994. function hunkBefore(test, check) {
  995. return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
  996. }
  997. function cloneHunk(hunk, offset) {
  998. return {
  999. oldStart: hunk.oldStart,
  1000. oldLines: hunk.oldLines,
  1001. newStart: hunk.newStart + offset,
  1002. newLines: hunk.newLines,
  1003. lines: hunk.lines
  1004. };
  1005. }
  1006. function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
  1007. // This will generally result in a conflicted hunk, but there are cases where the context
  1008. // is the only overlap where we can successfully merge the content here.
  1009. var mine = {
  1010. offset: mineOffset,
  1011. lines: mineLines,
  1012. index: 0
  1013. },
  1014. their = {
  1015. offset: theirOffset,
  1016. lines: theirLines,
  1017. index: 0
  1018. }; // Handle any leading content
  1019. insertLeading(hunk, mine, their);
  1020. insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
  1021. while (mine.index < mine.lines.length && their.index < their.lines.length) {
  1022. var mineCurrent = mine.lines[mine.index],
  1023. theirCurrent = their.lines[their.index];
  1024. if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
  1025. // Both modified ...
  1026. mutualChange(hunk, mine, their);
  1027. } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
  1028. var _hunk$lines;
  1029. // Mine inserted
  1030. (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
  1031. } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
  1032. var _hunk$lines2;
  1033. // Theirs inserted
  1034. (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
  1035. } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
  1036. // Mine removed or edited
  1037. removal(hunk, mine, their);
  1038. } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
  1039. // Their removed or edited
  1040. removal(hunk, their, mine, true);
  1041. } else if (mineCurrent === theirCurrent) {
  1042. // Context identity
  1043. hunk.lines.push(mineCurrent);
  1044. mine.index++;
  1045. their.index++;
  1046. } else {
  1047. // Context mismatch
  1048. conflict(hunk, collectChange(mine), collectChange(their));
  1049. }
  1050. } // Now push anything that may be remaining
  1051. insertTrailing(hunk, mine);
  1052. insertTrailing(hunk, their);
  1053. calcLineCount(hunk);
  1054. }
  1055. function mutualChange(hunk, mine, their) {
  1056. var myChanges = collectChange(mine),
  1057. theirChanges = collectChange(their);
  1058. if (allRemoves(myChanges) && allRemoves(theirChanges)) {
  1059. // Special case for remove changes that are supersets of one another
  1060. if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
  1061. var _hunk$lines3;
  1062. (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
  1063. return;
  1064. } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
  1065. var _hunk$lines4;
  1066. (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
  1067. return;
  1068. }
  1069. } else if (arrayEqual(myChanges, theirChanges)) {
  1070. var _hunk$lines5;
  1071. (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
  1072. return;
  1073. }
  1074. conflict(hunk, myChanges, theirChanges);
  1075. }
  1076. function removal(hunk, mine, their, swap) {
  1077. var myChanges = collectChange(mine),
  1078. theirChanges = collectContext(their, myChanges);
  1079. if (theirChanges.merged) {
  1080. var _hunk$lines6;
  1081. (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
  1082. } else {
  1083. conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
  1084. }
  1085. }
  1086. function conflict(hunk, mine, their) {
  1087. hunk.conflict = true;
  1088. hunk.lines.push({
  1089. conflict: true,
  1090. mine: mine,
  1091. theirs: their
  1092. });
  1093. }
  1094. function insertLeading(hunk, insert, their) {
  1095. while (insert.offset < their.offset && insert.index < insert.lines.length) {
  1096. var line = insert.lines[insert.index++];
  1097. hunk.lines.push(line);
  1098. insert.offset++;
  1099. }
  1100. }
  1101. function insertTrailing(hunk, insert) {
  1102. while (insert.index < insert.lines.length) {
  1103. var line = insert.lines[insert.index++];
  1104. hunk.lines.push(line);
  1105. }
  1106. }
  1107. function collectChange(state) {
  1108. var ret = [],
  1109. operation = state.lines[state.index][0];
  1110. while (state.index < state.lines.length) {
  1111. var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
  1112. if (operation === '-' && line[0] === '+') {
  1113. operation = '+';
  1114. }
  1115. if (operation === line[0]) {
  1116. ret.push(line);
  1117. state.index++;
  1118. } else {
  1119. break;
  1120. }
  1121. }
  1122. return ret;
  1123. }
  1124. function collectContext(state, matchChanges) {
  1125. var changes = [],
  1126. merged = [],
  1127. matchIndex = 0,
  1128. contextChanges = false,
  1129. conflicted = false;
  1130. while (matchIndex < matchChanges.length && state.index < state.lines.length) {
  1131. var change = state.lines[state.index],
  1132. match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
  1133. if (match[0] === '+') {
  1134. break;
  1135. }
  1136. contextChanges = contextChanges || change[0] !== ' ';
  1137. merged.push(match);
  1138. matchIndex++; // Consume any additions in the other block as a conflict to attempt
  1139. // to pull in the remaining context after this
  1140. if (change[0] === '+') {
  1141. conflicted = true;
  1142. while (change[0] === '+') {
  1143. changes.push(change);
  1144. change = state.lines[++state.index];
  1145. }
  1146. }
  1147. if (match.substr(1) === change.substr(1)) {
  1148. changes.push(change);
  1149. state.index++;
  1150. } else {
  1151. conflicted = true;
  1152. }
  1153. }
  1154. if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
  1155. conflicted = true;
  1156. }
  1157. if (conflicted) {
  1158. return changes;
  1159. }
  1160. while (matchIndex < matchChanges.length) {
  1161. merged.push(matchChanges[matchIndex++]);
  1162. }
  1163. return {
  1164. merged: merged,
  1165. changes: changes
  1166. };
  1167. }
  1168. function allRemoves(changes) {
  1169. return changes.reduce(function (prev, change) {
  1170. return prev && change[0] === '-';
  1171. }, true);
  1172. }
  1173. function skipRemoveSuperset(state, removeChanges, delta) {
  1174. for (var i = 0; i < delta; i++) {
  1175. var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
  1176. if (state.lines[state.index + i] !== ' ' + changeContent) {
  1177. return false;
  1178. }
  1179. }
  1180. state.index += delta;
  1181. return true;
  1182. }
  1183. function calcOldNewLineCount(lines) {
  1184. var oldLines = 0;
  1185. var newLines = 0;
  1186. lines.forEach(function (line) {
  1187. if (typeof line !== 'string') {
  1188. var myCount = calcOldNewLineCount(line.mine);
  1189. var theirCount = calcOldNewLineCount(line.theirs);
  1190. if (oldLines !== undefined) {
  1191. if (myCount.oldLines === theirCount.oldLines) {
  1192. oldLines += myCount.oldLines;
  1193. } else {
  1194. oldLines = undefined;
  1195. }
  1196. }
  1197. if (newLines !== undefined) {
  1198. if (myCount.newLines === theirCount.newLines) {
  1199. newLines += myCount.newLines;
  1200. } else {
  1201. newLines = undefined;
  1202. }
  1203. }
  1204. } else {
  1205. if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
  1206. newLines++;
  1207. }
  1208. if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
  1209. oldLines++;
  1210. }
  1211. }
  1212. });
  1213. return {
  1214. oldLines: oldLines,
  1215. newLines: newLines
  1216. };
  1217. }
  1218. // See: http://code.google.com/p/google-diff-match-patch/wiki/API
  1219. function convertChangesToDMP(changes) {
  1220. var ret = [],
  1221. change,
  1222. operation;
  1223. for (var i = 0; i < changes.length; i++) {
  1224. change = changes[i];
  1225. if (change.added) {
  1226. operation = 1;
  1227. } else if (change.removed) {
  1228. operation = -1;
  1229. } else {
  1230. operation = 0;
  1231. }
  1232. ret.push([operation, change.value]);
  1233. }
  1234. return ret;
  1235. }
  1236. function convertChangesToXML(changes) {
  1237. var ret = [];
  1238. for (var i = 0; i < changes.length; i++) {
  1239. var change = changes[i];
  1240. if (change.added) {
  1241. ret.push('<ins>');
  1242. } else if (change.removed) {
  1243. ret.push('<del>');
  1244. }
  1245. ret.push(escapeHTML(change.value));
  1246. if (change.added) {
  1247. ret.push('</ins>');
  1248. } else if (change.removed) {
  1249. ret.push('</del>');
  1250. }
  1251. }
  1252. return ret.join('');
  1253. }
  1254. function escapeHTML(s) {
  1255. var n = s;
  1256. n = n.replace(/&/g, '&amp;');
  1257. n = n.replace(/</g, '&lt;');
  1258. n = n.replace(/>/g, '&gt;');
  1259. n = n.replace(/"/g, '&quot;');
  1260. return n;
  1261. }
  1262. /* See LICENSE file for terms of use */
  1263. exports.Diff = Diff;
  1264. exports.diffChars = diffChars;
  1265. exports.diffWords = diffWords;
  1266. exports.diffWordsWithSpace = diffWordsWithSpace;
  1267. exports.diffLines = diffLines;
  1268. exports.diffTrimmedLines = diffTrimmedLines;
  1269. exports.diffSentences = diffSentences;
  1270. exports.diffCss = diffCss;
  1271. exports.diffJson = diffJson;
  1272. exports.diffArrays = diffArrays;
  1273. exports.structuredPatch = structuredPatch;
  1274. exports.createTwoFilesPatch = createTwoFilesPatch;
  1275. exports.createPatch = createPatch;
  1276. exports.applyPatch = applyPatch;
  1277. exports.applyPatches = applyPatches;
  1278. exports.parsePatch = parsePatch;
  1279. exports.merge = merge;
  1280. exports.convertChangesToDMP = convertChangesToDMP;
  1281. exports.convertChangesToXML = convertChangesToXML;
  1282. exports.canonicalize = canonicalize;
  1283. Object.defineProperty(exports, '__esModule', { value: true });
  1284. }));