diff.js 46 KB

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