Page MenuHomePhabricator
Paste P62683

poc_multiple_reviewers.py
ActivePublic

Authored by TheresNoTime on May 20 2024, 11:13 AM.
Tags
None
Referenced Files
F53940609: poc_multiple_reviewers.py
May 20 2024, 11:13 AM
Subscribers
None
import gitlab
import re
"""
Example commit/MR description:
```
A description of the merge request.
Reviewers: @user1, @user2, @user3
Bug: T123456
```
"""
gl = gitlab.Gitlab('https://gitlab.wikimedia.org')
# This regex will match the Reviewers: line in the MR description
reviewers_regex = re.compile(r"Reviewers: ?(?P<reviewers>.*?)\n", re.IGNORECASE)
notication_message = "\n\nYou have been added as a reviewer to this MR. Please review it and provide your feedback."
# I picked a project for testing
project_name = "repos/commtech/wishlist-intake"
project = gl.projects.get(project_name)
# We'd normally get the open MRs like this
mrs = project.mergerequests.list(state='opened', order_by='updated_at')
# But for testing, I just picked a well-known MR ID
mr = project.mergerequests.get(30)
"""
The returned description for MR 30 is:
```
[WIP]\n\n\nReviewers: @samtar, @test\n\nBug: T362275
```
"""
# Extract the reviewers from the MR description
reviewers_match = reviewers_regex.search(mr.description)
if reviewers_match:
reviewers = reviewers_match.group('reviewers').split(',')
users_to_notify = []
for reviewer in reviewers:
# Clean up the reviewer name
reviewer = reviewer.strip()
reviewer = reviewer[1:] if reviewer.startswith('@') else reviewer
user = gl.users.list(username=reviewer)
if len(user) == 1:
user = user[0]
print(f"[:)] User {reviewer} found: ", user.name, user.username, user.id)
# Subscribe the user to the MR
mr.subscribe(user.id)
# Append the user to the list of users to notify
users_to_notify.append("@" + user.username)
else:
print(f"[:(] User {reviewer} not found, or more than one result returned")
if users_to_notify:
# Notify the users
print("\n== Leaving the following message ==\n\n" + ', '.join(users_to_notify) + notication_message)
mr.notes.create({'body': ', '.join(users_to_notify) + notication_message})
"""
The output of running this script is:
```
[:)] User samtar found: Samtar samtar 267
[:(] User test not found, or more than one result returned
== Leaving the following message ==
@samtar
You have been added as a reviewer to this MR. Please review it and provide your feedback.
```
"""