Merge pull request #18 from rtfpessoa/webpack-for-the-browser

Webpack for the browser
This commit is contained in:
Rodrigo Fernandes 2015-09-06 17:07:39 +01:00
commit ca8cfe0528
17 changed files with 1913 additions and 2494 deletions

View file

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

View file

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

49
config.jscs.json Normal file
View file

@ -0,0 +1,49 @@
{
"disallowKeywords": [
"with"
],
"disallowKeywordsOnNewLine": [
"else"
],
"disallowMixedSpacesAndTabs": true,
"disallowMultipleVarDecl": "exceptUndefined",
"disallowNewlineBeforeBlockStatements": true,
"disallowQuotedKeysInObjects": true,
"disallowSpaceAfterObjectKeys": true,
"disallowSpaceAfterPrefixUnaryOperators": true,
"disallowSpacesInFunction": {
"beforeOpeningRoundBrace": true
},
"disallowSpacesInsideParentheses": true,
"disallowTrailingWhitespace": true,
"maximumLineLength": 120,
"requireCamelCaseOrUpperCaseIdentifiers": true,
"requireCapitalizedComments": true,
"requireCapitalizedConstructors": true,
"requireCurlyBraces": true,
"requireSpaceAfterKeywords": [
"if",
"else",
"for",
"while",
"do",
"switch",
"case",
"return",
"try",
"catch",
"typeof"
],
"requireSpaceAfterLineComment": true,
"requireSpaceAfterBinaryOperators": true,
"requireSpaceBeforeBinaryOperators": true,
"requireSpaceBeforeBlockStatements": true,
"requireSpaceBeforeObjectValues": true,
"requireSpacesInFunction": {
"beforeOpeningCurlyBrace": true
},
"requireTrailingComma": null,
"validateIndentation": 2,
"validateLineBreaks": "LF",
"validateQuoteMarks": "'"
}

