forked from azanli/conflict-bot
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
297 lines (244 loc) · 8.93 KB
/
index.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
const core = require("@actions/core");
const github = require("@actions/github");
const readFileSync = require("fs").readFileSync;
const { debug, runCommand } = require("./index.utils");
const {
Variables,
getOpenPullRequests,
getChangedFiles,
requestReviews,
requestReviewsInConflictingPRs,
createConflictComment,
} = require("./index.requests");
async function main() {
if (github.context.payload.pull_request.draft) {
debug(`Not running any checks because this pull request is a draft`)
return
}
const variables = new Variables();
if (variables.get("isFork")) {
debug(`Not running any checks because this pull request is from a fork`)
return
}
try {
await setup();
const conflictArray = await getConflictArrayData();
if (conflictArray.length > 0) {
const quiet = variables.get("quiet");
// Request reviews from conflicting PR authors for this PR.
const reviews_requested_on_pr = await requestReviews(conflictArray);
// Add this PR's author as a reviewer on conflicting PRs.
const reviews_requested_on_conflicting_prs = await requestReviewsInConflictingPRs(conflictArray);
if (!quiet && (reviews_requested_on_pr > 0 || reviews_requested_on_conflicting_prs > 0)) {
await createConflictComment(conflictArray);
}
}
} catch (error) {
core.setFailed(error.message);
} finally {
cleanup();
}
}
async function setup() {
const variables = new Variables();
const mainBranch = variables.get("mainBranch");
const pullRequestBranch = variables.get("pullRequestBranch");
const pullRequestAuthor = variables.get("pullRequestAuthor");
const pullRequestHeadUrl = variables.get("pullRequestHeadUrl");
try {
// Configure Git with a dummy user identity.
runCommand(`git config user.email "[email protected]"`);
runCommand(`git config user.name "GitHub Action"`);
debug(`Fetching branch: ${mainBranch}`);
runCommand(`git fetch origin ${mainBranch}:${mainBranch}`);
debug(`Fetching branch: ${pullRequestBranch}`);
// Fetch PR branches into temporary refs.
if (variables.get("isFork")) {
runCommand(
`git remote add ${pullRequestAuthor} ${pullRequestHeadUrl}`
);
runCommand(
`git fetch ${pullRequestAuthor} ${pullRequestBranch}:refs/remotes/origin/conflictbot_tmp_${pullRequestBranch}`
);
} else {
runCommand(
`git fetch origin ${pullRequestBranch}:refs/remotes/origin/conflictbot_tmp_${pullRequestBranch}`
);
}
// Merge main into pull request branch in memory.
runCommand(`git checkout refs/remotes/origin/conflictbot_tmp_${pullRequestBranch}`);
runCommand(`git merge ${mainBranch} --no-commit --no-ff`);
runCommand(`git reset --hard HEAD`);
} catch (error) {
console.error(`Error during setup: ${error.message}`);
throw error;
}
}
async function getConflictArrayData() {
const variables = new Variables();
const pullRequestNumber = variables.get("pullRequestNumber");
const openPullRequests = await getOpenPullRequests();
const otherPullRequests = openPullRequests.filter(
(pr) => pr.number !== pullRequestNumber
);
debug(
`Checking for conflicts against ${otherPullRequests.length} other pull requests`
);
const conflictArray = [];
for (const otherPullRequest of otherPullRequests) {
const conflictData = await checkForConflicts(otherPullRequest);
if (Object.keys(conflictData).length > 0) {
conflictArray.push({
author: otherPullRequest.author,
conflictData,
number: otherPullRequest.number,
title: otherPullRequest.title,
reviewers: otherPullRequest.reviewers,
});
}
}
return conflictArray;
}
async function checkForConflicts(otherPullRequest) {
const variables = new Variables();
const pullRequestBranch = variables.get("pullRequestBranch");
const pullRequestNumber = variables.get("pullRequestNumber");
if (!pullRequestBranch || !otherPullRequest.branch) {
throw new Error("Failed to fetch branch name for one or both PRs.");
}
const pullRequestFiles = await getChangedFiles(pullRequestNumber);
const otherPullRequestFiles = await getChangedFiles(otherPullRequest.number);
const overlappingFiles = pullRequestFiles.filter((file) =>
otherPullRequestFiles.includes(file)
);
if (!overlappingFiles.length) {
debug(`No overlapping files with #${otherPullRequest.branch}, will not attempt merge`)
return [];
}
const conflictData = await attemptMerge(otherPullRequest);
return conflictData;
}
async function attemptMerge(otherPullRequest) {
const variables = new Variables();
const mainBranch = variables.get("mainBranch");
const pullRequestBranch = variables.get("pullRequestBranch");
const quiet = variables.get("quiet");
const conflictData = {};
try {
debug(
`Attempting to merge #${otherPullRequest.branch} into #${pullRequestBranch}`
);
debug(`Fetching branch: ${otherPullRequest.branch}`);
if (otherPullRequest.isFork) {
// This is in another try catch because we may have already added this remote.
try {
runCommand(
`git remote add ${otherPullRequest.author} ${otherPullRequest.pullRequestHeadUrl}`
);
} catch(error) {
console.log(error)
}
runCommand(
`git fetch ${otherPullRequest.author} ${otherPullRequest.branch}:refs/remotes/origin/conflictbot_tmp_${otherPullRequest.branch}`
);
} else {
runCommand(
`git fetch origin ${otherPullRequest.branch}:refs/remotes/origin/conflictbot_tmp_${otherPullRequest.branch}`
);
}
// Merge main into other pull request in memory.
runCommand(`git checkout refs/remotes/origin/conflictbot_tmp_${otherPullRequest.branch}`);
runCommand(`git merge ${mainBranch} --no-commit --no-ff`);
runCommand(`git reset --hard HEAD`);
try {
// Attempt to merge other pull request branch in memory without committing or fast-forwarding.
runCommand(
`git merge refs/remotes/origin/conflictbot_tmp_${pullRequestBranch} --no-commit --no-ff`
);
debug(`${otherPullRequest.branch} merge successful. No conflicts found`);
} catch (mergeError) {
const stdoutStr = mergeError.stdout.toString();
if (stdoutStr.includes("Automatic merge failed")) {
if (quiet) {
return {
0: "Extracting data is unnecessary if commenting is disabled.",
};
}
const output = runCommand(
"git diff --name-only --diff-filter=U"
).toString();
const conflictFileNames = output.split("\n").filter(Boolean);
for (const filename of conflictFileNames) {
debug(`Extracting conflicting line numbers for ${filename}`);
conflictData[filename] = extractConflictingLineNumbers(
otherPullRequest.branch,
filename
);
}
}
}
} catch (error) {
console.error(`Error during merge process: ${error.message}`);
} finally {
// Reset any changes.
runCommand(`git reset --hard HEAD`);
// Cleanup by deleting temporary refs.
runCommand(
`git update-ref -d refs/remotes/origin/conflictbot_tmp_${otherPullRequest.branch}`
);
}
return conflictData;
}
function extractConflictingLineNumbers(otherPullRequestBranch, filePath) {
const fileContentWithoutConflicts = runCommand(
`git show refs/remotes/origin/conflictbot_tmp_${otherPullRequestBranch}:${filePath}`
).toString();
const linesFromNormalFile = fileContentWithoutConflicts.split("\n");
const fileContentWithConflicts = readFileSync(filePath, "utf8");
const linesFromConflictFile = fileContentWithConflicts.split("\n");
const conflictLines = [];
let oursBlock = [];
let inOursBlock = false;
for (const lineFromConflictFile of linesFromConflictFile) {
if (lineFromConflictFile.startsWith("<<<<<<< HEAD")) {
inOursBlock = true;
oursBlock = [];
continue;
}
if (lineFromConflictFile.startsWith("=======")) {
inOursBlock = false;
const startIndex = linesFromNormalFile.indexOf(oursBlock[0]);
if (startIndex !== -1) {
// Verify that the block matches.
const doesMatch = oursBlock.every(
(ourLine, index) =>
ourLine === linesFromNormalFile[startIndex + index]
);
if (doesMatch) {
for (let i = 0; i < oursBlock.length; i++) {
conflictLines.push(startIndex + i + 1); // +1 for 1-indexed line numbers
}
}
}
continue;
}
if (lineFromConflictFile.startsWith(">>>>>>>")) {
oursBlock = [];
continue;
}
if (inOursBlock) {
oursBlock.push(lineFromConflictFile);
}
}
return conflictLines;
}
function cleanup() {
try {
const pullRequest = github.context.payload.pull_request;
runCommand(`git update-ref -d refs/remotes/origin/conflictbot_tmp_${pullRequest.branch}`);
} catch (e) {
console.error(`Error during cleanup: ${error.message}`);
throw error;
}
}
main();