-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathCheckRunGHEventSubscriber.java
175 lines (149 loc) · 6.55 KB
/
CheckRunGHEventSubscriber.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
package io.jenkins.plugins.checks.github;
import edu.hm.hafner.util.VisibleForTesting;
import edu.umd.cs.findbugs.annotations.Nullable;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import hudson.model.*;
import hudson.security.ACL;
import hudson.security.ACLContext;
import io.jenkins.plugins.util.JenkinsFacade;
import jenkins.model.ParameterizedJobMixIn;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.jenkinsci.plugins.github.extension.GHEventsSubscriber;
import org.jenkinsci.plugins.github.extension.GHSubscriberEvent;
import org.jenkinsci.plugins.github_branch_source.GitHubSCMSource;
import org.kohsuke.github.*;
import java.io.IOException;
import java.io.StringReader;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This subscriber manages {@link GHEvent#CHECK_RUN} event and handles the re-run action request.
*/
@Extension
public class CheckRunGHEventSubscriber extends GHEventsSubscriber {
private static final Logger LOGGER = Logger.getLogger(CheckRunGHEventSubscriber.class.getName());
private final JenkinsFacade jenkinsFacade;
private final GitHubSCMFacade gitHubSCMFacade;
/**
* Construct the subscriber.
*/
public CheckRunGHEventSubscriber() {
this(new JenkinsFacade(), new GitHubSCMFacade());
}
@VisibleForTesting
CheckRunGHEventSubscriber(final JenkinsFacade jenkinsFacade, final GitHubSCMFacade gitHubSCMFacade) {
super();
this.jenkinsFacade = jenkinsFacade;
this.gitHubSCMFacade = gitHubSCMFacade;
}
@Override
protected boolean isApplicable(@Nullable final Item item) {
if (item instanceof Job<?, ?>) {
return gitHubSCMFacade.findGitHubSCMSource((Job<?, ?>)item).isPresent();
}
return false;
}
@Override
protected Set<GHEvent> events() {
return Collections.unmodifiableSet(new HashSet<>(Collections.singletonList(GHEvent.CHECK_RUN)));
}
@Override
protected void onEvent(final GHSubscriberEvent event) {
final String payload = event.getPayload();
GHEventPayload.CheckRun checkRun;
try {
checkRun = GitHub.offline().parseEventPayload(new StringReader(payload), GHEventPayload.CheckRun.class);
}
catch (IOException e) {
throw new IllegalStateException("Could not parse check run event: " + payload.replaceAll("[\r\n]", ""), e);
}
if (!checkRun.getAction().equals("rerequested")) {
LOGGER.log(Level.FINE, "Unsupported check run action: " + checkRun.getAction().replaceAll("[\r\n]", ""));
return;
}
LOGGER.log(Level.INFO, "Received rerun request through GitHub checks API.");
try (ACLContext ignored = ACL.as(ACL.SYSTEM)) {
scheduleRerun(checkRun, payload);
}
}
private void scheduleRerun(final GHEventPayload.CheckRun checkRun, final String payload) {
final GHRepository repository = checkRun.getRepository();
final String branchName = getBranchName(JSONObject.fromObject(payload));
for (Job<?, ?> job : jenkinsFacade.getAllJobs()) {
Optional<GitHubSCMSource> source = gitHubSCMFacade.findGitHubSCMSource(job);
if (source.isPresent() && source.get().getRepoOwner().equals(repository.getOwnerName())
&& source.get().getRepository().equals(repository.getName())
&& job.getName().equals(branchName)) {
Cause cause = new GitHubChecksRerunActionCause(checkRun.getSender().getLogin());
ParameterizedJobMixIn.scheduleBuild2(job, 0, new CauseAction(cause));
LOGGER.log(Level.INFO, String.format("Scheduled rerun (build #%d) for job %s, requested by %s",
job.getNextBuildNumber(), jenkinsFacade.getFullNameOf(job),
checkRun.getSender().getLogin()).replaceAll("[\r\n]", ""));
return;
}
}
LOGGER.log(Level.WARNING, String.format("No proper job found for the rerun request from repository: %s and "
+ "branch: %s", repository.getFullName(), branchName).replaceAll("[\r\n]", ""));
}
/**
* Get branch name from {@link JSONObject}.
*
* This method will be replaced by {@link CheckRunGHEventSubscriber#getBranchName(GHEventPayload.CheckRun, String)}
* after the release of github--api-plugin 1.116. The github-api has already released 1.116 and make
* {@code getPullRequests} method public, see https://github.com/hub4j/github-api/pull/909.
*
* @param json
* json object from check run payload
* @return name of the branch to be scheduled
*/
private String getBranchName(final JSONObject json) {
String branchName = "master";
JSONArray pullRequests = json.getJSONObject("check_run").getJSONArray("pull_requests");
if (!pullRequests.isEmpty()) {
branchName = "PR-" + pullRequests.getJSONObject(0).getString("number");
}
return branchName;
}
@SuppressFBWarnings("UPM_UNCALLED_PRIVATE_METHOD")
@SuppressWarnings({"PMD.UnusedPrivateMethod", "PMD.UnusedFormalParameter"})
private String getBranchName(final GHEventPayload.CheckRun checkRun, final String payload) {
// String branchName = "master";
// try {
// List<GHPullRequest> pullRequests = checkRun.getCheckRun().getPullRequests();
// if (!pullRequests.isEmpty()) {
// branchName = "PR" + pullRequests.get(0).getNumber();
// }
// }
// catch (IOException e) {
// throw new IllegalStateException("Could not get pull request participated in rerun request: "
// + payload.replaceAll("\r\n", ""), e);
// }
//
// return branchName;
return StringUtils.EMPTY;
}
/**
* Declares that a build was started due to a user's rerun request through GitHub checks API.
*/
public static class GitHubChecksRerunActionCause extends Cause {
private final String user;
/**
* Construct the cause with user who requested the rerun.
*
* @param user
* name of the user who made the request
*/
public GitHubChecksRerunActionCause(final String user) {
super();
this.user = user;
}
@Override
public String getShortDescription() {
return String.format("Rerun request by %s through GitHub checks API", user);
}
}
}