版博士V2.0程序
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

1562 líneas
44 KiB

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