Merge pull request #14 from rtfpessoa/merge-npm

Merge npm package
This commit is contained in:
Rodrigo Fernandes 2015-07-19 00:44:14 +01:00
commit 57f56978aa
9 changed files with 1274 additions and 1017 deletions

7
.gitignore vendored
View file

@ -14,3 +14,10 @@
# Maven # Maven
log/ log/
target/ target/
# Node
node_modules/
npm-debug.log
# Bower
bower_components/

View file

@ -22,7 +22,9 @@ Diff to Html generates pretty HTML diffs from git word diff output.
* [Node Module](https://www.npmjs.org/package/diff2html) * [Node Module](https://www.npmjs.org/package/diff2html)
* Manually download and import `diff2html.js` into your page * [Bower Package](http://bower.io/search/?q=diff2html)
* Manually download and import `dist/diff2html.min.js` into your page
## How to use ## How to use

3
bin/diff2html Executable file
View file

@ -0,0 +1,3 @@
#!/usr/bin/env node
require("../src/diff2html.js");

View file

@ -2,15 +2,7 @@
"name": "diff2html", "name": "diff2html",
"version": "0.2.5", "version": "0.2.5",
"homepage": "https://github.com/rtfpessoa/diff2html", "homepage": "https://github.com/rtfpessoa/diff2html",
"authors": [
"Rodrigo Fernandes <rtfrodrigo@gmail.com>"
],
"repository": {
"type": "git",
"url": "git://github.com/rtfpessoa/diff2html.git"
},
"description": "Fast Diff to colorized HTML", "description": "Fast Diff to colorized HTML",
"main": "./src/diff2html.js",
"keywords": [ "keywords": [
"git", "git",
"diff", "diff",
@ -28,12 +20,37 @@
"difftohtml", "difftohtml",
"colorized" "colorized"
], ],
"authors": [
"Rodrigo Fernandes <rtfrodrigo@gmail.com>"
],
"repository": {
"type": "git",
"url": "git://github.com/rtfpessoa/diff2html.git"
},
"main": "./src/diff2html.js",
"license": "MIT", "license": "MIT",
"moduleType": [
"globals",
"node"
],
"dependencies": {
"jsdiff": ">= 1.4.0"
},
"ignore": [ "ignore": [
"**/.*", "**/.*",
"node_modules", "node_modules",
"bower_components", "bower_components",
"test", "test",
"tests" "tests",
"bin",
"package.json",
"release.sh"
] ]
} }

411
dist/diff2html.js vendored
View file

