-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgit_diff.js
More file actions
63 lines (59 loc) · 2.29 KB
/
git_diff.js
File metadata and controls
63 lines (59 loc) · 2.29 KB
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
const { exec, execSync } = require("child_process");
function getDiffWithLineNumbers(baseBranch) {
return new Promise((resolve, reject) => {
exec(`git diff --name-only ${baseBranch}`, (error, stdout, stderr) => {
if (error) {
reject(error);
return;
}
let files = stdout.split("\n");
files.pop();
let prData = [];
for (const file of files) {
const regex = /\+([^\n]+)/g;
let allChangedLines;
try {
allChangedLines = execSync(
`git diff --unified=0 ${baseBranch} --ignore-all-space ${file} | grep -E '^\\+\\+\\+' -v | grep -E '^\\+'`
).toString();
} catch (err) {
console.log(`Seems Like No New Stuff was added in ${file}. Skipping It.`);
continue;
}
allChangedLines = allChangedLines.trim();
let linesNos = execSync(
`git diff --unified=0 ${baseBranch} --ignore-all-space ${file} | grep -e '^@@' | awk -F'@@' '{print $2}'`
).toString();
linesNos = linesNos.trim();
let matches = linesNos.match(regex).map((match) => match.substring(1));
matches = matches.map((s) => s.trim());
let data = [];
let changedLineArray = allChangedLines.split("\n");
for (const string of matches) {
if (string.includes(",")) {
const [number, iterations] = string.split(",");
if (!isNaN(Number(iterations))) {
const count = parseInt(iterations, 10);
let dataToConcat = { lineNumber: number, endsAfter: iterations, line: [] };
for (let i = 0; i < count; i++) {
let lineData = changedLineArray.shift();
lineData = lineData && lineData.replace(/^\+/, "").trim();
dataToConcat.line.push(lineData);
}
data.push(dataToConcat);
} else {
console.log("Invalid number of iterations");
}
} else {
let lineData = changedLineArray.shift();
lineData = lineData.replace(/^\+/, "").trim();
data.push({ lineNumber: string, endsAfter: "1", line: [lineData] });
}
}
prData.push({ fileName: file, data });
}
resolve(prData);
});
});
}
module.exports = getDiffWithLineNumbers;