Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

diff.js 47KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  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. // All whitespace symbols except newline group into one token, each newline - in separate token
  266. 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.
  267. for (var i = 0; i < tokens.length - 1; i++) {
  268. // If we have an empty string in the next field and we have only word chars before and after, merge
  269. if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
  270. tokens[i] += tokens[i + 2];
  271. tokens.splice(i + 1, 2);
  272. i--;
  273. }
  274. }
  275. return tokens;
  276. };
  277. function diffWords(oldStr, newStr, options) {
  278. options = generateOptions(options, {
  279. ignoreWhitespace: true
  280. });
  281. return wordDiff.diff(oldStr, newStr, options);
  282. }
  283. function diffWordsWithSpace(oldStr, newStr, options) {
  284. return wordDiff.diff(oldStr, newStr, options);
  285. }
  286. var lineDiff = new Diff();
  287. lineDiff.tokenize = function (value) {
  288. var retLines = [],
  289. linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
  290. if (!linesAndNewlines[linesAndNewlines.length - 1]) {
  291. linesAndNewlines.pop();
  292. } // Merge the content and line separators into single tokens
  293. for (var i = 0; i < linesAndNewlines.length; i++) {
  294. var line = linesAndNewlines[i];
  295. if (i % 2 && !this.options.newlineIsToken) {
  296. retLines[retLines.length - 1] += line;
  297. } else {
  298. if (this.options.ignoreWhitespace) {
  299. line = line.trim();
  300. }
  301. retLines.push(line);
  302. }
  303. }
  304. return retLines;
  305. };
  306. function diffLines(oldStr, newStr, callback) {
  307. return lineDiff.diff(oldStr, newStr, callback);
  308. }
  309. function diffTrimmedLines(oldStr, newStr, callback) {
  310. var options = generateOptions(callback, {
  311. ignoreWhitespace: true
  312. });
  313. return lineDiff.diff(oldStr, newStr, options);
  314. }
  315. var sentenceDiff = new Diff();
  316. sentenceDiff.tokenize = function (value) {
  317. return value.split(/(\S.+?[.!?])(?=\s+|$)/);
  318. };
  319. function diffSentences(oldStr, newStr, callback) {
  320. return sentenceDiff.diff(oldStr, newStr, callback);
  321. }
  322. var cssDiff = new Diff();
  323. cssDiff.tokenize = function (value) {
  324. return value.split(/([{}:;,]|\s+)/);
  325. };
  326. function diffCss(oldStr, newStr, callback) {
  327. return cssDiff.diff(oldStr, newStr, callback);
  328. }
  329. function _typeof(obj) {
  330. "@babel/helpers - typeof";
  331. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  332. _typeof = function (obj) {
  333. return typeof obj;
  334. };
  335. } else {
  336. _typeof = function (obj) {
  337. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  338. };
  339. }
  340. return _typeof(obj);
  341. }
  342. function _toConsumableArray(arr) {
  343. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  344. }
  345. function _arrayWithoutHoles(arr) {
  346. if (Array.isArray(arr)) return _arrayLikeToArray(arr);
  347. }
  348. function _iterableToArray(iter) {
  349. if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
  350. }
  351. function _unsupportedIterableToArray(o, minLen) {
  352. if (!o) return;
  353. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  354. var n = Object.prototype.toString.call(o).slice(8, -1);
  355. if (n === "Object" && o.constructor) n = o.constructor.name;
  356. if (n === "Map" || n === "Set") return Array.from(o);
  357. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  358. }
  359. function _arrayLikeToArray(arr, len) {
  360. if (len == null || len > arr.length) len = arr.length;
  361. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  362. return arr2;
  363. }
  364. function _nonIterableSpread() {
  365. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  366. }
  367. var objectPrototypeToString = Object.prototype.toString;
  368. var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
  369. // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
  370. jsonDiff.useLongestToken = true;
  371. jsonDiff.tokenize = lineDiff.tokenize;
  372. jsonDiff.castInput = function (value) {
  373. var _this$options = this.options,
  374. undefinedReplacement = _this$options.undefinedReplacement,
  375. _this$options$stringi = _this$options.stringifyReplacer,
  376. stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
  377. return typeof v === 'undefined' ? undefinedReplacement : v;
  378. } : _this$options$stringi;
  379. return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
  380. };
  381. jsonDiff.equals = function (left, right) {
  382. return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
  383. };
  384. function diffJson(oldObj, newObj, options) {
  385. return jsonDiff.diff(oldObj, newObj, options);
  386. } // This function handles the presence of circular references by bailing out when encountering an
  387. // object that is already on the "stack" of items being processed. Accepts an optional replacer
  388. function canonicalize(obj, stack, replacementStack, replacer, key) {
  389. stack = stack || [];
  390. replacementStack = replacementStack || [];
  391. if (replacer) {
  392. obj = replacer(key, obj);
  393. }
  394. var i;
  395. for (i = 0; i < stack.length; i += 1) {
  396. if (stack[i] === obj) {
  397. return replacementStack[i];
  398. }
  399. }
  400. var canonicalizedObj;
  401. if ('[object Array]' === objectPrototypeToString.call(obj)) {
  402. stack.push(obj);
  403. canonicalizedObj = new Array(obj.length);
  404. replacementStack.push(canonicalizedObj);
  405. for (i = 0; i < obj.length; i += 1) {
  406. canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
  407. }
  408. stack.pop();
  409. replacementStack.pop();
  410. return canonicalizedObj;
  411. }
  412. if (obj && obj.toJSON) {
  413. obj = obj.toJSON();
  414. }
  415. if (_typeof(obj) === 'object' && obj !== null) {
  416. stack.push(obj);
  417. canonicalizedObj = {};
  418. replacementStack.push(canonicalizedObj);
  419. var sortedKeys = [],
  420. _key;
  421. for (_key in obj) {
  422. /* istanbul ignore else */
  423. if (obj.hasOwnProperty(_key)) {
  424. sortedKeys.push(_key);
  425. }
  426. }
  427. sortedKeys.sort();
  428. for (i = 0; i < sortedKeys.length; i += 1) {
  429. _key = sortedKeys[i];
  430. canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
  431. }
  432. stack.pop();
  433. replacementStack.pop();
  434. } else {
  435. canonicalizedObj = obj;
  436. }
  437. return canonicalizedObj;
  438. }
  439. var arrayDiff = new Diff();
  440. arrayDiff.tokenize = function (value) {
  441. return value.slice();
  442. };
  443. arrayDiff.join = arrayDiff.removeEmpty = function (value) {
  444. return value;
  445. };
  446. function diffArrays(oldArr, newArr, callback) {
  447. return arrayDiff.diff(oldArr, newArr, callback);
  448. }
  449. function parsePatch(uniDiff) {
  450. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  451. var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
  452. delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
  453. list = [],
  454. i = 0;
  455. function parseIndex() {
  456. var index = {};
  457. list.push(index); // Parse diff metadata
  458. while (i < diffstr.length) {
  459. var line = diffstr[i]; // File header found, end parsing diff metadata
  460. if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
  461. break;
  462. } // Diff index
  463. var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
  464. if (header) {
  465. index.index = header[1];
  466. }
  467. i++;
  468. } // Parse file headers if they are defined. Unified diff requires them, but
  469. // there's no technical issues to have an isolated hunk without file header
  470. parseFileHeader(index);
  471. parseFileHeader(index); // Parse hunks
  472. index.hunks = [];
  473. while (i < diffstr.length) {
  474. var _line = diffstr[i];
  475. if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
  476. break;
  477. } else if (/^@@/.test(_line)) {
  478. index.hunks.push(parseHunk());
  479. } else if (_line && options.strict) {
  480. // Ignore unexpected content unless in strict mode
  481. throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
  482. } else {
  483. i++;
  484. }
  485. }
  486. } // Parses the --- and +++ headers, if none are found, no lines
  487. // are consumed.
  488. function parseFileHeader(index) {
  489. var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
  490. if (fileHeader) {
  491. var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
  492. var data = fileHeader[2].split('\t', 2);
  493. var fileName = data[0].replace(/\\\\/g, '\\');
  494. if (/^".*"$/.test(fileName)) {
  495. fileName = fileName.substr(1, fileName.length - 2);
  496. }
  497. index[keyPrefix + 'FileName'] = fileName;
  498. index[keyPrefix + 'Header'] = (data[1] || '').trim();
  499. i++;
  500. }
  501. } // Parses a hunk
  502. // This assumes that we are at the start of a hunk.
  503. function parseHunk() {
  504. var chunkHeaderIndex = i,
  505. chunkHeaderLine = diffstr[i++],
  506. chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
  507. var hunk = {
  508. oldStart: +chunkHeader[1],
  509. oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2],
  510. newStart: +chunkHeader[3],
  511. newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4],
  512. lines: [],
  513. linedelimiters: []
  514. }; // Unified Diff Format quirk: If the chunk size is 0,
  515. // the first number is one lower than one would expect.
  516. // https://www.artima.com/weblogs/viewpost.jsp?thread=164293
  517. if (hunk.oldLines === 0) {
  518. hunk.oldStart += 1;
  519. }
  520. if (hunk.newLines === 0) {
  521. hunk.newStart += 1;
  522. }
  523. var addCount = 0,
  524. removeCount = 0;
  525. for (; i < diffstr.length; i++) {
  526. // Lines starting with '---' could be mistaken for the "remove line" operation
  527. // But they could be the header for the next file. Therefore prune such cases out.
  528. if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
  529. break;
  530. }
  531. var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
  532. if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
  533. hunk.lines.push(diffstr[i]);
  534. hunk.linedelimiters.push(delimiters[i] || '\n');
  535. if (operation === '+') {
  536. addCount++;
  537. } else if (operation === '-') {
  538. removeCount++;
  539. } else if (operation === ' ') {
  540. addCount++;
  541. removeCount++;
  542. }
  543. } else {
  544. break;
  545. }
  546. } // Handle the empty block count case
  547. if (!addCount && hunk.newLines === 1) {
  548. hunk.newLines = 0;
  549. }
  550. if (!removeCount && hunk.oldLines === 1) {
  551. hunk.oldLines = 0;
  552. } // Perform optional sanity checking
  553. if (options.strict) {
  554. if (addCount !== hunk.newLines) {
  555. throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
  556. }
  557. if (removeCount !== hunk.oldLines) {
  558. throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
  559. }
  560. }
  561. return hunk;
  562. }
  563. while (i < diffstr.length) {
  564. parseIndex();
  565. }
  566. return list;
  567. }
  568. // Iterator that traverses in the range of [min, max], stepping
  569. // by distance from a given start position. I.e. for [0, 4], with
  570. // start of 2, this will iterate 2, 3, 1, 4, 0.
  571. function distanceIterator (start, minLine, maxLine) {
  572. var wantForward = true,
  573. backwardExhausted = false,
  574. forwardExhausted = false,
  575. localOffset = 1;
  576. return function iterator() {
  577. if (wantForward && !forwardExhausted) {
  578. if (backwardExhausted) {
  579. localOffset++;
  580. } else {
  581. wantForward = false;
  582. } // Check if trying to fit beyond text length, and if not, check it fits
  583. // after offset location (or desired location on first iteration)
  584. if (start + localOffset <= maxLine) {
  585. return localOffset;
  586. }
  587. forwardExhausted = true;
  588. }
  589. if (!backwardExhausted) {
  590. if (!forwardExhausted) {
  591. wantForward = true;
  592. } // Check if trying to fit before text beginning, and if not, check it fits
  593. // before offset location
  594. if (minLine <= start - localOffset) {
  595. return -localOffset++;
  596. }
  597. backwardExhausted = true;
  598. return iterator();
  599. } // We tried to fit hunk before text beginning and beyond text length, then
  600. // hunk can't fit on the text. Return undefined
  601. };
  602. }
  603. function applyPatch(source, uniDiff) {
  604. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  605. if (typeof uniDiff === 'string') {
  606. uniDiff = parsePatch(uniDiff);
  607. }
  608. if (Array.isArray(uniDiff)) {
  609. if (uniDiff.length > 1) {
  610. throw new Error('applyPatch only works with a single input.');
  611. }
  612. uniDiff = uniDiff[0];
  613. } // Apply the diff to the input
  614. var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
  615. delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
  616. hunks = uniDiff.hunks,
  617. compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
  618. return line === patchContent;
  619. },
  620. errorCount = 0,
  621. fuzzFactor = options.fuzzFactor || 0,
  622. minLine = 0,
  623. offset = 0,
  624. removeEOFNL,
  625. addEOFNL;
  626. /**
  627. * Checks if the hunk exactly fits on the provided location
  628. */
  629. function hunkFits(hunk, toPos) {
  630. for (var j = 0; j < hunk.lines.length; j++) {
  631. var line = hunk.lines[j],
  632. operation = line.length > 0 ? line[0] : ' ',
  633. content = line.length > 0 ? line.substr(1) : line;
  634. if (operation === ' ' || operation === '-') {
  635. // Context sanity check
  636. if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
  637. errorCount++;
  638. if (errorCount > fuzzFactor) {
  639. return false;
  640. }
  641. }
  642. toPos++;
  643. }
  644. }
  645. return true;
  646. } // Search best fit offsets for each hunk based on the previous ones
  647. for (var i = 0; i < hunks.length; i++) {
  648. var hunk = hunks[i],
  649. maxLine = lines.length - hunk.oldLines,
  650. localOffset = 0,
  651. toPos = offset + hunk.oldStart - 1;
  652. var iterator = distanceIterator(toPos, minLine, maxLine);
  653. for (; localOffset !== undefined; localOffset = iterator()) {
  654. if (hunkFits(hunk, toPos + localOffset)) {
  655. hunk.offset = offset += localOffset;
  656. break;
  657. }
  658. }
  659. if (localOffset === undefined) {
  660. return false;
  661. } // Set lower text limit to end of the current hunk, so next ones don't try
  662. // to fit over already patched text
  663. minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
  664. } // Apply patch hunks
  665. var diffOffset = 0;
  666. for (var _i = 0; _i < hunks.length; _i++) {
  667. var _hunk = hunks[_i],
  668. _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
  669. diffOffset += _hunk.newLines - _hunk.oldLines;
  670. for (var j = 0; j < _hunk.lines.length; j++) {
  671. var line = _hunk.lines[j],
  672. operation = line.length > 0 ? line[0] : ' ',
  673. content = line.length > 0 ? line.substr(1) : line,
  674. delimiter = _hunk.linedelimiters[j];
  675. if (operation === ' ') {
  676. _toPos++;
  677. } else if (operation === '-') {
  678. lines.splice(_toPos, 1);
  679. delimiters.splice(_toPos, 1);
  680. /* istanbul ignore else */
  681. } else if (operation === '+') {
  682. lines.splice(_toPos, 0, content);
  683. delimiters.splice(_toPos, 0, delimiter);
  684. _toPos++;
  685. } else if (operation === '\\') {
  686. var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
  687. if (previousOperation === '+') {
  688. removeEOFNL = true;
  689. } else if (previousOperation === '-') {
  690. addEOFNL = true;
  691. }
  692. }
  693. }
  694. } // Handle EOFNL insertion/removal
  695. if (removeEOFNL) {
  696. while (!lines[lines.length - 1]) {
  697. lines.pop();
  698. delimiters.pop();
  699. }
  700. } else if (addEOFNL) {
  701. lines.push('');
  702. delimiters.push('\n');
  703. }
  704. for (var _k = 0; _k < lines.length - 1; _k++) {
  705. lines[_k] = lines[_k] + delimiters[_k];
  706. }
  707. return lines.join('');
  708. } // Wrapper that supports multiple file patches via callbacks.
  709. function applyPatches(uniDiff, options) {
  710. if (typeof uniDiff === 'string') {
  711. uniDiff = parsePatch(uniDiff);
  712. }
  713. var currentIndex = 0;
  714. function processIndex() {
  715. var index = uniDiff[currentIndex++];
  716. if (!index) {
  717. return options.complete();
  718. }
  719. options.loadFile(index, function (err, data) {
  720. if (err) {
  721. return options.complete(err);
  722. }
  723. var updatedContent = applyPatch(data, index, options);
  724. options.patched(index, updatedContent, function (err) {
  725. if (err) {
  726. return options.complete(err);
  727. }
  728. processIndex();
  729. });
  730. });
  731. }
  732. processIndex();
  733. }
  734. function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
  735. if (!options) {
  736. options = {};
  737. }
  738. if (typeof options.context === 'undefined') {
  739. options.context = 4;
  740. }
  741. var diff = diffLines(oldStr, newStr, options);
  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. exports.Diff = Diff;
  1262. exports.applyPatch = applyPatch;
  1263. exports.applyPatches = applyPatches;
  1264. exports.canonicalize = canonicalize;
  1265. exports.convertChangesToDMP = convertChangesToDMP;
  1266. exports.convertChangesToXML = convertChangesToXML;
  1267. exports.createPatch = createPatch;
  1268. exports.createTwoFilesPatch = createTwoFilesPatch;
  1269. exports.diffArrays = diffArrays;
  1270. exports.diffChars = diffChars;
  1271. exports.diffCss = diffCss;
  1272. exports.diffJson = diffJson;
  1273. exports.diffLines = diffLines;
  1274. exports.diffSentences = diffSentences;
  1275. exports.diffTrimmedLines = diffTrimmedLines;
  1276. exports.diffWords = diffWords;
  1277. exports.diffWordsWithSpace = diffWordsWithSpace;
  1278. exports.merge = merge;
  1279. exports.parsePatch = parsePatch;
  1280. exports.structuredPatch = structuredPatch;
  1281. Object.defineProperty(exports, '__esModule', { value: true });
  1282. })));