-
Notifications
You must be signed in to change notification settings - Fork 27
/
pretty-diff.js
executable file
·82 lines (70 loc) · 1.88 KB
/
pretty-diff.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env node
var fs = require( "fs" );
var path = require( "path" );
var os = require( "os" );
var open = require( "open" );
var diff = require( "./diff" );
diff( process.argv.slice( 2 ).join( " " ), function( error, parsedDiff ) {
if ( error ) {
// Usage error, assume we're not in a git directory
if ( error.code === 129 ) {
process.stderr.write( "Error: Not a git repository\n" );
return;
}
process.stderr.write( error.message );
return;
}
if ( !parsedDiff ) {
console.log( "No differences" );
return;
}
generatePrettyDiff( parsedDiff );
});
function generatePrettyDiff( parsedDiff ) {
var template = fs.readFileSync( __dirname + "/template.html", "utf8" );
var diffHtml = "";
var tempPath = path.join( os.tmpdir(), "diff.html" );
for ( var file in parsedDiff ) {
diffHtml +=
"<h2>" +
"<div>" +
"<button class='collapse' onclick=" +
"'this.closest(\"h2\").nextElementSibling.classList.toggle(\"hidden\")'" +
">↕</button>" +
"<span class='title'>" + file + "</span>" +
"</div>" +
"<button class='copy' onclick=" +
"'navigator.clipboard.writeText(\"" + file + "\")'" +
">copy path</button>" +
"</h2>" +
"<div class='file-diff'>" +
markUpDiff( parsedDiff[ file ] ) +
"</div>";
}
fs.writeFileSync( tempPath, template.replace( "{{diff}}", diffHtml ) );
open( tempPath );
}
var markUpDiff = function() {
var diffClasses = {
"d": "file",
"i": "file",
"@": "info",
"-": "delete",
"+": "insert",
" ": "context"
};
function escape( str ) {
return str
.replace( /\$/g, "$$$$" )
.replace( /&/g, "&" )
.replace( /</g, "<" )
.replace( />/g, ">" )
.replace( /\t/g, " " );
}
return function( diff ) {
return diff.map(function( line ) {
var type = line.charAt( 0 );
return "<pre class='" + diffClasses[ type ] + "'>" + escape( line ) + "</pre>";
}).join( "\n" );
};
}();