1564
dist/diff2html.js vendored

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -1,643 +0,0 @@
/* See LICENSE file for terms of use */
/*
* Text diff implementation.
*
* This library supports the following APIS:
* JsDiff.diffChars: Character by character diff
* JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
* JsDiff.diffLines: Line based diff
*
* JsDiff.diffCss: Diff targeted at CSS content
*
* These methods are based on the implementation proposed in
* "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
* http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
*/
(function (global, undefined) {
var objectPrototypeToString = Object.prototype.toString;
/*istanbul ignore next*/
function map(arr, mapper, that) {
if (Array.prototype.map) {
return Array.prototype.map.call(arr, mapper, that);
}
var other = new Array(arr.length);
for (var i = 0, n = arr.length; i < n; i++) {
other[i] = mapper.call(that, arr[i], i, arr);
}
return other;
}
function clonePath(path) {
return {newPos: path.newPos, components: path.components.slice(0)};
}
function removeEmpty(array) {
var ret = [];
for (var i = 0; i < array.length; i++) {
if (array[i]) {
ret.push(array[i]);
}
}
return ret;
}
function escapeHTML(s) {
var n = s;
n = n.replace(/&/g, '&amp;');
n = n.replace(/</g, '&lt;');
n = n.replace(/>/g, '&gt;');
n = n.replace(/"/g, '&quot;');
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) {
var componentPos = 0,
componentLen = components.length,
newPos = 0,
oldPos = 0;
for (; componentPos < componentLen; componentPos++) {
var component = components[componentPos];
if (!component.removed) {
if (!component.added && useLongestToken) {
var value = newString.slice(newPos, newPos + component.count);
value = map(value, function (value, i) {
var oldValue = oldString[oldPos + i];
return oldValue.length > value.length ? oldValue : value;
});
component.value = value.join('');
} else {
component.value = newString.slice(newPos, newPos + component.count).join('');
}
newPos += component.count;
// Common case
if (!component.added) {
oldPos += component.count;
}
} else {
component.value = oldString.slice(oldPos, oldPos + component.count).join('');
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;
}
function Diff(ignoreWhitespace) {
this.ignoreWhitespace = ignoreWhitespace;
}
Diff.prototype = {
diff: function (oldString, newString, callback) {
var self = this;
function done(value) {
if (callback) {
setTimeout(function () {
callback(undefined, value);
}, 0);
return true;
} else {
return value;
}
}
// Handle the identity case (this is due to unrolling editLength == 0
if (newString === oldString) {
return done([{value: newString}]);
}
if (!newString) {
return done([{value: oldString, removed: true}]);
}
if (!oldString) {
return done([{value: newString, added: true}]);
}
newString = this.tokenize(newString);
oldString = this.tokenize(oldString);
var newLen = newString.length, oldLen = oldString.length;
var editLength = 1;
var maxEditLength = newLen + oldLen;
var bestPath = [{newPos: -1, components: []}];
// Seed editLength = 0, i.e. the content starts with the same values
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
// Identity per the equality and tokenizer
return done([{value: newString.join('')}]);
}
// Main worker method. checks all permutations of a given edit length for acceptance.
function execEditLength() {
for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
var basePath;
var addPath = bestPath[diagonalPath - 1],
removePath = bestPath[diagonalPath + 1],
oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
if (addPath) {
// No one else is going to attempt to use this value, clear it
bestPath[diagonalPath - 1] = undefined;
}
var canAdd = addPath && addPath.newPos + 1 < newLen,
canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
if (!canAdd && !canRemove) {
// If this path is a terminal then prune
bestPath[diagonalPath] = undefined;
continue;
}
// Select the diagonal that we want to branch from. We select the prior
// path whose position in the new string is the farthest from the origin
// and does not pass the bounds of the diff graph
if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
basePath = clonePath(removePath);
self.pushComponent(basePath.components, undefined, true);
} else {
basePath = addPath; // No need to clone, we've pulled it from the list
basePath.newPos++;
self.pushComponent(basePath.components, true, undefined);
}
oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath);
// If we have hit the end of both strings, then we are done
if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
return done(buildValues(basePath.components, newString, oldString, self.useLongestToken));
} else {
// Otherwise track this path as a potential candidate and continue.
bestPath[diagonalPath] = basePath;
}
}
editLength++;
}
// 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
// is produced.
if (callback) {
(function exec() {
setTimeout(function () {
// This should not happen, but we want to be safe.
/*istanbul ignore next */
if (editLength > maxEditLength) {
return callback();
}
if (!execEditLength()) {
exec();
}
}, 0);
}());
} else {
while (editLength <= maxEditLength) {
var ret = execEditLength();
if (ret) {
return ret;
}
}
}
},
pushComponent: function (components, added, removed) {
var last = components[components.length - 1];
if (last && last.added === added && last.removed === removed) {
// We need to clone here as the component clone operation is just
// as shallow array clone
components[components.length - 1] = {count: last.count + 1, added: added, removed: removed};
} else {
components.push({count: 1, added: added, removed: removed});
}
},
extractCommon: function (basePath, newString, oldString, diagonalPath) {
var newLen = newString.length,
oldLen = oldString.length,
newPos = basePath.newPos,
oldPos = newPos - diagonalPath,
commonCount = 0;
while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
newPos++;
oldPos++;
commonCount++;
}
if (commonCount) {
basePath.components.push({count: commonCount});
}
basePath.newPos = newPos;
return oldPos;
},
equals: function (left, right) {
var reWhitespace = /\S/;
return left === right || (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right));
},
tokenize: function (value) {
return value.split('');
}
};
var CharDiff = new Diff();
var WordDiff = new Diff(true);
var WordWithSpaceDiff = new Diff();
WordDiff.tokenize = WordWithSpaceDiff.tokenize = function (value) {
return removeEmpty(value.split(/(\s+|\b)/));
};
var CssDiff = new Diff(true);
CssDiff.tokenize = function (value) {
return removeEmpty(value.split(/([{}:;,]|\s+)/));
};
var LineDiff = new Diff();
var TrimmedLineDiff = new Diff();
TrimmedLineDiff.ignoreTrim = true;
LineDiff.tokenize = TrimmedLineDiff.tokenize = function (value) {
var retLines = [],
lines = value.split(/^/m);
for (var i = 0; i < lines.length; i++) {
var line = lines[i],
lastLine = lines[i - 1],
lastLineLastChar = lastLine && lastLine[lastLine.length - 1];
// Merge lines that may contain windows new lines
if (line === '\n' && lastLineLastChar === '\r') {
retLines[retLines.length - 1] = retLines[retLines.length - 1].slice(0, -1) + '\r\n';
} else {
if (this.ignoreTrim) {
line = line.trim();
// add a newline unless this is the last line.
if (i < lines.length - 1) {
line += '\n';
}
}
retLines.push(line);
}
}
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();
SentenceDiff.tokenize = function (value) {
return removeEmpty(value.split(/(\S.+?[.!?])(?=\s+|$)/));
};
var JsonDiff = new Diff();
// Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
JsonDiff.useLongestToken = true;
JsonDiff.tokenize = LineDiff.tokenize;
JsonDiff.equals = function (left, right) {
return LineDiff.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
};
var JsDiff = {
Diff: Diff,
diffChars: function (oldStr, newStr, callback) {
return CharDiff.diff(oldStr, newStr, callback);
},
diffWords: function (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);
},
diffCss: function (oldStr, newStr, callback) {
return CssDiff.diff(oldStr, newStr, callback);
},
diffJson: function (oldObj, newObj, callback) {
return JsonDiff.diff(
typeof oldObj === 'string' ? oldObj : JSON.stringify(canonicalize(oldObj), undefined, ' '),
typeof newObj === 'string' ? newObj : JSON.stringify(canonicalize(newObj), undefined, ' '),
callback
);
},
createTwoFilesPatch: function (oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader) {
var ret = [];
if (oldFileName == newFileName) {
ret.push('Index: ' + oldFileName);
}
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
// Formats a given set of lines for printing as context lines in a patch
function contextLines(lines) {
return map(lines, function (entry) {
return ' ' + entry;
});
}
// Outputs the no newline at end of file warning if needed
function eofNL(curRange, i, current) {
var last = diff[diff.length - 2],
isLast = i === diff.length - 2,
isLastOfType = i === diff.length - 3 && current.added !== last.added;
// Figure out if this is the last line for the given file and missing NL
if (!(/\n$/.test(current.value)) && (isLast || isLastOfType)) {
curRange.push('\\ No newline at end of file');
}
}
var oldRangeStart = 0, newRangeStart = 0, curRange = [],
oldLine = 1, newLine = 1;
for (var i = 0; i < diff.length; i++) {
var current = diff[i],
lines = current.lines || current.value.replace(/\n$/, '').split('\n');
current.lines = lines;
if (current.added || current.removed) {
// If we have previous context, start with that
if (!oldRangeStart) {
var prev = diff[i - 1];
oldRangeStart = oldLine;
newRangeStart = newLine;
if (prev) {
curRange = contextLines(prev.lines.slice(-4));
oldRangeStart -= curRange.length;
newRangeStart -= curRange.length;
}
}
// Output our changes
curRange.push.apply(curRange, map(lines, function (entry) {
return (current.added ? '+' : '-') + entry;
}));
eofNL(curRange, i, current);
// Track the updated file position
if (current.added) {
newLine += lines.length;
} else {
oldLine += lines.length;
}
} else {
// Identical context lines. Track line changes
if (oldRangeStart) {
// Close out any changes that have been output (or join overlapping)
if (lines.length <= 8 && i < diff.length - 2) {
// Overlapping
curRange.push.apply(curRange, contextLines(lines));
} else {
// end the range and output
var contextSize = Math.min(lines.length, 4);
ret.push(
'@@ -' + oldRangeStart + ',' + (oldLine - oldRangeStart + contextSize)
+ ' +' + newRangeStart + ',' + (newLine - newRangeStart + contextSize)
+ ' @@');
ret.push.apply(ret, curRange);
ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
if (lines.length <= 4) {
eofNL(ret, i, current);
}
oldRangeStart = 0;
newRangeStart = 0;
curRange = [];
}
}
oldLine += lines.length;
newLine += lines.length;
}
}
return ret.join('\n') + '\n';
},
createPatch: function (fileName, oldStr, newStr, oldHeader, newHeader) {
return JsDiff.createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader);
},
applyPatch: function (oldStr, uniDiff) {
var diffstr = uniDiff.split('\n'),
hunks = [],
i = 0,
remEOFNL = false,
addEOFNL = false;
// Skip to the first change hunk
while (i < diffstr.length && !(/^@@/.test(diffstr[i]))) {
i++;
}
// Parse the unified diff
for (; i < diffstr.length; i++) {
if (diffstr[i][0] === '@') {
var chnukHeader = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
hunks.unshift({
start: chnukHeader[3],
oldlength: +chnukHeader[2],
removed: [],
newlength: chnukHeader[4],
added: []
});
} else if (diffstr[i][0] === '+') {
hunks[0].added.push(diffstr[i].substr(1));
} else if (diffstr[i][0] === '-') {
hunks[0].removed.push(diffstr[i].substr(1));
} else if (diffstr[i][0] === ' ') {
hunks[0].added.push(diffstr[i].substr(1));
hunks[0].removed.push(diffstr[i].substr(1));
} else if (diffstr[i][0] === '\\') {
if (diffstr[i - 1][0] === '+') {
remEOFNL = true;
} else if (diffstr[i - 1][0] === '-') {
addEOFNL = true;
}
}
}
// Apply the diff to the input
var lines = oldStr.split('\n');
for (i = hunks.length - 1; i >= 0; i--) {
var hunk = hunks[i];
// 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;
}
}
Array.prototype.splice.apply(lines, [hunk.start - 1, hunk.oldlength].concat(hunk.added));
}
// Handle EOFNL insertion/removal
if (remEOFNL) {
while (!lines[lines.length - 1]) {
lines.pop();
}
} else if (addEOFNL) {
lines.push('');
}
return lines.join('\n');
},
convertChangesToXML: function (changes) {
var ret = [];
for (var i = 0; i < changes.length; i++) {
var change = changes[i];
if (change.added) {
ret.push('<ins>');
} else if (change.removed) {
ret.push('<del>');
}
ret.push(escapeHTML(change.value));
if (change.added) {
ret.push('</ins>');
} else if (change.removed) {
ret.push('</del>');
}
}
return ret.join('');
},
// See: http://code.google.com/p/google-diff-match-patch/wiki/API
convertChangesToDMP: function (changes) {
var ret = [],
change,
operation;
for (var i = 0; i < changes.length; i++) {
change = changes[i];
if (change.added) {
operation = 1;
} else if (change.removed) {
operation = -1;
} else {
operation = 0;
}
ret.push([operation, change.value]);
}
return ret;
},
canonicalize: canonicalize
};
/*istanbul ignore next */
/*global module */
if (typeof module !== 'undefined' && module.exports) {
module.exports = JsDiff;
} else if (typeof define === 'function' && define.amd) {
/*global define */
define([], function () {
return JsDiff;
});
} else if (typeof global.JsDiff === 'undefined') {
global.JsDiff = JsDiff;
}
}(this));

