Skip to content

Commit c2cd2d0

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 c2cd2d0

File tree

3 files changed

+272
-0
lines changed

3 files changed

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