Add Random Reviewers to Pull Request from Group.
As a tech leader, I want to add random reviewers to pull requests from my development team group in order to improve the way of sharing the pull request review between the team members. The reviewers should be added after the pull request has been created.
Custom listener
for the PullRequestOpenedEvent
event by someone with at least global administrator permission.GROUP_NAME
string to set the group name that will be used get the reviewers.PROJECT_KEY
and REPOSITORY_NAME
strings to specify the project and repository that this script will be executed.NUMBER_OF_USERS
integer to set how many reviewers from the group should be added to the pull request.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
import com.atlassian.bitbucket.pull.PullRequestService
import com.atlassian.bitbucket.user.UserService
import com.atlassian.bitbucket.user.ApplicationUser
import com.atlassian.bitbucket.util.PageUtils
import com.atlassian.sal.api.component.ComponentLocator
def final GROUP_NAME = 'dev-reviewer-group'
def final PROJECT_KEY = 'LIBRARY'
def final REPOSITORY_NAME = 'scripts-repository'
def final NUMBER_OF_USERS = 2
def final PAGE_SIZE = 1000
def pullRequestService = ComponentLocator.getComponent(PullRequestService)
def userService = ComponentLocator.getComponent(UserService)
def pullRequest = event.pullRequest
if (pullRequest.toRef.repository.project.key != PROJECT_KEY || pullRequest.toRef.repository.name != REPOSITORY_NAME) {
return
}
def usersFromGroup = PageUtils.toStream({ pageRequest ->
userService.findUsersByGroup(GROUP_NAME, pageRequest)
}, PAGE_SIZE).collect { it as ApplicationUser }
def randomUsersFromGroup = getRandomUsersFromGroup(usersFromGroup, NUMBER_OF_USERS, pullRequest.author.user)
randomUsersFromGroup.each { user ->
pullRequestService.addReviewer(pullRequest.toRef.repository.id, pullRequest.id, user.name)
}
Set<ApplicationUser> getRandomUsersFromGroup (List<ApplicationUser> users, int numberOfUsers, ApplicationUser prUserAuthor) {
def randomUsers = [] as Set<ApplicationUser>
while (randomUsers.size() < numberOfUsers) {
Collections.shuffle(users)
// The PR Author can't be reviewer and to avoid the user being duplicated
if (prUserAuthor != users.first() && !randomUsers.contains(users.first())) {
randomUsers << users.first()
}
}
randomUsers
}