@ -17,13 +17,10 @@ function require() {
* These methods are based on the implementation proposed in * These methods are based on the implementation proposed in
* "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
* http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
*
* AUTHOR: https://github.com/kpdecker/jsdiff
*/ */
(function(global, undefined) { (function (global, undefined) {
var objectPrototypeToString = Object.prototype.toString;
var JsDiff = (function() {
/*jshint maxparams: 5*/
/*istanbul ignore next*/ /*istanbul ignore next*/
function map(arr, mapper, that) { function map(arr, mapper, that) {
if (Array.prototype.map) { if (Array.prototype.map) {
@ -37,9 +34,11 @@ function require() {
} }
return other; return other;
} }
function clonePath(path) { function clonePath(path) {
return { newPos: path.newPos, components: path.components.slice(0) }; return {newPos: path.newPos, components: path.components.slice(0)};
} }
function removeEmpty(array) { function removeEmpty(array) {
var ret = []; var ret = [];
for (var i = 0; i < array.length; i++) { for (var i = 0; i < array.length; i++) {
@ -49,6 +48,7 @@ function require() {
} }
return ret; return ret;
} }
function escapeHTML(s) { function escapeHTML(s) {
var n = s; var n = s;
n = n.replace(/&/g, '&amp;'); n = n.replace(/&/g, '&amp;');
@ -59,6 +59,53 @@ function require() {
return n; return n;
} }
// This function handles the presence of circular references by bailing out when encountering an
// object that is already on the "stack" of items being processed.
function canonicalize(obj, stack, replacementStack) {
stack = stack || [];
replacementStack = replacementStack || [];
var i;
for (i = 0; i < stack.length; i += 1) {
if (stack[i] === obj) {
return replacementStack[i];
}
}
var canonicalizedObj;
if ('[object Array]' === objectPrototypeToString.call(obj)) {
stack.push(obj);
canonicalizedObj = new Array(obj.length);
replacementStack.push(canonicalizedObj);
for (i = 0; i < obj.length; i += 1) {
canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack);
}
stack.pop();
replacementStack.pop();
} else if (typeof obj === 'object' && obj !== null) {
stack.push(obj);
canonicalizedObj = {};
replacementStack.push(canonicalizedObj);
var sortedKeys = [],
key;
for (key in obj) {
sortedKeys.push(key);
}
sortedKeys.sort();
for (i = 0; i < sortedKeys.length; i += 1) {
key = sortedKeys[i];
canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack);
}
stack.pop();
replacementStack.pop();
} else {
canonicalizedObj = obj;
}
return canonicalizedObj;
}
function buildValues(components, newString, oldString, useLongestToken) { function buildValues(components, newString, oldString, useLongestToken) {
var componentPos = 0, var componentPos = 0,
componentLen = components.length, componentLen = components.length,
@ -70,7 +117,7 @@ function require() {
if (!component.removed) { if (!component.removed) {
if (!component.added && useLongestToken) { if (!component.added && useLongestToken) {
var value = newString.slice(newPos, newPos + component.count); var value = newString.slice(newPos, newPos + component.count);
value = map(value, function(value, i) { value = map(value, function (value, i) {
var oldValue = oldString[oldPos + i]; var oldValue = oldString[oldPos + i];
return oldValue.length > value.length ? oldValue : value; return oldValue.length > value.length ? oldValue : value;
}); });
@ -88,22 +135,34 @@ function require() {
} else { } else {
component.value = oldString.slice(oldPos, oldPos + component.count).join(''); component.value = oldString.slice(oldPos, oldPos + component.count).join('');
oldPos += component.count; oldPos += component.count;
// Reverse add and remove so removes are output first to match common convention
// The diffing algorithm is tied to add then remove output and this is the simplest
// route to get the desired output with minimal overhead.
if (componentPos && components[componentPos - 1].added) {
var tmp = components[componentPos - 1];
components[componentPos - 1] = components[componentPos];
components[componentPos] = tmp;
}
} }
} }
return components; return components;
} }
var Diff = function(ignoreWhitespace) { function Diff(ignoreWhitespace) {
this.ignoreWhitespace = ignoreWhitespace; this.ignoreWhitespace = ignoreWhitespace;
}; }
Diff.prototype = { Diff.prototype = {
diff: function(oldString, newString, callback) { diff: function (oldString, newString, callback) {
var self = this; var self = this;
function done(value) { function done(value) {
if (callback) { if (callback) {
setTimeout(function() { callback(undefined, value); }, 0); setTimeout(function () {
callback(undefined, value);
}, 0);
return true; return true;
} else { } else {
return value; return value;
@ -112,43 +171,44 @@ function require() {
// Handle the identity case (this is due to unrolling editLength == 0 // Handle the identity case (this is due to unrolling editLength == 0
if (newString === oldString) { if (newString === oldString) {
return done([{ value: newString }]); return done([{value: newString}]);
} }
if (!newString) { if (!newString) {
return done([{ value: oldString, removed: true }]); return done([{value: oldString, removed: true}]);
} }
if (!oldString) { if (!oldString) {
return done([{ value: newString, added: true }]); return done([{value: newString, added: true}]);
} }
newString = this.tokenize(newString); newString = this.tokenize(newString);
oldString = this.tokenize(oldString); oldString = this.tokenize(oldString);
var newLen = newString.length, oldLen = oldString.length; var newLen = newString.length, oldLen = oldString.length;
var editLength = 1;
var maxEditLength = newLen + oldLen; var maxEditLength = newLen + oldLen;
var bestPath = [{ newPos: -1, components: [] }]; var bestPath = [{newPos: -1, components: []}];
// Seed editLength = 0, i.e. the content starts with the same values // Seed editLength = 0, i.e. the content starts with the same values
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
// Identity per the equality and tokenizer // Identity per the equality and tokenizer
return done([{value: newString.join('')}]); return done([{value: newString.join('')}]);
} }
// Main worker method. checks all permutations of a given edit length for acceptance. // Main worker method. checks all permutations of a given edit length for acceptance.
function execEditLength() { function execEditLength() {
for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
var basePath; var basePath;
var addPath = bestPath[diagonalPath-1], var addPath = bestPath[diagonalPath - 1],
removePath = bestPath[diagonalPath+1]; removePath = bestPath[diagonalPath + 1],
oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
if (addPath) { if (addPath) {
// No one else is going to attempt to use this value, clear it // No one else is going to attempt to use this value, clear it
bestPath[diagonalPath-1] = undefined; bestPath[diagonalPath - 1] = undefined;
} }
var canAdd = addPath && addPath.newPos+1 < newLen; var canAdd = addPath && addPath.newPos + 1 < newLen,
var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
if (!canAdd && !canRemove) { if (!canAdd && !canRemove) {
// If this path is a terminal then prune // If this path is a terminal then prune
bestPath[diagonalPath] = undefined; bestPath[diagonalPath] = undefined;
@ -167,10 +227,10 @@ function require() {
self.pushComponent(basePath.components, true, undefined); self.pushComponent(basePath.components, true, undefined);
} }
var oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath);
// If we have hit the end of both strings, then we are done // If we have hit the end of both strings, then we are done
if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
return done(buildValues(basePath.components, newString, oldString, self.useLongestToken)); return done(buildValues(basePath.components, newString, oldString, self.useLongestToken));
} else { } else {
// Otherwise track this path as a potential candidate and continue. // Otherwise track this path as a potential candidate and continue.
@ -184,10 +244,9 @@ function require() {
// Performs the length of edit iteration. Is a bit fugly as this has to support the // Performs the length of edit iteration. Is a bit fugly as this has to support the
// sync and async mode which is never fun. Loops over execEditLength until a value // sync and async mode which is never fun. Loops over execEditLength until a value
// is produced. // is produced.
var editLength = 1;
if (callback) { if (callback) {
(function exec() { (function exec() {
setTimeout(function() { setTimeout(function () {
// This should not happen, but we want to be safe. // This should not happen, but we want to be safe.
/*istanbul ignore next */ /*istanbul ignore next */
if (editLength > maxEditLength) { if (editLength > maxEditLength) {
@ -198,9 +257,9 @@ function require() {
exec(); exec();
} }
}, 0); }, 0);
})(); }());
} else { } else {
while(editLength <= maxEditLength) { while (editLength <= maxEditLength) {
var ret = execEditLength(); var ret = execEditLength();
if (ret) { if (ret) {
return ret; return ret;
@ -209,24 +268,24 @@ function require() {
} }
}, },
pushComponent: function(components, added, removed) { pushComponent: function (components, added, removed) {
var last = components[components.length-1]; var last = components[components.length - 1];
if (last && last.added === added && last.removed === removed) { if (last && last.added === added && last.removed === removed) {
// We need to clone here as the component clone operation is just // We need to clone here as the component clone operation is just
// as shallow array clone // as shallow array clone
components[components.length-1] = {count: last.count + 1, added: added, removed: removed }; components[components.length - 1] = {count: last.count + 1, added: added, removed: removed};
} else { } else {
components.push({count: 1, added: added, removed: removed }); components.push({count: 1, added: added, removed: removed});
} }
}, },
extractCommon: function(basePath, newString, oldString, diagonalPath) { extractCommon: function (basePath, newString, oldString, diagonalPath) {
var newLen = newString.length, var newLen = newString.length,
oldLen = oldString.length, oldLen = oldString.length,
newPos = basePath.newPos, newPos = basePath.newPos,
oldPos = newPos - diagonalPath, oldPos = newPos - diagonalPath,
commonCount = 0; commonCount = 0;
while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
newPos++; newPos++;
oldPos++; oldPos++;
commonCount++; commonCount++;
@ -240,11 +299,11 @@ function require() {
return oldPos; return oldPos;
}, },
equals: function(left, right) { equals: function (left, right) {
var reWhitespace = /\S/; var reWhitespace = /\S/;
return left === right || (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)); return left === right || (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right));
}, },
tokenize: function(value) { tokenize: function (value) {
return value.split(''); return value.split('');
} }
}; };
@ -253,12 +312,12 @@ function require() {
var WordDiff = new Diff(true); var WordDiff = new Diff(true);
var WordWithSpaceDiff = new Diff(); var WordWithSpaceDiff = new Diff();
WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) { WordDiff.tokenize = WordWithSpaceDiff.tokenize = function (value) {
return removeEmpty(value.split(/(\s+|\b)/)); return removeEmpty(value.split(/(\s+|\b)/));
}; };
var CssDiff = new Diff(true); var CssDiff = new Diff(true);
CssDiff.tokenize = function(value) { CssDiff.tokenize = function (value) {
return removeEmpty(value.split(/([{}:;,]|\s+)/)); return removeEmpty(value.split(/([{}:;,]|\s+)/));
}; };
@ -267,21 +326,21 @@ function require() {
var TrimmedLineDiff = new Diff(); var TrimmedLineDiff = new Diff();
TrimmedLineDiff.ignoreTrim = true; TrimmedLineDiff.ignoreTrim = true;
LineDiff.tokenize = TrimmedLineDiff.tokenize = function(value) { LineDiff.tokenize = TrimmedLineDiff.tokenize = function (value) {
var retLines = [], var retLines = [],
lines = value.split(/^/m); lines = value.split(/^/m);
for(var i = 0; i < lines.length; i++) { for (var i = 0; i < lines.length; i++) {
var line = lines[i], var line = lines[i],
lastLine = lines[i - 1], lastLine = lines[i - 1],
lastLineLastChar = lastLine ? lastLine[lastLine.length - 1] : ''; lastLineLastChar = lastLine && lastLine[lastLine.length - 1];
// Merge lines that may contain windows new lines // Merge lines that may contain windows new lines
if (line === '\n' && lastLineLastChar === '\r') { if (line === '\n' && lastLineLastChar === '\r') {
retLines[retLines.length - 1] = retLines[retLines.length - 1].slice(0,-1) + '\r\n'; retLines[retLines.length - 1] = retLines[retLines.length - 1].slice(0, -1) + '\r\n';
} else if (line) { } else {
if (this.ignoreTrim) { if (this.ignoreTrim) {
line = line.trim(); line = line.trim();
//add a newline unless this is the last line. // add a newline unless this is the last line.
if (i < lines.length - 1) { if (i < lines.length - 1) {
line += '\n'; line += '\n';
} }
@ -293,6 +352,28 @@ function require() {
return retLines; return retLines;
}; };
var PatchDiff = new Diff();
PatchDiff.tokenize = function (value) {
var ret = [],
linesAndNewlines = value.split(/(\n|\r\n)/);
// Ignore the final empty token that occurs if the string ends with a new line
if (!linesAndNewlines[linesAndNewlines.length - 1]) {
linesAndNewlines.pop();
}
// Merge the content and line separators into single tokens
for (var i = 0; i < linesAndNewlines.length; i++) {
var line = linesAndNewlines[i];
if (i % 2) {
ret[ret.length - 1] += line;
} else {
ret.push(line);
}
}
return ret;
};
var SentenceDiff = new Diff(); var SentenceDiff = new Diff();
SentenceDiff.tokenize = function (value) { SentenceDiff.tokenize = function (value) {
@ -304,71 +385,37 @@ function require() {
// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
JsonDiff.useLongestToken = true; JsonDiff.useLongestToken = true;
JsonDiff.tokenize = LineDiff.tokenize; JsonDiff.tokenize = LineDiff.tokenize;
JsonDiff.equals = function(left, right) { JsonDiff.equals = function (left, right) {
return LineDiff.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); return LineDiff.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
}; };
var objectPrototypeToString = Object.prototype.toString; var JsDiff = {
// This function handles the presence of circular references by bailing out when encountering an
// object that is already on the "stack" of items being processed.
function canonicalize(obj, stack, replacementStack) {
stack = stack || [];
replacementStack = replacementStack || [];
var i;
for (var i = 0 ; i < stack.length ; i += 1) {
if (stack[i] === obj) {
return replacementStack[i];
}
}
var canonicalizedObj;
if ('[object Array]' === objectPrototypeToString.call(obj)) {
stack.push(obj);
canonicalizedObj = new Array(obj.length);
replacementStack.push(canonicalizedObj);
for (i = 0 ; i < obj.length ; i += 1) {
canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack);
}
stack.pop();
replacementStack.pop();
} else if (typeof obj === 'object' && obj !== null) {
stack.push(obj);
canonicalizedObj = {};
replacementStack.push(canonicalizedObj);
var sortedKeys = [];
for (var key in obj) {
sortedKeys.push(key);
}
sortedKeys.sort();
for (i = 0 ; i < sortedKeys.length ; i += 1) {
var key = sortedKeys[i];
canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack);
}
stack.pop();
replacementStack.pop();
} else {
canonicalizedObj = obj;
}
return canonicalizedObj;
}
return {
Diff: Diff, Diff: Diff,
diffChars: function(oldStr, newStr, callback) { return CharDiff.diff(oldStr, newStr, callback); }, diffChars: function (oldStr, newStr, callback) {
diffWords: function(oldStr, newStr, callback) { return WordDiff.diff(oldStr, newStr, callback); }, return CharDiff.diff(oldStr, newStr, callback);
diffWordsWithSpace: function(oldStr, newStr, callback) { return WordWithSpaceDiff.diff(oldStr, newStr, callback); }, },
diffLines: function(oldStr, newStr, callback) { return LineDiff.diff(oldStr, newStr, callback); }, diffWords: function (oldStr, newStr, callback) {
diffTrimmedLines: function(oldStr, newStr, callback) { return TrimmedLineDiff.diff(oldStr, newStr, callback); }, return WordDiff.diff(oldStr, newStr, callback);
},
diffWordsWithSpace: function (oldStr, newStr, callback) {
return WordWithSpaceDiff.diff(oldStr, newStr, callback);
},
diffLines: function (oldStr, newStr, callback) {
return LineDiff.diff(oldStr, newStr, callback);
},
diffTrimmedLines: function (oldStr, newStr, callback) {
return TrimmedLineDiff.diff(oldStr, newStr, callback);
},
diffSentences: function(oldStr, newStr, callback) { return SentenceDiff.diff(oldStr, newStr, callback); }, diffSentences: function (oldStr, newStr, callback) {
return SentenceDiff.diff(oldStr, newStr, callback);
},
diffCss: function(oldStr, newStr, callback) { return CssDiff.diff(oldStr, newStr, callback); }, diffCss: function (oldStr, newStr, callback) {
diffJson: function(oldObj, newObj, callback) { return CssDiff.diff(oldStr, newStr, callback);
},
diffJson: function (oldObj, newObj, callback) {
return JsonDiff.diff( return JsonDiff.diff(
typeof oldObj === 'string' ? oldObj : JSON.stringify(canonicalize(oldObj), undefined, ' '), typeof oldObj === 'string' ? oldObj : JSON.stringify(canonicalize(oldObj), undefined, ' '),
typeof newObj === 'string' ? newObj : JSON.stringify(canonicalize(newObj), undefined, ' '), typeof newObj === 'string' ? newObj : JSON.stringify(canonicalize(newObj), undefined, ' '),
@ -376,30 +423,34 @@ function require() {
); );
}, },
createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { createTwoFilesPatch: function (oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader) {
var ret = []; var ret = [];
ret.push('Index: ' + fileName); if (oldFileName == newFileName) {
ret.push('==================================================================='); ret.push('Index: ' + oldFileName);
ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
var diff = LineDiff.diff(oldStr, newStr);
if (!diff[diff.length-1].value) {
diff.pop(); // Remove trailing newline add
} }
ret.push('===================================================================');
ret.push('--- ' + oldFileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
ret.push('+++ ' + newFileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
var diff = PatchDiff.diff(oldStr, newStr);
diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier
// Formats a given set of lines for printing as context lines in a patch
function contextLines(lines) { function contextLines(lines) {
return map(lines, function(entry) { return ' ' + entry; }); return map(lines, function (entry) {
return ' ' + entry;
});
} }
// Outputs the no newline at end of file warning if needed
function eofNL(curRange, i, current) { function eofNL(curRange, i, current) {
var last = diff[diff.length-2], var last = diff[diff.length - 2],
isLast = i === diff.length-2, isLast = i === diff.length - 2,
isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed); isLastOfType = i === diff.length - 3 && current.added !== last.added;
// Figure out if this is the last line for the given file and missing NL // Figure out if this is the last line for the given file and missing NL
if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { if (!(/\n$/.test(current.value)) && (isLast || isLastOfType)) {
curRange.push('\\ No newline at end of file'); curRange.push('\\ No newline at end of file');
} }
} }
@ -412,8 +463,9 @@ function require() {
current.lines = lines; current.lines = lines;
if (current.added || current.removed) { if (current.added || current.removed) {
// If we have previous context, start with that
if (!oldRangeStart) { if (!oldRangeStart) {
var prev = diff[i-1]; var prev = diff[i - 1];
oldRangeStart = oldLine; oldRangeStart = oldLine;
newRangeStart = newLine; newRangeStart = newLine;
@ -423,26 +475,32 @@ function require() {
newRangeStart -= curRange.length; newRangeStart -= curRange.length;
} }
} }
curRange.push.apply(curRange, map(lines, function(entry) { return (current.added?'+':'-') + entry; }));
// Output our changes
curRange.push.apply(curRange, map(lines, function (entry) {
return (current.added ? '+' : '-') + entry;
}));
eofNL(curRange, i, current); eofNL(curRange, i, current);
// Track the updated file position
if (current.added) { if (current.added) {
newLine += lines.length; newLine += lines.length;
} else { } else {
oldLine += lines.length; oldLine += lines.length;
} }
} else { } else {
// Identical context lines. Track line changes
if (oldRangeStart) { if (oldRangeStart) {
// Close out any changes that have been output (or join overlapping) // Close out any changes that have been output (or join overlapping)
if (lines.length <= 8 && i < diff.length-2) { if (lines.length <= 8 && i < diff.length - 2) {
// Overlapping // Overlapping
curRange.push.apply(curRange, contextLines(lines)); curRange.push.apply(curRange, contextLines(lines));
} else { } else {
// end the range and output // end the range and output
var contextSize = Math.min(lines.length, 4); var contextSize = Math.min(lines.length, 4);
ret.push( ret.push(
'@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize) '@@ -' + oldRangeStart + ',' + (oldLine - oldRangeStart + contextSize)
+ ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize) + ' +' + newRangeStart + ',' + (newLine - newRangeStart + contextSize)
+ ' @@'); + ' @@');
ret.push.apply(ret, curRange); ret.push.apply(ret, curRange);
ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
@ -450,7 +508,9 @@ function require() {
eofNL(ret, i, current); eofNL(ret, i, current);
} }
oldRangeStart = 0; newRangeStart = 0; curRange = []; oldRangeStart = 0;
newRangeStart = 0;
curRange = [];
} }
} }
oldLine += lines.length; oldLine += lines.length;
@ -461,68 +521,76 @@ function require() {
return ret.join('\n') + '\n'; return ret.join('\n') + '\n';
}, },
applyPatch: function(oldStr, uniDiff) { createPatch: function (fileName, oldStr, newStr, oldHeader, newHeader) {
var diffstr = uniDiff.split('\n'); return JsDiff.createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader);
var diff = []; },
var i = 0,
applyPatch: function (oldStr, uniDiff) {
var diffstr = uniDiff.split('\n'),
hunks = [],
i = 0,
remEOFNL = false, remEOFNL = false,
addEOFNL = false; addEOFNL = false;
// Skip to the first change chunk // Skip to the first change hunk
while (i < diffstr.length && !/^@@/.test(diffstr[i])) { while (i < diffstr.length && !(/^@@/.test(diffstr[i]))) {
i++; i++;
} }
// Parse the unified diff
for (; i < diffstr.length; i++) { for (; i < diffstr.length; i++) {
if (diffstr[i][0] === '@') { if (diffstr[i][0] === '@') {
var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/); var chnukHeader = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
diff.unshift({ hunks.unshift({
start:meh[3], start: chnukHeader[3],
oldlength:meh[2], oldlength: +chnukHeader[2],
oldlines:[], removed: [],
newlength:meh[4], newlength: chnukHeader[4],
newlines:[] added: []
}); });
} else if (diffstr[i][0] === '+') { } else if (diffstr[i][0] === '+') {
diff[0].newlines.push(diffstr[i].substr(1)); hunks[0].added.push(diffstr[i].substr(1));
} else if (diffstr[i][0] === '-') { } else if (diffstr[i][0] === '-') {
diff[0].oldlines.push(diffstr[i].substr(1)); hunks[0].removed.push(diffstr[i].substr(1));
} else if (diffstr[i][0] === ' ') { } else if (diffstr[i][0] === ' ') {
diff[0].newlines.push(diffstr[i].substr(1)); hunks[0].added.push(diffstr[i].substr(1));
diff[0].oldlines.push(diffstr[i].substr(1)); hunks[0].removed.push(diffstr[i].substr(1));
} else if (diffstr[i][0] === '\\') { } else if (diffstr[i][0] === '\\') {
if (diffstr[i-1][0] === '+') { if (diffstr[i - 1][0] === '+') {
remEOFNL = true; remEOFNL = true;
} else if (diffstr[i-1][0] === '-') { } else if (diffstr[i - 1][0] === '-') {
addEOFNL = true; addEOFNL = true;
} }
} }
} }
var str = oldStr.split('\n'); // Apply the diff to the input
for (var i = diff.length - 1; i >= 0; i--) { var lines = oldStr.split('\n');
var d = diff[i]; for (i = hunks.length - 1; i >= 0; i--) {
for (var j = 0; j < d.oldlength; j++) { var hunk = hunks[i];
if (str[d.start-1+j] !== d.oldlines[j]) { // Sanity check the input string. Bail if we don't match.
for (var j = 0; j < hunk.oldlength; j++) {
if (lines[hunk.start - 1 + j] !== hunk.removed[j]) {
return false; return false;
} }
} }
Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines)); Array.prototype.splice.apply(lines, [hunk.start - 1, hunk.oldlength].concat(hunk.added));
} }
// Handle EOFNL insertion/removal
if (remEOFNL) { if (remEOFNL) {
while (!str[str.length-1]) { while (!lines[lines.length - 1]) {
str.pop(); lines.pop();
} }
} else if (addEOFNL) { } else if (addEOFNL) {
str.push(''); lines.push('');
} }
return str.join('\n'); return lines.join('\n');
}, },
convertChangesToXML: function(changes){ convertChangesToXML: function (changes) {
var ret = []; var ret = [];
for ( var i = 0; i < changes.length; i++) { for (var i = 0; i < changes.length; i++) {
var change = changes[i]; var change = changes[i];
if (change.added) { if (change.added) {
ret.push('<ins>'); ret.push('<ins>');
@ -542,31 +610,42 @@ function require() {
}, },
// See: http://code.google.com/p/google-diff-match-patch/wiki/API // See: http://code.google.com/p/google-diff-match-patch/wiki/API
convertChangesToDMP: function(changes){ convertChangesToDMP: function (changes) {
var ret = [], change; var ret = [],
for ( var i = 0; i < changes.length; i++) { change,
operation;
for (var i = 0; i < changes.length; i++) {
change = changes[i]; change = changes[i];
ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]); if (change.added) {
operation = 1;
} else if (change.removed) {
operation = -1;
} else {
operation = 0;
}
ret.push([operation, change.value]);
} }
return ret; return ret;
}, },
canonicalize: canonicalize canonicalize: canonicalize
}; };
})();
/*istanbul ignore next */ /*istanbul ignore next */
/*global module */
if (typeof module !== 'undefined' && module.exports) { if (typeof module !== 'undefined' && module.exports) {
module.exports = JsDiff; module.exports = JsDiff;
} } else if (typeof define === 'function' && define.amd) {
else if (typeof define === 'function' && define.amd) {
/*global define */ /*global define */
define([], function() { return JsDiff; }); define([], function () {
} return JsDiff;
else if (typeof global.JsDiff === 'undefined') { });
} else if (typeof global.JsDiff === 'undefined') {
global.JsDiff = JsDiff; global.JsDiff = JsDiff;
} }
})(this);/* }(this));
/*
* *
* Utils (utils.js) * Utils (utils.js)
* Author: rtfpessoa * Author: rtfpessoa
@ -833,7 +912,9 @@ function require() {
(function (global, undefined) { (function (global, undefined) {
// dirty hack for browser compatibility // dirty hack for browser compatibility
var jsDiff = (typeof JsDiff !== "undefined" && JsDiff) || require("../lib/diff.js"); var jsDiff = (typeof JsDiff !== "undefined" && JsDiff) ||
require("diff") ||
require("../lib/diff.js");
var utils = require("./utils.js").Utils; var utils = require("./utils.js").Utils;
function PrinterUtils() { function PrinterUtils() {

File diff suppressed because one or more lines are too long

View file

@ -13,13 +13,10 @@
* These methods are based on the implementation proposed in * These methods are based on the implementation proposed in
* "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
* http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
*
* AUTHOR: https://github.com/kpdecker/jsdiff
*/ */
(function(global, undefined) { (function (global, undefined) {
var objectPrototypeToString = Object.prototype.toString;
var JsDiff = (function() {
/*jshint maxparams: 5*/
/*istanbul ignore next*/ /*istanbul ignore next*/
function map(arr, mapper, that) { function map(arr, mapper, that) {
if (Array.prototype.map) { if (Array.prototype.map) {
@ -33,9 +30,11 @@
} }
return other; return other;
} }
function clonePath(path) { function clonePath(path) {
return { newPos: path.newPos, components: path.components.slice(0) }; return {newPos: path.newPos, components: path.components.slice(0)};
} }
function removeEmpty(array) { function removeEmpty(array) {
var ret = []; var ret = [];
for (var i = 0; i < array.length; i++) { for (var i = 0; i < array.length; i++) {
@ -45,6 +44,7 @@
} }
return ret; return ret;
} }
function escapeHTML(s) { function escapeHTML(s) {
var n = s; var n = s;
n = n.replace(/&/g, '&amp;'); n = n.replace(/&/g, '&amp;');
@ -55,6 +55,53 @@
return n; return n;
} }
// This function handles the presence of circular references by bailing out when encountering an
// object that is already on the "stack" of items being processed.
function canonicalize(obj, stack, replacementStack) {
stack = stack || [];
replacementStack = replacementStack || [];
var i;
for (i = 0; i < stack.length; i += 1) {
if (stack[i] === obj) {
return replacementStack[i];
}
}
var canonicalizedObj;
if ('[object Array]' === objectPrototypeToString.call(obj)) {
stack.push(obj);
canonicalizedObj = new Array(obj.length);
replacementStack.push(canonicalizedObj);
for (i = 0; i < obj.length; i += 1) {
canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack);
}
stack.pop();
replacementStack.pop();
} else if (typeof obj === 'object' && obj !== null) {
stack.push(obj);
canonicalizedObj = {};
replacementStack.push(canonicalizedObj);
var sortedKeys = [],
key;
for (key in obj) {
sortedKeys.push(key);
}
sortedKeys.sort();
for (i = 0; i < sortedKeys.length; i += 1) {
key = sortedKeys[i];
canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack);
}
stack.pop();
replacementStack.pop();
} else {
canonicalizedObj = obj;
}
return canonicalizedObj;
}
function buildValues(components, newString, oldString, useLongestToken) { function buildValues(components, newString, oldString, useLongestToken) {
var componentPos = 0, var componentPos = 0,
componentLen = components.length, componentLen = components.length,
@ -66,7 +113,7 @@
if (!component.removed) { if (!component.removed) {
if (!component.added && useLongestToken) { if (!component.added && useLongestToken) {
var value = newString.slice(newPos, newPos + component.count); var value = newString.slice(newPos, newPos + component.count);
value = map(value, function(value, i) { value = map(value, function (value, i) {
var oldValue = oldString[oldPos + i]; var oldValue = oldString[oldPos + i];
return oldValue.length > value.length ? oldValue : value; return oldValue.length > value.length ? oldValue : value;
}); });
@ -84,22 +131,34 @@
} else { } else {
component.value = oldString.slice(oldPos, oldPos + component.count).join(''); component.value = oldString.slice(oldPos, oldPos + component.count).join('');
oldPos += component.count; oldPos += component.count;
// Reverse add and remove so removes are output first to match common convention
// The diffing algorithm is tied to add then remove output and this is the simplest
// route to get the desired output with minimal overhead.
if (componentPos && components[componentPos - 1].added) {
var tmp = components[componentPos - 1];
components[componentPos - 1] = components[componentPos];
components[componentPos] = tmp;
}
} }
} }
return components; return components;
} }
var Diff = function(ignoreWhitespace) { function Diff(ignoreWhitespace) {
this.ignoreWhitespace = ignoreWhitespace; this.ignoreWhitespace = ignoreWhitespace;
}; }
Diff.prototype = { Diff.prototype = {
diff: function(oldString, newString, callback) { diff: function (oldString, newString, callback) {
var self = this; var self = this;
function done(value) { function done(value) {
if (callback) { if (callback) {
setTimeout(function() { callback(undefined, value); }, 0); setTimeout(function () {
callback(undefined, value);
}, 0);
return true; return true;
} else { } else {
return value; return value;
@ -108,43 +167,44 @@
// Handle the identity case (this is due to unrolling editLength == 0 // Handle the identity case (this is due to unrolling editLength == 0
if (newString === oldString) { if (newString === oldString) {
return done([{ value: newString }]); return done([{value: newString}]);
} }
if (!newString) { if (!newString) {
return done([{ value: oldString, removed: true }]); return done([{value: oldString, removed: true}]);
} }
if (!oldString) { if (!oldString) {
return done([{ value: newString, added: true }]); return done([{value: newString, added: true}]);
} }
newString = this.tokenize(newString); newString = this.tokenize(newString);
oldString = this.tokenize(oldString); oldString = this.tokenize(oldString);
var newLen = newString.length, oldLen = oldString.length; var newLen = newString.length, oldLen = oldString.length;
var editLength = 1;
var maxEditLength = newLen + oldLen; var maxEditLength = newLen + oldLen;
var bestPath = [{ newPos: -1, components: [] }]; var bestPath = [{newPos: -1, components: []}];
// Seed editLength = 0, i.e. the content starts with the same values // Seed editLength = 0, i.e. the content starts with the same values
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
// Identity per the equality and tokenizer // Identity per the equality and tokenizer
return done([{value: newString.join('')}]); return done([{value: newString.join('')}]);
} }
// Main worker method. checks all permutations of a given edit length for acceptance. // Main worker method. checks all permutations of a given edit length for acceptance.
function execEditLength() { function execEditLength() {
for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
var basePath; var basePath;
var addPath = bestPath[diagonalPath-1], var addPath = bestPath[diagonalPath - 1],
removePath = bestPath[diagonalPath+1]; removePath = bestPath[diagonalPath + 1],
oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
if (addPath) { if (addPath) {
// No one else is going to attempt to use this value, clear it // No one else is going to attempt to use this value, clear it
bestPath[diagonalPath-1] = undefined; bestPath[diagonalPath - 1] = undefined;
} }
var canAdd = addPath && addPath.newPos+1 < newLen; var canAdd = addPath && addPath.newPos + 1 < newLen,
var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
if (!canAdd && !canRemove) { if (!canAdd && !canRemove) {
// If this path is a terminal then prune // If this path is a terminal then prune
bestPath[diagonalPath] = undefined; bestPath[diagonalPath] = undefined;
@ -163,10 +223,10 @@
self.pushComponent(basePath.components, true, undefined); self.pushComponent(basePath.components, true, undefined);
} }
var oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath);
// If we have hit the end of both strings, then we are done // If we have hit the end of both strings, then we are done
if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
return done(buildValues(basePath.components, newString, oldString, self.useLongestToken)); return done(buildValues(basePath.components, newString, oldString, self.useLongestToken));
} else { } else {
// Otherwise track this path as a potential candidate and continue. // Otherwise track this path as a potential candidate and continue.
@ -180,10 +240,9 @@
// Performs the length of edit iteration. Is a bit fugly as this has to support the // Performs the length of edit iteration. Is a bit fugly as this has to support the
// sync and async mode which is never fun. Loops over execEditLength until a value // sync and async mode which is never fun. Loops over execEditLength until a value
// is produced. // is produced.
var editLength = 1;
if (callback) { if (callback) {
(function exec() { (function exec() {
setTimeout(function() { setTimeout(function () {
// This should not happen, but we want to be safe. // This should not happen, but we want to be safe.
/*istanbul ignore next */ /*istanbul ignore next */
if (editLength > maxEditLength) { if (editLength > maxEditLength) {
@ -194,9 +253,9 @@
exec(); exec();
} }
}, 0); }, 0);
})(); }());
} else { } else {
while(editLength <= maxEditLength) { while (editLength <= maxEditLength) {
var ret = execEditLength(); var ret = execEditLength();
if (ret) { if (ret) {
return ret; return ret;
@ -205,24 +264,24 @@
} }
}, },
pushComponent: function(components, added, removed) { pushComponent: function (components, added, removed) {
var last = components[components.length-1]; var last = components[components.length - 1];
if (last && last.added === added && last.removed === removed) { if (last && last.added === added && last.removed === removed) {
// We need to clone here as the component clone operation is just // We need to clone here as the component clone operation is just
// as shallow array clone // as shallow array clone
components[components.length-1] = {count: last.count + 1, added: added, removed: removed }; components[components.length - 1] = {count: last.count + 1, added: added, removed: removed};
} else { } else {
components.push({count: 1, added: added, removed: removed }); components.push({count: 1, added: added, removed: removed});
} }
}, },
extractCommon: function(basePath, newString, oldString, diagonalPath) { extractCommon: function (basePath, newString, oldString, diagonalPath) {
var newLen = newString.length, var newLen = newString.length,
oldLen = oldString.length, oldLen = oldString.length,
newPos = basePath.newPos, newPos = basePath.newPos,
oldPos = newPos - diagonalPath, oldPos = newPos - diagonalPath,
commonCount = 0; commonCount = 0;
while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
newPos++; newPos++;
oldPos++; oldPos++;
commonCount++; commonCount++;
@ -236,11 +295,11 @@
return oldPos; return oldPos;
}, },
equals: function(left, right) { equals: function (left, right) {
var reWhitespace = /\S/; var reWhitespace = /\S/;
return left === right || (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)); return left === right || (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right));
}, },
tokenize: function(value) { tokenize: function (value) {
return value.split(''); return value.split('');
} }
}; };
@ -249,12 +308,12 @@
var WordDiff = new Diff(true); var WordDiff = new Diff(true);
var WordWithSpaceDiff = new Diff(); var WordWithSpaceDiff = new Diff();
WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) { WordDiff.tokenize = WordWithSpaceDiff.tokenize = function (value) {
return removeEmpty(value.split(/(\s+|\b)/)); return removeEmpty(value.split(/(\s+|\b)/));
}; };
var CssDiff = new Diff(true); var CssDiff = new Diff(true);
CssDiff.tokenize = function(value) { CssDiff.tokenize = function (value) {
return removeEmpty(value.split(/([{}:;,]|\s+)/)); return removeEmpty(value.split(/([{}:;,]|\s+)/));
}; };
@ -263,21 +322,21 @@
var TrimmedLineDiff = new Diff(); var TrimmedLineDiff = new Diff();
TrimmedLineDiff.ignoreTrim = true; TrimmedLineDiff.ignoreTrim = true;
LineDiff.tokenize = TrimmedLineDiff.tokenize = function(value) { LineDiff.tokenize = TrimmedLineDiff.tokenize = function (value) {
var retLines = [], var retLines = [],
lines = value.split(/^/m); lines = value.split(/^/m);
for(var i = 0; i < lines.length; i++) { for (var i = 0; i < lines.length; i++) {
var line = lines[i], var line = lines[i],
lastLine = lines[i - 1], lastLine = lines[i - 1],
lastLineLastChar = lastLine ? lastLine[lastLine.length - 1] : ''; lastLineLastChar = lastLine && lastLine[lastLine.length - 1];
// Merge lines that may contain windows new lines // Merge lines that may contain windows new lines
if (line === '\n' && lastLineLastChar === '\r') { if (line === '\n' && lastLineLastChar === '\r') {
retLines[retLines.length - 1] = retLines[retLines.length - 1].slice(0,-1) + '\r\n'; retLines[retLines.length - 1] = retLines[retLines.length - 1].slice(0, -1) + '\r\n';
} else if (line) { } else {
if (this.ignoreTrim) { if (this.ignoreTrim) {
line = line.trim(); line = line.trim();
//add a newline unless this is the last line. // add a newline unless this is the last line.
if (i < lines.length - 1) { if (i < lines.length - 1) {
line += '\n'; line += '\n';
} }
@ -289,6 +348,28 @@
return retLines; return retLines;
}; };
var PatchDiff = new Diff();
PatchDiff.tokenize = function (value) {
var ret = [],
linesAndNewlines = value.split(/(\n|\r\n)/);
// Ignore the final empty token that occurs if the string ends with a new line
if (!linesAndNewlines[linesAndNewlines.length - 1]) {
linesAndNewlines.pop();
}
// Merge the content and line separators into single tokens
for (var i = 0; i < linesAndNewlines.length; i++) {
var line = linesAndNewlines[i];
if (i % 2) {
ret[ret.length - 1] += line;
} else {
ret.push(line);
}
}
return ret;
};
var SentenceDiff = new Diff(); var SentenceDiff = new Diff();
SentenceDiff.tokenize = function (value) { SentenceDiff.tokenize = function (value) {
@ -300,71 +381,37 @@
// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
JsonDiff.useLongestToken = true; JsonDiff.useLongestToken = true;
JsonDiff.tokenize = LineDiff.tokenize; JsonDiff.tokenize = LineDiff.tokenize;
JsonDiff.equals = function(left, right) { JsonDiff.equals = function (left, right) {
return LineDiff.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); return LineDiff.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
}; };
var objectPrototypeToString = Object.prototype.toString; var JsDiff = {
// This function handles the presence of circular references by bailing out when encountering an
// object that is already on the "stack" of items being processed.
function canonicalize(obj, stack, replacementStack) {
stack = stack || [];
replacementStack = replacementStack || [];
var i;
for (var i = 0 ; i < stack.length ; i += 1) {
if (stack[i] === obj) {
return replacementStack[i];
}
}
var canonicalizedObj;
if ('[object Array]' === objectPrototypeToString.call(obj)) {
stack.push(obj);
canonicalizedObj = new Array(obj.length);
replacementStack.push(canonicalizedObj);
for (i = 0 ; i < obj.length ; i += 1) {
canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack);
}
stack.pop();
replacementStack.pop();
} else if (typeof obj === 'object' && obj !== null) {
stack.push(obj);
canonicalizedObj = {};
replacementStack.push(canonicalizedObj);
var sortedKeys = [];
for (var key in obj) {
sortedKeys.push(key);
}
sortedKeys.sort();
for (i = 0 ; i < sortedKeys.length ; i += 1) {
var key = sortedKeys[i];
canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack);
}
stack.pop();
replacementStack.pop();
} else {
canonicalizedObj = obj;
}
return canonicalizedObj;
}
return {
Diff: Diff, Diff: Diff,
diffChars: function(oldStr, newStr, callback) { return CharDiff.diff(oldStr, newStr, callback); }, diffChars: function (oldStr, newStr, callback) {
diffWords: function(oldStr, newStr, callback) { return WordDiff.diff(oldStr, newStr, callback); }, return CharDiff.diff(oldStr, newStr, callback);
diffWordsWithSpace: function(oldStr, newStr, callback) { return WordWithSpaceDiff.diff(oldStr, newStr, callback); }, },
diffLines: function(oldStr, newStr, callback) { return LineDiff.diff(oldStr, newStr, callback); }, diffWords: function (oldStr, newStr, callback) {
diffTrimmedLines: function(oldStr, newStr, callback) { return TrimmedLineDiff.diff(oldStr, newStr, callback); }, return WordDiff.diff(oldStr, newStr, callback);
},
diffWordsWithSpace: function (oldStr, newStr, callback) {
return WordWithSpaceDiff.diff(oldStr, newStr, callback);
},
diffLines: function (oldStr, newStr, callback) {
return LineDiff.diff(oldStr, newStr, callback);
},
diffTrimmedLines: function (oldStr, newStr, callback) {
return TrimmedLineDiff.diff(oldStr, newStr, callback);
},
diffSentences: function(oldStr, newStr, callback) { return SentenceDiff.diff(oldStr, newStr, callback); }, diffSentences: function (oldStr, newStr, callback) {
return SentenceDiff.diff(oldStr, newStr, callback);
},
diffCss: function(oldStr, newStr, callback) { return CssDiff.diff(oldStr, newStr, callback); }, diffCss: function (oldStr, newStr, callback) {
diffJson: function(oldObj, newObj, callback) { return CssDiff.diff(oldStr, newStr, callback);
},
diffJson: function (oldObj, newObj, callback) {
return JsonDiff.diff( return JsonDiff.diff(
typeof oldObj === 'string' ? oldObj : JSON.stringify(canonicalize(oldObj), undefined, ' '), typeof oldObj === 'string' ? oldObj : JSON.stringify(canonicalize(oldObj), undefined, ' '),
typeof newObj === 'string' ? newObj : JSON.stringify(canonicalize(newObj), undefined, ' '), typeof newObj === 'string' ? newObj : JSON.stringify(canonicalize(newObj), undefined, ' '),
@ -372,30 +419,34 @@
); );
}, },
createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { createTwoFilesPatch: function (oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader) {
var ret = []; var ret = [];
ret.push('Index: ' + fileName); if (oldFileName == newFileName) {
ret.push('==================================================================='); ret.push('Index: ' + oldFileName);
ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
var diff = LineDiff.diff(oldStr, newStr);
if (!diff[diff.length-1].value) {
diff.pop(); // Remove trailing newline add
} }
ret.push('===================================================================');
ret.push('--- ' + oldFileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
ret.push('+++ ' + newFileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
var diff = PatchDiff.diff(oldStr, newStr);
diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier
// Formats a given set of lines for printing as context lines in a patch
function contextLines(lines) { function contextLines(lines) {
return map(lines, function(entry) { return ' ' + entry; }); return map(lines, function (entry) {
return ' ' + entry;
});
} }
// Outputs the no newline at end of file warning if needed
function eofNL(curRange, i, current) { function eofNL(curRange, i, current) {
var last = diff[diff.length-2], var last = diff[diff.length - 2],
isLast = i === diff.length-2, isLast = i === diff.length - 2,
isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed); isLastOfType = i === diff.length - 3 && current.added !== last.added;
// Figure out if this is the last line for the given file and missing NL // Figure out if this is the last line for the given file and missing NL
if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { if (!(/\n$/.test(current.value)) && (isLast || isLastOfType)) {
curRange.push('\\ No newline at end of file'); curRange.push('\\ No newline at end of file');
} }
} }
@ -408,8 +459,9 @@
current.lines = lines; current.lines = lines;
if (current.added || current.removed) { if (current.added || current.removed) {
// If we have previous context, start with that
if (!oldRangeStart) { if (!oldRangeStart) {
var prev = diff[i-1]; var prev = diff[i - 1];
oldRangeStart = oldLine; oldRangeStart = oldLine;
newRangeStart = newLine; newRangeStart = newLine;
@ -419,26 +471,32 @@
newRangeStart -= curRange.length; newRangeStart -= curRange.length;
} }
} }
curRange.push.apply(curRange, map(lines, function(entry) { return (current.added?'+':'-') + entry; }));
// Output our changes
curRange.push.apply(curRange, map(lines, function (entry) {
return (current.added ? '+' : '-') + entry;
}));
eofNL(curRange, i, current); eofNL(curRange, i, current);
// Track the updated file position
if (current.added) { if (current.added) {
newLine += lines.length; newLine += lines.length;
} else { } else {
oldLine += lines.length; oldLine += lines.length;
} }
} else { } else {
// Identical context lines. Track line changes
if (oldRangeStart) { if (oldRangeStart) {
// Close out any changes that have been output (or join overlapping) // Close out any changes that have been output (or join overlapping)
if (lines.length <= 8 && i < diff.length-2) { if (lines.length <= 8 && i < diff.length - 2) {
// Overlapping // Overlapping
curRange.push.apply(curRange, contextLines(lines)); curRange.push.apply(curRange, contextLines(lines));
} else { } else {
// end the range and output // end the range and output
var contextSize = Math.min(lines.length, 4); var contextSize = Math.min(lines.length, 4);
ret.push( ret.push(
'@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize) '@@ -' + oldRangeStart + ',' + (oldLine - oldRangeStart + contextSize)
+ ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize) + ' +' + newRangeStart + ',' + (newLine - newRangeStart + contextSize)
+ ' @@'); + ' @@');
ret.push.apply(ret, curRange); ret.push.apply(ret, curRange);
ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
@ -446,7 +504,9 @@
eofNL(ret, i, current); eofNL(ret, i, current);
} }
oldRangeStart = 0; newRangeStart = 0; curRange = []; oldRangeStart = 0;
newRangeStart = 0;
curRange = [];
} }
} }
oldLine += lines.length; oldLine += lines.length;
@ -457,68 +517,76 @@
return ret.join('\n') + '\n'; return ret.join('\n') + '\n';
}, },
applyPatch: function(oldStr, uniDiff) { createPatch: function (fileName, oldStr, newStr, oldHeader, newHeader) {
var diffstr = uniDiff.split('\n'); return JsDiff.createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader);
var diff = []; },
var i = 0,
applyPatch: function (oldStr, uniDiff) {
var diffstr = uniDiff.split('\n'),
hunks = [],
i = 0,
remEOFNL = false, remEOFNL = false,
addEOFNL = false; addEOFNL = false;
// Skip to the first change chunk // Skip to the first change hunk
while (i < diffstr.length && !/^@@/.test(diffstr[i])) { while (i < diffstr.length && !(/^@@/.test(diffstr[i]))) {
i++; i++;
} }
// Parse the unified diff
for (; i < diffstr.length; i++) { for (; i < diffstr.length; i++) {
if (diffstr[i][0] === '@') { if (diffstr[i][0] === '@') {
var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/); var chnukHeader = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
diff.unshift({ hunks.unshift({
start:meh[3], start: chnukHeader[3],
oldlength:meh[2], oldlength: +chnukHeader[2],
oldlines:[], removed: [],
newlength:meh[4], newlength: chnukHeader[4],
newlines:[] added: []
}); });
} else if (diffstr[i][0] === '+') { } else if (diffstr[i][0] === '+') {
diff[0].newlines.push(diffstr[i].substr(1)); hunks[0].added.push(diffstr[i].substr(1));
} else if (diffstr[i][0] === '-') { } else if (diffstr[i][0] === '-') {
diff[0].oldlines.push(diffstr[i].substr(1)); hunks[0].removed.push(diffstr[i].substr(1));
} else if (diffstr[i][0] === ' ') { } else if (diffstr[i][0] === ' ') {
diff[0].newlines.push(diffstr[i].substr(1)); hunks[0].added.push(diffstr[i].substr(1));
diff[0].oldlines.push(diffstr[i].substr(1)); hunks[0].removed.push(diffstr[i].substr(1));
} else if (diffstr[i][0] === '\\') { } else if (diffstr[i][0] === '\\') {
if (diffstr[i-1][0] === '+') { if (diffstr[i - 1][0] === '+') {
remEOFNL = true; remEOFNL = true;
} else if (diffstr[i-1][0] === '-') { } else if (diffstr[i - 1][0] === '-') {
addEOFNL = true; addEOFNL = true;
} }
} }
} }
var str = oldStr.split('\n'); // Apply the diff to the input
for (var i = diff.length - 1; i >= 0; i--) { var lines = oldStr.split('\n');
var d = diff[i]; for (i = hunks.length - 1; i >= 0; i--) {
for (var j = 0; j < d.oldlength; j++) { var hunk = hunks[i];
if (str[d.start-1+j] !== d.oldlines[j]) { // Sanity check the input string. Bail if we don't match.
for (var j = 0; j < hunk.oldlength; j++) {
if (lines[hunk.start - 1 + j] !== hunk.removed[j]) {
return false; return false;
} }
} }
Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines)); Array.prototype.splice.apply(lines, [hunk.start - 1, hunk.oldlength].concat(hunk.added));
} }
// Handle EOFNL insertion/removal
if (remEOFNL) { if (remEOFNL) {
while (!str[str.length-1]) { while (!lines[lines.length - 1]) {
str.pop(); lines.pop();
} }
} else if (addEOFNL) { } else if (addEOFNL) {
str.push(''); lines.push('');
} }
return str.join('\n'); return lines.join('\n');
}, },
convertChangesToXML: function(changes){ convertChangesToXML: function (changes) {
var ret = []; var ret = [];
for ( var i = 0; i < changes.length; i++) { for (var i = 0; i < changes.length; i++) {
var change = changes[i]; var change = changes[i];
if (change.added) { if (change.added) {
ret.push('<ins>'); ret.push('<ins>');
@ -538,28 +606,38 @@
}, },
// See: http://code.google.com/p/google-diff-match-patch/wiki/API // See: http://code.google.com/p/google-diff-match-patch/wiki/API
convertChangesToDMP: function(changes){ convertChangesToDMP: function (changes) {
var ret = [], change; var ret = [],
for ( var i = 0; i < changes.length; i++) { change,
operation;
for (var i = 0; i < changes.length; i++) {
change = changes[i]; change = changes[i];
ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]); if (change.added) {
operation = 1;
} else if (change.removed) {
operation = -1;
} else {
operation = 0;
}
ret.push([operation, change.value]);
} }
return ret; return ret;
}, },
canonicalize: canonicalize canonicalize: canonicalize
}; };
})();
/*istanbul ignore next */ /*istanbul ignore next */
/*global module */
if (typeof module !== 'undefined' && module.exports) { if (typeof module !== 'undefined' && module.exports) {
module.exports = JsDiff; module.exports = JsDiff;
} } else if (typeof define === 'function' && define.amd) {
else if (typeof define === 'function' && define.amd) {
/*global define */ /*global define */
define([], function() { return JsDiff; }); define([], function () {
} return JsDiff;
else if (typeof global.JsDiff === 'undefined') { });
} else if (typeof global.JsDiff === 'undefined') {
global.JsDiff = JsDiff; global.JsDiff = JsDiff;
} }
})(this); }(this));

67
package.json Normal file
View file

@ -0,0 +1,67 @@
{
"name": "diff2html",
"version": "0.2.4",
"homepage": "https://www.github.com/rtfpessoa/diff2html",
"description": "Fast Diff to colorized HTML",
"keywords": [
"git",
"diff",
"pretty",
"side",
"line",
"side-by-side",
"line-by-line",
"character",
"highlight",
"pretty",
"color",
"html",
"diff2html",
"difftohtml",
"colorized"
],
"author": {
"name": "Rodrigo Fernandes",
"email": "rtfrodrigo@gmail.com"
},
"repository": {
"type": "git",
"url": "https://www.github.com/rtfpessoa/diff2html.git"
},
"bugs": {
"url": "https://www.github.com/rtfpessoa/diff2html/issues"
},
"engines": {
"node": ">=0.10"
},
"preferGlobal": "true",
"scripts": {
"test": ""
},
"bin": {
"diff2html-lib": "./bin/diff2html"
},
"main": "./src/diff2html.js",
"dependencies": {
"diff": "1.4.0"
},
"devDependencies": {},
"license": "MIT",
"files": [
"bin",
"lib",
"src"
]
}

View file

@ -8,7 +8,9 @@
(function (global, undefined) { (function (global, undefined) {
// dirty hack for browser compatibility // dirty hack for browser compatibility
var jsDiff = (typeof JsDiff !== "undefined" && JsDiff) || require("../lib/diff.js"); var jsDiff = (typeof JsDiff !== "undefined" && JsDiff) ||
require("diff") ||
require("../lib/diff.js");
var utils = require("./utils.js").Utils; var utils = require("./utils.js").Utils;
function PrinterUtils() { function PrinterUtils() {