Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// http://ido.nu/kuma/2007/10/01/diff-onp-javascript-implementation/
/*
Copyright (c) 2007, KUMAGAI Kentaro
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of this project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
function Diff(B, A) {
this.path = {};
if ( A.length < B.length ) {
this.a = A;
this.b = B;
} else {
this.a = B;
this.b = A;
this.reverse = true;
}
// push dummy.
this.a.unshift(null);
this.b.unshift(null);
this.a.unshift(null);
this.b.unshift(null);
this.fp = {};
this.lcs = this.onp();
}
Diff.prototype.getM = function () { return this.a.length - 1; };
Diff.prototype.getN = function () { return this.b.length - 1; };
Diff.prototype.onp = function () {
var M = this.getM();
var N = this.getN();
var delta = N - M;
var p = 0;
do {
for (var k = -p ; k <= delta - 1 ; k++) {
var y = this.snake(k);
this.fp[k] = y;
}
for (var k = delta + p ; k >= delta + 1 ; k--) {
var y = this.snake(k);
this.fp[k] = y;
}
/////// k = delta
var k = delta;
var y = this.snake(k);
this.fp[k] = y;
p++;
} while ( this.fp[delta] != N );
return this.path[delta];
};
Diff.prototype.snake = function(k) {
var i = ( this.fp[k - 1] || -1 ) + 1;
var j = this.fp[k + 1] || -1;
var v;
if ( i > j ) {
if ( this.path[k - 1] )
this.path[k] = this.path[k - 1].slice(0);
v = 1;
} else {
if ( this.path[k + 1] )
this.path[k] = this.path[k + 1].slice(0);
v = -1;
}
if ( ! this.path[k] )
this.path[k] = [];
this.path[k].push(v);
var y = Math.max(i, j);
var x = y - k;
while (
( x < this.getM() && y < this.getN() ) &&
this.compare( this.a[x+1], this.b[y+1] )
) {
x++;
y++;
this.path[k].push(0);
}
return y;
};
Diff.prototype.compare = function (a, b) {
return a == b;
};
// UnifiedDiff class; added by ucnv
// http://gist.github.com/105908
function UnifiedDiff(B, A, l) {
this.diff = new Diff(B.split(/\r?\n/), A.split(/\r?\n/));
this.lines = new Array();
var a = (this.diff.reverse) ? this.diff.b : this.diff.a;
var b = (this.diff.reverse) ? this.diff.a : this.diff.b;
var r = (this.diff.reverse) ? function(e) { return e * -1 } : function(e) { return e };
var lcs = this.diff.lcs;
a.shift();
b.shift();
lcs.shift();
var marks = new Array(lcs.length);
for(var i = 1, p = false, n; i < marks.length; i++) {
n = lcs[i];
if(n != 0) {
if(!p) {
for(var j = 0; j <= l; j++) {
if(i - j >= 0 && !marks[i - j]) marks[i - j] = ' ';
}
}
marks[i] = (r(n) > 0) ? '-' : '+';
} else {
if(p) {
for(var j = 0; j < l; j++) {
if(i + j < marks.length) marks[i + j] = ' ';
}
}
}
p = (n != 0);
}
marks.push('');
for(var i = 1, printing = false, ap = 1, bp = 1, ac = 0, bc = 0, sp, m; i < marks.length; i++) {
m = marks[i];
if(!m) {
if(printing && sp >= 0) {
this.lines[sp] = this.lines[sp].replace(/\$ac/, ac).replace(/\$bc/, bc).replace(/\,1 /, '');
}
printing = false;
ac = bc = 0;
ap++;
bp++;
continue;
}
if(!printing) {
sp = this.lines.length;
this.lines.push('@@ -' + bp + ',$bc +' + ap + ',$ac @@');
printing = true;
}
if(m == ' ') {
this.lines.push(m + a[ap++]);
bp++;
ac++;
bc++;
} else if(m == '-') {
this.lines.push(m + b[bp++]);
bc++;
} else if(m == '+') {
this.lines.push(m + a[ap++]);
ac++;
}
}
}
UnifiedDiff.prototype.toString = function() {
return this.lines.join('\n') + '\n';
};
// ==UserScript==
// @name Diff for gists for Opera
// @include http://gist.github.com/*
// @include https://gist.github.com/*
// ==/UserScript==
// forked from https://gist.github.com/227881
window.addEventListener('DOMContentLoaded',function(){
(function(window, $, rev) {
if (!$ || ((rev = $('#revisions li')).length < 2)) return;
var diffSelect = function(e) {
var me = e.target, c = $('#revisions li input:checked'), length = c.length;
if (length > 2)
c.each(function() { if (this != me) this.checked = false; });
$('#diffExec').attr('disabled', (length != 2));
},
diffExec = function() {
var filelist = [], // [{name, url1, url2}, ...]
template = [
'<div class="file" id="file_test.txt">',
' <div class="meta clearfix instapaper_ignore readability-extra">',
' <div class="info">',
' <span class="code"></span>',
' </div>',
' </div>',
' <div class="data type-text">',
' <table cellpadding="0" cellspacing="0">',
' <tr>',
' <td>',
' <pre class="line_numbers"></pre>',
' </td>',
' <td width="100%">',
' <div class="highlight"><pre></pre></div>',
' </td>',
' </tr>',
' </table>',
' </div>',
'</div>',
].join('\n'),
req = function(url, func) {
var x = new window.XMLHttpRequest();
x.open('GET', url, false);
x.onload = function() {func(x.responseText)};
x.send(null);
},
req2 = function(url1, url2, func) {
var c = 2, text1, text2, next = function() {if (!--c) func(text1, text2)};
req(url1, function(text) {text1 = text; next()});
req(url2, function(text) {text2 = text; next()});
},
selected = $('#revisions').find('input:checkbox:checked'),
link = selected.map(function() {return this.value.replace(/(https?:\/\/[^\/]+\/)/, '$1raw/')}),
desc = selected.map(function() { return $(this).parent().text().replace(/\s+/g, ' '); }),
loadCommits = function() {
req2(
link[0] + '/meta',
link[1] + '/meta',
loadTrees);
},
loadTrees = function(commit1, commit2){
req2(
link[0].replace(/[^\/]*$/, commit1.split(/\n/)[0].split(/\s/)[1]) + '/meta',
link[1].replace(/[^\/]*$/, commit2.split(/\n/)[0].split(/\s/)[1]) + '/meta',
makeFileList);
},
makeFileList = function(tree1, tree2){
tree1.split(/\n/).forEach(function(line) {
var s = line.split(/\s+/);
filelist.unshift({name: s[3], url1: link[0].replace(/[^\/]*$/, s[2]) + '/' + s[3]});
});
tree2.split(/\n/).forEach(function(line) {
var s = line.split(/\s+/),
url = link[1].replace(/[^\/]*$/, s[2]) + '/' + s[3],
idx;
if (filelist.some(function(f, i) {idx = i; return f.name === s[3]})) {
filelist[idx].url2 = url;
} else {
filelist.unshift({name: s[3], url2: url});
}
});
nextFile();
},
nextFile = function() {
var f = filelist.shift();
if (!f) return;
if (/\.(?:jpe?g|png|gif|bmp)$/.test(f.name)) return nextFile();
if (!f.url1) return req(f.url2, function(raw) {showDiff(f.name, null, raw);});
if (!f.url2) return req(f.url1, function(raw) {showDiff(f.name, raw, null);});
req2(f.url1, f.url2, function(raw1, raw2) {showDiff(f.name, raw1, raw2)});
},
showDiff = function(filename, raw1, raw2){
var udiff, title;
if (raw1 === null) {
var l = raw2.split('\n').map(function(line) {return '-' + line});
udiff = '@@ -1' + (l.length ? ',' + l.length : '') + ' +0,0 @@\n' + l.join('\n') + '\n';
title = '*DELETED* ' + filename;
} else if (raw2 === null) {
var l = raw1.split('\n').map(function(line) {return '+' + line});
udiff = '@@ -0,0 +1' + (l.length ? ',' + l.length : '') + ' @@\n' + l.join('\n') + '\n';
title = '*CREATED* ' + filename;
} else {
udiff = new UnifiedDiff(raw2, raw1, 4).toString();
if (udiff === '\n') return nextFile();
title = '*CHANGED* ' + filename;
}
var $diff = $(template);
$diff.find('.info > span.code').text(title);
$diff.hide().prependTo('#files');
var pre = $diff.find('.highlight > pre');
udiff = [
'--- ' + filename + ' ' + desc[1],
'+++ ' + filename + ' ' + desc[0],
pre.text(udiff).html()
].join('\n');
var len = udiff.split(/\n/).length;
if(len < 5000) {
udiff = udiff.replace(/^(\+.*)$/mg, '<span class="gi">$1</span>')
.replace(/^(\-.*)$/mg, '<span class="gd">$1</span>')
.replace(/^(\@.*)$/mg, '<span class="gu">$1</span>')
.replace(/^(.*)\n/mg, '<div class="line">$1</div>');
$diff.find('.line_numbers').html($.map(Array(len - 1), function(a,i){return '<span>'+(1+i)+'</span>'}).join('\n'));
}
pre.html(udiff);
$diff.slideDown('normal');
nextFile();
};
loadCommits();
};
$('<input type="button" id="diffExec" value="Compare" disabled="disabled"/>')
.appendTo('#revisions')
.click(diffExec);
rev.each(function() {
$('<input type="checkbox" name="diff" />')
.val($(this).find('.id').attr('href'))
.prependTo(this)
.click(diffSelect);
});
})(this, this.jQuery);
},false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.