-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathdiff.js
executable file
·69 lines (62 loc) · 1.49 KB
/
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
var spawn = require( "child_process" ).spawn;
module.exports = function( args, fn ) {
var childArgs = args ? [ "diff" ].concat( args.split( /\s/ ) ) : [ "diff" ],
child = spawn( "git", childArgs ),
stdout = "",
stderr = "";
child.stdout.on( "data", function( chunk ) {
stdout += chunk;
});
child.stderr.on( "data", function( chunk ) {
stderr += chunk;
});
child.on( "close", function( code ) {
if ( code !== 0 ) {
fn( new Error( stderr ) );
} else if ( !stdout.length ) {
fn( null, null );
} else {
fn( null, splitByFile( stdout ) );
}
});
};
function splitByFile( diff ) {
var filename,
files = {},
matches,
oldLineNum,
newLineNum;
diff.split( "\n" ).forEach(function( line, i ) {
if ( line.charAt( 0 ) === "d" ) {
filename = line.replace( /^diff --git a\/(\S+).*$/, "$1" );
files[ filename ] = [];
oldLineNum = null;
} else if ( matches = line.match( /@@\ -[0-9]+(,[0-9]+)?\ \+([0-9]+)(,[0-9]+)?\ @@.*/ ) ) {
oldLineNum = newLineNum = matches[ 2 ];
files[ filename ].push({
line: line,
oldLineNum: null,
newLineNum: null
});
} else if ( matches = line.match( /^(\[[0-9;]+m)*([\ +-])/ ) ) {
files[ filename ].push({
line: line,
oldLineNum: oldLineNum,
newLineNum: newLineNum
});
if ( matches[ 2 ] != '-' ) {
newLineNum++;
}
if ( matches[ 2 ] != '+' ) {
oldLineNum++;
}
} else {
files[ filename ].push({
line: line,
oldLineNum: null,
newLineNum: null
});
}
});
return files;
}