-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathline-diff.js
56 lines (50 loc) · 1.38 KB
/
line-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
'use strict';
const { execSync } = require('child_process');
const fileNameReg = /diff --git a(.*) b.*/;
const lineReg = /@@ -(.*) \+(.*) @@/;
module.exports = (options = {}) => {
const {
targetBranch = 'master',
currentBranch,
filetypes,
} = options;
const filter = filetypes ? `-- '${filetypes.join("' '")}'` : '';
const cmd = [
'git',
'diff',
'--unified=0',
'--diff-filter=AM',
'--color=never',
targetBranch,
currentBranch,
filter,
].join(' ');
const str = execSync(cmd).toString().trim();
if (!str) return null;
const diffMap = {};
const diffArray = str.split('\n');
let currentFileName = '';
diffArray
.filter(str => !str.startsWith('+')
&& !str.startsWith('-')
&& !str.startsWith('index')
)
.forEach(str => {
const fileNameMatched = str.match(fileNameReg);
if (fileNameMatched) {
currentFileName = fileNameMatched[1];
diffMap[currentFileName] = [];
}
const matched = str.match(lineReg);
if (matched) {
const [ startLine, changedLength ] = matched[2].split(',');
const start = Number(startLine);
const end = changedLength ? start + Number(changedLength) - 1 : start;
if (start <= end) {
const modifiedCol = [ start, end ];
diffMap[currentFileName].push(modifiedCol);
}
}
});
return diffMap;
};