-
Notifications
You must be signed in to change notification settings - Fork 24
/
ApproveWorkflow.java
214 lines (174 loc) · 8.49 KB
/
ApproveWorkflow.java
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
package io.quarkus.bot;
import io.quarkiverse.githubapp.ConfigFile;
import io.quarkiverse.githubapp.event.WorkflowRun;
import io.quarkus.bot.config.Feature;
import io.quarkus.bot.config.QuarkusGitHubBotConfig;
import io.quarkus.bot.config.QuarkusGitHubBotConfigFile;
import io.quarkus.bot.util.PullRequestFilesMatcher;
import io.quarkus.cache.CacheKey;
import io.quarkus.cache.CacheResult;
import org.jboss.logging.Logger;
import org.kohsuke.github.GHEventPayload;
import org.kohsuke.github.GHPullRequest;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GHRepositoryStatistics;
import org.kohsuke.github.GHWorkflowRun;
import org.kohsuke.github.PagedIterable;
import javax.inject.Inject;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
class ApproveWorkflow {
private static final Logger LOG = Logger.getLogger(ApproveWorkflow.class);
@Inject
QuarkusGitHubBotConfig quarkusBotConfig;
void evaluatePullRequest(
@WorkflowRun GHEventPayload.WorkflowRun workflowPayload,
@ConfigFile("quarkus-github-bot.yml") QuarkusGitHubBotConfigFile quarkusBotConfigFile) throws IOException {
if (!Feature.APPROVE_WORKFLOWS.isEnabled(quarkusBotConfigFile)) {
return;
}
// Don't bother checking if there are no rules
if (quarkusBotConfigFile.workflows.rules != null && quarkusBotConfigFile.workflows.rules.isEmpty()) {
return;
}
GHWorkflowRun workflowRun = workflowPayload.getWorkflowRun();
// Only check workflows which need action
if (!GHWorkflowRun.Conclusion.ACTION_REQUIRED.equals(workflowRun.getConclusion())) {
return;
}
ApprovalStatus approval = new ApprovalStatus();
checkUser(workflowPayload, quarkusBotConfigFile, approval);
// Don't bother checking more if we have a red flag
// (but don't return because we need to do stuff with the answer)
if (!approval.hasRedFlag()) {
checkFiles(quarkusBotConfigFile, workflowRun, approval);
}
if (approval.isApproved()) {
processApproval(workflowRun);
}
}
private void processApproval(GHWorkflowRun workflowRun) throws IOException {
// We could also do things here like adding comments, subject to config
if (!quarkusBotConfig.isDryRun()) {
workflowRun.approve();
}
}
private void checkUser(GHEventPayload.WorkflowRun workflowPayload, QuarkusGitHubBotConfigFile quarkusBotConfigFile,
ApprovalStatus approval) {
for (QuarkusGitHubBotConfigFile.WorkflowApprovalRule rule : quarkusBotConfigFile.workflows.rules) {
// We allow if the files or directories match the allow rule ...
if ((rule.allow != null && rule.allow.users != null) || (rule.unless != null && rule.unless.users != null)) {
GHRepositoryStatistics.ContributorStats stats = getStatsForUser(workflowPayload);
if (matchRuleForUser(stats, rule.allow)) {
approval.shouldApprove = true;
}
if (matchRuleForUser(stats, rule.unless)) {
approval.shouldNotApprove = true;
}
}
}
}
private void checkFiles(QuarkusGitHubBotConfigFile quarkusBotConfigFile, GHWorkflowRun workflowRun,
ApprovalStatus approval) {
String sha = workflowRun.getHeadSha();
// Now we want to get the pull request we're supposed to be checking.
// It would be nice to use commit.listPullRequests() but that only returns something if the
// base and head of the PR are from the same repository, which rules out most scenarios where we would want to do an approval
String fullyQualifiedBranchName = workflowRun.getHeadRepository().getOwnerName() + ":" + workflowRun.getHeadBranch();
PagedIterable<GHPullRequest> pullRequestsForThisBranch = workflowRun.getRepository().queryPullRequests()
.head(fullyQualifiedBranchName)
.list();
// The number of PRs with matching branch name should be exactly one, but if the PR
// has been closed it sometimes disappears from the list; also, if two branch names
// start with the same string, both will turn up in the query.
for (GHPullRequest pullRequest : pullRequestsForThisBranch) {
// Only look at PRs whose commit sha matches
if (sha.equals(pullRequest.getHead().getSha())) {
for (QuarkusGitHubBotConfigFile.WorkflowApprovalRule rule : quarkusBotConfigFile.workflows.rules) {
// We allow if the files or directories match the allow rule ...
if (matchRuleFromChangedFiles(pullRequest, rule.allow)) {
approval.shouldApprove = true;
}
// ... unless we also match the unless rule
if (matchRuleFromChangedFiles(pullRequest, rule.unless)) {
approval.shouldNotApprove = true;
}
}
}
}
}
public static boolean matchRuleFromChangedFiles(GHPullRequest pullRequest,
QuarkusGitHubBotConfigFile.WorkflowApprovalCondition rule) {
// for now, we only use the files but we could also use the other rules at some point
if (rule == null) {
return false;
}
if (rule.directories == null || rule.directories.isEmpty()) {
return false;
}
PullRequestFilesMatcher prMatcher = new PullRequestFilesMatcher(pullRequest);
return prMatcher.changedFilesMatch(rule.directories);
}
private boolean matchRuleForUser(GHRepositoryStatistics.ContributorStats stats,
QuarkusGitHubBotConfigFile.WorkflowApprovalCondition rule) {
if (rule == null || stats == null) {
return false;
}
if (rule.users == null) {
return false;
}
if (rule.users.minContributions != null && stats.getTotal() >= rule.users.minContributions) {
return true;
}
// We can add more rules here, for example how long the user has been contributing
return false;
}
private GHRepositoryStatistics.ContributorStats getStatsForUser(GHEventPayload.WorkflowRun workflowPayload) {
String login = workflowPayload.getSender().getLogin();
if (login != null) {
return getStatsForUser(workflowPayload.getRepository(), login);
}
return null;
}
@CacheResult(cacheName = "contributor-cache")
GHRepositoryStatistics.ContributorStats getStatsForUser(GHRepository repository, @CacheKey String login) {
try {
Map<String, GHRepositoryStatistics.ContributorStats> contributorStats = getContributorStats(repository);
return contributorStats.get(login);
} catch (IOException | InterruptedException e) {
LOG.error("Could not get repository contributor statistics", e);
}
return null;
}
@CacheResult(cacheName = "stats-cache")
Map<String, GHRepositoryStatistics.ContributorStats> getContributorStats(GHRepository repository)
throws IOException, InterruptedException {
GHRepositoryStatistics statistics = repository.getStatistics();
if (statistics != null) {
PagedIterable<GHRepositoryStatistics.ContributorStats> contributors = statistics.getContributorStats();
// Pull the iterable into a list object to force the traversal of the entire list,
// since then we get a fully-warmed cache on our first request
// Convert to a map for convenience of retrieval
List<GHRepositoryStatistics.ContributorStats> statsList = contributors.toList();
return statsList.stream()
.collect(
Collectors.toMap(contributorStats -> contributorStats.getAuthor().getLogin(), Function.identity()));
}
return null;
}
private static class ApprovalStatus {
// There are two variables here because we check a number of indicators and a number of counter-indicators
// (ie green flags and red flags)
boolean shouldApprove = false;
boolean shouldNotApprove = false;
boolean isApproved() {
return shouldApprove && !shouldNotApprove;
}
public boolean hasRedFlag() {
return shouldNotApprove;
}
}
}