-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathcheck-merge-safety.js
More file actions
217 lines (213 loc) · 7.87 KB
/
check-merge-safety.js
File metadata and controls
217 lines (213 loc) · 7.87 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
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
import {
setCommitStatus
} from "../main-3vz73ekb.js";
import {
require_micromatch
} from "../main-v9jqraeg.js";
import {
simpleGit
} from "../main-8cy5s7xq.js";
import {
paginateAllOpenPullRequests
} from "../main-zd3p3dtn.js";
import"../main-dkdfy8cx.js";
import {
require_bluebird
} from "../main-ttmzs6m5.js";
import {
HelperInputs
} from "../main-8h70j5cy.js";
import {
octokit
} from "../main-4c5nddsb.js";
import {
context
} from "../main-6avxv4a6.js";
import"../main-9m3k9gt0.js";
import {
error,
info,
setFailed
} from "../main-q70tmm6g.js";
import {
__toESM
} from "../main-wckvcay0.js";
// src/helpers/check-merge-safety.ts
var import_micromatch = __toESM(require_micromatch(), 1);
var import_bluebird = __toESM(require_bluebird(), 1);
var git = simpleGit();
var maxBranchNameLength = 50;
class CheckMergeSafety extends HelperInputs {
}
var checkMergeSafety = async (inputs) => {
const isPrWorkflow = Boolean(context.issue.number);
if (!isPrWorkflow) {
return handlePushWorkflow(inputs);
}
const { data: pullRequest } = await octokit.pulls.get({ pull_number: context.issue.number, ...context.repo });
const { state, message } = await setMergeSafetyStatus(pullRequest, inputs);
if (state === "failure") {
setFailed(message);
}
};
var setMergeSafetyStatus = async (pullRequest, { context: context2 = "Merge Safety", ...inputs }) => {
const { state, message } = await getMergeSafetyStateAndMessage(pullRequest, inputs);
const hasExistingFailureStatus = await checkForExistingFailureStatus(pullRequest, context2);
if (hasExistingFailureStatus && state === "failure") {
const {
head: {
ref,
user: { login: username }
}
} = pullRequest;
const truncatedRef = ref.length > maxBranchNameLength ? `${ref.substring(0, maxBranchNameLength)}...` : ref;
const truncatedBranchName = `${username}:${truncatedRef}`;
info(`Found existing failure status for ${truncatedBranchName}, skipping setting new status`);
} else {
await setCommitStatus({
sha: pullRequest.head.sha,
state,
context: context2,
description: message,
...context.repo
});
}
return { state, message };
};
var handlePushWorkflow = async (inputs) => {
const pullRequests = await paginateAllOpenPullRequests();
const filteredPullRequests = pullRequests.filter(({ base, draft }) => !draft && base.ref === base.repo.default_branch);
await import_bluebird.map(filteredPullRequests, (pullRequest) => setMergeSafetyStatus(pullRequest, inputs));
};
var checkForExistingFailureStatus = async (pullRequest, context2) => {
const { data } = await octokit.repos.getCombinedStatusForRef({
...context.repo,
ref: pullRequest.head.sha
});
if (data.state === "failure") {
const existingContext = data.statuses.find((status) => status.context === context2);
return Boolean(existingContext);
}
return false;
};
var fetchSha = async (repoUrl, sha) => {
try {
await git.fetch(repoUrl, sha, { "--depth": 1 });
info(`Fetched ${sha} from ${repoUrl}`);
} catch (err) {
info(`Failed to fetch ${sha} from ${repoUrl}: ${err.message}`);
throw new Error(`Failed to fetch ${sha} from ${repoUrl}: ${err.message}`);
}
};
var getDiffUsingGitCommand = async (repoUrl, baseSha, headSha) => {
await fetchSha(repoUrl, baseSha);
await fetchSha(repoUrl, headSha);
try {
const diff = await git.diff(["--name-only", baseSha, headSha]);
return (diff ?? "").split(`
`).filter(Boolean);
} catch (err) {
error(`Failed to run local git diff for ${repoUrl}: ${err.message}`);
throw new Error(`Failed to run local git diff for ${repoUrl}: ${err.message}`);
}
};
var getDiff = async (compareBase, compareHead, basehead) => {
let changedFileNames = [];
try {
const { data: { files: changedFiles } = {}, status } = await octokit.repos.compareCommitsWithBasehead({
...context.repo,
basehead
});
if (status > 400) {
throw { status };
}
changedFileNames = changedFiles?.map((file) => file.filename) ?? [];
} catch (err) {
info(`Failed to fetch diff: ${err.message} Status: ${err.status}`);
if (err?.status === 406 || err?.message.includes("diff is taking too long to generate")) {
info(`Attempting to generate diff using local git command`);
if (compareBase.repo?.html_url) {
changedFileNames = await getDiffUsingGitCommand(compareBase.repo?.html_url, compareBase.sha, compareHead.sha);
} else {
error(`Could not fetch repo url to run local git diff`);
throw err;
}
} else {
throw err;
}
}
return changedFileNames;
};
var getMergeSafetyStateAndMessage = async (pullRequest, { paths, ignore_globs, override_filter_paths, override_filter_globs }) => {
const {
base: {
repo: {
default_branch,
owner: { login: baseOwner }
}
},
head: {
ref,
user: { login: username }
}
} = pullRequest;
const branchName = `${username}:${ref}`;
const diffAgainstUserBranch = `${branchName}...${baseOwner}:${default_branch}`;
let fileNamesWhichBranchIsBehindOn;
try {
fileNamesWhichBranchIsBehindOn = await getDiff(pullRequest.head, pullRequest.base, diffAgainstUserBranch);
} catch (err) {
const message = diffErrorMessage(diffAgainstUserBranch, err.message);
error(message);
return { state: "failure", message };
}
const truncatedRef = ref.length > maxBranchNameLength ? `${ref.substring(0, maxBranchNameLength)}...` : ref;
const truncatedBranchName = `${username}:${truncatedRef}`;
const globalFilesOutdatedOnBranch = override_filter_globs ? import_micromatch.default(fileNamesWhichBranchIsBehindOn, override_filter_globs.split(/[\n,]/)) : override_filter_paths ? fileNamesWhichBranchIsBehindOn.filter((changedFile) => override_filter_paths.split(/[\n,]/).includes(changedFile)) : [];
if (globalFilesOutdatedOnBranch.length) {
error(buildErrorMessage(globalFilesOutdatedOnBranch, "global files", truncatedBranchName));
return {
state: "failure",
message: `This branch has one or more outdated global files. Please update with ${default_branch}.`
};
}
const diffAgainstDefaultBranch = `${baseOwner}:${default_branch}...${branchName}`;
let changedFileNames;
try {
changedFileNames = await getDiff(pullRequest.base, pullRequest.head, diffAgainstDefaultBranch);
} catch (err) {
const message = diffErrorMessage(diffAgainstDefaultBranch, err.message);
error(message);
return { state: "failure", message };
}
const changedFilesToIgnore = changedFileNames && ignore_globs ? import_micromatch.default(changedFileNames, ignore_globs.split(/[\n,]/)) : [];
const filteredFileNames = changedFileNames?.filter((file) => !changedFilesToIgnore.includes(file));
const allProjectDirectories = paths?.split(/[\n,]/);
const changedProjectsOutdatedOnBranch = allProjectDirectories?.filter((dir) => fileNamesWhichBranchIsBehindOn.some((file) => file.includes(dir)) && filteredFileNames?.some((file) => file.includes(dir)));
if (changedProjectsOutdatedOnBranch?.length) {
error(buildErrorMessage(changedProjectsOutdatedOnBranch, "projects", truncatedBranchName));
return {
state: "failure",
message: `This branch has one or more outdated projects. Please update with ${default_branch}.`
};
}
const safeMessage = buildSuccessMessage(truncatedBranchName);
info(safeMessage);
return {
state: "success",
message: safeMessage
};
};
var buildErrorMessage = (paths, pathType, branchName) => `
The following ${pathType} are outdated on branch ${branchName}
${paths.map((path) => `* ${path}`).join(`
`)}
`;
var diffErrorMessage = (basehead, message = "") => `Failed to generate diff for ${basehead}. Please verify SHAs are valid and try again.${message ? `
Error: ${message}` : ""}`;
var buildSuccessMessage = (branchName) => `Branch ${branchName} is safe to merge!`;
export {
checkMergeSafety,
CheckMergeSafety
};
//# debugId=852D8F69D0103B1E64756E2164756E21