-
Notifications
You must be signed in to change notification settings - Fork 356
/
Copy pathBitbucketSCMSource.java
1679 lines (1528 loc) · 72.5 KB
/
BitbucketSCMSource.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
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
/*
* The MIT License
*
* Copyright (c) 2016-2017, CloudBees, Inc., Nikolas Falco
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.cloudbees.jenkins.plugins.bitbucket;
import com.cloudbees.jenkins.plugins.bitbucket.api.BitbucketApi;
import com.cloudbees.jenkins.plugins.bitbucket.api.BitbucketApiFactory;
import com.cloudbees.jenkins.plugins.bitbucket.api.BitbucketAuthenticator;
import com.cloudbees.jenkins.plugins.bitbucket.api.BitbucketBranch;
import com.cloudbees.jenkins.plugins.bitbucket.api.BitbucketCommit;
import com.cloudbees.jenkins.plugins.bitbucket.api.BitbucketHref;
import com.cloudbees.jenkins.plugins.bitbucket.api.BitbucketMirroredRepository;
import com.cloudbees.jenkins.plugins.bitbucket.api.BitbucketMirroredRepositoryDescriptor;
import com.cloudbees.jenkins.plugins.bitbucket.api.BitbucketProject;
import com.cloudbees.jenkins.plugins.bitbucket.api.BitbucketPullRequest;
import com.cloudbees.jenkins.plugins.bitbucket.api.BitbucketRepository;
import com.cloudbees.jenkins.plugins.bitbucket.api.BitbucketRequestException;
import com.cloudbees.jenkins.plugins.bitbucket.api.BitbucketTeam;
import com.cloudbees.jenkins.plugins.bitbucket.client.BitbucketCloudApiClient;
import com.cloudbees.jenkins.plugins.bitbucket.client.repository.UserRoleInRepository;
import com.cloudbees.jenkins.plugins.bitbucket.endpoints.AbstractBitbucketEndpoint;
import com.cloudbees.jenkins.plugins.bitbucket.endpoints.BitbucketCloudEndpoint;
import com.cloudbees.jenkins.plugins.bitbucket.endpoints.BitbucketEndpointConfiguration;
import com.cloudbees.jenkins.plugins.bitbucket.endpoints.BitbucketServerEndpoint;
import com.cloudbees.jenkins.plugins.bitbucket.hooks.HasPullRequests;
import com.cloudbees.jenkins.plugins.bitbucket.impl.avatars.BitbucketRepoAvatarMetadataAction;
import com.cloudbees.jenkins.plugins.bitbucket.impl.extension.BitbucketEnvVarExtension;
import com.cloudbees.jenkins.plugins.bitbucket.impl.extension.GitClientAuthenticatorExtension;
import com.cloudbees.jenkins.plugins.bitbucket.impl.util.BitbucketApiUtils;
import com.cloudbees.jenkins.plugins.bitbucket.impl.util.BitbucketApiUtils.BitbucketSupplier;
import com.cloudbees.jenkins.plugins.bitbucket.impl.util.BitbucketCredentials;
import com.cloudbees.jenkins.plugins.bitbucket.impl.util.MirrorListSupplier;
import com.cloudbees.jenkins.plugins.bitbucket.impl.util.URLUtils;
import com.cloudbees.jenkins.plugins.bitbucket.server.BitbucketServerWebhookImplementation;
import com.cloudbees.jenkins.plugins.bitbucket.server.client.BitbucketServerAPIClient;
import com.cloudbees.jenkins.plugins.bitbucket.server.client.repository.BitbucketServerRepository;
import com.cloudbees.jenkins.plugins.bitbucket.trait.ShowBitbucketAvatarTrait;
import com.cloudbees.plugins.credentials.CredentialsNameProvider;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import com.damnhandy.uri.template.UriTemplate;
import com.fasterxml.jackson.databind.util.StdDateFormat;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import hudson.RestrictedSince;
import hudson.Util;
import hudson.console.HyperlinkNote;
import hudson.model.Action;
import hudson.model.Actionable;
import hudson.model.Item;
import hudson.model.TaskListener;
import hudson.plugins.git.GitSCM;
import hudson.scm.SCM;
import hudson.security.AccessControlled;
import hudson.util.FormFillFailure;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import java.io.IOException;
import java.io.ObjectStreamException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.authentication.tokens.api.AuthenticationTokens;
import jenkins.model.Jenkins;
import jenkins.plugins.git.AbstractGitSCMSource;
import jenkins.plugins.git.GitTagSCMHead;
import jenkins.plugins.git.traits.GitBrowserSCMSourceTrait;
import jenkins.scm.api.SCMHead;
import jenkins.scm.api.SCMHeadCategory;
import jenkins.scm.api.SCMHeadEvent;
import jenkins.scm.api.SCMHeadObserver;
import jenkins.scm.api.SCMHeadOrigin;
import jenkins.scm.api.SCMRevision;
import jenkins.scm.api.SCMSourceCriteria;
import jenkins.scm.api.SCMSourceCriteria.Probe;
import jenkins.scm.api.SCMSourceDescriptor;
import jenkins.scm.api.SCMSourceEvent;
import jenkins.scm.api.SCMSourceOwner;
import jenkins.scm.api.metadata.ContributorMetadataAction;
import jenkins.scm.api.metadata.ObjectMetadataAction;
import jenkins.scm.api.metadata.PrimaryInstanceMetadataAction;
import jenkins.scm.api.mixin.ChangeRequestCheckoutStrategy;
import jenkins.scm.api.trait.SCMSourceRequest;
import jenkins.scm.api.trait.SCMSourceRequest.IntermediateLambda;
import jenkins.scm.api.trait.SCMSourceTrait;
import jenkins.scm.api.trait.SCMSourceTraitDescriptor;
import jenkins.scm.impl.ChangeRequestSCMHeadCategory;
import jenkins.scm.impl.TagSCMHeadCategory;
import jenkins.scm.impl.UncategorizedSCMHeadCategory;
import jenkins.scm.impl.form.NamedArrayList;
import jenkins.scm.impl.trait.Discovery;
import jenkins.scm.impl.trait.Selection;
import jenkins.scm.impl.trait.WildcardSCMHeadFilterTrait;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jgit.lib.Constants;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.accmod.restrictions.ProtectedExternally;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.interceptor.RequirePOST;
import static com.cloudbees.jenkins.plugins.bitbucket.impl.util.BitbucketApiUtils.getFromBitbucket;
/**
* SCM source implementation for Bitbucket.
*
* It provides a way to discover/retrieve branches and pull requests through the Bitbucket REST API
* which is much faster than the plain Git SCM source implementation.
*/
public class BitbucketSCMSource extends AbstractGitSCMSource {
private static final Logger LOGGER = Logger.getLogger(BitbucketSCMSource.class.getName());
private static final String CLOUD_REPO_TEMPLATE = "{/owner,repo}";
private static final String SERVER_REPO_TEMPLATE = "/projects{/owner}/repos{/repo}";
/** How long to delay events received from Bitbucket in order to allow the API caches to sync. */
private static /*mostly final*/ int eventDelaySeconds =
Math.min(
300,
Math.max(
0, Integer.getInteger(BitbucketSCMSource.class.getName() + ".eventDelaySeconds", 5)));
/**
* Bitbucket URL.
*/
@NonNull
private String serverUrl = BitbucketCloudEndpoint.SERVER_URL;
/**
* Credentials used to access the Bitbucket REST API.
*/
@CheckForNull
private String credentialsId;
/**
* Bitbucket mirror id
*/
@CheckForNull
private String mirrorId;
/**
* Repository owner.
* Used to build the repository URL.
*/
@NonNull
private final String repoOwner;
/**
* Repository name.
* Used to build the repository URL.
*/
@NonNull
private final String repository;
/**
* The behaviours to apply to this source.
*/
@NonNull
private List<SCMSourceTrait> traits;
/**
* Credentials used to clone the repository/repositories.
*/
@Deprecated
@Restricted(NoExternalUse.class)
@RestrictedSince("2.2.0")
private transient String checkoutCredentialsId;
/**
* Ant match expression that indicates what branches to include in the retrieve process.
*/
@Deprecated
@Restricted(NoExternalUse.class)
@RestrictedSince("2.2.0")
private transient String includes;
/**
* Ant match expression that indicates what branches to exclude in the retrieve process.
*/
@Deprecated
@Restricted(NoExternalUse.class)
@RestrictedSince("2.2.0")
private transient String excludes;
/**
* If true, a webhook will be auto-registered in the repository managed by this source.
*/
@Deprecated
@Restricted(NoExternalUse.class)
@RestrictedSince("2.2.0")
private transient boolean autoRegisterHook;
/**
* Bitbucket Server URL.
* A specific HTTP client is used if this field is not null.
* This value (or serverUrl if this is null) is used in particular
* to find the current endpoint configuration for this server.
*/
@Deprecated
@Restricted(NoExternalUse.class)
@RestrictedSince("2.2.0")
private transient String bitbucketServerUrl;
/**
* The cache of pull request titles for each open PR.
*/
@CheckForNull
private transient /*effectively final*/ Map<String, String> pullRequestTitleCache;
/**
* The cache of pull request contributors for each open PR.
*/
@CheckForNull
private transient /*effectively final*/ Map<String, ContributorMetadataAction> pullRequestContributorCache;
/**
* The cache of the primary clone links.
*/
@CheckForNull
private transient List<BitbucketHref> primaryCloneLinks = null;
/**
* The cache of the mirror clone links.
*/
@CheckForNull
private transient List<BitbucketHref> mirrorCloneLinks = null;
/**
* Constructor.
*
* @param repoOwner the repository owner.
* @param repository the repository name.
* @since 2.2.0
*/
@DataBoundConstructor
public BitbucketSCMSource(@NonNull String repoOwner, @NonNull String repository) {
this.serverUrl = BitbucketCloudEndpoint.SERVER_URL;
this.repoOwner = repoOwner;
this.repository = repository;
this.traits = new ArrayList<>();
}
/**
* Legacy Constructor.
*
* @param id the id.
* @param repoOwner the repository owner.
* @param repository the repository name.
* @deprecated use {@link #BitbucketSCMSource(String, String)} and {@link #setId(String)}
*/
@Deprecated
public BitbucketSCMSource(@CheckForNull String id, @NonNull String repoOwner, @NonNull String repository) {
this(repoOwner, repository);
setId(id);
traits.add(new BranchDiscoveryTrait(true, true));
traits.add(new OriginPullRequestDiscoveryTrait(EnumSet.of(ChangeRequestCheckoutStrategy.MERGE)));
traits.add(new ForkPullRequestDiscoveryTrait(EnumSet.of(ChangeRequestCheckoutStrategy.MERGE),
new ForkPullRequestDiscoveryTrait.TrustTeamForks()));
}
/**
* Migrate legacy serialization formats.
*
* @return {@code this}
* @throws ObjectStreamException if things go wrong.
*/
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE",
justification = "Only non-null after we set them here!")
private Object readResolve() throws ObjectStreamException {
if (serverUrl == null) {
serverUrl = BitbucketEndpointConfiguration.get().readResolveServerUrl(bitbucketServerUrl);
}
if (serverUrl == null) {
LOGGER.log(Level.WARNING, "BitbucketSCMSource::readResolve : serverUrl is still empty");
}
if (traits == null) {
traits = new ArrayList<>();
if (!"*".equals(includes) || !"".equals(excludes)) {
traits.add(new WildcardSCMHeadFilterTrait(includes, excludes));
}
if (checkoutCredentialsId != null
&& !DescriptorImpl.SAME.equals(checkoutCredentialsId)
&& !checkoutCredentialsId.equals(credentialsId)) {
traits.add(new SSHCheckoutTrait(checkoutCredentialsId));
}
traits.add(new WebhookRegistrationTrait(
autoRegisterHook ? WebhookRegistration.ITEM : WebhookRegistration.DISABLE)
);
traits.add(new BranchDiscoveryTrait(true, true));
traits.add(new OriginPullRequestDiscoveryTrait(EnumSet.of(ChangeRequestCheckoutStrategy.HEAD)));
traits.add(new ForkPullRequestDiscoveryTrait(EnumSet.of(ChangeRequestCheckoutStrategy.HEAD),
new ForkPullRequestDiscoveryTrait.TrustEveryone()));
traits.add(new PublicRepoPullRequestFilterTrait());
}
return this;
}
@CheckForNull
public String getCredentialsId() {
return credentialsId;
}
@Override
public String getRemote() {
initCloneLinks();
return BitbucketGitSCMHelper.getCloneLink(this, primaryCloneLinks, mirrorCloneLinks);
}
@DataBoundSetter
public void setCredentialsId(@CheckForNull String credentialsId) {
this.credentialsId = Util.fixEmpty(credentialsId);
}
public String getMirrorId() {
return mirrorId;
}
@DataBoundSetter
public void setMirrorId(String mirrorId) {
this.mirrorId = Util.fixEmpty(mirrorId);
}
@NonNull
public String getRepoOwner() {
return repoOwner;
}
@NonNull
public String getRepository() {
return repository;
}
@NonNull
public String getServerUrl() {
return serverUrl;
}
@DataBoundSetter
public void setServerUrl(@CheckForNull String serverUrl) {
String url = BitbucketEndpointConfiguration.normalizeServerUrl(serverUrl);
if (url == null) {
url = BitbucketEndpointConfiguration.get().getDefaultEndpoint().getServerUrl();
}
this.serverUrl = url;
}
@NonNull
public String getEndpointJenkinsRootURL() {
return AbstractBitbucketEndpoint.getEndpointJenkinsRootUrl(serverUrl);
}
@Override
@NonNull
public List<SCMSourceTrait> getTraits() {
return Collections.unmodifiableList(traits);
}
@Override
@DataBoundSetter
public void setTraits(@CheckForNull List<SCMSourceTrait> traits) {
this.traits = new ArrayList<>(Util.fixNull(traits));
}
@Deprecated
@Restricted(NoExternalUse.class)
@RestrictedSince("2.2.0")
@DataBoundSetter
public void setBitbucketServerUrl(String url) {
url = BitbucketEndpointConfiguration.normalizeServerUrl(url);
url = StringUtils.defaultIfBlank(url, BitbucketCloudEndpoint.SERVER_URL);
AbstractBitbucketEndpoint endpoint = BitbucketEndpointConfiguration.get()
.findEndpoint(url)
.orElse(null);
if (endpoint != null) {
// we have a match
setServerUrl(endpoint.getServerUrl());
} else {
LOGGER.log(Level.WARNING, "Call to legacy setBitbucketServerUrl({0}) method is configuring a url missing "
+ "from the global configuration.", url);
setServerUrl(url);
}
}
@Deprecated
@Restricted(NoExternalUse.class)
@RestrictedSince("2.2.0")
@CheckForNull
public String getBitbucketServerUrl() {
String serverUrl = getServerUrl();
if (BitbucketEndpointConfiguration.get()
.findEndpoint(serverUrl)
.filter(BitbucketCloudEndpoint.class::isInstance)
.isPresent()) {
return null;
}
return serverUrl;
}
@Deprecated
@Restricted(NoExternalUse.class)
@RestrictedSince("2.2.0")
@CheckForNull
public String getCheckoutCredentialsId() {
for (SCMSourceTrait t : traits) {
if (t instanceof SSHCheckoutTrait sshTrait) {
return StringUtils.defaultString(sshTrait.getCredentialsId(), DescriptorImpl.ANONYMOUS);
}
}
return DescriptorImpl.SAME;
}
@Deprecated
@Restricted(NoExternalUse.class)
@RestrictedSince("2.2.0")
@DataBoundSetter
public void setCheckoutCredentialsId(String checkoutCredentialsId) {
traits.removeIf(trait -> trait instanceof SSHCheckoutTrait);
if (checkoutCredentialsId != null && !DescriptorImpl.SAME.equals(checkoutCredentialsId)) {
traits.add(new SSHCheckoutTrait(checkoutCredentialsId));
}
}
@Deprecated
@Restricted(NoExternalUse.class)
@RestrictedSince("2.2.0")
@NonNull
public String getIncludes() {
for (SCMSourceTrait trait : traits) {
if (trait instanceof WildcardSCMHeadFilterTrait wildcardTrait) {
return wildcardTrait.getIncludes();
}
}
return "*";
}
@Deprecated
@Restricted(NoExternalUse.class)
@RestrictedSince("2.2.0")
@DataBoundSetter
public void setIncludes(@NonNull String includes) {
for (int i = 0; i < traits.size(); i++) {
SCMSourceTrait trait = traits.get(i);
if (trait instanceof WildcardSCMHeadFilterTrait) {
WildcardSCMHeadFilterTrait existing = (WildcardSCMHeadFilterTrait) trait;
if ("*".equals(includes) && "".equals(existing.getExcludes())) {
traits.remove(i);
} else {
traits.set(i, new WildcardSCMHeadFilterTrait(includes, existing.getExcludes()));
}
return;
}
}
if (!"*".equals(includes)) {
traits.add(new WildcardSCMHeadFilterTrait(includes, ""));
}
}
@Deprecated
@Restricted(NoExternalUse.class)
@RestrictedSince("2.2.0")
@NonNull
public String getExcludes() {
for (SCMSourceTrait trait : traits) {
if (trait instanceof WildcardSCMHeadFilterTrait) {
return ((WildcardSCMHeadFilterTrait) trait).getExcludes();
}
}
return "";
}
@Deprecated
@Restricted(NoExternalUse.class)
@RestrictedSince("2.2.0")
@DataBoundSetter
public void setExcludes(@NonNull String excludes) {
for (int i = 0; i < traits.size(); i++) {
SCMSourceTrait trait = traits.get(i);
if (trait instanceof WildcardSCMHeadFilterTrait) {
WildcardSCMHeadFilterTrait existing = (WildcardSCMHeadFilterTrait) trait;
if ("*".equals(existing.getIncludes()) && "".equals(excludes)) {
traits.remove(i);
} else {
traits.set(i, new WildcardSCMHeadFilterTrait(existing.getIncludes(), excludes));
}
return;
}
}
if (!"".equals(excludes)) {
traits.add(new WildcardSCMHeadFilterTrait("*", excludes));
}
}
@Deprecated
@Restricted(NoExternalUse.class)
@RestrictedSince("2.2.0")
@DataBoundSetter
public void setAutoRegisterHook(boolean autoRegisterHook) {
traits.removeIf(trait -> trait instanceof WebhookRegistrationTrait);
traits.add(new WebhookRegistrationTrait(
autoRegisterHook ? WebhookRegistration.ITEM : WebhookRegistration.DISABLE
));
}
@Deprecated
@Restricted(NoExternalUse.class)
@RestrictedSince("2.2.0")
public boolean isAutoRegisterHook() {
for (SCMSourceTrait t : traits) {
if (t instanceof WebhookRegistrationTrait) {
return ((WebhookRegistrationTrait) t).getMode() != WebhookRegistration.DISABLE;
}
}
return true;
}
public BitbucketApi buildBitbucketClient() {
return buildBitbucketClient(repoOwner, repository);
}
public BitbucketApi buildBitbucketClient(PullRequestSCMHead head) {
return buildBitbucketClient(head.getRepoOwner(), head.getRepository());
}
public BitbucketApi buildBitbucketClient(String repoOwner, String repository) {
return BitbucketApiFactory.newInstance(getServerUrl(), authenticator(), repoOwner, null, repository);
}
@Override
public void afterSave() {
try {
gatherPrimaryCloneLinks(buildBitbucketClient());
} catch (InterruptedException | IOException e) {
LOGGER.log(Level.SEVERE,
"Could not determine clone links of " + getRepoOwner() + "/" + getRepository() +
" on " + getServerUrl() + " for " + getOwner() + " falling back to generated links", e);
}
}
private void gatherPrimaryCloneLinks(@NonNull BitbucketApi apiClient) throws IOException, InterruptedException {
BitbucketRepository r = apiClient.getRepository();
Map<String, List<BitbucketHref>> links = r.getLinks();
if (links != null && links.containsKey("clone")) {
setPrimaryCloneLinks(links.get("clone"));
}
}
@Override
protected void retrieve(@CheckForNull SCMSourceCriteria criteria, @NonNull SCMHeadObserver observer,
@CheckForNull SCMHeadEvent<?> event, @NonNull TaskListener listener)
throws IOException, InterruptedException {
try (BitbucketSCMSourceRequest request = new BitbucketSCMSourceContext(criteria, observer)
.withTraits(traits)
.newRequest(this, listener)) {
StandardCredentials scanCredentials = credentials();
if (scanCredentials == null) {
listener.getLogger().format("Connecting to %s with no credentials, anonymous access%n", getServerUrl());
} else {
listener.getLogger().format("Connecting to %s using %s%n", getServerUrl(),
CredentialsNameProvider.name(scanCredentials));
}
BitbucketApi apiClient = buildBitbucketClient();
gatherPrimaryCloneLinks(apiClient);
// populate the request with its data sources
if (request.isFetchPRs()) {
request.setPullRequests(new LazyIterable<BitbucketPullRequest>() {
@Override
protected Iterable<BitbucketPullRequest> create() {
try {
if (event instanceof HasPullRequests hasPrEvent) {
return getBitbucketPullRequestsFromEvent(hasPrEvent, listener);
}
return (Iterable<BitbucketPullRequest>) apiClient.getPullRequests();
} catch (IOException | InterruptedException e) {
throw new BitbucketSCMSource.WrappedException(e);
}
}
});
}
if (request.isFetchBranches()) {
request.setBranches(new LazyIterable<BitbucketBranch>() {
@Override
protected Iterable<BitbucketBranch> create() {
try {
return (Iterable<BitbucketBranch>) apiClient.getBranches();
} catch (IOException | InterruptedException e) {
throw new BitbucketSCMSource.WrappedException(e);
}
}
});
}
if (request.isFetchTags()) {
request.setTags(new LazyIterable<BitbucketBranch>() {
@Override
protected Iterable<BitbucketBranch> create() {
try {
return (Iterable<BitbucketBranch>) apiClient.getTags();
} catch (IOException | InterruptedException e) {
throw new BitbucketSCMSource.WrappedException(e);
}
}
});
}
// now server the request
if (request.isFetchBranches() && !request.isComplete()) {
// Search branches
retrieveBranches(request);
}
if (request.isFetchPRs() && !request.isComplete()) {
// Search pull requests
retrievePullRequests(request);
}
if (request.isFetchTags() && !request.isComplete()) {
// Search tags
retrieveTags(request);
}
} catch (WrappedException e) {
e.unwrap();
}
}
private Iterable<BitbucketPullRequest> getBitbucketPullRequestsFromEvent(@NonNull HasPullRequests incomingPrEvent, @NonNull TaskListener listener) {
BitbucketApi bitBucket = buildBitbucketClient();
Collection<BitbucketPullRequest> initializedPRs = new HashSet<>();
try {
Iterable<BitbucketPullRequest> pullRequests =
incomingPrEvent.getPullRequests(BitbucketSCMSource.this);
for (BitbucketPullRequest pr : pullRequests) {
// ensure that the PR is properly initialized via /changes API
// see BitbucketServerAPIClient.setupPullRequest()
initializedPRs.add(bitBucket.getPullRequestById(Integer.parseInt(pr.getId())));
listener.getLogger().format("Initialized PR: %s%n", pr.getLink());
}
} catch (IOException | InterruptedException e) {
throw new BitbucketSCMSource.WrappedException(e);
}
return initializedPRs;
}
private void retrievePullRequests(final BitbucketSCMSourceRequest request) throws IOException, InterruptedException {
final String fullName = repoOwner + "/" + repository;
class Skip extends IOException {
}
final BitbucketApi originBitbucket = buildBitbucketClient();
if (request.isSkipPublicPRs() && !originBitbucket.isPrivate()) {
request.listener().getLogger().printf("Skipping pull requests for %s (public repository)%n", fullName);
return;
}
request.listener().getLogger().printf("Looking up %s for pull requests%n", fullName);
final Set<String> livePRs = new HashSet<>();
int count = 0;
Map<Boolean, Set<ChangeRequestCheckoutStrategy>> strategies = request.getPRStrategies();
for (final BitbucketPullRequest pull : request.getPullRequests()) {
String originalBranchName = pull.getSource().getBranch().getName();
request.listener().getLogger().printf(
"Checking PR-%s from %s and branch %s%n",
pull.getId(),
pull.getSource().getRepository().getFullName(),
originalBranchName
);
boolean fork = !StringUtils.equalsIgnoreCase(fullName, pull.getSource().getRepository().getFullName());
String pullRepoOwner = pull.getSource().getRepository().getOwnerName();
String pullRepository = pull.getSource().getRepository().getRepositoryName();
final BitbucketApi client = fork && BitbucketApiUtils.isCloud(originBitbucket)
? BitbucketApiFactory.newInstance(
getServerUrl(),
authenticator(),
pullRepoOwner,
null,
pullRepository
)
: originBitbucket;
count++;
livePRs.add(pull.getId());
getPullRequestTitleCache()
.put(pull.getId(), StringUtils.defaultString(pull.getTitle()));
getPullRequestContributorCache().put(pull.getId(),
new ContributorMetadataAction(pull.getAuthorIdentifier(), pull.getAuthorLogin(), pull.getAuthorEmail()));
try {
// We store resolved hashes here so to avoid resolving the commits multiple times
for (final ChangeRequestCheckoutStrategy strategy : strategies.get(fork)) {
String branchName = "PR-" + pull.getId();
if (strategies.get(fork).size() > 1) {
branchName = "PR-" + pull.getId() + "-" + strategy.name().toLowerCase(Locale.ENGLISH);
}
PullRequestSCMHead head = new PullRequestSCMHead( //
branchName, //
pullRepoOwner, //
pullRepository, //
originalBranchName, //
pull, //
originOf(pullRepoOwner, pullRepository), //
strategy
);
if (request.process(head, //
() -> {
// use branch instead of commit to postpone closure initialisation
return new BranchHeadCommit(pull.getSource().getBranch());
}, //
new BitbucketProbeFactory<>(client, request), //
new BitbucketRevisionFactory<BitbucketCommit>(client) {
@NonNull
@Override
public SCMRevision create(@NonNull SCMHead head, @Nullable BitbucketCommit sourceCommit)
throws IOException, InterruptedException {
try {
// use branch instead of commit to postpone closure initialisation
BranchHeadCommit targetCommit = new BranchHeadCommit(pull.getDestination().getBranch());
return super.create(head, sourceCommit, targetCommit);
} catch (BitbucketRequestException e) {
if (originBitbucket instanceof BitbucketCloudApiClient) {
if (e.getHttpCode() == 403) {
request.listener().getLogger().printf( //
"Skipping %s because of %s%n", //
pull.getId(), //
HyperlinkNote.encodeTo("https://bitbucket.org/site/master" //
+ "/issues/5814/reify-pull-requests-by-making-them-a-ref", //
"a permission issue accessing pull requests from forks"));
throw new Skip();
}
}
// https://bitbucket.org/site/master/issues/5814/reify-pull-requests-by-making-them-a-ref
e.printStackTrace(request.listener().getLogger());
if (e.getHttpCode() == 403) {
// the credentials do not have permission, so we should not observe the
// PR ever the PR is dead to us, so this is the one case where we can
// squash the exception.
throw new Skip();
}
throw e;
}
}
}, //
new CriteriaWitness(request))) {
request.listener().getLogger() //
.format("%n %d pull requests were processed (query completed)%n", count);
return;
}
}
} catch (Skip e) {
request.listener().getLogger().println(
"Do not have permission to view PR from " + pull.getSource().getRepository()
.getFullName()
+ " and branch "
+ originalBranchName);
continue;
}
}
request.listener().getLogger().format("%n %d pull requests were processed%n", count);
getPullRequestTitleCache().keySet().retainAll(livePRs);
getPullRequestContributorCache().keySet().retainAll(livePRs);
}
private void retrieveBranches(final BitbucketSCMSourceRequest request)
throws IOException, InterruptedException {
String fullName = repoOwner + "/" + repository;
request.listener().getLogger().println("Looking up " + fullName + " for branches");
final BitbucketApi bitbucket = buildBitbucketClient();
int count = 0;
for (final BitbucketBranch branch : request.getBranches()) {
request.listener().getLogger().println("Checking branch " + branch.getName() + " from " + fullName);
count++;
if (request.process(new BranchSCMHead(branch.getName()), //
(IntermediateLambda<BitbucketCommit>) () -> new BranchHeadCommit(branch), //
new BitbucketProbeFactory<>(bitbucket, request), //
new BitbucketRevisionFactory<>(bitbucket), //
new CriteriaWitness(request))) {
request.listener().getLogger().format("%n %d branches were processed (query completed)%n", count);
return;
}
}
request.listener().getLogger().format("%n %d branches were processed%n", count);
}
private void retrieveTags(final BitbucketSCMSourceRequest request) throws IOException, InterruptedException {
String fullName = repoOwner + "/" + repository;
request.listener().getLogger().println("Looking up " + fullName + " for tags");
final BitbucketApi bitbucket = buildBitbucketClient();
int count = 0;
for (final BitbucketBranch tag : request.getTags()) {
request.listener().getLogger().println("Checking tag " + tag.getName() + " from " + fullName);
count++;
if (request.process(new BitbucketTagSCMHead(tag.getName(), tag.getDateMillis()), //
tag::getRawNode, //
new BitbucketProbeFactory<>(bitbucket, request), //
new BitbucketRevisionFactory<>(bitbucket), //
new CriteriaWitness(request))) {
request.listener().getLogger().format("%n %d tags were processed (query completed)%n", count);
return;
}
}
request.listener().getLogger().format("%n %d tags were processed%n", count);
}
@Override
protected SCMRevision retrieve(SCMHead head, TaskListener listener) throws IOException, InterruptedException {
final BitbucketApi bitbucket = buildBitbucketClient();
try {
if (head instanceof PullRequestSCMHead prHead) {
BitbucketCommit sourceRevision;
BitbucketCommit targetRevision;
if (bitbucket instanceof BitbucketCloudApiClient) {
// Bitbucket Cloud /pullrequests/{id} API endpoint only returns short commit IDs of the source
// and target branch. We therefore retrieve the branches directly
BitbucketBranch targetBranch = bitbucket.getBranch(prHead.getTarget().getName());
if(targetBranch == null) {
listener.getLogger().format("No branch found in {0}/{1} with name [{2}]",
repoOwner, repository, prHead.getTarget().getName());
return null;
}
targetRevision = findCommit(targetBranch, listener);
if (targetRevision == null) {
listener.getLogger().format("No branch found in {0}/{1} with name [{2}]",
repoOwner, repository, prHead.getTarget().getName());
return null;
}
// Retrieve the source branch commit
BitbucketBranch branch;
if (head.getOrigin() == SCMHeadOrigin.DEFAULT) {
branch = bitbucket.getBranch(prHead.getBranchName());
} else {
// In case of a forked branch, retrieve the branch as that owner
branch = buildBitbucketClient(prHead).getBranch(prHead.getBranchName());
}
if(branch == null) {
listener.getLogger().format("No branch found in {0}/{1} with name [{2}]",
repoOwner, repository, head.getName());
return null;
}
sourceRevision = findCommit(branch, listener);
} else {
BitbucketPullRequest pr;
try {
pr = bitbucket.getPullRequestById(Integer.parseInt(prHead.getId()));
} catch (NumberFormatException nfe) {
LOGGER.log(Level.WARNING, "Cannot parse the PR id {0}", prHead.getId());
return null;
}
targetRevision = findPRDestinationCommit(pr, listener);
if (targetRevision == null) {
listener.getLogger().format("No branch found in {0}/{1} with name [{2}]",
repoOwner, repository, prHead.getTarget().getName());
return null;
}
sourceRevision = findPRSourceCommit(pr, listener);
}
if (sourceRevision == null) {
listener.getLogger().format("No revision found in {0}/{1} for PR-{2} [{3}]",
prHead.getRepoOwner(),
prHead.getRepository(),
prHead.getId(),
prHead.getBranchName());
return null;
}
return new PullRequestSCMRevision(
prHead,
new BitbucketGitSCMRevision(prHead.getTarget(), targetRevision),
new BitbucketGitSCMRevision(prHead, sourceRevision)
);
} else if (head instanceof BitbucketTagSCMHead tagHead) {
BitbucketBranch tag = bitbucket.getTag(tagHead.getName());
if(tag == null) {
listener.getLogger().format( "No tag found in {0}/{1} with name [{2}]",
repoOwner, repository, head.getName());
return null;
}
BitbucketCommit revision = findCommit(tag, listener);
if (revision == null) {
listener.getLogger().format( "No revision found in {0}/{1} with name [{2}]",
repoOwner, repository, head.getName());
return null;
}
return new BitbucketTagSCMRevision(tagHead, revision);
} else {
BitbucketBranch branch = bitbucket.getBranch(head.getName());
if(branch == null) {
listener.getLogger().format("No branch found in {0}/{1} with name [{2}]",
repoOwner, repository, head.getName());
return null;
}
BitbucketCommit revision = findCommit(branch, listener);
if (revision == null) {
listener.getLogger().format("No revision found in {0}/{1} with name [{2}]",
repoOwner, repository, head.getName());
return null;
}
return new BitbucketGitSCMRevision(head, revision);
}
} catch (IOException e) {
// here we only want to display the job name to have it in the log
if (e instanceof BitbucketRequestException bre) {
SCMSourceOwner scmSourceOwner = getOwner();
if (bre.getHttpCode() == 401 && scmSourceOwner != null) {
LOGGER.log(Level.WARNING, "BitbucketRequestException: Authz error. Status: 401 for Item '{0}' using credentialId '{1}'",
new Object[]{scmSourceOwner.getFullDisplayName(), getCredentialsId()});
}
}
throw e;
}
}
private BitbucketCommit findCommit(@NonNull BitbucketBranch branch, TaskListener listener) {
String revision = branch.getRawNode();
if (revision == null) {
if (BitbucketCloudEndpoint.SERVER_URL.equals(getServerUrl())) {
listener.getLogger().format("Cannot resolve the hash of the revision in branch %s%n",
branch.getName());
} else {
listener.getLogger().format("Cannot resolve the hash of the revision in branch %s. "
+ "Perhaps you are using Bitbucket Server previous to 4.x%n",
branch.getName());
}
return null;
}
return new BranchHeadCommit(branch);
}
private BitbucketCommit findPRSourceCommit(BitbucketPullRequest pr, TaskListener listener) {
// if I use getCommit() the branch closure is trigger immediately
BitbucketBranch branch = pr.getSource().getBranch();
String hash = branch.getRawNode();
if (hash == null) {
if (BitbucketCloudEndpoint.SERVER_URL.equals(getServerUrl())) {
listener.getLogger().format("Cannot resolve the hash of the revision in PR-%s%n",
pr.getId());
} else {
listener.getLogger().format("Cannot resolve the hash of the revision in PR-%s. "
+ "Perhaps you are using Bitbucket Server previous to 4.x%n",
pr.getId());
}
return null;
}
return new BranchHeadCommit(branch);
}
private BitbucketCommit findPRDestinationCommit(BitbucketPullRequest pr, TaskListener listener) {
// if I use getCommit() the branch closure is trigger immediately
BitbucketBranch branch = pr.getDestination().getBranch();
String hash = branch.getRawNode();
if (hash == null) {
if (BitbucketCloudEndpoint.SERVER_URL.equals(getServerUrl())) {
listener.getLogger().format("Cannot resolve the hash of the revision in PR-%s%n",
pr.getId());
} else {