View file

@ -1,20 +0,0 @@
/*
* Hack to allow nodejs require("package/file") in the browser
* How?
* Since every require is used as an object:
* `require("./utils.js").Utils` // (notice the `.Utils`)
*
* We can say that when there is no require method
* we use the global object in which the `Utils`
* object was already injected.
*/
var $globalHolder = (typeof module !== 'undefined' && module.exports) ||
(typeof exports !== 'undefined' && exports) ||
(typeof window !== 'undefined' && window) ||
(typeof self !== 'undefined' && self) ||
(typeof this !== 'undefined' && this) ||
Function('return this')();
function require() {
return $globalHolder;
}

View file

@ -1,6 +1,6 @@
{ {
"name": "diff2html", "name": "diff2html",
"version": "0.2.6-1", "version": "1.0.0",
"homepage": "http://rtfpessoa.github.io/diff2html/", "homepage": "http://rtfpessoa.github.io/diff2html/",
"description": "Fast Diff to colorized HTML", "description": "Fast Diff to colorized HTML",
"keywords": [ "keywords": [
@ -20,48 +20,31 @@
"difftohtml", "difftohtml",
"colorized" "colorized"
], ],
"author": { "author": {
"name": "Rodrigo Fernandes", "name": "Rodrigo Fernandes",
"email": "rtfrodrigo@gmail.com" "email": "rtfrodrigo@gmail.com"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://www.github.com/rtfpessoa/diff2html.git" "url": "https://www.github.com/rtfpessoa/diff2html.git"
}, },
"bugs": { "bugs": {
"url": "https://www.github.com/rtfpessoa/diff2html/issues" "url": "https://www.github.com/rtfpessoa/diff2html/issues"
}, },
"engines": { "engines": {
"node": ">=0.10" "node": ">=0.10"
}, },
"preferGlobal": "true", "preferGlobal": "true",
"scripts": { "scripts": {
"test": "" "test": ""
}, },
"bin": {
"diff2html-lib": "./bin/diff2html"
},
"main": "./src/diff2html.js", "main": "./src/diff2html.js",
"dependencies": { "dependencies": {
"diff": "1.4.0" "diff": "1.4.0"
}, },
"devDependencies": {}, "devDependencies": {},
"license": "MIT", "license": "MIT",
"files": [ "files": [
"bin",
"lib",
"src" "src"
] ]
} }

View file

@ -1,7 +1,8 @@
#!/bin/bash #!/bin/bash
# #
# Diff2Html release script # diff2html release script
# by rtfpessoa
# #
OUTPUT_DIR=dist OUTPUT_DIR=dist
@ -10,24 +11,19 @@ OUTPUT_MIN_JS_FILE=${OUTPUT_DIR}/diff2html.min.js
OUTPUT_CSS_FILE=${OUTPUT_DIR}/diff2html.css OUTPUT_CSS_FILE=${OUTPUT_DIR}/diff2html.css
OUTPUT_MIN_CSS_FILE=${OUTPUT_DIR}/diff2html.min.css OUTPUT_MIN_CSS_FILE=${OUTPUT_DIR}/diff2html.min.css
echo "Creating Diff2Html release ..." echo "Creating diff2html release ..."
echo "Cleaning previous versions ..." echo "Cleaning previous versions ..."
rm -rf ${OUTPUT_DIR} rm -rf ${OUTPUT_DIR}
mkdir -p ${OUTPUT_DIR} mkdir -p ${OUTPUT_DIR}
echo "Preparing dependencies ..."
rm -rf node_modules
npm install
echo "Generating js aggregation file in ${OUTPUT_JS_FILE}" echo "Generating js aggregation file in ${OUTPUT_JS_FILE}"
echo "// Diff2Html minifier version (automatically generated)" > ${OUTPUT_JS_FILE} webpack ./src/diff2html.js ${OUTPUT_JS_FILE}
cat lib/fakeRequire.js >> ${OUTPUT_JS_FILE}
cat lib/diff.js >> ${OUTPUT_JS_FILE}
cat src/utils.js >> ${OUTPUT_JS_FILE}
cat src/diff-parser.js >> ${OUTPUT_JS_FILE}
cat src/printer-utils.js >> ${OUTPUT_JS_FILE}
cat src/side-by-side-printer.js >> ${OUTPUT_JS_FILE}
cat src/line-by-line-printer.js >> ${OUTPUT_JS_FILE}
cat src/html-printer.js >> ${OUTPUT_JS_FILE}
cat src/diff2html.js >> ${OUTPUT_JS_FILE}
echo "Minifying ${OUTPUT_JS_FILE} to ${OUTPUT_MIN_JS_FILE}" echo "Minifying ${OUTPUT_JS_FILE} to ${OUTPUT_MIN_JS_FILE}"
@ -41,4 +37,4 @@ echo "Minifying ${OUTPUT_CSS_FILE} to ${OUTPUT_MIN_CSS_FILE}"
lessc -x ${OUTPUT_CSS_FILE} ${OUTPUT_MIN_CSS_FILE} lessc -x ${OUTPUT_CSS_FILE} ${OUTPUT_MIN_CSS_FILE}
echo "Diff2Html release created successfully!" echo "diff2html release created successfully!"

View file

