diff --git a/src/main/java/com/cloudbees/jenkins/plugins/bitbucket/impl/notifier/BitbucketBuildStatusNotifications.java b/src/main/java/com/cloudbees/jenkins/plugins/bitbucket/impl/notifier/BitbucketBuildStatusNotifications.java index 04182408a..015e881a4 100644 --- a/src/main/java/com/cloudbees/jenkins/plugins/bitbucket/impl/notifier/BitbucketBuildStatusNotifications.java +++ b/src/main/java/com/cloudbees/jenkins/plugins/bitbucket/impl/notifier/BitbucketBuildStatusNotifications.java @@ -218,29 +218,36 @@ private static void sendNotifications(BitbucketSCMSource source, Run build .filters().stream() .anyMatch(ExcludeOriginPRBranchesSCMHeadFilter.class::isInstance); - String key; - String refName; - BitbucketApi bitbucket; + final String key; + final String refName; + final BitbucketApi bitbucket; if (rev instanceof PullRequestSCMRevision) { listener.getLogger().println("[Bitbucket] Notifying pull request build result"); PullRequestSCMHead head = (PullRequestSCMHead) rev.getHead(); key = getBuildKey(build, head.getOriginName(), shareBuildKeyBetweenBranchAndPR); - /* - * Poor documentation for bitbucket cloud at: - * https://community.atlassian.com/t5/Bitbucket-questions/Re-Builds-not-appearing-in-pull-requests/qaq-p/1805991/comment-id/65864#M65864 - * that means refName null or valued with only head.getBranchName() - * - * For Bitbucket Server, refName should be "refs/heads/" + the name - * of the source branch of the pull request, and the build status - * should be posted to the repository that contains that branch. - * If refName is null, then Bitbucket Server does not show the - * build status in the list of pull requests, but still shows it - * on the web page of the individual pull request. - */ - bitbucket = source.buildBitbucketClient(head); - if (BitbucketApiUtils.isCloud(bitbucket)) { + if (BitbucketApiUtils.isCloud(source.getServerUrl())) { + /* + * Poor documentation for bitbucket cloud at: + * https://community.atlassian.com/t5/Bitbucket-questions/Re-Builds-not-appearing-in-pull-requests/qaq-p/1805991/comment-id/65864#M65864 + * that means refName null or valued with only head.getBranchName() + */ refName = null; + bitbucket = source.buildBitbucketClient(head); } else { + /* + * Head may point to a forked repository that the credentials do + * not have access to, resulting in a 401 error. So we need to + * push build status to the target repository + */ + bitbucket = source.buildBitbucketClient(); + /* + * For Bitbucket Server, refName should be "refs/heads/" + the + * name of the source branch of the pull request, and the build + * status should be posted to the repository that contains that + * branch. If refName is null, then Bitbucket Server does not + * show the build status in the list of pull requests, but still + * shows it on the web page of the individual pull request. + */ refName = "refs/heads/" + head.getBranchName(); } } else {