forked from jenkinsci/ghprb-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGhprbRepository.java
More file actions
445 lines (386 loc) · 15.2 KB
/
GhprbRepository.java
File metadata and controls
445 lines (386 loc) · 15.2 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
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package org.jenkinsci.plugins.ghprb;
import hudson.BulkChange;
import hudson.XmlFile;
import hudson.model.Items;
import hudson.model.Job;
import hudson.model.Run;
import hudson.model.Saveable;
import hudson.model.TaskListener;
import hudson.model.listeners.SaveableListener;
import hudson.util.Secret;
import jenkins.model.Jenkins;
import jenkins.util.SystemProperties;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.ghprb.extensions.GhprbCommentAppender;
import org.jenkinsci.plugins.ghprb.extensions.GhprbCommitStatusException;
import org.jenkinsci.plugins.ghprb.extensions.GhprbExtension;
import org.jenkinsci.plugins.ghprb.extensions.comments.GhprbBuildStatus;
import org.kohsuke.github.GHCommitState;
import org.kohsuke.github.GHEvent;
import org.kohsuke.github.GHEventPayload.IssueComment;
import org.kohsuke.github.GHEventPayload.PullRequest;
import org.kohsuke.github.GHHook;
import org.kohsuke.github.GHIssueState;
import org.kohsuke.github.GHPullRequest;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GitHub;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Honza Brázdil jbrazdil@redhat.com
*/
public class GhprbRepository implements Saveable {
private static final transient Logger LOGGER = Logger.getLogger(GhprbRepository.class.getName());
private static final transient EnumSet<GHEvent> HOOK_EVENTS = EnumSet.of(GHEvent.ISSUE_COMMENT, GHEvent.PULL_REQUEST);
private static final transient boolean INSECURE_WEBHOOKS = SystemProperties.getBoolean(
GhprbRepository.class.getName() + ".webhook.insecure", false);
private final String reponame;
private final Map<Integer, GhprbPullRequest> pullRequests;
private transient GHRepository ghRepository;
private transient GhprbTrigger trigger;
public GhprbRepository(String reponame, GhprbTrigger trigger) {
this.pullRequests = new ConcurrentHashMap<>();
this.reponame = reponame;
this.trigger = trigger;
}
public void addPullRequests(Map<Integer, GhprbPullRequest> prs) {
pullRequests.putAll(prs);
}
public void init() {
for (Entry<Integer, GhprbPullRequest> next : pullRequests.entrySet()) {
GhprbPullRequest pull = next.getValue();
pull.init(trigger.getHelper(), this);
}
}
private boolean initGhRepository() {
if (ghRepository != null) {
return true;
}
GitHub gitHub = null;
try {
gitHub = trigger.getGitHub();
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Error while accessing rate limit API", ex);
return false;
}
if (gitHub == null) {
LOGGER.log(Level.SEVERE, "No connection returned to GitHub server!");
return false;
}
try {
if (gitHub.getRateLimit().getRemaining() == 0) {
LOGGER.log(Level.INFO, "Exceeded rate limit for repository");
return false;
}
} catch (FileNotFoundException ex) {
LOGGER.log(Level.INFO, "Rate limit API not found.");
return false;
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Error while accessing rate limit API", ex);
return false;
}
try {
ghRepository = gitHub.getRepository(reponame);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Could not retrieve GitHub repository named " + reponame
+ " (Do you have properly set 'GitHub project' field in job configuration?)", ex);
return false;
}
return true;
}
// This method is used when not running with webhooks. We pull in the
// active PRs for the repo associated with the trigger and check the
// comments/hashes that have been added since the last time we checked.
public void check() {
if (!trigger.isActive()) {
LOGGER.log(Level.FINE, "Project is not active, not checking github state");
return;
}
if (!initGhRepository()) {
return;
}
GHRepository repo = getGitHubRepo();
List<GHPullRequest> openPulls;
try {
openPulls = repo.getPullRequests(GHIssueState.OPEN);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Could not retrieve open pull requests.", ex);
return;
}
Set<Integer> closedPulls = new HashSet<Integer>(pullRequests.keySet());
for (GHPullRequest pr : openPulls) {
if (pr.getHead() == null) { // Not sure if we need this, but leaving it for now.
try {
pr = getActualPullRequest(pr.getNumber());
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Could not retrieve pr " + pr.getNumber(), ex);
return;
}
}
check(pr);
closedPulls.remove(pr.getNumber());
}
// remove closed pulls so we don't check them again
for (Integer id : closedPulls) {
pullRequests.remove(id);
}
try {
this.save();
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Unable to save repository!", e);
}
}
private void check(GHPullRequest pr) {
int number = pr.getNumber();
try {
GhprbPullRequest pull = getPullRequest(null, number);
pull.check(pr, false);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Unable to check pr: " + number, e);
}
try {
this.save();
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Unable to save repository!", e);
}
}
public void commentOnFailure(Run<?, ?> build, TaskListener listener, GhprbCommitStatusException ex) {
PrintStream stream = null;
if (listener != null) {
stream = listener.getLogger();
}
GHCommitState state = ex.getState();
Exception baseException = ex.getException();
String newMessage;
if (baseException instanceof FileNotFoundException) {
newMessage = "FileNotFoundException means that the credentials Jenkins is using is probably wrong. "
+ "Or the user account does not have write access to the repo.";
} else {
newMessage = "Could not update commit status of the Pull Request on GitHub.";
}
if (stream != null) {
stream.println(newMessage);
baseException.printStackTrace(stream);
} else {
LOGGER.log(Level.INFO, newMessage, baseException);
}
if (GhprbTrigger.getDscp().getUseComments()) {
StringBuilder msg = new StringBuilder(ex.getMessage());
if (build != null) {
msg.append("\n");
GhprbTrigger trigger = Ghprb.extractTrigger(build);
for (GhprbExtension ext : Ghprb.matchesAll(trigger.getExtensions(), GhprbBuildStatus.class)) {
if (ext instanceof GhprbCommentAppender) {
msg.append(((GhprbCommentAppender) ext).postBuildComment(build, null));
}
}
}
if (GhprbTrigger.getDscp().getUseDetailedComments() || (state == GHCommitState.SUCCESS || state == GHCommitState.FAILURE)) {
LOGGER.log(Level.INFO, "Trying to send comment.", baseException);
addComment(ex.getId(), msg.toString());
}
} else {
LOGGER.log(Level.SEVERE, "Could not update commit status of the Pull Request on GitHub.");
}
}
public String getName() {
return reponame;
}
public void addComment(int id, String comment) {
addComment(id, comment, null, null);
}
public void addComment(int id, String comment, Run<?, ?> build, TaskListener listener) {
if (comment.trim().isEmpty()) {
return;
}
if (build != null && listener != null) {
try {
comment = build.getEnvironment(listener).expand(comment);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error", e);
}
}
try {
GHRepository repo = getGitHubRepo();
GHPullRequest pr = repo.getPullRequest(id);
pr.comment(comment);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Could not add comment to pull request #" + id + ": '" + comment + "'", ex);
}
}
public void closePullRequest(int id) {
try {
GHRepository repo = getGitHubRepo();
GHPullRequest pr = repo.getPullRequest(id);
pr.close();
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Could not close the pull request #" + id + ": '", ex);
}
}
private boolean hookExist() throws IOException {
GHRepository ghRepository = getGitHubRepo();
if (ghRepository == null) {
throw new IOException("Unable to get repo [ " + reponame + " ]");
}
for (GHHook h : ghRepository.getHooks()) {
if (!"web".equals(h.getName())) {
continue;
}
if (!getHookUrl().equals(h.getConfig().get("url"))) {
continue;
}
return true;
}
return false;
}
private static final Object CREATE_HOOK_LOCK = new Object();
public boolean createHook() {
try {
// Avoid a race to update the hooks in a repo (we could end up with
// multiple hooks). Lock on before we try this
synchronized (CREATE_HOOK_LOCK) {
if (hookExist()) {
return true;
}
Map<String, String> config = new HashMap<String, String>();
String secret = getSecret();
config.put("url", new URL(getHookUrl()).toExternalForm());
config.put("insecure_ssl", INSECURE_WEBHOOKS ? "1" : "0");
if (!StringUtils.isEmpty(secret)) {
config.put("secret", secret);
}
getGitHubRepo().createHook("web", config, HOOK_EVENTS, true);
return true;
}
} catch (IOException ex) {
LOGGER.log(Level.SEVERE,
"Could not create web hook for repository {0}. "
+ "Does the user (from global configuration) have admin rights to the repository?",
reponame);
return false;
}
}
private String getSecret() {
Secret secret = trigger.getGitHubApiAuth().getSecret();
return secret == null ? "" : secret.getPlainText();
}
private String getHookUrl() {
String baseUrl = trigger.getGitHubApiAuth().getJenkinsUrl();
if (baseUrl == null) {
baseUrl = Jenkins.getInstance().getRootUrl();
}
return baseUrl + GhprbRootAction.URL + "/";
}
public GhprbPullRequest getPullRequest(int id) {
return pullRequests.get(id);
}
public GHPullRequest getActualPullRequest(int id) throws IOException {
return getGitHubRepo().getPullRequest(id);
}
void onIssueCommentHook(IssueComment issueComment) throws IOException {
if (!trigger.isActive()) {
LOGGER.log(Level.FINE, "Not checking comments since build is disabled");
return;
}
int number = issueComment.getIssue().getNumber();
LOGGER.log(Level.FINER, "Comment on issue #{0} from {1}: {2}",
new Object[] {number, issueComment.getComment().getUser(), issueComment.getComment().getBody()});
if (!"created".equals(issueComment.getAction())) {
return;
}
GhprbPullRequest pull = getPullRequest(null, number);
pull.check(issueComment.getComment());
try {
this.save();
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Unable to save repository!", e);
}
}
private GhprbPullRequest getPullRequest(GHPullRequest ghpr, Integer number) throws IOException {
if (number == null) {
number = ghpr.getNumber();
}
synchronized (this) {
GhprbPullRequest pr = pullRequests.get(number);
if (pr == null) {
if (ghpr == null) {
GHRepository repo = getGitHubRepo();
ghpr = repo.getPullRequest(number);
}
pr = new GhprbPullRequest(ghpr, trigger.getHelper(), this);
pullRequests.put(number, pr);
}
return pr;
}
}
void onPullRequestHook(PullRequest pr) throws IOException {
GHPullRequest ghpr = pr.getPullRequest();
int number = pr.getNumber();
String action = pr.getAction();
boolean doSave = false;
if ("closed".equals(action)) {
pullRequests.remove(number);
doSave = true;
} else if (!trigger.isActive()) {
LOGGER.log(Level.FINE, "Not processing Pull request since the build is disabled");
} else if ("edited".equals(action) || "opened".equals(action) || "reopened".equals(action) || "synchronize".equals(action)) {
GhprbPullRequest pull = getPullRequest(ghpr, number);
pull.check(ghpr, true);
doSave = true;
} else {
LOGGER.log(Level.WARNING, "Unknown Pull Request hook action: {0}", action);
}
if (doSave) {
try {
this.save();
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Unable to save repository!", e);
}
}
}
public GHRepository getGitHubRepo() {
if (ghRepository == null && !initGhRepository()) {
LOGGER.log(Level.SEVERE, "Unable to get repository [ {0} ]", reponame);
}
return ghRepository;
}
public void load() throws IOException {
XmlFile xml = getConfigXml(trigger.getActualProject());
if (xml.exists()) {
xml.unmarshal(this);
}
save();
}
public void save() throws IOException {
if (BulkChange.contains(this)) {
return;
}
XmlFile config = getConfigXml(trigger.getActualProject());
config.write(this);
SaveableListener.fireOnChange(this, config);
}
protected XmlFile getConfigXml(Job<?, ?> project) throws IOException {
try {
String escapedRepoName = URLEncoder.encode(reponame, "UTF8");
File file = new File(project.getBuildDir() + "/pullrequests", escapedRepoName);
return Items.getConfigFile(file);
} catch (UnsupportedEncodingException e) {
throw new IOException(e);
}
}
}