3 diff: function diff(oldString, newString) {
4 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
5 var callback = options.callback;
7 if (typeof options === 'function') {
12 this.options = options;
15 function done(value) {
17 setTimeout(function () {
18 callback(undefined, value);
24 } // 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;
34 var maxEditLength = newLen + oldLen;
38 }]; // Seed editLength = 0, i.e. the content starts with the same values
40 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
42 if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
43 // Identity per the equality and tokenizer
45 value: this.join(newString),
46 count: newString.length
48 } // Main worker method. checks all permutations of a given edit length for acceptance.
51 function execEditLength() {
52 for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
53 var basePath = void 0;
55 var addPath = bestPath[diagonalPath - 1],
56 removePath = bestPath[diagonalPath + 1],
57 _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
60 // No one else is going to attempt to use this value, clear it
61 bestPath[diagonalPath - 1] = undefined;
64 var canAdd = addPath && addPath.newPos + 1 < newLen,
65 canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
67 if (!canAdd && !canRemove) {
68 // If this path is a terminal then prune
69 bestPath[diagonalPath] = undefined;
71 } // Select the diagonal that we want to branch from. We select the prior
72 // path whose position in the new string is the farthest from the origin
73 // and does not pass the bounds of the diff graph
76 if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
77 basePath = clonePath(removePath);
78 self.pushComponent(basePath.components, undefined, true);
80 basePath = addPath; // No need to clone, we've pulled it from the list
83 self.pushComponent(basePath.components, true, undefined);
86 _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
88 if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
89 return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
91 // Otherwise track this path as a potential candidate and continue.
92 bestPath[diagonalPath] = basePath;
97 } // Performs the length of edit iteration. Is a bit fugly as this has to support the
98 // sync and async mode which is never fun. Loops over execEditLength until a value
104 setTimeout(function () {
105 // This should not happen, but we want to be safe.
107 /* istanbul ignore next */
108 if (editLength > maxEditLength) {
112 if (!execEditLength()) {
118 while (editLength <= maxEditLength) {
119 var ret = execEditLength();
127 pushComponent: function pushComponent(components, added, removed) {
128 var last = components[components.length - 1];
130 if (last && last.added === added && last.removed === removed) {
131 // We need to clone here as the component clone operation is just
132 // as shallow array clone
133 components[components.length - 1] = {
134 count: last.count + 1,
146 extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
147 var newLen = newString.length,
148 oldLen = oldString.length,
149 newPos = basePath.newPos,
150 oldPos = newPos - diagonalPath,
153 while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
160 basePath.components.push({
165 basePath.newPos = newPos;
168 equals: function equals(left, right) {
169 if (this.options.comparator) {
170 return this.options.comparator(left, right);
172 return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
175 removeEmpty: function removeEmpty(array) {
178 for (var i = 0; i < array.length; i++) {
186 castInput: function castInput(value) {
189 tokenize: function tokenize(value) {
190 return value.split('');
192 join: function join(chars) {
193 return chars.join('');
197 function buildValues(diff, components, newString, oldString, useLongestToken) {
198 var componentPos = 0,
199 componentLen = components.length,
203 for (; componentPos < componentLen; componentPos++) {
204 var component = components[componentPos];
206 if (!component.removed) {
207 if (!component.added && useLongestToken) {
208 var value = newString.slice(newPos, newPos + component.count);
209 value = value.map(function (value, i) {
210 var oldValue = oldString[oldPos + i];
211 return oldValue.length > value.length ? oldValue : value;
213 component.value = diff.join(value);
215 component.value = diff.join(newString.slice(newPos, newPos + component.count));
218 newPos += component.count; // Common case
220 if (!component.added) {
221 oldPos += component.count;
224 component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
225 oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
226 // The diffing algorithm is tied to add then remove output and this is the simplest
227 // route to get the desired output with minimal overhead.
229 if (componentPos && components[componentPos - 1].added) {
230 var tmp = components[componentPos - 1];
231 components[componentPos - 1] = components[componentPos];
232 components[componentPos] = tmp;
235 } // Special case handle for when one terminal is ignored (i.e. whitespace).
236 // For this case we merge the terminal into the prior string and drop the change.
237 // This is only available for string mode.
240 var lastComponent = components[componentLen - 1];
242 if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
243 components[componentLen - 2].value += lastComponent.value;
250 function clonePath(path) {
253 components: path.components.slice(0)
257 var characterDiff = new Diff();
258 function diffChars(oldStr, newStr, options) {
259 return characterDiff.diff(oldStr, newStr, options);
262 function generateOptions(options, defaults) {
263 if (typeof options === 'function') {
264 defaults.callback = options;
265 } else if (options) {
266 for (var name in options) {
267 /* istanbul ignore else */
268 if (options.hasOwnProperty(name)) {
269 defaults[name] = options[name];
278 // Ranges and exceptions:
279 // Latin-1 Supplement, 0080–00FF
280 // - U+00D7 × Multiplication sign
281 // - U+00F7 ÷ Division sign
282 // Latin Extended-A, 0100–017F
283 // Latin Extended-B, 0180–024F
284 // IPA Extensions, 0250–02AF
285 // Spacing Modifier Letters, 02B0–02FF
286 // - U+02C7 ˇ ˇ Caron
287 // - U+02D8 ˘ ˘ Breve
288 // - U+02D9 ˙ ˙ Dot Above
289 // - U+02DA ˚ ˚ Ring Above
290 // - U+02DB ˛ ˛ Ogonek
291 // - U+02DC ˜ ˜ Small Tilde
292 // - U+02DD ˝ ˝ Double Acute Accent
293 // Latin Extended Additional, 1E00–1EFF
295 var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
296 var reWhitespace = /\S/;
297 var wordDiff = new Diff();
299 wordDiff.equals = function (left, right) {
300 if (this.options.ignoreCase) {
301 left = left.toLowerCase();
302 right = right.toLowerCase();
305 return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
308 wordDiff.tokenize = function (value) {
309 var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
311 for (var i = 0; i < tokens.length - 1; i++) {
312 // If we have an empty string in the next field and we have only word chars before and after, merge
313 if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
314 tokens[i] += tokens[i + 2];
315 tokens.splice(i + 1, 2);
323 function diffWords(oldStr, newStr, options) {
324 options = generateOptions(options, {
325 ignoreWhitespace: true
327 return wordDiff.diff(oldStr, newStr, options);
329 function diffWordsWithSpace(oldStr, newStr, options) {
330 return wordDiff.diff(oldStr, newStr, options);
333 var lineDiff = new Diff();
335 lineDiff.tokenize = function (value) {
337 linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
339 if (!linesAndNewlines[linesAndNewlines.length - 1]) {
340 linesAndNewlines.pop();
341 } // Merge the content and line separators into single tokens
344 for (var i = 0; i < linesAndNewlines.length; i++) {
345 var line = linesAndNewlines[i];
347 if (i % 2 && !this.options.newlineIsToken) {
348 retLines[retLines.length - 1] += line;
350 if (this.options.ignoreWhitespace) {
361 function diffLines(oldStr, newStr, callback) {
362 return lineDiff.diff(oldStr, newStr, callback);
364 function diffTrimmedLines(oldStr, newStr, callback) {
365 var options = generateOptions(callback, {
366 ignoreWhitespace: true
368 return lineDiff.diff(oldStr, newStr, options);
371 var sentenceDiff = new Diff();
373 sentenceDiff.tokenize = function (value) {
374 return value.split(/(\S.+?[.!?])(?=\s+|$)/);
377 function diffSentences(oldStr, newStr, callback) {
378 return sentenceDiff.diff(oldStr, newStr, callback);
381 var cssDiff = new Diff();
383 cssDiff.tokenize = function (value) {
384 return value.split(/([{}:;,]|\s+)/);
387 function diffCss(oldStr, newStr, callback) {
388 return cssDiff.diff(oldStr, newStr, callback);
391 function _typeof(obj) {
392 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
393 _typeof = function (obj) {
397 _typeof = function (obj) {
398 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
405 function _toConsumableArray(arr) {
406 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
409 function _arrayWithoutHoles(arr) {
410 if (Array.isArray(arr)) {
411 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
417 function _iterableToArray(iter) {
418 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
421 function _nonIterableSpread() {
422 throw new TypeError("Invalid attempt to spread non-iterable instance");
425 var objectPrototypeToString = Object.prototype.toString;
426 var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
427 // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
429 jsonDiff.useLongestToken = true;
430 jsonDiff.tokenize = lineDiff.tokenize;
432 jsonDiff.castInput = function (value) {
433 var _this$options = this.options,
434 undefinedReplacement = _this$options.undefinedReplacement,
435 _this$options$stringi = _this$options.stringifyReplacer,
436 stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
437 return typeof v === 'undefined' ? undefinedReplacement : v;
438 } : _this$options$stringi;
439 return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
442 jsonDiff.equals = function (left, right) {
443 return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
446 function diffJson(oldObj, newObj, options) {
447 return jsonDiff.diff(oldObj, newObj, options);
448 } // This function handles the presence of circular references by bailing out when encountering an
449 // object that is already on the "stack" of items being processed. Accepts an optional replacer
451 function canonicalize(obj, stack, replacementStack, replacer, key) {
453 replacementStack = replacementStack || [];
456 obj = replacer(key, obj);
461 for (i = 0; i < stack.length; i += 1) {
462 if (stack[i] === obj) {
463 return replacementStack[i];
467 var canonicalizedObj;
469 if ('[object Array]' === objectPrototypeToString.call(obj)) {
471 canonicalizedObj = new Array(obj.length);
472 replacementStack.push(canonicalizedObj);
474 for (i = 0; i < obj.length; i += 1) {
475 canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
479 replacementStack.pop();
480 return canonicalizedObj;
483 if (obj && obj.toJSON) {
487 if (_typeof(obj) === 'object' && obj !== null) {
489 canonicalizedObj = {};
490 replacementStack.push(canonicalizedObj);
496 /* istanbul ignore else */
497 if (obj.hasOwnProperty(_key)) {
498 sortedKeys.push(_key);
504 for (i = 0; i < sortedKeys.length; i += 1) {
505 _key = sortedKeys[i];
506 canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
510 replacementStack.pop();
512 canonicalizedObj = obj;
515 return canonicalizedObj;
518 var arrayDiff = new Diff();
520 arrayDiff.tokenize = function (value) {
521 return value.slice();
524 arrayDiff.join = arrayDiff.removeEmpty = function (value) {
528 function diffArrays(oldArr, newArr, callback) {
529 return arrayDiff.diff(oldArr, newArr, callback);
532 function parsePatch(uniDiff) {
533 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
534 var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
535 delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
539 function parseIndex() {
541 list.push(index); // Parse diff metadata
543 while (i < diffstr.length) {
544 var line = diffstr[i]; // File header found, end parsing diff metadata
546 if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
551 var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
554 index.index = header[1];
558 } // Parse file headers if they are defined. Unified diff requires them, but
559 // there's no technical issues to have an isolated hunk without file header
562 parseFileHeader(index);
563 parseFileHeader(index); // Parse hunks
567 while (i < diffstr.length) {
568 var _line = diffstr[i];
570 if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
572 } else if (/^@@/.test(_line)) {
573 index.hunks.push(parseHunk());
574 } else if (_line && options.strict) {
575 // Ignore unexpected content unless in strict mode
576 throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
581 } // Parses the --- and +++ headers, if none are found, no lines
585 function parseFileHeader(index) {
586 var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
589 var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
590 var data = fileHeader[2].split('\t', 2);
591 var fileName = data[0].replace(/\\\\/g, '\\');
593 if (/^".*"$/.test(fileName)) {
594 fileName = fileName.substr(1, fileName.length - 2);
597 index[keyPrefix + 'FileName'] = fileName;
598 index[keyPrefix + 'Header'] = (data[1] || '').trim();
602 // This assumes that we are at the start of a hunk.
605 function parseHunk() {
606 var chunkHeaderIndex = i,
607 chunkHeaderLine = diffstr[i++],
608 chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
610 oldStart: +chunkHeader[1],
611 oldLines: +chunkHeader[2] || 1,
612 newStart: +chunkHeader[3],
613 newLines: +chunkHeader[4] || 1,
620 for (; i < diffstr.length; i++) {
621 // Lines starting with '---' could be mistaken for the "remove line" operation
622 // But they could be the header for the next file. Therefore prune such cases out.
623 if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
627 var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
629 if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
630 hunk.lines.push(diffstr[i]);
631 hunk.linedelimiters.push(delimiters[i] || '\n');
633 if (operation === '+') {
635 } else if (operation === '-') {
637 } else if (operation === ' ') {
644 } // Handle the empty block count case
647 if (!addCount && hunk.newLines === 1) {
651 if (!removeCount && hunk.oldLines === 1) {
653 } // Perform optional sanity checking
656 if (options.strict) {
657 if (addCount !== hunk.newLines) {
658 throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
661 if (removeCount !== hunk.oldLines) {
662 throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
669 while (i < diffstr.length) {
676 // Iterator that traverses in the range of [min, max], stepping
677 // by distance from a given start position. I.e. for [0, 4], with
678 // start of 2, this will iterate 2, 3, 1, 4, 0.
679 function distanceIterator (start, minLine, maxLine) {
680 var wantForward = true,
681 backwardExhausted = false,
682 forwardExhausted = false,
684 return function iterator() {
685 if (wantForward && !forwardExhausted) {
686 if (backwardExhausted) {
690 } // Check if trying to fit beyond text length, and if not, check it fits
691 // after offset location (or desired location on first iteration)
694 if (start + localOffset <= maxLine) {
698 forwardExhausted = true;
701 if (!backwardExhausted) {
702 if (!forwardExhausted) {
704 } // Check if trying to fit before text beginning, and if not, check it fits
705 // before offset location
708 if (minLine <= start - localOffset) {
709 return -localOffset++;
712 backwardExhausted = true;
714 } // We tried to fit hunk before text beginning and beyond text length, then
715 // hunk can't fit on the text. Return undefined
720 function applyPatch(source, uniDiff) {
721 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
723 if (typeof uniDiff === 'string') {
724 uniDiff = parsePatch(uniDiff);
727 if (Array.isArray(uniDiff)) {
728 if (uniDiff.length > 1) {
729 throw new Error('applyPatch only works with a single input.');
732 uniDiff = uniDiff[0];
733 } // Apply the diff to the input
736 var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
737 delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
738 hunks = uniDiff.hunks,
739 compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
740 return line === patchContent;
743 fuzzFactor = options.fuzzFactor || 0,
749 * Checks if the hunk exactly fits on the provided location
753 function hunkFits(hunk, toPos) {
754 for (var j = 0; j < hunk.lines.length; j++) {
755 var line = hunk.lines[j],
756 operation = line.length > 0 ? line[0] : ' ',
757 content = line.length > 0 ? line.substr(1) : line;
759 if (operation === ' ' || operation === '-') {
760 // Context sanity check
761 if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
764 if (errorCount > fuzzFactor) {
774 } // Search best fit offsets for each hunk based on the previous ones
777 for (var i = 0; i < hunks.length; i++) {
779 maxLine = lines.length - hunk.oldLines,
781 toPos = offset + hunk.oldStart - 1;
782 var iterator = distanceIterator(toPos, minLine, maxLine);
784 for (; localOffset !== undefined; localOffset = iterator()) {
785 if (hunkFits(hunk, toPos + localOffset)) {
786 hunk.offset = offset += localOffset;
791 if (localOffset === undefined) {
793 } // Set lower text limit to end of the current hunk, so next ones don't try
794 // to fit over already patched text
797 minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
798 } // Apply patch hunks
803 for (var _i = 0; _i < hunks.length; _i++) {
804 var _hunk = hunks[_i],
805 _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
807 diffOffset += _hunk.newLines - _hunk.oldLines;
810 // Creating a new file
814 for (var j = 0; j < _hunk.lines.length; j++) {
815 var line = _hunk.lines[j],
816 operation = line.length > 0 ? line[0] : ' ',
817 content = line.length > 0 ? line.substr(1) : line,
818 delimiter = _hunk.linedelimiters[j];
820 if (operation === ' ') {
822 } else if (operation === '-') {
823 lines.splice(_toPos, 1);
824 delimiters.splice(_toPos, 1);
825 /* istanbul ignore else */
826 } else if (operation === '+') {
827 lines.splice(_toPos, 0, content);
828 delimiters.splice(_toPos, 0, delimiter);
830 } else if (operation === '\\') {
831 var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
833 if (previousOperation === '+') {
835 } else if (previousOperation === '-') {
840 } // Handle EOFNL insertion/removal
844 while (!lines[lines.length - 1]) {
848 } else if (addEOFNL) {
850 delimiters.push('\n');
853 for (var _k = 0; _k < lines.length - 1; _k++) {
854 lines[_k] = lines[_k] + delimiters[_k];
857 return lines.join('');
858 } // Wrapper that supports multiple file patches via callbacks.
860 function applyPatches(uniDiff, options) {
861 if (typeof uniDiff === 'string') {
862 uniDiff = parsePatch(uniDiff);
865 var currentIndex = 0;
867 function processIndex() {
868 var index = uniDiff[currentIndex++];
871 return options.complete();
874 options.loadFile(index, function (err, data) {
876 return options.complete(err);
879 var updatedContent = applyPatch(data, index, options);
880 options.patched(index, updatedContent, function (err) {
882 return options.complete(err);
893 function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
898 if (typeof options.context === 'undefined') {
902 var diff = diffLines(oldStr, newStr, options);
906 }); // Append an empty value to make cleanup easier
908 function contextLines(lines) {
909 return lines.map(function (entry) {
915 var oldRangeStart = 0,
921 var _loop = function _loop(i) {
922 var current = diff[i],
923 lines = current.lines || current.value.replace(/\n$/, '').split('\n');
924 current.lines = lines;
926 if (current.added || current.removed) {
929 // If we have previous context, start with that
930 if (!oldRangeStart) {
931 var prev = diff[i - 1];
932 oldRangeStart = oldLine;
933 newRangeStart = newLine;
936 curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
937 oldRangeStart -= curRange.length;
938 newRangeStart -= curRange.length;
940 } // Output our changes
943 (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
944 return (current.added ? '+' : '-') + entry;
945 }))); // Track the updated file position
949 newLine += lines.length;
951 oldLine += lines.length;
954 // Identical context lines. Track line changes
956 // Close out any changes that have been output (or join overlapping)
957 if (lines.length <= options.context * 2 && i < diff.length - 2) {
961 (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
965 // end the range and output
966 var contextSize = Math.min(lines.length, options.context);
968 (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
971 oldStart: oldRangeStart,
972 oldLines: oldLine - oldRangeStart + contextSize,
973 newStart: newRangeStart,
974 newLines: newLine - newRangeStart + contextSize,
978 if (i >= diff.length - 2 && lines.length <= options.context) {
979 // EOF is inside this hunk
980 var oldEOFNewline = /\n$/.test(oldStr);
981 var newEOFNewline = /\n$/.test(newStr);
982 var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
984 if (!oldEOFNewline && noNlBeforeAdds) {
985 // special case: old has no eol and no trailing context; no-nl can end up before adds
986 curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
989 if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
990 curRange.push('\\ No newline at end of file');
1001 oldLine += lines.length;
1002 newLine += lines.length;
1006 for (var i = 0; i < diff.length; i++) {
1011 oldFileName: oldFileName,
1012 newFileName: newFileName,
1013 oldHeader: oldHeader,
1014 newHeader: newHeader,
1018 function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1019 var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
1022 if (oldFileName == newFileName) {
1023 ret.push('Index: ' + oldFileName);
1026 ret.push('===================================================================');
1027 ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
1028 ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
1030 for (var i = 0; i < diff.hunks.length; i++) {
1031 var hunk = diff.hunks[i];
1032 ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
1033 ret.push.apply(ret, hunk.lines);
1036 return ret.join('\n') + '\n';
1038 function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
1039 return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
1042 function arrayEqual(a, b) {
1043 if (a.length !== b.length) {
1047 return arrayStartsWith(a, b);
1049 function arrayStartsWith(array, start) {
1050 if (start.length > array.length) {
1054 for (var i = 0; i < start.length; i++) {
1055 if (start[i] !== array[i]) {
1063 function calcLineCount(hunk) {
1064 var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
1065 oldLines = _calcOldNewLineCount.oldLines,
1066 newLines = _calcOldNewLineCount.newLines;
1068 if (oldLines !== undefined) {
1069 hunk.oldLines = oldLines;
1071 delete hunk.oldLines;
1074 if (newLines !== undefined) {
1075 hunk.newLines = newLines;
1077 delete hunk.newLines;
1080 function merge(mine, theirs, base) {
1081 mine = loadPatch(mine, base);
1082 theirs = loadPatch(theirs, base);
1083 var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
1084 // Leaving sanity checks on this to the API consumer that may know more about the
1085 // meaning in their own context.
1087 if (mine.index || theirs.index) {
1088 ret.index = mine.index || theirs.index;
1091 if (mine.newFileName || theirs.newFileName) {
1092 if (!fileNameChanged(mine)) {
1093 // No header or no change in ours, use theirs (and ours if theirs does not exist)
1094 ret.oldFileName = theirs.oldFileName || mine.oldFileName;
1095 ret.newFileName = theirs.newFileName || mine.newFileName;
1096 ret.oldHeader = theirs.oldHeader || mine.oldHeader;
1097 ret.newHeader = theirs.newHeader || mine.newHeader;
1098 } else if (!fileNameChanged(theirs)) {
1099 // No header or no change in theirs, use ours
1100 ret.oldFileName = mine.oldFileName;
1101 ret.newFileName = mine.newFileName;
1102 ret.oldHeader = mine.oldHeader;
1103 ret.newHeader = mine.newHeader;
1105 // Both changed... figure it out
1106 ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
1107 ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
1108 ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
1109 ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
1119 while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
1120 var mineCurrent = mine.hunks[mineIndex] || {
1123 theirsCurrent = theirs.hunks[theirsIndex] || {
1127 if (hunkBefore(mineCurrent, theirsCurrent)) {
1128 // This patch does not overlap with any of the others, yay.
1129 ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
1131 theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
1132 } else if (hunkBefore(theirsCurrent, mineCurrent)) {
1133 // This patch does not overlap with any of the others, yay.
1134 ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
1136 mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
1138 // Overlap, merge as best we can
1140 oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
1142 newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
1146 mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
1149 ret.hunks.push(mergedHunk);
1156 function loadPatch(param, base) {
1157 if (typeof param === 'string') {
1158 if (/^@@/m.test(param) || /^Index:/m.test(param)) {
1159 return parsePatch(param)[0];
1163 throw new Error('Must provide a base reference or pass in a patch');
1166 return structuredPatch(undefined, undefined, base, param);
1172 function fileNameChanged(patch) {
1173 return patch.newFileName && patch.newFileName !== patch.oldFileName;
1176 function selectField(index, mine, theirs) {
1177 if (mine === theirs) {
1180 index.conflict = true;
1188 function hunkBefore(test, check) {
1189 return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
1192 function cloneHunk(hunk, offset) {
1194 oldStart: hunk.oldStart,
1195 oldLines: hunk.oldLines,
1196 newStart: hunk.newStart + offset,
1197 newLines: hunk.newLines,
1202 function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
1203 // This will generally result in a conflicted hunk, but there are cases where the context
1204 // is the only overlap where we can successfully merge the content here.
1211 offset: theirOffset,
1214 }; // Handle any leading content
1216 insertLeading(hunk, mine, their);
1217 insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
1219 while (mine.index < mine.lines.length && their.index < their.lines.length) {
1220 var mineCurrent = mine.lines[mine.index],
1221 theirCurrent = their.lines[their.index];
1223 if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
1224 // Both modified ...
1225 mutualChange(hunk, mine, their);
1226 } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
1230 (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
1231 } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
1235 (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
1236 } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
1237 // Mine removed or edited
1238 removal(hunk, mine, their);
1239 } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
1240 // Their removed or edited
1241 removal(hunk, their, mine, true);
1242 } else if (mineCurrent === theirCurrent) {
1244 hunk.lines.push(mineCurrent);
1249 conflict(hunk, collectChange(mine), collectChange(their));
1251 } // Now push anything that may be remaining
1254 insertTrailing(hunk, mine);
1255 insertTrailing(hunk, their);
1256 calcLineCount(hunk);
1259 function mutualChange(hunk, mine, their) {
1260 var myChanges = collectChange(mine),
1261 theirChanges = collectChange(their);
1263 if (allRemoves(myChanges) && allRemoves(theirChanges)) {
1264 // Special case for remove changes that are supersets of one another
1265 if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
1268 (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
1271 } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
1274 (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
1278 } else if (arrayEqual(myChanges, theirChanges)) {
1281 (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
1286 conflict(hunk, myChanges, theirChanges);
1289 function removal(hunk, mine, their, swap) {
1290 var myChanges = collectChange(mine),
1291 theirChanges = collectContext(their, myChanges);
1293 if (theirChanges.merged) {
1296 (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
1298 conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
1302 function conflict(hunk, mine, their) {
1303 hunk.conflict = true;
1311 function insertLeading(hunk, insert, their) {
1312 while (insert.offset < their.offset && insert.index < insert.lines.length) {
1313 var line = insert.lines[insert.index++];
1314 hunk.lines.push(line);
1319 function insertTrailing(hunk, insert) {
1320 while (insert.index < insert.lines.length) {
1321 var line = insert.lines[insert.index++];
1322 hunk.lines.push(line);
1326 function collectChange(state) {
1328 operation = state.lines[state.index][0];
1330 while (state.index < state.lines.length) {
1331 var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
1333 if (operation === '-' && line[0] === '+') {
1337 if (operation === line[0]) {
1348 function collectContext(state, matchChanges) {
1352 contextChanges = false,
1355 while (matchIndex < matchChanges.length && state.index < state.lines.length) {
1356 var change = state.lines[state.index],
1357 match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
1359 if (match[0] === '+') {
1363 contextChanges = contextChanges || change[0] !== ' ';
1365 matchIndex++; // Consume any additions in the other block as a conflict to attempt
1366 // to pull in the remaining context after this
1368 if (change[0] === '+') {
1371 while (change[0] === '+') {
1372 changes.push(change);
1373 change = state.lines[++state.index];
1377 if (match.substr(1) === change.substr(1)) {
1378 changes.push(change);
1385 if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
1393 while (matchIndex < matchChanges.length) {
1394 merged.push(matchChanges[matchIndex++]);
1403 function allRemoves(changes) {
1404 return changes.reduce(function (prev, change) {
1405 return prev && change[0] === '-';
1409 function skipRemoveSuperset(state, removeChanges, delta) {
1410 for (var i = 0; i < delta; i++) {
1411 var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
1413 if (state.lines[state.index + i] !== ' ' + changeContent) {
1418 state.index += delta;
1422 function calcOldNewLineCount(lines) {
1425 lines.forEach(function (line) {
1426 if (typeof line !== 'string') {
1427 var myCount = calcOldNewLineCount(line.mine);
1428 var theirCount = calcOldNewLineCount(line.theirs);
1430 if (oldLines !== undefined) {
1431 if (myCount.oldLines === theirCount.oldLines) {
1432 oldLines += myCount.oldLines;
1434 oldLines = undefined;
1438 if (newLines !== undefined) {
1439 if (myCount.newLines === theirCount.newLines) {
1440 newLines += myCount.newLines;
1442 newLines = undefined;
1446 if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
1450 if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
1461 // See: http://code.google.com/p/google-diff-match-patch/wiki/API
1462 function convertChangesToDMP(changes) {
1467 for (var i = 0; i < changes.length; i++) {
1468 change = changes[i];
1472 } else if (change.removed) {
1478 ret.push([operation, change.value]);
1484 function convertChangesToXML(changes) {
1487 for (var i = 0; i < changes.length; i++) {
1488 var change = changes[i];
1492 } else if (change.removed) {
1496 ret.push(escapeHTML(change.value));
1500 } else if (change.removed) {
1505 return ret.join('');
1508 function escapeHTML(s) {
1510 n = n.replace(/&/g, '&');
1511 n = n.replace(/</g, '<');
1512 n = n.replace(/>/g, '>');
1513 n = n.replace(/"/g, '"');
1517 /* See LICENSE file for terms of use */
1519 export { Diff, diffChars, diffWords, diffWordsWithSpace, diffLines, diffTrimmedLines, diffSentences, diffCss, diffJson, diffArrays, structuredPatch, createTwoFilesPatch, createPatch, applyPatch, applyPatches, parsePatch, merge, convertChangesToDMP, convertChangesToXML, canonicalize };