@ -11,19 +11,6 @@
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.6/styles/github.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.6/styles/github.min.css">
<!--
<link rel="stylesheet" type="text/css" href="../css/diff2html.css">
<script type="text/javascript" src="../lib/diff.js"></script>
<script type="text/javascript" src="../lib/fakeRequire.js"></script>
<script type="text/javascript" src="../src/utils.js"></script>
<script type="text/javascript" src="../src/diff-parser.js"></script>
<script type="text/javascript" src="../src/printer-utils.js"></script>
<script type="text/javascript" src="../src/side-by-side-printer.js"></script>
<script type="text/javascript" src="../src/line-by-line-printer.js"></script>
<script type="text/javascript" src="../src/html-printer.js"></script>
<script type="text/javascript" src="../src/diff2html.js"></script>
-->
<!-- --> <!-- -->
<link rel="stylesheet" type="text/css" href="../dist/diff2html.min.css"> <link rel="stylesheet" type="text/css" href="../dist/diff2html.min.css">
<script type="text/javascript" src="../dist/diff2html.min.js"></script> <script type="text/javascript" src="../dist/diff2html.min.js"></script>
@ -215,7 +202,17 @@
"+var text = 'diff --git a/components/app/app.html b/components/app/app.html\\nindex ecb7a95..027bd9b 100644\\n--- a/components/app/app.html\\n+++ b/components/app/app.html\\n@@ -52,0 +53,3 @@\\n+\\n+\\n+\\n@@ -56,0 +60,3 @@\\n+\\n+\\n+\\n'\n" + "+var text = 'diff --git a/components/app/app.html b/components/app/app.html\\nindex ecb7a95..027bd9b 100644\\n--- a/components/app/app.html\\n+++ b/components/app/app.html\\n@@ -52,0 +53,3 @@\\n+\\n+\\n+\\n@@ -56,0 +60,3 @@\\n+\\n+\\n+\\n'\n" +
'+var patchLineList = [ false, false, false, false ];\n' + '+var patchLineList = [ false, false, false, false ];\n' +
'+\n' + '+\n' +
'+console.log(parser.parsePatchDiffResult(text, patchLineList));\n'; '+console.log(parser.parsePatchDiffResult(text, patchLineList));\n' +
"diff --git a/a.xml b/b.xml\n" +
"index e54317e..82a9a56 100644\n" +
"--- a/a.xml\n" +
"+++ b/b.xml\n" +
"@@ -242,4 +242,6 @@ need to create a new job for native server java api and move these tests to a ne\n" +
" </packages>\n" +
" </test>\n" +
" -->\n" +
"+\n" +
"+\n";
document.addEventListener("DOMContentLoaded", function() { document.addEventListener("DOMContentLoaded", function() {
// parse the diff to json // parse the diff to json

View file

@ -7,13 +7,13 @@
(function(ctx, undefined) { (function(ctx, undefined) {
var utils = require("./utils.js").Utils; var utils = require('./utils.js').Utils;
var LINE_TYPE = { var LINE_TYPE = {
INSERTS: "d2h-ins", INSERTS: 'd2h-ins',
DELETES: "d2h-del", DELETES: 'd2h-del',
CONTEXT: "d2h-cntx", CONTEXT: 'd2h-cntx',
INFO: "d2h-info" INFO: 'd2h-info'
}; };
function DiffParser() { function DiffParser() {
@ -22,14 +22,14 @@
DiffParser.prototype.LINE_TYPE = LINE_TYPE; DiffParser.prototype.LINE_TYPE = LINE_TYPE;
DiffParser.prototype.generateDiffJson = function(diffInput) { DiffParser.prototype.generateDiffJson = function(diffInput) {
var files = [], var files = [];
currentFile = null, var currentFile = null;
currentBlock = null, var currentBlock = null;
oldLine = null, var oldLine = null;
newLine = null; var newLine = null;
var saveBlock = function() { var saveBlock = function() {
/* add previous block(if exists) before start a new file */ /* Add previous block(if exists) before start a new file */
if (currentBlock) { if (currentBlock) {
currentFile.blocks.push(currentBlock); currentFile.blocks.push(currentBlock);
currentBlock = null; currentBlock = null;
@ -38,7 +38,7 @@
var saveFile = function() { var saveFile = function() {
/* /*
* add previous file(if exists) before start a new one * Add previous file(if exists) before start a new one
* if it has name (to avoid binary files errors) * if it has name (to avoid binary files errors)
*/ */
if (currentFile && currentFile.newName) { if (currentFile && currentFile.newName) {
@ -51,7 +51,7 @@
saveBlock(); saveBlock();
saveFile(); saveFile();
/* create file structure */ /* Create file structure */
currentFile = {}; currentFile = {};
currentFile.blocks = []; currentFile.blocks = [];
currentFile.deletedLines = 0; currentFile.deletedLines = 0;
@ -75,7 +75,7 @@
oldLine = values[1]; oldLine = values[1];
newLine = values[2]; newLine = values[2];
/* create block metadata */ /* Create block metadata */
currentBlock = {}; currentBlock = {};
currentBlock.lines = []; currentBlock.lines = [];
currentBlock.oldStartLine = oldLine; currentBlock.oldStartLine = oldLine;
@ -87,8 +87,11 @@
var currentLine = {}; var currentLine = {};
currentLine.content = line; currentLine.content = line;
/* fill the line data */ var newLinePrefixes = !currentFile.isCombined ? ['+'] : ['+', ' +'];
if (utils.startsWith(line, "+") || utils.startsWith(line, " +")) { var delLinePrefixes = !currentFile.isCombined ? ['-'] : ['-', ' -'];
/* Fill the line data */
if (utils.startsWith(line, newLinePrefixes)) {
currentFile.addedLines++; currentFile.addedLines++;
currentLine.type = LINE_TYPE.INSERTS; currentLine.type = LINE_TYPE.INSERTS;
@ -97,7 +100,7 @@
currentBlock.lines.push(currentLine); currentBlock.lines.push(currentLine);
} else if (utils.startsWith(line, "-") || utils.startsWith(line, " -")) { } else if (utils.startsWith(line, delLinePrefixes)) {
currentFile.deletedLines++; currentFile.deletedLines++;
currentLine.type = LINE_TYPE.DELETES; currentLine.type = LINE_TYPE.DELETES;
@ -115,13 +118,12 @@
} }
}; };
var diffLines = diffInput.split("\n"); var diffLines = diffInput.split('\n');
diffLines.forEach(function(line) { diffLines.forEach(function(line) {
// Unmerged paths, and possibly other non-diffable files // Unmerged paths, and possibly other non-diffable files
// https://github.com/scottgonzalez/pretty-diff/issues/11 // https://github.com/scottgonzalez/pretty-diff/issues/11
// Also, remove some useless lines // Also, remove some useless lines
if (!line || utils.startsWith(line, "*")) { if (!line || utils.startsWith(line, '*')) {
//|| utils.startsWith(line, "new") || utils.startsWith(line, "index")
return; return;
} }
@ -148,7 +150,7 @@
var combinedDeletedFile = /^deleted file mode (\d{6}),(\d{6})/; var combinedDeletedFile = /^deleted file mode (\d{6}),(\d{6})/;
var values = []; var values = [];
if (utils.startsWith(line, "diff")) { if (utils.startsWith(line, 'diff')) {
startFile(); startFile();
} else if (currentFile && !currentFile.oldName && (values = /^--- a\/(\S+).*$/.exec(line))) { } else if (currentFile && !currentFile.oldName && (values = /^--- a\/(\S+).*$/.exec(line))) {
currentFile.oldName = values[1]; currentFile.oldName = values[1];
@ -156,7 +158,7 @@
} else if (currentFile && !currentFile.newName && (values = /^\+\+\+ [b]?\/(\S+).*$/.exec(line))) { } else if (currentFile && !currentFile.newName && (values = /^\+\+\+ [b]?\/(\S+).*$/.exec(line))) {
currentFile.newName = values[1]; currentFile.newName = values[1];
currentFile.language = getExtension(currentFile.newName, currentFile.language); currentFile.language = getExtension(currentFile.newName, currentFile.language);
} else if (currentFile && utils.startsWith(line, "@@")) { } else if (currentFile && utils.startsWith(line, '@@')) {
startBlock(line); startBlock(line);
} else if ((values = oldMode.exec(line))) { } else if ((values = oldMode.exec(line))) {
currentFile.oldMode = values[1]; currentFile.oldMode = values[1];
@ -208,17 +210,14 @@
}; };
function getExtension(filename, language) { function getExtension(filename, language) {
var nameSplit = filename.split("."); var nameSplit = filename.split('.');
if (nameSplit.length > 1) return nameSplit[nameSplit.length - 1]; if (nameSplit.length > 1) {
else return language; return nameSplit[nameSplit.length - 1];
} else {
return language;
}
} }
// expose this module module.exports['DiffParser'] = new DiffParser();
((typeof module !== 'undefined' && module.exports) ||
(typeof exports !== 'undefined' && exports) ||
(typeof window !== 'undefined' && window) ||
(typeof self !== 'undefined' && self) ||
(typeof $this !== 'undefined' && $this) ||
Function('return this')())["DiffParser"] = new DiffParser();
})(this); })(this);

View file

@ -7,8 +7,8 @@
(function(ctx, undefined) { (function(ctx, undefined) {
var diffParser = require("./diff-parser.js").DiffParser; var diffParser = require('./diff-parser.js').DiffParser;
var htmlPrinter = require("./html-printer.js").HtmlPrinter; var htmlPrinter = require('./html-printer.js').HtmlPrinter;
function Diff2Html() { function Diff2Html() {
} }
@ -64,12 +64,10 @@
return htmlPrinter.generateSideBySideJsonHtml(diffJson, configOrEmpty); return htmlPrinter.generateSideBySideJsonHtml(diffJson, configOrEmpty);
}; };
// expose this module var diffName = 'Diff2Html';
((typeof module !== 'undefined' && module.exports) || var diffObject = new Diff2Html();
(typeof exports !== 'undefined' && exports) || module.exports[diffName] = diffObject;
(typeof window !== 'undefined' && window) || // Expose diff2html in the browser
(typeof self !== 'undefined' && self) || global[diffName] = diffObject;
(typeof $this !== 'undefined' && $this) ||
Function('return this')())["Diff2Html"] = new Diff2Html();
})(this); })(this);

View file

@ -7,8 +7,8 @@
(function(ctx, undefined) { (function(ctx, undefined) {
var lineByLinePrinter = require("./line-by-line-printer.js").LineByLinePrinter; var lineByLinePrinter = require('./line-by-line-printer.js').LineByLinePrinter;
var sideBySidePrinter = require("./side-by-side-printer.js").SideBySidePrinter; var sideBySidePrinter = require('./side-by-side-printer.js').SideBySidePrinter;
function HtmlPrinter() { function HtmlPrinter() {
} }
@ -17,12 +17,6 @@
HtmlPrinter.prototype.generateSideBySideJsonHtml = sideBySidePrinter.generateSideBySideJsonHtml; HtmlPrinter.prototype.generateSideBySideJsonHtml = sideBySidePrinter.generateSideBySideJsonHtml;
// expose this module module.exports['HtmlPrinter'] = new HtmlPrinter();
((typeof module !== 'undefined' && module.exports) ||
(typeof exports !== 'undefined' && exports) ||
(typeof window !== 'undefined' && window) ||
(typeof self !== 'undefined' && self) ||
(typeof $this !== 'undefined' && $this) ||
Function('return this')())["HtmlPrinter"] = new HtmlPrinter();
})(this); })(this);

View file

@ -7,55 +7,60 @@
(function(ctx, undefined) { (function(ctx, undefined) {
var diffParser = require("./diff-parser.js").DiffParser; var diffParser = require('./diff-parser.js').DiffParser;
var printerUtils = require("./printer-utils.js").PrinterUtils; var printerUtils = require('./printer-utils.js').PrinterUtils;
var utils = require("./utils.js").Utils; var utils = require('./utils.js').Utils;
function LineByLinePrinter() { function LineByLinePrinter() {
} }
LineByLinePrinter.prototype.generateLineByLineJsonHtml = function(diffFiles, config) { LineByLinePrinter.prototype.generateLineByLineJsonHtml = function(diffFiles, config) {
return "<div class=\"d2h-wrapper\">\n" + return '<div class="d2h-wrapper">\n' +
diffFiles.map(function(file) { diffFiles.map(function(file) {
var diffs; var diffs;
if (file.blocks.length) diffs = generateFileHtml(file, config); if (file.blocks.length) {
else diffs = generateEmptyDiff(); diffs = generateFileHtml(file, config);
} else {
diffs = generateEmptyDiff();
}
return "<div class=\"d2h-file-wrapper\" data-lang=\"" + file.language + "\">\n" + return '<div class="d2h-file-wrapper" data-lang="' + file.language + '">\n' +
" <div class=\"d2h-file-header\">\n" + ' <div class="d2h-file-header">\n' +
" <div class=\"d2h-file-stats\">\n" + ' <div class="d2h-file-stats">\n' +
" <span class=\"d2h-lines-added\">+" + file.addedLines + "</span>\n" + ' <span class="d2h-lines-added">+' + file.addedLines + '</span>\n' +
" <span class=\"d2h-lines-deleted\">-" + file.deletedLines + "</span>\n" + ' <span class="d2h-lines-deleted">-' + file.deletedLines + '</span>\n' +
" </div>\n" + ' </div>\n' +
" <div class=\"d2h-file-name\">" + printerUtils.getDiffName(file) + "</div>\n" + ' <div class="d2h-file-name">' + printerUtils.getDiffName(file) + '</div>\n' +
" </div>\n" + ' </div>\n' +
" <div class=\"d2h-file-diff\">\n" + ' <div class="d2h-file-diff">\n' +
" <div class=\"d2h-code-wrapper\">\n" + ' <div class="d2h-code-wrapper">\n' +
" <table class=\"d2h-diff-table\">\n" + ' <table class="d2h-diff-table">\n' +
" <tbody class=\"d2h-diff-tbody\">\n" + ' <tbody class="d2h-diff-tbody">\n' +
" " + diffs + ' ' + diffs +
" </tbody>\n" + ' </tbody>\n' +
" </table>\n" + ' </table>\n' +
" </div>\n" + ' </div>\n' +
" </div>\n" + ' </div>\n' +
" </div>\n"; ' </div>\n';
}).join("\n") + }).join('\n') +
"</div>\n"; '</div>\n';
}; };
function generateFileHtml(file, config) { function generateFileHtml(file, config) {
return file.blocks.map(function(block) { return file.blocks.map(function(block) {
var lines = "<tr>\n" + var lines = '<tr>\n' +
" <td class=\"d2h-code-linenumber " + diffParser.LINE_TYPE.INFO + "\"></td>\n" + ' <td class="d2h-code-linenumber ' + diffParser.LINE_TYPE.INFO + '"></td>\n' +
" <td class=\"" + diffParser.LINE_TYPE.INFO + "\">" + ' <td class="' + diffParser.LINE_TYPE.INFO + '">' +
" <div class=\"d2h-code-line " + diffParser.LINE_TYPE.INFO + "\">" + utils.escape(block.header) + "</div>" + ' <div class="d2h-code-line ' + diffParser.LINE_TYPE.INFO + '">' + utils.escape(block.header) + '</div>' +
" </td>\n" + ' </td>\n' +
"</tr>\n"; '</tr>\n';
var oldLines = [], newLines = []; var oldLines = [];
var processedOldLines = [], processedNewLines = []; var newLines = [];
var processedOldLines = [];
var processedNewLines = [];
for (var i = 0; i < block.lines.length; i++) { for (var i = 0; i < block.lines.length; i++) {
var line = block.lines[i]; var line = block.lines[i];
@ -81,8 +86,12 @@
config.isCombined = file.isCombined; config.isCombined = file.isCombined;
var diff = printerUtils.diffHighlight(oldLine.content, newLine.content, config); var diff = printerUtils.diffHighlight(oldLine.content, newLine.content, config);
processedOldLines += generateLineHtml(oldLine.type, oldLine.oldNumber, oldLine.newNumber, diff.first.line, diff.first.prefix); processedOldLines +=
processedNewLines += generateLineHtml(newLine.type, newLine.oldNumber, newLine.newNumber, diff.second.line, diff.second.prefix); generateLineHtml(oldLine.type, oldLine.oldNumber, oldLine.newNumber,
diff.first.line, diff.first.prefix);
processedNewLines +=
generateLineHtml(newLine.type, newLine.oldNumber, newLine.newNumber,
diff.second.line, diff.second.prefix);
} }
lines += processedOldLines + processedNewLines; lines += processedOldLines + processedNewLines;
@ -101,11 +110,11 @@
lines += processLines(oldLines, newLines); lines += processLines(oldLines, newLines);
return lines; return lines;
}).join("\n"); }).join('\n');
} }
function processLines(oldLines, newLines) { function processLines(oldLines, newLines) {
var lines = ""; var lines = '';
for (j = 0; j < oldLines.length; j++) { for (j = 0; j < oldLines.length; j++) {
var oldLine = oldLines[j]; var oldLine = oldLines[j];
@ -123,39 +132,37 @@
} }
function generateLineHtml(type, oldNumber, newNumber, content, prefix) { function generateLineHtml(type, oldNumber, newNumber, content, prefix) {
var htmlPrefix = ""; var htmlPrefix = '';
if (prefix) htmlPrefix = "<span class=\"d2h-code-line-prefix\">" + prefix + "</span>"; if (prefix) {
htmlPrefix = '<span class="d2h-code-line-prefix">' + prefix + '</span>';
}
var htmlContent = ""; var htmlContent = '';
if (content) htmlContent = "<span class=\"d2h-code-line-ctn\">" + content + "</span>"; if (content) {
htmlContent = '<span class="d2h-code-line-ctn">' + content + '</span>';
}
return "<tr>\n" + return '<tr>\n' +
" <td class=\"d2h-code-linenumber " + type + "\">" + ' <td class="d2h-code-linenumber ' + type + '">' +
" <div class=\"line-num1\">" + utils.valueOrEmpty(oldNumber) + "</div>" + ' <div class="line-num1">' + utils.valueOrEmpty(oldNumber) + '</div>' +
" <div class=\"line-num2\">" + utils.valueOrEmpty(newNumber) + "</div>" + ' <div class="line-num2">' + utils.valueOrEmpty(newNumber) + '</div>' +
" </td>\n" + ' </td>\n' +
" <td class=\"" + type + "\">" + ' <td class="' + type + '">' +
" <div class=\"d2h-code-line " + type + "\">" + htmlPrefix + htmlContent + "</div>" + ' <div class="d2h-code-line ' + type + '">' + htmlPrefix + htmlContent + '</div>' +
" </td>\n" + ' </td>\n' +
"</tr>\n"; '</tr>\n';
} }
function generateEmptyDiff() { function generateEmptyDiff() {
return "<tr>\n" + return '<tr>\n' +
" <td class=\"" + diffParser.LINE_TYPE.INFO + "\">" + ' <td class="' + diffParser.LINE_TYPE.INFO + '">' +
" <div class=\"d2h-code-line " + diffParser.LINE_TYPE.INFO + "\">" + ' <div class="d2h-code-line ' + diffParser.LINE_TYPE.INFO + '">' +
"File without changes" + 'File without changes' +
" </div>" + ' </div>' +
" </td>\n" + ' </td>\n' +
"</tr>\n"; '</tr>\n';
} }
// expose this module module.exports['LineByLinePrinter'] = new LineByLinePrinter();
((typeof module !== 'undefined' && module.exports) ||
(typeof exports !== 'undefined' && exports) ||
(typeof window !== 'undefined' && window) ||
(typeof self !== 'undefined' && self) ||
(typeof $this !== 'undefined' && $this) ||
Function('return this')())["LineByLinePrinter"] = new LineByLinePrinter();
})(this); })(this);

View file

@ -7,9 +7,8 @@
(function(ctx, undefined) { (function(ctx, undefined) {
// dirty hack for browser compatibility var jsDiff = require('diff');
var jsDiff = (typeof JsDiff !== "undefined" && JsDiff) || require("diff"); var utils = require('./utils.js').Utils;
var utils = require("./utils.js").Utils;
function PrinterUtils() { function PrinterUtils() {
} }
@ -21,13 +20,13 @@
if (oldFilename && newFilename if (oldFilename && newFilename
&& oldFilename !== newFilename && oldFilename !== newFilename
&& !isDeletedName(newFilename)) { && !isDeletedName(newFilename)) {
return oldFilename + " -> " + newFilename; return oldFilename + ' -> ' + newFilename;
} else if (newFilename && !isDeletedName(newFilename)) { } else if (newFilename && !isDeletedName(newFilename)) {
return newFilename; return newFilename;
} else if (oldFilename) { } else if (oldFilename) {
return oldFilename; return oldFilename;
} else { } else {
return "Unknown filename"; return 'Unknown filename';
} }
}; };
@ -36,7 +35,9 @@
var prefixSize = 1; var prefixSize = 1;
if (config.isCombined) prefixSize = 2; if (config.isCombined) {
prefixSize = 2;
}
lineStart1 = diffLine1.substr(0, prefixSize); lineStart1 = diffLine1.substr(0, prefixSize);
lineStart2 = diffLine2.substr(0, prefixSize); lineStart2 = diffLine2.substr(0, prefixSize);
@ -45,17 +46,23 @@
diffLine2 = diffLine2.substr(prefixSize); diffLine2 = diffLine2.substr(prefixSize);
var diff; var diff;
if (config.charByChar) diff = jsDiff.diffChars(diffLine1, diffLine2); if (config.charByChar) {
else diff = jsDiff.diffWordsWithSpace(diffLine1, diffLine2); diff = jsDiff.diffChars(diffLine1, diffLine2);
} else {
diff = jsDiff.diffWordsWithSpace(diffLine1, diffLine2);
}
var highlightedLine = ""; var highlightedLine = '';
diff.forEach(function(part) { diff.forEach(function(part) {
var elemType = part.added ? 'ins' : part.removed ? 'del' : null; var elemType = part.added ? 'ins' : part.removed ? 'del' : null;
var escapedValue = utils.escape(part.value); var escapedValue = utils.escape(part.value);
if (elemType !== null) highlightedLine += "<" + elemType + ">" + escapedValue + "</" + elemType + ">"; if (elemType !== null) {
else highlightedLine += escapedValue; highlightedLine += '<' + elemType + '>' + escapedValue + '</' + elemType + '>';
} else {
highlightedLine += escapedValue;
}
}); });
return { return {
@ -71,23 +78,17 @@
}; };
function isDeletedName(name) { function isDeletedName(name) {
return name === "dev/null"; return name === 'dev/null';
} }
function removeIns(line) { function removeIns(line) {
return line.replace(/(<ins>((.|\n)*?)<\/ins>)/g, ""); return line.replace(/(<ins>((.|\n)*?)<\/ins>)/g, '');
} }
function removeDel(line) { function removeDel(line) {
return line.replace(/(<del>((.|\n)*?)<\/del>)/g, ""); return line.replace(/(<del>((.|\n)*?)<\/del>)/g, '');
} }
// expose this module module.exports['PrinterUtils'] = new PrinterUtils();
((typeof module !== 'undefined' && module.exports) ||
(typeof exports !== 'undefined' && exports) ||
(typeof window !== 'undefined' && window) ||
(typeof self !== 'undefined' && self) ||
(typeof $this !== 'undefined' && $this) ||
Function('return this')())["PrinterUtils"] = new PrinterUtils();
})(this); })(this);

View file

@ -7,77 +7,83 @@
(function(ctx, undefined) { (function(ctx, undefined) {
var diffParser = require("./diff-parser.js").DiffParser; var diffParser = require('./diff-parser.js').DiffParser;
var printerUtils = require("./printer-utils.js").PrinterUtils; var printerUtils = require('./printer-utils.js').PrinterUtils;
var utils = require("./utils.js").Utils; var utils = require('./utils.js').Utils;
function SideBySidePrinter() { function SideBySidePrinter() {
} }
SideBySidePrinter.prototype.generateSideBySideJsonHtml = function(diffFiles, config) { SideBySidePrinter.prototype.generateSideBySideJsonHtml = function(diffFiles, config) {
return "<div class=\"d2h-wrapper\">\n" + return '<div class="d2h-wrapper">\n' +
diffFiles.map(function(file) { diffFiles.map(function(file) {
var diffs; var diffs;
if (file.blocks.length) diffs = generateSideBySideFileHtml(file, config); if (file.blocks.length) {
else diffs = generateEmptyDiff(); diffs = generateSideBySideFileHtml(file, config);
} else {
diffs = generateEmptyDiff();
}
return "<div class=\"d2h-file-wrapper\" data-lang=\"" + file.language + "\">\n" + return '<div class="d2h-file-wrapper" data-lang="' + file.language + '">\n' +
" <div class=\"d2h-file-header\">\n" + ' <div class="d2h-file-header">\n' +
" <div class=\"d2h-file-stats\">\n" + ' <div class="d2h-file-stats">\n' +
" <span class=\"d2h-lines-added\">+" + file.addedLines + "</span>\n" + ' <span class="d2h-lines-added">+' + file.addedLines + '</span>\n' +
" <span class=\"d2h-lines-deleted\">-" + file.deletedLines + "</span>\n" + ' <span class="d2h-lines-deleted">-' + file.deletedLines + '</span>\n' +
" </div>\n" + ' </div>\n' +
" <div class=\"d2h-file-name\">" + printerUtils.getDiffName(file) + "</div>\n" + ' <div class="d2h-file-name">' + printerUtils.getDiffName(file) + '</div>\n' +
" </div>\n" + ' </div>\n' +
" <div class=\"d2h-files-diff\">\n" + ' <div class="d2h-files-diff">\n' +
" <div class=\"d2h-file-side-diff\">\n" + ' <div class="d2h-file-side-diff">\n' +
" <div class=\"d2h-code-wrapper\">\n" + ' <div class="d2h-code-wrapper">\n' +
" <table class=\"d2h-diff-table\">\n" + ' <table class="d2h-diff-table">\n' +
" <tbody class=\"d2h-diff-tbody\">\n" + ' <tbody class="d2h-diff-tbody">\n' +
" " + diffs.left + ' ' + diffs.left +
" </tbody>\n" + ' </tbody>\n' +
" </table>\n" + ' </table>\n' +
" </div>\n" + ' </div>\n' +
" </div>\n" + ' </div>\n' +
" <div class=\"d2h-file-side-diff\">\n" + ' <div class="d2h-file-side-diff">\n' +
" <div class=\"d2h-code-wrapper\">\n" + ' <div class="d2h-code-wrapper">\n' +
" <table class=\"d2h-diff-table\">\n" + ' <table class="d2h-diff-table">\n' +
" <tbody class=\"d2h-diff-tbody\">\n" + ' <tbody class="d2h-diff-tbody">\n' +
" " + diffs.right + ' ' + diffs.right +
" </tbody>\n" + ' </tbody>\n' +
" </table>\n" + ' </table>\n' +
" </div>\n" + ' </div>\n' +
" </div>\n" + ' </div>\n' +
" </div>\n" + ' </div>\n' +
" </div>\n"; ' </div>\n';
}).join("\n") + }).join('\n') +
"</div>\n"; '</div>\n';
}; };
function generateSideBySideFileHtml(file, config) { function generateSideBySideFileHtml(file, config) {
var fileHtml = {}; var fileHtml = {};
fileHtml.left = ""; fileHtml.left = '';
fileHtml.right = ""; fileHtml.right = '';
file.blocks.forEach(function(block) { file.blocks.forEach(function(block) {
fileHtml.left += "<tr>\n" + fileHtml.left += '<tr>\n' +
" <td class=\"d2h-code-side-linenumber " + diffParser.LINE_TYPE.INFO + "\"></td>\n" + ' <td class="d2h-code-side-linenumber ' + diffParser.LINE_TYPE.INFO + '"></td>\n' +
" <td class=\"" + diffParser.LINE_TYPE.INFO + "\">" + ' <td class="' + diffParser.LINE_TYPE.INFO + '">' +
" <div class=\"d2h-code-side-line " + diffParser.LINE_TYPE.INFO + "\">" + utils.escape(block.header) + "</div>" + ' <div class="d2h-code-side-line ' + diffParser.LINE_TYPE.INFO + '">' +
" </td>\n" + ' ' + utils.escape(block.header) +
"</tr>\n"; ' </div>' +
' </td>\n' +
'</tr>\n';
fileHtml.right += "<tr>\n" + fileHtml.right += '<tr>\n' +
" <td class=\"d2h-code-side-linenumber " + diffParser.LINE_TYPE.INFO + "\"></td>\n" + ' <td class="d2h-code-side-linenumber ' + diffParser.LINE_TYPE.INFO + '"></td>\n' +
" <td class=\"" + diffParser.LINE_TYPE.INFO + "\">" + ' <td class="' + diffParser.LINE_TYPE.INFO + '">' +
" <div class=\"d2h-code-side-line " + diffParser.LINE_TYPE.INFO + "\"></div>" + ' <div class="d2h-code-side-line ' + diffParser.LINE_TYPE.INFO + '"></div>' +
" </td>\n" + ' </td>\n' +
"</tr>\n"; '</tr>\n';
var oldLines = [], newLines = []; var oldLines = [];
var tmpHtml = ""; var newLines = [];
var tmpHtml = '';
for (var i = 0; i < block.lines.length; i++) { for (var i = 0; i < block.lines.length; i++) {
var line = block.lines[i]; var line = block.lines[i];
@ -87,7 +93,7 @@
fileHtml.left += generateSingleLineHtml(line.type, line.oldNumber, escapedLine); fileHtml.left += generateSingleLineHtml(line.type, line.oldNumber, escapedLine);
fileHtml.right += generateSingleLineHtml(line.type, line.newNumber, escapedLine); fileHtml.right += generateSingleLineHtml(line.type, line.newNumber, escapedLine);
} else if (line.type == diffParser.LINE_TYPE.INSERTS && !oldLines.length && !newLines.length) { } else if (line.type == diffParser.LINE_TYPE.INSERTS && !oldLines.length && !newLines.length) {
fileHtml.left += generateSingleLineHtml(diffParser.LINE_TYPE.CONTEXT, "", "", ""); fileHtml.left += generateSingleLineHtml(diffParser.LINE_TYPE.CONTEXT, '', '', '');
fileHtml.right += generateSingleLineHtml(line.type, line.newNumber, escapedLine); fileHtml.right += generateSingleLineHtml(line.type, line.newNumber, escapedLine);
} else if (line.type == diffParser.LINE_TYPE.DELETES && !newLines.length) { } else if (line.type == diffParser.LINE_TYPE.DELETES && !newLines.length) {
oldLines.push(line); oldLines.push(line);
@ -106,8 +112,12 @@
var diff = printerUtils.diffHighlight(oldLine.content, newLine.content, config); var diff = printerUtils.diffHighlight(oldLine.content, newLine.content, config);
fileHtml.left += generateSingleLineHtml(oldLine.type, oldLine.oldNumber, diff.first.line, diff.first.prefix); fileHtml.left +=
fileHtml.right += generateSingleLineHtml(newLine.type, newLine.newNumber, diff.second.line, diff.second.prefix); generateSingleLineHtml(oldLine.type, oldLine.oldNumber,
diff.first.line, diff.first.prefix);
fileHtml.right +=
generateSingleLineHtml(newLine.type, newLine.newNumber,
diff.second.line, diff.second.prefix);
} }
} else { } else {
tmpHtml = processLines(oldLines, newLines); tmpHtml = processLines(oldLines, newLines);
@ -131,8 +141,8 @@
function processLines(oldLines, newLines) { function processLines(oldLines, newLines) {
var fileHtml = {}; var fileHtml = {};
fileHtml.left = ""; fileHtml.left = '';
fileHtml.right = ""; fileHtml.right = '';
var maxLinesNumber = Math.max(oldLines.length, newLines.length); var maxLinesNumber = Math.max(oldLines.length, newLines.length);
for (j = 0; j < maxLinesNumber; j++) { for (j = 0; j < maxLinesNumber; j++) {
@ -144,12 +154,12 @@
fileHtml.right += generateSingleLineHtml(newLine.type, newLine.newNumber, utils.escape(newLine.content)); fileHtml.right += generateSingleLineHtml(newLine.type, newLine.newNumber, utils.escape(newLine.content));
} else if (oldLine) { } else if (oldLine) {
fileHtml.left += generateSingleLineHtml(oldLine.type, oldLine.oldNumber, utils.escape(oldLine.content)); fileHtml.left += generateSingleLineHtml(oldLine.type, oldLine.oldNumber, utils.escape(oldLine.content));
fileHtml.right += generateSingleLineHtml(diffParser.LINE_TYPE.CONTEXT, "", "", ""); fileHtml.right += generateSingleLineHtml(diffParser.LINE_TYPE.CONTEXT, '', '', '');
} else if (newLine) { } else if (newLine) {
fileHtml.left += generateSingleLineHtml(diffParser.LINE_TYPE.CONTEXT, "", "", ""); fileHtml.left += generateSingleLineHtml(diffParser.LINE_TYPE.CONTEXT, '', '', '');
fileHtml.right += generateSingleLineHtml(newLine.type, newLine.newNumber, utils.escape(newLine.content)); fileHtml.right += generateSingleLineHtml(newLine.type, newLine.newNumber, utils.escape(newLine.content));
} else { } else {
console.error("How did it get here?"); console.error('How did it get here?');
} }
} }
@ -157,41 +167,39 @@
} }
function generateSingleLineHtml(type, number, content, prefix) { function generateSingleLineHtml(type, number, content, prefix) {
var htmlPrefix = ""; var htmlPrefix = '';
if (prefix) htmlPrefix = "<span class=\"d2h-code-line-prefix\">" + prefix + "</span>"; if (prefix) {
htmlPrefix = '<span class="d2h-code-line-prefix">' + prefix + '</span>';
}
var htmlContent = ""; var htmlContent = '';
if (content) htmlContent = "<span class=\"d2h-code-line-ctn\">" + content + "</span>"; if (content) {
htmlContent = '<span class="d2h-code-line-ctn">' + content + '</span>';
}
return "<tr>\n" + return '<tr>\n' +
" <td class=\"d2h-code-side-linenumber " + type + "\">" + number + "</td>\n" + ' <td class="d2h-code-side-linenumber ' + type + '">' + number + '</td>\n' +
" <td class=\"" + type + "\">" + ' <td class="' + type + '">' +
" <div class=\"d2h-code-side-line " + type + "\">" + htmlPrefix + htmlContent + "</div>" + ' <div class="d2h-code-side-line ' + type + '">' + htmlPrefix + htmlContent + '</div>' +
" </td>\n" + ' </td>\n' +
" </tr>\n"; ' </tr>\n';
} }
function generateEmptyDiff() { function generateEmptyDiff() {
var fileHtml = {}; var fileHtml = {};
fileHtml.right = ""; fileHtml.right = '';
fileHtml.left = "<tr>\n" + fileHtml.left = '<tr>\n' +
" <td class=\"" + diffParser.LINE_TYPE.INFO + "\">" + ' <td class="' + diffParser.LINE_TYPE.INFO + '">' +
" <div class=\"d2h-code-side-line " + diffParser.LINE_TYPE.INFO + "\">" + ' <div class="d2h-code-side-line ' + diffParser.LINE_TYPE.INFO + '">' +
"File without changes" + 'File without changes' +
" </div>" + ' </div>' +
" </td>\n" + ' </td>\n' +
"</tr>\n"; '</tr>\n';
return fileHtml; return fileHtml;
} }
// expose this module module.exports['SideBySidePrinter'] = new SideBySidePrinter();
((typeof module !== 'undefined' && module.exports) ||
(typeof exports !== 'undefined' && exports) ||
(typeof window !== 'undefined' && window) ||
(typeof self !== 'undefined' && self) ||
(typeof $this !== 'undefined' && $this) ||
Function('return this')())["SideBySidePrinter"] = new SideBySidePrinter();
})(this); })(this);

View file

@ -12,26 +12,31 @@
Utils.prototype.escape = function(str) { Utils.prototype.escape = function(str) {
return str.slice(0) return str.slice(0)
.replace(/&/g, "&amp;") .replace(/&/g, '&amp;')
.replace(/</g, "&lt;") .replace(/</g, '&lt;')
.replace(/>/g, "&gt;") .replace(/>/g, '&gt;')
.replace(/\t/g, " "); .replace(/\t/g, ' ');
}; };
Utils.prototype.startsWith = function(str, start) { Utils.prototype.startsWith = function(str, start) {
if (typeof start === 'object') {
var result = false;
start.forEach(function(s) {
if (str.indexOf(s) === 0) {
result = true;
}
});
return result;
}
return str.indexOf(start) === 0; return str.indexOf(start) === 0;
}; };
Utils.prototype.valueOrEmpty = function(value) { Utils.prototype.valueOrEmpty = function(value) {
return value ? value : ""; return value ? value : '';
}; };
// expose this module module.exports['Utils'] = new Utils();
((typeof module !== 'undefined' && module.exports) ||
(typeof exports !== 'undefined' && exports) ||
(typeof window !== 'undefined' && window) ||
(typeof self !== 'undefined' && self) ||
(typeof $this !== 'undefined' && $this) ||
Function('return this')())["Utils"] = new Utils();
})(this); })(this);