-
-
Notifications
You must be signed in to change notification settings - Fork 602
Expand file tree
/
Copy pathGhprbTrigger.java
More file actions
1251 lines (1024 loc) · 44.9 KB
/
GhprbTrigger.java
File metadata and controls
1251 lines (1024 loc) · 44.9 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
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.jenkinsci.plugins.ghprb;
import antlr.ANTLRException;
import com.coravy.hudson.plugins.github.GithubProjectProperty;
import com.google.common.annotations.VisibleForTesting;
import hudson.Extension;
import hudson.Util;
import hudson.matrix.MatrixProject;
import hudson.model.CauseAction;
import hudson.model.Item;
import hudson.model.Job;
import hudson.model.ParameterDefinition;
import hudson.model.ParameterValue;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.Run;
import hudson.model.Saveable;
import hudson.model.StringParameterValue;
import hudson.model.queue.QueueTaskFuture;
import hudson.plugins.git.util.BuildData;
import hudson.triggers.TriggerDescriptor;
import hudson.util.DescribableList;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import hudson.util.ListBoxModel.Option;
import jenkins.model.Jenkins;
import jenkins.model.ParameterizedJobMixIn;
import jenkins.util.SystemProperties;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.ghprb.extensions.GhprbBuildStep;
import org.jenkinsci.plugins.ghprb.extensions.GhprbExtension;
import org.jenkinsci.plugins.ghprb.extensions.GhprbExtensionDescriptor;
import org.jenkinsci.plugins.ghprb.extensions.GhprbGlobalDefault;
import org.jenkinsci.plugins.ghprb.extensions.comments.GhprbBuildLog;
import org.jenkinsci.plugins.ghprb.extensions.comments.GhprbBuildResultMessage;
import org.jenkinsci.plugins.ghprb.extensions.comments.GhprbBuildStatus;
import org.jenkinsci.plugins.ghprb.extensions.comments.GhprbPublishJenkinsUrl;
import org.jenkinsci.plugins.ghprb.extensions.status.GhprbSimpleStatus;
import org.kohsuke.github.GHCommitState;
import org.kohsuke.github.GHEventPayload.IssueComment;
import org.kohsuke.github.GHEventPayload.PullRequest;
import org.kohsuke.github.GitHub;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Honza Brázdil jbrazdil@redhat.com
*/
public class GhprbTrigger extends GhprbTriggerBackwardsCompatible {
@Extension
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
private static final Logger LOGGER = Logger.getLogger(GhprbTrigger.class.getName());
/**
* pool is a thread pool which is used to service registering hooks with
* GitHub. The number of threads defined can be customized with the system
* property org.jenkinsci.plugins.ghprb.GhprbTrigger.poolSize=N where N is
* an integer for number of threads. (default pool size: 5)
*/
private static final ExecutorService POOL = Executors.newFixedThreadPool(
SystemProperties.getInteger(GhprbTrigger.class.getName() + ".poolSize", 5)
);
/**
* disableRegisterOnStartup system property allows an admin to disable
* registering GitHub hooks during Jenkins startup. This assumes hooks are
* already properly registered when a job is first created. Configured via
* system property:
* <p>
* org.jenkinsci.plugins.ghprb.GhprbTrigger.disableRegisterOnStartup=true
* (default: false)
*/
private static final boolean DISABLE_REGISTER_ON_STARTUP =
SystemProperties.getBoolean(GhprbTrigger.class.getName() + ".disableRegisterOnStartup", false);
private final String adminlist;
private final Boolean allowMembersOfWhitelistedOrgsAsAdmin;
private final String orgslist;
private final String cron;
private final String buildDescTemplate;
private final Boolean onlyTriggerPhrase;
private final Boolean useGitHubHooks;
private final Boolean permitAll;
private String whitelist;
private Boolean autoCloseFailedPullRequests;
private Boolean displayBuildErrorsOnDownstreamBuilds;
private List<GhprbBranch> whiteListTargetBranches;
private List<GhprbBranch> blackListTargetBranches;
private String gitHubAuthId;
private String triggerPhrase;
private String skipBuildPhrase;
private String blackListCommitAuthor;
private String blackListLabels;
private String whiteListLabels;
private String includedRegions;
private String excludedRegions;
private Boolean reportSuccessIfNotRegion;
private transient Ghprb helper;
private transient GhprbRepository repository;
private transient GhprbBuilds builds;
private transient GhprbGitHub ghprbGitHub;
private DescribableList<GhprbExtension, GhprbExtensionDescriptor> extensions =
new DescribableList<GhprbExtension, GhprbExtensionDescriptor>(Saveable.NOOP);
public DescribableList<GhprbExtension, GhprbExtensionDescriptor> getExtensions() {
if (extensions == null) {
extensions = new DescribableList<GhprbExtension, GhprbExtensionDescriptor>(Saveable.NOOP, Util.fixNull(extensions));
extensions.add(new GhprbSimpleStatus());
}
return extensions;
}
private void setExtensions(List<GhprbExtension> extensions) {
DescribableList<GhprbExtension, GhprbExtensionDescriptor> rawList = new DescribableList<GhprbExtension, GhprbExtensionDescriptor>(
Saveable.NOOP, Util.fixNull(extensions));
// Filter out items that we only want one of, like the status updater.
this.extensions = Ghprb.onlyOneEntry(rawList,
GhprbSimpleStatus.class
);
// Make sure we have at least one of the types we need one of.
for (GhprbExtension ext : getDescriptor().getExtensions()) {
if (ext instanceof GhprbGlobalDefault) {
Ghprb.addIfMissing(this.extensions, Ghprb.getGlobal(ext.getClass()), ext.getClass());
}
}
}
@DataBoundConstructor
public GhprbTrigger(String adminlist,
String whitelist,
String orgslist,
String cron,
String triggerPhrase,
Boolean onlyTriggerPhrase,
Boolean useGitHubHooks,
Boolean permitAll,
Boolean autoCloseFailedPullRequests,
Boolean displayBuildErrorsOnDownstreamBuilds,
String commentFilePath,
String skipBuildPhrase,
String blackListCommitAuthor,
List<GhprbBranch> whiteListTargetBranches,
List<GhprbBranch> blackListTargetBranches,
Boolean allowMembersOfWhitelistedOrgsAsAdmin,
String msgSuccess,
String msgFailure,
String commitStatusContext,
String gitHubAuthId,
String buildDescTemplate,
String blackListLabels,
String whiteListLabels,
List<GhprbExtension> extensions,
String includedRegions,
String excludedRegions,
Boolean reportSuccessIfNotRegion
) throws ANTLRException {
super(cron);
this.adminlist = adminlist;
this.whitelist = whitelist;
this.orgslist = orgslist;
this.cron = cron;
this.triggerPhrase = triggerPhrase;
this.onlyTriggerPhrase = onlyTriggerPhrase;
this.useGitHubHooks = useGitHubHooks;
this.permitAll = permitAll;
this.autoCloseFailedPullRequests = autoCloseFailedPullRequests;
this.displayBuildErrorsOnDownstreamBuilds = displayBuildErrorsOnDownstreamBuilds;
this.skipBuildPhrase = skipBuildPhrase;
this.blackListCommitAuthor = blackListCommitAuthor;
this.whiteListTargetBranches = whiteListTargetBranches;
this.blackListTargetBranches = blackListTargetBranches;
this.gitHubAuthId = gitHubAuthId;
this.allowMembersOfWhitelistedOrgsAsAdmin = allowMembersOfWhitelistedOrgsAsAdmin;
this.buildDescTemplate = buildDescTemplate;
this.blackListLabels = blackListLabels;
this.whiteListLabels = whiteListLabels;
this.includedRegions = includedRegions;
this.excludedRegions = excludedRegions;
this.reportSuccessIfNotRegion = reportSuccessIfNotRegion;
setExtensions(extensions);
configVersion = LATEST_VERSION;
}
@Override
public Object readResolve() {
convertPropertiesToExtensions();
checkGitHubApiAuth();
return this;
}
@SuppressWarnings("deprecation")
private void checkGitHubApiAuth() {
if (gitHubApiAuth != null) {
gitHubAuthId = gitHubApiAuth.getId();
gitHubApiAuth = null;
}
}
public static DescriptorImpl getDscp() {
return DESCRIPTOR;
}
@SuppressWarnings("deprecation")
private void initState() throws IOException {
final GithubProjectProperty ghpp = super.job.getProperty(GithubProjectProperty.class);
if (ghpp == null || ghpp.getProjectUrl() == null) {
throw new IllegalStateException("A GitHub project url is required.");
}
String baseUrl = ghpp.getProjectUrl().baseUrl();
Matcher m = Ghprb.GITHUB_USER_REPO_PATTERN.matcher(baseUrl);
if (!m.matches()) {
throw new IllegalStateException(String.format("Invalid GitHub project url: %s", baseUrl));
}
final String reponame = m.group(2);
this.repository = new GhprbRepository(reponame, this);
this.repository.load();
Map<Integer, GhprbPullRequest> pulls = this.pullRequests;
this.pullRequests = null;
try {
Map<Integer, GhprbPullRequest> prs = getDescriptor().getPullRequests(super.job.getFullName());
if (prs != null) {
prs = new ConcurrentHashMap<Integer, GhprbPullRequest>(prs);
if (pulls == null) {
pulls = prs;
} else {
pulls.putAll(prs);
}
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Unable to transfer map of pull requests", e);
}
if (pulls != null) {
this.repository.addPullRequests(pulls);
this.repository.save();
}
this.builds = new GhprbBuilds(this, repository);
this.repository.init();
this.ghprbGitHub = new GhprbGitHub(this);
}
/**
* Called when a {@link hudson.triggers.Trigger} is loaded into memory and started.
*
* @param project given so that the persisted form of this object won't have to have a back pointer.
* @param newInstance True if this may be a newly created trigger first attached to the
* {@link hudson.model.Project} (generally if the project is being created or configured).
* False if this is invoked for a {@link hudson.model.Project} loaded from disk.
* @see hudson.model.Items#currentlyUpdatingByXml
*/
@Override
public void start(Job<?, ?> project, boolean newInstance) {
// We should always start the trigger, and handle cases where we don't run in the run function.
super.start(project, newInstance);
String name = project.getFullName();
if (!project.isBuildable()) {
LOGGER.log(Level.FINE, "Project is disabled, not starting trigger for job " + name);
return;
}
if (project.getProperty(GithubProjectProperty.class) == null) {
LOGGER.log(Level.INFO, "GitHub project property is missing the URL, cannot start ghprb trigger for job " + name);
return;
}
try {
initState();
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "Can't start ghprb trigger", ex);
return;
}
LOGGER.log(Level.INFO, "Starting the ghprb trigger for the {0} job; newInstance is {1}",
new String[] {name, String.valueOf(newInstance)});
helper = new Ghprb(this);
if (getUseGitHubHooks()) {
LOGGER.log(Level.FINEST, "Disable registering hooks on startup: {0}",
new String[] {String.valueOf(DISABLE_REGISTER_ON_STARTUP)});
if (GhprbTrigger.getDscp().getManageWebhooks() && (newInstance || !DISABLE_REGISTER_ON_STARTUP)) {
final String[] params = {
String.valueOf(SystemProperties.getInteger(GhprbTrigger.class.getName() + ".poolSize", 5))
};
LOGGER.log(Level.FINEST, "Registering hook with GitHub. Thread pool size: {0}", params);
POOL.submit(new StartHookRunnable(this.repository));
}
DESCRIPTOR.addRepoTrigger(getRepository().getName(), super.job);
}
}
@Override
public void stop() {
String name = super.job != null ? super.job.getFullName() : "NOT STARTED";
LOGGER.log(Level.INFO, "Stopping the ghprb trigger for project {0}", name);
if (this.repository != null) {
String repo = this.repository.getName();
if (!StringUtils.isEmpty(repo)) {
DESCRIPTOR.removeRepoTrigger(repo, super.job);
}
}
super.stop();
}
@Override
public void run() {
// triggers are always triggered on the cron, but we just no-op if we are using GitHub hooks.
if (getUseGitHubHooks()) {
LOGGER.log(Level.FINE, "Use webHooks is set, so not running trigger");
return;
}
if (!isActive()) {
return;
}
LOGGER.log(Level.FINE, "Running trigger for {0}", super.job.getFullName());
this.repository.check();
}
public QueueTaskFuture<?> scheduleBuild(GhprbCause cause, GhprbRepository repo) {
try {
for (GhprbExtension ext : Ghprb.getJobExtensions(this, GhprbBuildStep.class)) {
if (ext instanceof GhprbBuildStep) {
((GhprbBuildStep) ext).onScheduleBuild(super.job, cause);
}
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Unable to execute extentions for scheduleBuild", e);
}
ArrayList<ParameterValue> values = getDefaultParameters();
final String commitSha = cause.isMerged() ? "origin/pr/" + cause.getPullID() + "/merge" : cause.getCommit();
values.add(new StringParameterValue("sha1", commitSha));
values.add(new StringParameterValue("ghprbActualCommit", cause.getCommit()));
String triggerAuthor = "";
String triggerAuthorEmail = "";
String triggerAuthorLogin = "";
GhprbPullRequest pr = getRepository().getPullRequest(cause.getPullID());
String lastBuildId = pr.getLastBuildId();
BuildData buildData = null;
if (!(job instanceof MatrixProject) && !StringUtils.isEmpty(lastBuildId)) {
Run<?, ?> lastBuild = job.getBuild(lastBuildId);
if (lastBuild != null) {
buildData = lastBuild.getAction(BuildData.class);
}
}
try {
triggerAuthor = getString(cause.getTriggerSender().getName(), "");
} catch (Exception e) {
}
try {
triggerAuthorEmail = getString(cause.getTriggerSender().getEmail(), "");
} catch (Exception e) {
}
try {
triggerAuthorLogin = getString(cause.getTriggerSender().getLogin(), "");
} catch (Exception e) {
}
setCommitAuthor(cause, values);
values.add(new StringParameterValue("ghprbAuthorRepoGitUrl", getString(cause.getAuthorRepoGitUrl(), "")));
values.add(new StringParameterValue("ghprbTriggerAuthor", triggerAuthor));
values.add(new StringParameterValue("ghprbTriggerAuthorEmail", triggerAuthorEmail));
values.add(new StringParameterValue("ghprbTriggerAuthorLogin", triggerAuthorLogin));
values.add(new StringParameterValue("ghprbTriggerAuthorLoginMention", !triggerAuthorLogin.isEmpty() ? "@"
+ triggerAuthorLogin : ""));
final StringParameterValue pullIdPv = new StringParameterValue("ghprbPullId", String.valueOf(cause.getPullID()));
values.add(pullIdPv);
values.add(new StringParameterValue("ghprbTargetBranch", String.valueOf(cause.getTargetBranch())));
values.add(new StringParameterValue("ghprbSourceBranch", String.valueOf(cause.getSourceBranch())));
values.add(new StringParameterValue("GIT_BRANCH", String.valueOf(cause.getSourceBranch())));
// it's possible the GHUser doesn't have an associated email address
values.add(new StringParameterValue("ghprbPullAuthorEmail", getString(cause.getAuthorEmail(), "")));
values.add(new StringParameterValue("ghprbPullAuthorLogin", String.valueOf(cause.getPullRequestAuthor().getLogin())));
values.add(new StringParameterValue("ghprbPullAuthorLoginMention", "@" + cause.getPullRequestAuthor().getLogin()));
values.add(new StringParameterValue("ghprbPullDescription", escapeText(String.valueOf(cause.getShortDescription()))));
values.add(new StringParameterValue("ghprbPullTitle", escapeText(String.valueOf(cause.getTitle()))));
values.add(new StringParameterValue("ghprbPullLink", String.valueOf(cause.getUrl())));
values.add(new StringParameterValue("ghprbPullLongDescription", escapeText(String.valueOf(cause.getDescription()))));
values.add(new StringParameterValue("ghprbCommentBody", escapeText(String.valueOf(cause.getCommentBody()))));
values.add(new StringParameterValue("ghprbGhRepository", getString(cause.getRepositoryName(), "")));
values.add(new StringParameterValue("ghprbCredentialsId", getString(cause.getCredentialsId(), "")));
ParameterizedJobMixIn scheduledJob = new ParameterizedJobMixIn() {
@Override
protected Job asJob() {
return job;
}
};
// add the previous pr BuildData as an action so that the correct change log is generated by the GitSCM plugin
// note that this will be removed from the Actions list after the job is completed so that the old (and incorrect)
// one isn't there
return scheduledJob.scheduleBuild2(
Jenkins.getInstance().getQuietPeriod(),
new CauseAction(cause),
new GhprbParametersAction(values),
buildData
);
}
private void setCommitAuthor(GhprbCause cause, ArrayList<ParameterValue> values) {
String authorName = "";
String authorEmail = "";
if (cause.getCommitAuthor() != null) {
authorName = getString(cause.getCommitAuthor().getName(), "");
authorEmail = getString(cause.getCommitAuthor().getEmail(), "");
}
values.add(new StringParameterValue("ghprbActualCommitAuthor", authorName));
values.add(new StringParameterValue("ghprbActualCommitAuthorEmail", authorEmail));
}
private String escapeText(String text) {
return text.replace("\n", "\\n").replace("\r", "\\r").replace("\"", "\\\"");
}
private ArrayList<ParameterValue> getDefaultParameters() {
ArrayList<ParameterValue> values = new ArrayList<ParameterValue>();
ParametersDefinitionProperty pdp = this.job.getProperty(ParametersDefinitionProperty.class);
if (pdp != null) {
for (ParameterDefinition pd : pdp.getParameterDefinitions()) {
values.add(pd.getDefaultParameterValue());
}
}
return values;
}
private String getString(String actual, String d) {
return actual == null ? d : actual;
}
public String getGitHubAuthId() {
return gitHubAuthId == null ? "" : gitHubAuthId;
}
public GhprbGitHubAuth getGitHubApiAuth() {
if (gitHubAuthId == null) {
for (GhprbGitHubAuth auth : getDescriptor().getGithubAuth()) {
gitHubAuthId = auth.getId();
getDescriptor().save();
return auth;
}
}
return getDescriptor().getGitHubAuth(gitHubAuthId);
}
public GitHub getGitHub() throws IOException {
GhprbGitHubAuth auth = getGitHubApiAuth();
return auth.getConnection(getActualProject());
}
public Job<?, ?> getActualProject() {
return super.job;
}
public void addWhitelist(String author) {
whitelist = whitelist + " " + author;
try {
this.job.save();
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Failed to save new whitelist", ex);
}
}
public String getBuildDescTemplate() {
return buildDescTemplate == null ? "" : buildDescTemplate;
}
public String getAdminlist() {
if (adminlist == null) {
return "";
}
return adminlist;
}
public Boolean getAllowMembersOfWhitelistedOrgsAsAdmin() {
return allowMembersOfWhitelistedOrgsAsAdmin != null && allowMembersOfWhitelistedOrgsAsAdmin;
}
public String getWhitelist() {
if (whitelist == null) {
return "";
}
return whitelist;
}
public String getOrgslist() {
if (orgslist == null) {
return "";
}
return orgslist;
}
public String getCron() {
return cron;
}
public String getTriggerPhrase() {
if (triggerPhrase == null) {
return "";
}
return triggerPhrase;
}
public String getSkipBuildPhrase() {
if (StringUtils.isEmpty(skipBuildPhrase)) {
// if it's empty grab the global value
return getDescriptor().getSkipBuildPhrase();
}
return skipBuildPhrase;
}
public String getBlackListCommitAuthor() {
if (StringUtils.isEmpty(blackListCommitAuthor)) {
// if it's empty grab the global value
return getDescriptor().getBlackListCommitAuthor();
}
return blackListCommitAuthor;
}
public String getBlackListLabels() {
if (blackListLabels == null) {
return "";
}
return blackListLabels;
}
public String getWhiteListLabels() {
if (whiteListLabels == null) {
return "";
}
return whiteListLabels;
}
public Boolean getOnlyTriggerPhrase() {
return onlyTriggerPhrase != null && onlyTriggerPhrase;
}
public Boolean getUseGitHubHooks() {
return useGitHubHooks != null && useGitHubHooks;
}
public Ghprb getHelper() {
if (helper == null) {
helper = new Ghprb(this);
}
return helper;
}
public Boolean getPermitAll() {
return permitAll != null && permitAll;
}
public Boolean getAutoCloseFailedPullRequests() {
if (autoCloseFailedPullRequests == null) {
Boolean autoClose = getDescriptor().getAutoCloseFailedPullRequests();
return (autoClose != null && autoClose);
}
return autoCloseFailedPullRequests;
}
public Boolean getDisplayBuildErrorsOnDownstreamBuilds() {
if (displayBuildErrorsOnDownstreamBuilds == null) {
Boolean displayErrors = getDescriptor().getDisplayBuildErrorsOnDownstreamBuilds();
return (displayErrors != null && displayErrors);
}
return displayBuildErrorsOnDownstreamBuilds;
}
private List<GhprbBranch> normalizeTargetBranches(List<GhprbBranch> branches) {
if (branches == null || (branches.size() == 1 && branches.get(0).getBranch().equals(""))) {
return new ArrayList<GhprbBranch>();
} else {
return branches;
}
}
public List<GhprbBranch> getWhiteListTargetBranches() {
return normalizeTargetBranches(whiteListTargetBranches);
}
public List<GhprbBranch> getBlackListTargetBranches() {
return normalizeTargetBranches(blackListTargetBranches);
}
public String getIncludedRegions() {
if (includedRegions == null) {
return "";
}
return includedRegions;
}
public String getExcludedRegions() {
if (excludedRegions == null) {
return "";
}
return excludedRegions;
}
public Boolean getReportSuccessIfNotRegion() {
if (reportSuccessIfNotRegion == null) {
return false;
}
return reportSuccessIfNotRegion;
}
@Override
public DescriptorImpl getDescriptor() {
return DESCRIPTOR;
}
@VisibleForTesting
void setHelper(Ghprb helper) {
this.helper = helper;
}
public GhprbBuilds getBuilds() {
if (this.builds == null && this.isActive()) {
this.builds = new GhprbBuilds(this, getRepository());
}
return this.builds;
}
public GhprbGitHub getGhprbGitHub() {
if (this.ghprbGitHub == null && this.isActive()) {
this.ghprbGitHub = new GhprbGitHub(this);
}
return this.ghprbGitHub;
}
public boolean isActive() {
String name = super.job != null ? super.job.getFullName() : "NOT STARTED";
boolean isActive = true;
if (super.job == null) {
LOGGER.log(Level.FINE, "Project was never set, start was never run");
isActive = false;
} else if (!super.job.isBuildable()) {
LOGGER.log(Level.FINE, "Project is disabled, ignoring trigger run call for job {0}", name);
isActive = false;
} else if (getRepository() == null) {
LOGGER.log(Level.SEVERE, "The ghprb trigger for {0} wasn''t properly started - repository is null", name);
isActive = false;
}
return isActive;
}
public GhprbRepository getRepository() {
if (this.repository == null && super.job != null && super.job.isBuildable()) {
try {
this.initState();
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Unable to init trigger state!", e);
}
}
return this.repository;
}
public String getProjectName() {
String projectName = super.job == null ? "NOT_STARTED" : super.job.getFullName();
return projectName;
}
public boolean matchSignature(String body, String signature) {
if (!isActive()) {
return false;
}
GhprbGitHubAuth auth = getGitHubApiAuth();
return auth == null ? false : auth.checkSignature(body, signature);
}
public void handleComment(IssueComment issueComment) throws IOException {
GhprbRepository repo = getRepository();
LOGGER.log(
Level.INFO,
"Checking comment on PR #{0} for job {1}",
new Object[] {issueComment.getIssue().getNumber(), getProjectName()}
);
repo.onIssueCommentHook(issueComment);
}
public void handlePR(PullRequest pr) throws IOException {
GhprbRepository repo = getRepository();
LOGGER.log(Level.INFO, "Checking PR #{0} for job {1}", new Object[] {pr.getNumber(), getProjectName()});
repo.onPullRequestHook(pr);
}
public static final class DescriptorImpl extends TriggerDescriptor {
// GitHub username may only contain alphanumeric characters or dashes and cannot begin with a dash
private static final Pattern ADMIN_LIST_PATTERN = Pattern.compile("(\\p{Alnum}(-?+\\p{Alnum})*+|\\s)*+");
static final int INITIAL_CAPACITY = 5;
static final int MAX_DESCRIPTION_LENGTH = 50;
static final int DELAY = 5000;
private Integer configVersion;
/**
* These settings only really affect testing. When Jenkins calls configure() then the formdata will
* be used to replace all of these fields. Leaving them here is useful for
* testing, but must not be confused with a default. They also should not be used as the default
* value in the global.jelly file as this value is dynamic and will not be
* retained once configure() is called.
*/
private String whitelistPhrase = ".*add\\W+to\\W+whitelist.*";
private String okToTestPhrase = ".*ok\\W+to\\W+test.*";
private String retestPhrase = ".*test\\W+this\\W+please.*";
private String skipBuildPhrase = ".*\\[skip\\W+ci\\].*";
private String blackListCommitAuthor = "";
private String cron = "H/5 * * * *";
private Boolean useComments = false;
private Boolean useDetailedComments = false;
private Boolean manageWebhooks = true;
private GHCommitState unstableAs = GHCommitState.FAILURE;
private List<GhprbBranch> whiteListTargetBranches;
private List<GhprbBranch> blackListTargetBranches;
private Boolean autoCloseFailedPullRequests = false;
private Boolean displayBuildErrorsOnDownstreamBuilds = false;
private String blackListLabels;
private String whiteListLabels;
private List<GhprbGitHubAuth> githubAuth;
public GhprbGitHubAuth getGitHubAuth(String gitHubAuthId) {
if (gitHubAuthId == null) {
return getGithubAuth().get(0);
}
GhprbGitHubAuth firstAuth = null;
for (GhprbGitHubAuth auth : getGithubAuth()) {
if (firstAuth == null) {
firstAuth = auth;
}
if (auth.getId().equals(gitHubAuthId)) {
return auth;
}
}
return firstAuth;
}
public List<GhprbGitHubAuth> getGithubAuth() {
if (githubAuth == null || githubAuth.size() == 0) {
githubAuth = new ArrayList<GhprbGitHubAuth>(1);
githubAuth.add(new GhprbGitHubAuth(null, null, null, "Anonymous connection", null, null));
}
return githubAuth;
}
public List<GhprbGitHubAuth> getDefaultAuth(List<GhprbGitHubAuth> githubAuth) {
if (githubAuth != null && githubAuth.size() > 0) {
return githubAuth;
}
return getGithubAuth();
}
private String adminlist;
private String requestForTestingPhrase;
// map of jobs (by their fullName) and their map of pull requests
private transient Map<String, Map<Integer, GhprbPullRequest>> jobs;
/**
* map of jobs (by the repo name); No need to keep the projects from shutdown to startup.
* New triggers will register here, and ones that are stopping will remove themselves.
*/
private transient Map<String, Set<Job<?, ?>>> repoJobs;
public List<GhprbExtensionDescriptor> getExtensionDescriptors() {
return GhprbExtensionDescriptor.allProject();
}
public List<GhprbExtensionDescriptor> getGlobalExtensionDescriptors() {
return GhprbExtensionDescriptor.allGlobal();
}
private DescribableList<GhprbExtension, GhprbExtensionDescriptor> extensions;
public DescribableList<GhprbExtension, GhprbExtensionDescriptor> getExtensions() {
if (extensions == null) {
extensions = new DescribableList<GhprbExtension, GhprbExtensionDescriptor>(Saveable.NOOP);
}
return extensions;
}
public DescriptorImpl() {
load();
readBackFromLegacy();
if (repoJobs == null) {
repoJobs = new ConcurrentHashMap<String, Set<Job<?, ?>>>();
}
saveAfterPause();
}
private void saveAfterPause() {
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
save();
}
},
DELAY
);
}
@Override
public boolean isApplicable(Item item) {
return item instanceof Job && item instanceof ParameterizedJobMixIn.ParameterizedJob;
}
@Override
public String getDisplayName() {
return "GitHub Pull Request Builder";
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
adminlist = formData.getString("adminlist");
requestForTestingPhrase = formData.getString("requestForTestingPhrase");
whitelistPhrase = formData.getString("whitelistPhrase");
okToTestPhrase = formData.getString("okToTestPhrase");
retestPhrase = formData.getString("retestPhrase");
skipBuildPhrase = formData.getString("skipBuildPhrase");
blackListCommitAuthor = formData.getString("blackListCommitAuthor");
cron = formData.getString("cron");
useComments = formData.getBoolean("useComments");
useDetailedComments = formData.getBoolean("useDetailedComments");
manageWebhooks = formData.getBoolean("manageWebhooks");
unstableAs = GHCommitState.valueOf(formData.getString("unstableAs"));
autoCloseFailedPullRequests = formData.getBoolean("autoCloseFailedPullRequests");
displayBuildErrorsOnDownstreamBuilds = formData.getBoolean("displayBuildErrorsOnDownstreamBuilds");
blackListLabels = formData.getString("blackListLabels");
whiteListLabels = formData.getString("whiteListLabels");
githubAuth = req.bindJSONToList(GhprbGitHubAuth.class, formData.get("githubAuth"));
extensions = new DescribableList<GhprbExtension, GhprbExtensionDescriptor>(Saveable.NOOP);
try {
extensions.rebuildHetero(req, formData, getGlobalExtensionDescriptors(), "extensions");
Ghprb.addIfMissing(this.extensions, new GhprbSimpleStatus(), GhprbSimpleStatus.class);
} catch (IOException e) {
e.printStackTrace();
}
readBackFromLegacy();
saveAfterPause();
return super.configure(req, formData);
}
public FormValidation doCheckAdminlist(@QueryParameter String value) throws ServletException {
if (!ADMIN_LIST_PATTERN.matcher(value).matches()) {
return FormValidation.error("GitHub username may only contain alphanumeric characters or dashes "
+ "and cannot have multiple consecutive dashes "
+ "and cannot begin or end with a dash. "
+ "Separate them with whitespaces.");
}
return FormValidation.ok();
}
public ListBoxModel doFillUnstableAsItems() {
ListBoxModel items = new ListBoxModel();
GHCommitState[] results = new GHCommitState[] {GHCommitState.SUCCESS, GHCommitState.ERROR, GHCommitState.FAILURE};
for (GHCommitState nextResult : results) {
String text = StringUtils.capitalize(nextResult.toString().toLowerCase());
items.add(text, nextResult.toString());
if (unstableAs.toString().equals(nextResult.toString())) {
items.get(items.size() - 1).selected = true;
}
}
return items;
}
public String getAdminlist() {
return adminlist;
}
public String getRequestForTestingPhrase() {
return requestForTestingPhrase;
}
public String getWhitelistPhrase() {
return whitelistPhrase;
}
public String getOkToTestPhrase() {
return okToTestPhrase;
}
public String getRetestPhrase() {
return retestPhrase;
}
public String getSkipBuildPhrase() {
return skipBuildPhrase;
}
public String getBlackListCommitAuthor() {
return blackListCommitAuthor;
}
public String getCron() {
return cron;
}
public Boolean getUseComments() {