Skip to content

Commit 551a0cc

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 551a0cc

File tree

3 files changed

+309
-0
lines changed

3 files changed

+309
-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: 270 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,270 @@
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, timezone
14+
from typing import List, Optional, TypedDict
15+
16+
17+
class RotationInfo(TypedDict):
18+
start_date: Optional[datetime]
19+
rotation_cycle_weeks: int
20+
weeks_since_start: float
21+
before_start: bool
22+
error: Optional[str]
23+
24+
25+
class SprintInfo(TypedDict):
26+
sprint_number: int
27+
week_in_sprint: int
28+
total_weeks: int
29+
before_start: Optional[bool]
30+
31+
32+
def load_config(config_path: str) -> dict:
33+
"""Load the reviewer configuration from YAML file."""
34+
try:
35+
with open(config_path, 'r') as f:
36+
return yaml.safe_load(f)
37+
except FileNotFoundError:
38+
print(f"Error: Configuration file {config_path} not found", file=sys.stderr)
39+
sys.exit(1)
40+
except yaml.YAMLError as e:
41+
print(f"Error parsing YAML configuration: {e}", file=sys.stderr)
42+
sys.exit(1)
43+
44+
45+
def extract_reviewers_from_maintainers() -> List[str]:
46+
"""Extract GitHub usernames from MAINTAINERS.md file by parsing the table structure."""
47+
maintainers_path = os.environ.get("MAINTAINERS_PATH", 'MAINTAINERS.md')
48+
reviewers = []
49+
50+
try:
51+
with open(maintainers_path, 'r') as f:
52+
content = f.read()
53+
54+
lines = content.splitlines()
55+
github_id_column_index = None
56+
in_table = False
57+
58+
for line in lines:
59+
line = line.strip()
60+
61+
# Skip empty lines
62+
if not line:
63+
continue
64+
65+
# Look for table header to find GitHub ID column
66+
if line.startswith('|') and 'GitHub ID' in line:
67+
in_table = True
68+
columns = [col.strip() for col in line.split('|')[1:-1]] # Remove empty first/last elements
69+
try:
70+
github_id_column_index = columns.index('GitHub ID')
71+
except ValueError:
72+
print("Error: Could not find 'GitHub ID' column in MAINTAINERS.md table")
73+
sys.exit(1)
74+
continue
75+
76+
# Skip separator line (|---|---|...)
77+
if in_table and line.startswith('|') and '---' in line:
78+
continue
79+
80+
# Process table data rows
81+
if in_table and line.startswith('|') and github_id_column_index is not None:
82+
columns = [col.strip() for col in line.split('|')[1:-1]]
83+
if len(columns) > github_id_column_index:
84+
github_id_cell = columns[github_id_column_index]
85+
match = re.search(r'\[([^\]]+)\]\(https://github\.com/[^)]+\)', github_id_cell)
86+
if match:
87+
username = match.group(1)
88+
if username and username not in reviewers:
89+
reviewers.append(username)
90+
91+
# Stop parsing when we hit the end of the table
92+
if in_table and not line.startswith('|'):
93+
break
94+
95+
if reviewers:
96+
print(f"Found {len(reviewers)} reviewers from MAINTAINERS.md: {', '.join(reviewers)}")
97+
else:
98+
print("Warning: No GitHub usernames found in MAINTAINERS.md")
99+
100+
except FileNotFoundError:
101+
print(f"Error: MAINTAINERS.md file not found")
102+
sys.exit(1)
103+
except IOError as e:
104+
print(f"Error reading MAINTAINERS.md: {e}")
105+
sys.exit(1)
106+
107+
return reviewers
108+
109+
110+
def calculate_rotation_info(config: dict) -> RotationInfo:
111+
"""Calculate rotation information from config (helper function)."""
112+
start_date_str = config.get('start_date')
113+
rotation_cycle_weeks = config.get('rotation_cycle_weeks', 3)
114+
115+
if not start_date_str:
116+
return {
117+
"start_date": None,
118+
"rotation_cycle_weeks": rotation_cycle_weeks,
119+
"weeks_since_start": 0,
120+
"before_start": False,
121+
"error": "No start_date configured"
122+
}
123+
124+
try:
125+
start_date = datetime.strptime(start_date_str, "%Y-%m-%d").replace(tzinfo=timezone.utc)
126+
current_date = datetime.now(timezone.utc)
127+
weeks_since_start = (current_date - start_date).total_seconds() / (7 * 24 * 3600)
128+
129+
return {
130+
"start_date": start_date,
131+
"rotation_cycle_weeks": rotation_cycle_weeks,
132+
"weeks_since_start": weeks_since_start,
133+
"before_start": weeks_since_start < 0,
134+
"error": None
135+
}
136+
except ValueError:
137+
return {
138+
"start_date": None,
139+
"rotation_cycle_weeks": rotation_cycle_weeks,
140+
"weeks_since_start": 0,
141+
"before_start": False,
142+
"error": f"Invalid start_date format: {start_date_str}"
143+
}
144+
145+
146+
def get_current_sprint_info(rotation_info: RotationInfo) -> SprintInfo:
147+
"""Calculate current sprint information."""
148+
149+
if rotation_info["before_start"]:
150+
return {
151+
"sprint_number": 1,
152+
"week_in_sprint": 1,
153+
"total_weeks": 0,
154+
"before_start": True
155+
}
156+
157+
weeks_since_start = rotation_info["weeks_since_start"]
158+
rotation_cycle_weeks = rotation_info["rotation_cycle_weeks"]
159+
160+
sprint_number = int(weeks_since_start // rotation_cycle_weeks) + 1
161+
week_in_sprint = int(weeks_since_start % rotation_cycle_weeks) + 1
162+
163+
return {
164+
"sprint_number": sprint_number,
165+
"week_in_sprint": week_in_sprint,
166+
"total_weeks": int(weeks_since_start)
167+
}
168+
169+
170+
def calculate_current_reviewer(reviewers: List[str], rotation_info: RotationInfo) -> Optional[str]:
171+
"""Calculate the current reviewer based on the rotation schedule."""
172+
if not reviewers:
173+
print("Error: No reviewers found")
174+
return None
175+
176+
if rotation_info["before_start"]:
177+
print(f"Warning: Current date is before start date. Using first reviewer.")
178+
return reviewers[0]
179+
180+
# Calculate total weeks since start and map to reviewer
181+
# Each reviewer gets rotation_cycle_weeks weeks, then we cycle to the next
182+
total_weeks = int(rotation_info["weeks_since_start"])
183+
rotation_cycle_weeks = rotation_info["rotation_cycle_weeks"]
184+
reviewer_index = (total_weeks // rotation_cycle_weeks) % len(reviewers)
185+
186+
return reviewers[reviewer_index]
187+
188+
189+
def get_existing_reviewers(pr_number: str) -> List[str]:
190+
"""Get list of reviewers already assigned to the PR."""
191+
try:
192+
result = subprocess.run(
193+
['gh', 'pr', 'view', pr_number, '--json', 'reviewRequests', '--jq', '.reviewRequests[].login'],
194+
capture_output=True, text=True, check=True
195+
)
196+
return result.stdout.strip().split('\n') if result.stdout.strip() else []
197+
except FileNotFoundError:
198+
print("Error: 'gh' command not found. Is the GitHub CLI installed and in the PATH?")
199+
sys.exit(1)
200+
except subprocess.CalledProcessError as e:
201+
print(f"Error: Could not fetch existing reviewers for PR {pr_number}: {e.stderr}", file=sys.stderr)
202+
sys.exit(1)
203+
204+
205+
def assign_reviewer(pr_number: str, reviewer: str) -> bool:
206+
"""Assign a reviewer to the PR using GitHub CLI."""
207+
try:
208+
subprocess.run(
209+
['gh', 'pr', 'edit', pr_number, '--add-reviewer', reviewer],
210+
check=True, capture_output=True, text=True
211+
)
212+
print(f"Successfully assigned reviewer {reviewer} to PR {pr_number}")
213+
return True
214+
except FileNotFoundError:
215+
print("Error: 'gh' command not found. Is the GitHub CLI installed and in the PATH?")
216+
sys.exit(1)
217+
except subprocess.CalledProcessError as e:
218+
print(f"Error assigning reviewer {reviewer} to PR {pr_number}: {e.stderr}", file=sys.stderr)
219+
sys.exit(1)
220+
221+
222+
def main():
223+
"""Main function to handle reviewer assignment."""
224+
# Get PR number from environment variable
225+
pr_number = os.environ.get('PR_NUMBER')
226+
if not pr_number:
227+
print("Error: PR_NUMBER environment variable not set")
228+
sys.exit(1)
229+
230+
# Load configuration (for start_date and rotation_cycle_weeks)
231+
config_path = os.environ.get('AUTO_REVIEW_CONFIG_PATH', '.github/auto-review-config.yml')
232+
config = load_config(config_path)
233+
234+
# Extract reviewers from MAINTAINERS.md
235+
reviewers = extract_reviewers_from_maintainers()
236+
if not reviewers:
237+
print("Error: No reviewers found in MAINTAINERS.md")
238+
sys.exit(1)
239+
240+
# Calculate rotation information once
241+
rotation_info = calculate_rotation_info(config)
242+
if rotation_info['error']:
243+
print(f"Error in configuration: {rotation_info['error']}", file=sys.stderr)
244+
sys.exit(1)
245+
246+
# Get sprint information
247+
sprint_info = get_current_sprint_info(rotation_info)
248+
print(f"Current sprint: {sprint_info['sprint_number']}, week: {sprint_info['week_in_sprint']}")
249+
250+
# Calculate current reviewer
251+
current_reviewer = calculate_current_reviewer(reviewers, rotation_info)
252+
if not current_reviewer:
253+
print("Error: Could not calculate current reviewer")
254+
sys.exit(1)
255+
256+
print(f"Assigned reviewer for this week: {current_reviewer}")
257+
258+
# Get existing reviewers
259+
existing_reviewers = get_existing_reviewers(pr_number)
260+
261+
# Check if current reviewer is already assigned
262+
if current_reviewer in existing_reviewers:
263+
print(f"Reviewer {current_reviewer} is already assigned to PR {pr_number}")
264+
return
265+
266+
# Assign the current reviewer
267+
assign_reviewer(pr_number, current_reviewer)
268+
269+
if __name__ == "__main__":
270+
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)