-
Notifications
You must be signed in to change notification settings - Fork 608
/
Ghprb.java
661 lines (551 loc) · 23.9 KB
/
Ghprb.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
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
package org.jenkinsci.plugins.ghprb;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.CredentialsStore;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.domains.DomainSpecification;
import com.cloudbees.plugins.credentials.domains.HostnamePortSpecification;
import com.cloudbees.plugins.credentials.domains.HostnameSpecification;
import com.cloudbees.plugins.credentials.domains.PathSpecification;
import com.cloudbees.plugins.credentials.domains.SchemeSpecification;
import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder;
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.Cause;
import hudson.model.Item;
import hudson.model.Job;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.Saveable;
import hudson.model.TaskListener;
import hudson.security.ACL;
import hudson.util.DescribableList;
import hudson.util.Secret;
import jenkins.model.ParameterizedJobMixIn;
import org.apache.commons.collections.Predicate;
import org.apache.commons.collections.PredicateUtils;
import org.apache.commons.collections.functors.InstanceofPredicate;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.ghprb.extensions.GhprbExtension;
import org.jenkinsci.plugins.ghprb.extensions.GhprbExtensionDescriptor;
import org.jenkinsci.plugins.ghprb.extensions.GhprbProjectExtension;
import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl;
import org.kohsuke.github.GHCommitState;
import org.kohsuke.github.GHIssue;
import org.kohsuke.github.GHUser;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/**
* @author janinko
*/
public class Ghprb {
private static final Logger LOGGER = Logger.getLogger(Ghprb.class.getName());
static final Pattern GITHUB_USER_REPO_PATTERN = Pattern.compile("^(http[s]?://[^/]*)/([^/]*/[^/]*).*");
private final GhprbTrigger trigger;
public Ghprb(GhprbTrigger trigger) {
this.trigger = trigger;
}
public void addWhitelist(String author) {
LOGGER.log(Level.INFO, "Adding {0} to whitelist", author);
trigger.addWhitelist(author);
}
public boolean isProjectDisabled() {
return !trigger.isActive();
}
public GhprbBuilds getBuilds() {
return trigger.getBuilds();
}
public GhprbTrigger getTrigger() {
return trigger;
}
public GhprbGitHub getGitHub() {
return trigger.getGhprbGitHub();
}
public static Pattern compilePattern(String regex) {
try {
return Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Failed to compile pattern " + regex, e);
return null;
}
}
private static boolean checkPattern(Pattern pattern, String comment) {
return pattern != null && pattern.matcher(comment).matches();
}
// These used to be stored on the object in the constructor.
// But because the object is only instantiated once per PR, configuration would go stale.
// Some optimization could be done around re-compiling regex/hash sets, but beyond that we still have to re-pull the text.
private Pattern retestPhrasePattern() {
return compilePattern(trigger.getDescriptor().getRetestPhrase());
}
/**
* Returns skip build phrases from Jenkins global configuration
*
* @return skip build phrases
*/
public Set<String> getSkipBuildPhrases() {
return new HashSet<String>(Arrays.asList(getTrigger().getSkipBuildPhrase().split("[\\r\\n]+")));
}
public Set<String> getBlacklistedCommitAuthors() {
return new HashSet<String>(Arrays.asList(getTrigger().getBlackListCommitAuthor().split("[\\r\\n]+")));
}
/**
* Checks for skip build commit author.
*
* @param author The GitHub commit author
* @return the skip sender or null if should not skip
*/
public String checkBlackListCommitAuthor(String author) {
Set<String> authors = getBlacklistedCommitAuthors();
authors.remove("");
Map<Pattern, String> skipPatterns = new HashMap<Pattern, String>();
for (String s : authors) {
s = s.trim();
if (compilePattern(s).matcher(author).matches()) {
return s;
}
}
return null;
}
/**
* Checks for skip build phrase in pull request title and body. If present it updates shouldRun as false.
*
* @param issue The GitHub issue
* @return the skip phrase or null if should not skip
*/
public String checkSkipBuildPhrase(GHIssue issue) {
Set<String> skipBuildPhrases = getSkipBuildPhrases();
skipBuildPhrases.remove("");
Map<Pattern, String> skipPatterns = new HashMap<Pattern, String>();
for (String skipBuildPhrase : skipBuildPhrases) {
skipBuildPhrase = skipBuildPhrase.trim();
skipPatterns.put(compilePattern(skipBuildPhrase), skipBuildPhrase);
}
// check in title
String pullRequestTitle = issue.getTitle();
String skipBuildPhrase = checkSkipBuildInString(skipPatterns, pullRequestTitle);
if (StringUtils.isNotBlank(skipBuildPhrase)) {
return skipBuildPhrase;
}
// not found in title, check in body
String pullRequestBody = issue.getBody();
skipBuildPhrase = checkSkipBuildInString(skipPatterns, pullRequestBody);
if (StringUtils.isNotBlank(skipBuildPhrase)) {
return skipBuildPhrase;
}
return null;
}
/**
* Checks for skip pattern in the passed string
*
* @param patterns The map of Patter to String values
* @param string The string we're looking for the phrase in
* @return the skip value or null if we don't find it
*/
private String checkSkipBuildInString(Map<Pattern, String> patterns, String string) {
// check for skip build phrase in the passed string
if (!patterns.isEmpty() && StringUtils.isNotBlank(string)) {
for (Map.Entry<Pattern, String> e : patterns.entrySet()) {
if (e.getKey().matcher(string).matches()) {
return e.getValue();
}
}
}
return null;
}
public Set<String> getBlackListLabels() {
return spiltLabels(getTrigger().getBlackListLabels());
}
public Set<String> getWhiteListLabels() {
return spiltLabels(getTrigger().getWhiteListLabels());
}
private Set<String> spiltLabels(String labelsField) {
Set<String> labels = new HashSet<String>();
if (labelsField != null && !labelsField.trim().isEmpty()) {
String[] split = labelsField.split("\\n+");
for (int i = 0; i < split.length; i++) {
split[i] = split[i].trim();
}
Collections.addAll(labels, split);
}
return labels;
}
private Pattern whitelistPhrasePattern() {
return compilePattern(trigger.getDescriptor().getWhitelistPhrase());
}
private Pattern oktotestPhrasePattern() {
return compilePattern(trigger.getDescriptor().getOkToTestPhrase());
}
private Pattern triggerPhrase() {
return compilePattern(trigger.getTriggerPhrase());
}
private HashSet<String> admins() {
HashSet<String> adminList;
adminList = new HashSet<String>(Arrays.asList(trigger.getAdminlist().toLowerCase().split("\\s+")));
adminList.remove("");
return adminList;
}
private HashSet<String> whitelisted() {
HashSet<String> whitelistedList;
whitelistedList = new HashSet<String>(Arrays.asList(trigger.getWhitelist().toLowerCase().split("\\s+")));
whitelistedList.remove("");
return whitelistedList;
}
private HashSet<String> organisations() {
HashSet<String> organisationsList;
organisationsList = new HashSet<String>(Arrays.asList(trigger.getOrgslist().split("\\s+")));
organisationsList.remove("");
return organisationsList;
}
public boolean isRetestPhrase(String comment) {
return checkPattern(retestPhrasePattern(), comment);
}
public boolean isWhitelistPhrase(String comment) {
return checkPattern(whitelistPhrasePattern(), comment);
}
public boolean isOktotestPhrase(String comment) {
return checkPattern(oktotestPhrasePattern(), comment);
}
public boolean isTriggerPhrase(String comment) {
return checkPattern(triggerPhrase(), comment);
}
public boolean ifOnlyTriggerPhrase() {
return trigger.getOnlyTriggerPhrase();
}
public boolean isWhitelisted(GHUser user) {
return trigger.getPermitAll()
|| whitelisted().contains(user.getLogin().toLowerCase())
|| admins().contains(user.getLogin().toLowerCase())
|| isInWhitelistedOrganisation(user);
}
public boolean isAdmin(GHUser user) {
return admins().contains(user.getLogin().toLowerCase())
|| (trigger.getAllowMembersOfWhitelistedOrgsAsAdmin()
&& isInWhitelistedOrganisation(user));
}
public boolean isBotUser(GHUser user) {
return user != null && user.getLogin().equals(getGitHub().getBotUserLogin());
}
private boolean isInWhitelistedOrganisation(GHUser user) {
for (String organisation : organisations()) {
if (getGitHub().isUserMemberOfOrganization(organisation, user)) {
return true;
}
}
return false;
}
List<GhprbBranch> getBlackListTargetBranches() {
return trigger.getBlackListTargetBranches();
}
List<GhprbBranch> getWhiteListTargetBranches() {
return trigger.getWhiteListTargetBranches();
}
public List<Pattern> getIncludedRegionPatterns() {
List<String> regions = Arrays.asList(trigger.getIncludedRegions().split("\\s+"));
List<Pattern> patterns = new ArrayList<Pattern>(regions.size());
for (String region : regions) {
if (StringUtils.isNotEmpty(region)) {
patterns.add(Pattern.compile(region));
}
}
return patterns;
}
public List<Pattern> getExcludedRegionPatterns() {
List<String> regions = Arrays.asList(trigger.getExcludedRegions().split("\\s+"));
List<Pattern> patterns = new ArrayList<Pattern>(regions.size());
for (String region : regions) {
if (StringUtils.isNotEmpty(region)) {
patterns.add(Pattern.compile(region));
}
}
return patterns;
}
public static String replaceMacros(Run<?, ?> build, TaskListener listener, String inputString) {
String returnString = inputString;
if (build != null && inputString != null) {
try {
Map<String, String> messageEnvVars = getEnvVars(build, listener);
returnString = Util.replaceMacro(inputString, messageEnvVars);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Couldn't replace macros in message: ", e);
}
}
return returnString;
}
public static Map<String, String> getEnvVars(Run<?, ?> build, TaskListener listener) {
Map<String, String> messageEnvVars = new HashMap<String, String>();
if (build != null) {
messageEnvVars.putAll(build.getCharacteristicEnvVars());
if (build instanceof AbstractBuild) {
messageEnvVars.putAll(((AbstractBuild) build).getBuildVariables());
}
try {
messageEnvVars.putAll(build.getEnvironment(listener));
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Couldn't get Env Variables: ", e);
}
}
return messageEnvVars;
}
public static String replaceMacros(Job<?, ?> project, String inputString) {
String returnString = inputString;
if (project != null && inputString != null) {
try {
Map<String, String> messageEnvVars = new HashMap<String, String>();
messageEnvVars.putAll(project.getCharacteristicEnvVars());
returnString = Util.replaceMacro(inputString, messageEnvVars);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Couldn't replace macros in message: ", e);
}
}
return returnString;
}
public static GHCommitState getState(Run<?, ?> build) {
GHCommitState state;
if (build.getResult() == Result.SUCCESS) {
state = GHCommitState.SUCCESS;
} else if (build.getResult() == Result.UNSTABLE) {
state = GhprbTrigger.getDscp().getUnstableAs();
} else {
state = GHCommitState.FAILURE;
}
return state;
}
public static Set<String> createSet(String list) {
String listString = list == null ? "" : list;
List<String> listList = Arrays.asList(listString.split("\\s+"));
Set<String> listSet = new HashSet<String>(listList);
listSet.remove("");
return listSet;
}
public static GhprbCause getCause(Run<?, ?> build) {
Cause cause = build.getCause(GhprbCause.class);
if (cause == null || (!(cause instanceof GhprbCause))) {
return null;
}
return (GhprbCause) cause;
}
public static GhprbTrigger extractTrigger(Run<?, ?> build) {
return extractTrigger(build.getParent());
}
public static GhprbTrigger extractTrigger(Job<?, ?> p) {
ParameterizedJobMixIn.ParameterizedJob pJob = (ParameterizedJobMixIn.ParameterizedJob) p;
GhprbTrigger ghprbTrigger = null;
if (p instanceof ParameterizedJobMixIn.ParameterizedJob) {
for (Object trigger : pJob.getTriggers().values()) {
if (trigger instanceof GhprbTrigger) {
ghprbTrigger = (GhprbTrigger) trigger;
break;
}
}
}
return ghprbTrigger;
}
private static List<Predicate> createPredicate(Class<?>... types) {
List<Predicate> predicates = new ArrayList<Predicate>(types.length);
for (Class<?> type : types) {
predicates.add(InstanceofPredicate.getInstance(type));
}
return predicates;
}
public static void filterList(DescribableList<GhprbExtension, GhprbExtensionDescriptor> descriptors, Predicate predicate) {
for (GhprbExtension descriptor : descriptors) {
if (!predicate.evaluate(descriptor)) {
descriptors.remove(descriptor);
}
}
}
private static DescribableList<GhprbExtension, GhprbExtensionDescriptor> copyExtensions(
DescribableList<GhprbExtension, GhprbExtensionDescriptor>... extensionsList
) {
DescribableList<GhprbExtension, GhprbExtensionDescriptor> copiedList = new DescribableList<>(Saveable.NOOP);
for (DescribableList<GhprbExtension, GhprbExtensionDescriptor> extensions : extensionsList) {
copiedList.addAll(extensions);
}
return copiedList;
}
@SuppressWarnings("unchecked")
public static DescribableList<GhprbExtension, GhprbExtensionDescriptor> getJobExtensions(
GhprbTrigger trigger, Class<?>... types
) {
// First get all global extensions
DescribableList<GhprbExtension, GhprbExtensionDescriptor> copied = copyExtensions(trigger.getDescriptor().getExtensions());
// Remove extensions that are specified by job
filterList(copied, PredicateUtils.notPredicate(InstanceofPredicate.getInstance(GhprbProjectExtension.class)));
// Then get the rest of the extensions from the job
copied = copyExtensions(copied, trigger.getExtensions());
// Filter extensions by desired interface
filterList(copied, PredicateUtils.anyPredicate(createPredicate(types)));
return copied;
}
public static DescribableList<GhprbExtension, GhprbExtensionDescriptor> matchesAll(
DescribableList<GhprbExtension, GhprbExtensionDescriptor> extensions,
Class<?>... types
) {
Predicate predicate = PredicateUtils.allPredicate(createPredicate(types));
DescribableList<GhprbExtension, GhprbExtensionDescriptor> copyExtensions = new DescribableList<>(Saveable.NOOP);
copyExtensions.addAll(extensions);
filterList(copyExtensions, predicate);
return copyExtensions;
}
public static DescribableList<GhprbExtension, GhprbExtensionDescriptor> matchesSome(
DescribableList<GhprbExtension, GhprbExtensionDescriptor> extensions,
Class<?>... types
) {
Predicate predicate = PredicateUtils.anyPredicate(createPredicate(types));
DescribableList<GhprbExtension, GhprbExtensionDescriptor> copyExtensions = new DescribableList<>(Saveable.NOOP);
copyExtensions.addAll(extensions);
filterList(copyExtensions, predicate);
return copyExtensions;
}
public static DescribableList<GhprbExtension, GhprbExtensionDescriptor> onlyOneEntry(
DescribableList<GhprbExtension, GhprbExtensionDescriptor> extensions, Class<?>... types
) {
DescribableList<GhprbExtension, GhprbExtensionDescriptor> copyExtensions = new DescribableList<>(Saveable.NOOP);
Set<Class<?>> extSet = new HashSet<>(types.length);
List<Predicate> predicates = createPredicate(types);
for (GhprbExtension extension : extensions) {
if (addExtension(extension, predicates, extSet)) {
copyExtensions.add(extension);
}
}
return copyExtensions;
}
private static boolean addExtension(GhprbExtension extension, List<Predicate> predicates, Set<Class<?>> extSet) {
for (Predicate predicate : predicates) {
if (predicate.evaluate(extension)) {
Class<?> clazz = ((InstanceofPredicate) predicate).getType();
if (extSet.contains(clazz)) {
return false;
} else {
extSet.add(clazz);
return true;
}
}
}
return true;
}
public static void addIfMissing(
DescribableList<GhprbExtension, GhprbExtensionDescriptor> extensions,
GhprbExtension ext,
Class<?> type
) {
if (ext == null) {
return;
}
Predicate predicate = InstanceofPredicate.getInstance(type);
for (GhprbExtension extension : extensions) {
if (predicate.evaluate(extension)) {
return;
}
}
extensions.add(ext);
}
public static StandardCredentials lookupCredentials(Item context, String credentialId, String uri) {
String contextName = "(Jenkins.instance)";
if (context != null) {
contextName = context.getFullName();
}
LOGGER.log(
Level.FINE,
"Looking up credentials for {0}, using context {1} for url {2}",
new Object[] {credentialId, contextName, uri}
);
List<StandardCredentials> credentials;
LOGGER.log(Level.FINE, "Using null context because of issues not getting all credentials");
credentials = CredentialsProvider.lookupCredentials(StandardCredentials.class, (Item) null, ACL.SYSTEM,
URIRequirementBuilder.fromUri(uri).build());
LOGGER.log(Level.FINE, "Found {0} credentials", new Object[] {credentials.size()});
return (credentialId == null) ? null : CredentialsMatchers.firstOrNull(credentials,
CredentialsMatchers.withId(credentialId));
}
public static String createCredentials(String serverAPIUrl, String token) throws Exception {
String description = serverAPIUrl + " GitHub auto generated token credentials";
StringCredentialsImpl credentials = new StringCredentialsImpl(
CredentialsScope.GLOBAL,
UUID.randomUUID().toString(),
description,
Secret.fromString(token));
return createCredentials(serverAPIUrl, credentials);
}
public static String createCredentials(String serverAPIUrl, String username, String password) throws Exception {
String description = serverAPIUrl + " GitHub auto generated Username password credentials";
UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(
CredentialsScope.GLOBAL,
UUID.randomUUID().toString(),
description,
username,
password);
return createCredentials(serverAPIUrl, credentials);
}
private static String createCredentials(String serverAPIUrl, StandardCredentials credentials) throws Exception {
List<DomainSpecification> specifications = new ArrayList<DomainSpecification>(2);
URI serverUri = new URI(serverAPIUrl);
if (serverUri.getPort() > 0) {
specifications.add(new HostnamePortSpecification(serverUri.getHost() + ":" + serverUri.getPort(), null));
} else {
specifications.add(new HostnameSpecification(serverUri.getHost(), null));
}
specifications.add(new SchemeSpecification(serverUri.getScheme()));
String path = serverUri.getPath();
if (StringUtils.isEmpty(path)) {
path = "/";
}
specifications.add(new PathSpecification(path, null, false));
Domain domain = new Domain(serverUri.getHost(), "Auto generated credentials domain", specifications);
CredentialsStore provider = new SystemCredentialsProvider.StoreImpl();
provider.addDomain(domain, credentials);
return credentials.getId();
}
public static <T extends GhprbExtension> T getGlobal(Class<T> clazz) {
DescribableList<GhprbExtension, GhprbExtensionDescriptor> copyExtensions = new DescribableList<>(Saveable.NOOP);
copyExtensions.addAll(GhprbTrigger.DESCRIPTOR.getExtensions());
filterList(copyExtensions, InstanceofPredicate.getInstance(clazz));
return copyExtensions.get(clazz);
}
@SuppressWarnings(value = {"unchecked", "rawtypes"})
public static <T, S extends GhprbExtension> T getDefaultValue(S local, Class<S> globalClass, String methodName) {
T toReturn = null;
S global = getGlobal(globalClass);
if (local == null && global == null) {
return null;
}
try {
if (local == null) {
return (T) global.getClass().getMethod(methodName).invoke(global);
} else if (global == null) {
return (T) local.getClass().getMethod(methodName).invoke(local);
}
T localValue = (T) local.getClass().getMethod(methodName).invoke(local);
T globalValue = (T) global.getClass().getMethod(methodName).invoke(global);
if (localValue instanceof String) {
if (StringUtils.isEmpty((String) localValue)) {
return globalValue;
}
} else if (localValue instanceof List) {
if (((List) localValue).isEmpty()) {
return globalValue;
}
}
return localValue;
} catch (Exception e) {
LOGGER.log(Level.INFO, "Swallowing exception", e);
}
return toReturn;
}
}