Skip to content

Commit 97110e7

Browse files
committed
Add automated PR reviewer rotation system
- Add GitHub Action workflow for automatic reviewer assignment - Create Python script that reads reviewers from MAINTAINERS.md - Implement 3-week sprint-based rotation cycle - Preserve existing reviewer assignments (manual/GitHub auto) - Add configuration for start date and rotation cycle
1 parent 06a643c commit 97110e7

File tree

3 files changed

+266
-0
lines changed

3 files changed

+266
-0
lines changed

.github/auto-review-config.yml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Auto-reviewer configuration
2+
# Start date for the rotation cycle (YYYY-MM-DD format)
3+
start_date: "2025-08-04"
4+
5+
# Rotation cycle in weeks
6+
rotation_cycle_weeks: 3

.github/scripts/assign_reviewer.py

Lines changed: 227 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,227 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Auto-reviewer assignment script for GitHub PRs.
4+
Rotates through a list of reviewers based on a weekly cycle.
5+
Automatically reads reviewers from MAINTAINERS.md
6+
"""
7+
8+
import os
9+
import sys
10+
import yaml
11+
import subprocess
12+
import re
13+
from datetime import datetime
14+
from typing import List, Optional
15+
16+
17+
def load_config(config_path: str) -> dict:
18+
"""Load the reviewer configuration from YAML file."""
19+
try:
20+
with open(config_path, 'r') as f:
21+
return yaml.safe_load(f)
22+
except FileNotFoundError:
23+
print(f"Error: Configuration file {config_path} not found")
24+
sys.exit(1)
25+
except yaml.YAMLError as e:
26+
print(f"Error parsing YAML configuration: {e}")
27+
sys.exit(1)
28+
29+
30+
def extract_reviewers_from_maintainers() -> List[str]:
31+
"""Extract GitHub usernames from MAINTAINERS.md file."""
32+
maintainers_path = 'MAINTAINERS.md'
33+
reviewers = []
34+
35+
try:
36+
with open(maintainers_path, 'r') as f:
37+
content = f.read()
38+
39+
# Look for GitHub usernames in the format [username](https://github.com/...)
40+
# This regex matches the GitHub ID column in the maintainers table
41+
pattern = r'\[([^\]]+)\]\(https://github\.com/[^)]+\)'
42+
matches = re.findall(pattern, content)
43+
44+
if matches:
45+
reviewers = matches
46+
print(f"Found {len(reviewers)} reviewers from MAINTAINERS.md: {', '.join(reviewers)}")
47+
else:
48+
print("Warning: No GitHub usernames found in MAINTAINERS.md")
49+
50+
except FileNotFoundError:
51+
print(f"Error: MAINTAINERS.md file not found")
52+
sys.exit(1)
53+
except Exception as e:
54+
print(f"Error reading MAINTAINERS.md: {e}")
55+
sys.exit(1)
56+
57+
return reviewers
58+
59+
60+
def calculate_rotation_info(config: dict) -> dict:
61+
"""Calculate rotation information from config (helper function)."""
62+
start_date_str = config.get('start_date')
63+
rotation_cycle_weeks = config.get('rotation_cycle_weeks', 3)
64+
65+
if not start_date_str:
66+
return {
67+
"start_date": None,
68+
"rotation_cycle_weeks": rotation_cycle_weeks,
69+
"weeks_since_start": 0,
70+
"before_start": False,
71+
"error": "No start_date configured"
72+
}
73+
74+
try:
75+
start_date = datetime.strptime(start_date_str, "%Y-%m-%d")
76+
current_date = datetime.now()
77+
weeks_since_start = (current_date - start_date).days / 7
78+
79+
return {
80+
"start_date": start_date,
81+
"rotation_cycle_weeks": rotation_cycle_weeks,
82+
"weeks_since_start": weeks_since_start,
83+
"before_start": weeks_since_start < 0,
84+
"error": None
85+
}
86+
except ValueError:
87+
return {
88+
"start_date": None,
89+
"rotation_cycle_weeks": rotation_cycle_weeks,
90+
"weeks_since_start": 0,
91+
"before_start": False,
92+
"error": f"Invalid start_date format: {start_date_str}"
93+
}
94+
95+
96+
def get_current_sprint_info(config: dict) -> dict:
97+
"""Calculate current sprint information."""
98+
rotation_info = calculate_rotation_info(config)
99+
100+
if rotation_info["error"]:
101+
return {"sprint_number": 1, "week_in_sprint": 1}
102+
103+
if rotation_info["before_start"]:
104+
return {
105+
"sprint_number": 1,
106+
"week_in_sprint": 1,
107+
"total_weeks": 0,
108+
"before_start": True
109+
}
110+
111+
weeks_since_start = rotation_info["weeks_since_start"]
112+
rotation_cycle_weeks = rotation_info["rotation_cycle_weeks"]
113+
114+
sprint_number = int(weeks_since_start // rotation_cycle_weeks) + 1
115+
week_in_sprint = int(weeks_since_start % rotation_cycle_weeks) + 1
116+
117+
return {
118+
"sprint_number": sprint_number,
119+
"week_in_sprint": week_in_sprint,
120+
"total_weeks": int(weeks_since_start)
121+
}
122+
123+
124+
def calculate_current_reviewer(config: dict, reviewers: List[str]) -> Optional[str]:
125+
"""Calculate the current reviewer based on the rotation schedule."""
126+
if not reviewers:
127+
print("Error: No reviewers found")
128+
return None
129+
130+
rotation_info = calculate_rotation_info(config)
131+
132+
if rotation_info["error"]:
133+
print(f"Error: {rotation_info['error']}")
134+
return None
135+
136+
if rotation_info["before_start"]:
137+
print(f"Warning: Current date is before start date. Using first reviewer.")
138+
return reviewers[0]
139+
140+
# Calculate total weeks since start and map to reviewer
141+
# Each reviewer gets rotation_cycle_weeks weeks, then we cycle to the next
142+
total_weeks = int(rotation_info["weeks_since_start"])
143+
rotation_cycle_weeks = rotation_info["rotation_cycle_weeks"]
144+
reviewer_index = (total_weeks // rotation_cycle_weeks) % len(reviewers)
145+
146+
return reviewers[reviewer_index]
147+
148+
149+
def get_existing_reviewers(pr_number: str) -> List[str]:
150+
"""Get list of reviewers already assigned to the PR."""
151+
try:
152+
result = subprocess.run(
153+
['gh', 'pr', 'view', pr_number, '--json', 'reviewRequests', '--jq', '.reviewRequests[].login'],
154+
capture_output=True, text=True, check=True
155+
)
156+
return result.stdout.strip().split('\n') if result.stdout.strip() else []
157+
except FileNotFoundError:
158+
print("Error: 'gh' command not found. Is the GitHub CLI installed and in the PATH?")
159+
sys.exit(1)
160+
except subprocess.CalledProcessError:
161+
print(f"Warning: Could not fetch existing reviewers for PR {pr_number}")
162+
return []
163+
164+
165+
def assign_reviewer(pr_number: str, reviewer: str) -> bool:
166+
"""Assign a reviewer to the PR using GitHub CLI."""
167+
try:
168+
subprocess.run(
169+
['gh', 'pr', 'edit', pr_number, '--add-reviewer', reviewer],
170+
check=True, capture_output=True, text=True
171+
)
172+
print(f"Successfully assigned reviewer {reviewer} to PR {pr_number}")
173+
return True
174+
except FileNotFoundError:
175+
print("Error: 'gh' command not found. Is the GitHub CLI installed and in the PATH?")
176+
return False
177+
except subprocess.CalledProcessError as e:
178+
print(f"Error assigning reviewer {reviewer} to PR {pr_number}: {e.stderr}")
179+
return False
180+
181+
182+
def main():
183+
"""Main function to handle reviewer assignment."""
184+
# Get PR number from environment variable
185+
pr_number = os.environ.get('PR_NUMBER')
186+
if not pr_number:
187+
print("Error: PR_NUMBER environment variable not set")
188+
sys.exit(1)
189+
190+
# Load configuration (for start_date and rotation_cycle_weeks)
191+
config_path = '.github/auto-review-config.yml'
192+
config = load_config(config_path)
193+
194+
# Extract reviewers from MAINTAINERS.md
195+
reviewers = extract_reviewers_from_maintainers()
196+
if not reviewers:
197+
print("Error: No reviewers found in MAINTAINERS.md")
198+
sys.exit(1)
199+
200+
# Get sprint information
201+
sprint_info = get_current_sprint_info(config)
202+
print(f"Current sprint: {sprint_info['sprint_number']}, week: {sprint_info['week_in_sprint']}")
203+
204+
# Calculate current reviewer
205+
current_reviewer = calculate_current_reviewer(config, reviewers)
206+
if not current_reviewer:
207+
print("Error: Could not calculate current reviewer")
208+
sys.exit(1)
209+
210+
print(f"Assigned reviewer for this week: {current_reviewer}")
211+
212+
# Get existing reviewers
213+
existing_reviewers = get_existing_reviewers(pr_number)
214+
215+
# Check if current reviewer is already assigned
216+
if current_reviewer in existing_reviewers:
217+
print(f"Reviewer {current_reviewer} is already assigned to PR {pr_number}")
218+
return
219+
220+
# Assign the current reviewer
221+
success = assign_reviewer(pr_number, current_reviewer)
222+
if not success:
223+
sys.exit(1)
224+
225+
226+
if __name__ == "__main__":
227+
main()

.github/workflows/auto-review.yml

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
name: Auto Assign Reviewer
2+
3+
on:
4+
pull_request:
5+
types: [opened, ready_for_review]
6+
7+
jobs:
8+
assign-reviewer:
9+
runs-on: ubuntu-latest
10+
11+
steps:
12+
- name: Checkout code
13+
uses: actions/checkout@v4
14+
15+
- name: Setup Python
16+
uses: actions/setup-python@v4
17+
with:
18+
python-version: '3.11'
19+
20+
- name: Install dependencies
21+
run: |
22+
python -m pip install --upgrade pip
23+
pip install pyyaml
24+
25+
- name: Authenticate with GitHub
26+
run: |
27+
echo "${{ secrets.GITHUB_TOKEN }}" | gh auth login --with-token
28+
29+
- name: Assign reviewer
30+
env:
31+
PR_NUMBER: ${{ github.event.pull_request.number }}
32+
run: |
33+
python .github/scripts/assign_reviewer.py

0 commit comments

Comments
 (0)