index.es6.js 42 KB

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