#!/usr/bin/env python3 """ Pull Request Review Script Reviews all pull requests and creates a comprehensive summary """ import subprocess import sys import json from pathlib import Path from datetime import datetime from collections import defaultdict REPO_ROOT = Path(__file__).resolve().parents[1] def run_command(cmd, capture_output=True): """Run a command and return the result.""" try: result = subprocess.run( cmd, cwd=REPO_ROOT, capture_output=capture_output, text=True, timeout=30, encoding='utf-8', errors='replace' ) return result except Exception as e: print(f"Error running command: {e}", file=sys.stderr) return None def get_prs_via_gh_cli(): """Get PRs using GitHub CLI.""" result = run_command(["gh", "pr", "list", "--state", "all", "--json", "number,title,state,author,createdAt,updatedAt,headRefName,baseRefName,isDraft,labels"]) if result and result.returncode == 0: try: return json.loads(result.stdout) except json.JSONDecodeError: return [] return None def analyze_branch_name(branch_name): """Analyze branch name to extract PR information.""" branch = branch_name.replace("origin/", "") info = { "type": "unknown", "category": "other", "description": branch } # Categorize branches if branch.startswith("Cursor/"): info["type"] = "cursor" info["category"] = "ai-generated" info["description"] = branch.replace("Cursor/A6-9V/", "") elif branch.startswith("copilot/"): info["type"] = "copilot" info["category"] = "ai-generated" info["description"] = branch.replace("copilot/", "") elif branch.startswith("bolt-"): info["type"] = "bolt" info["category"] = "optimization" info["description"] = branch.replace("bolt-", "") elif branch.startswith("feat/"): info["type"] = "feature" info["category"] = "feature" info["description"] = branch.replace("feat/", "") elif branch.startswith("feature/"): info["type"] = "feature" info["category"] = "feature" info["description"] = branch.replace("feature/", "") return info def get_branches_info_git(): """ Get all remote branches and their status (ahead/behind main) using a single git command. Returns a dictionary with 'open' and 'merged' lists of branch info dicts. """ # Format: refname|committerdate|ahead-behind:origin/main # Note: ahead-behind requires git 2.41+. cmd = [ "git", "for-each-ref", "--format=%(refname:short)|%(committerdate:iso)|%(ahead-behind:origin/main)", "refs/remotes/origin" ] result = run_command(cmd) open_branches = [] merged_branches = [] if result and result.returncode == 0: lines = result.stdout.strip().split("\n") for line in lines: if not line.strip(): continue parts = line.split("|") if len(parts) < 3: continue branch_name = parts[0] last_commit_date = parts[1] ahead_behind = parts[2] # "ahead behind" # Skip main itself and HEAD if "origin/main" in branch_name or "HEAD" in branch_name: continue try: ahead, behind = map(int, ahead_behind.split()) except ValueError: # Fallback if format parsing fails ahead, behind = 0, 0 info = analyze_branch_name(branch_name) branch_data = { "branch": branch_name.replace("origin/", ""), # Short name "full_name": branch_name, "commit_count": ahead, "last_commit_date": last_commit_date, "description": info["description"], "category": info["category"] } # If ahead == 0, it means all commits in branch are already in main (merged) if ahead == 0: merged_branches.append(branch_data) else: open_branches.append(branch_data) return { "open": open_branches, "merged": merged_branches } def main(): """Main review function.""" print("=" * 80) print("PULL REQUEST REVIEW") print(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") print("=" * 80) print() # Try GitHub CLI first prs = get_prs_via_gh_cli() if prs is not None: print(f"Found {len(prs)} pull requests via GitHub CLI") print() # Group by state by_state = defaultdict(list) for pr in prs: by_state[pr.get("state", "unknown")].append(pr) print("Pull Requests by State:") for state, pr_list in sorted(by_state.items()): print(f" {state.upper()}: {len(pr_list)}") print() # Show open PRs open_prs = by_state.get("OPEN", []) if open_prs: print("=" * 80) print("OPEN PULL REQUESTS") print("=" * 80) for pr in open_prs: print(f"\nPR #{pr.get('number', 'N/A')}: {pr.get('title', 'No title')}") print(f" Author: {pr.get('author', {}).get('login', 'Unknown')}") print(f" Branch: {pr.get('headRefName', 'N/A')} -> {pr.get('baseRefName', 'main')}") print(f" Created: {pr.get('createdAt', 'N/A')}") print(f" Updated: {pr.get('updatedAt', 'N/A')}") print(f" Draft: {'Yes' if pr.get('isDraft') else 'No'}") labels = [l.get('name') for l in pr.get('labels', [])] if labels: print(f" Labels: {', '.join(labels)}") # Show merged PRs merged_prs = by_state.get("MERGED", []) if merged_prs: print("\n" + "=" * 80) print(f"MERGED PULL REQUESTS ({len(merged_prs)} total)") print("=" * 80) print(f"\nShowing last 10 merged PRs:") for pr in merged_prs[-10:]: print(f" PR #{pr.get('number', 'N/A')}: {pr.get('title', 'No title')}") else: # Fallback to git branch analysis (Optimized for Git 2.41+) print("GitHub CLI not available, analyzing branches...") print() branch_data = get_branches_info_git() open_branches = branch_data["open"] merged_branches = branch_data["merged"] print(f"Open branches (potential PRs): {len(open_branches)}") print(f"Merged branches (completed PRs): {len(merged_branches)}") print() # Categorize open branches categories = defaultdict(list) for b_data in open_branches: categories[b_data["category"]].append(b_data) print("=" * 80) print("OPEN BRANCHES (Potential Pull Requests)") print("=" * 80) print() for category, b_list in sorted(categories.items()): print(f"{category.upper()}: {len(b_list)} branches") for b_data in b_list[:10]: # Show first 10 print(f" - {b_data['description']}") print(f" Branch: {b_data['branch']}") print(f" Commits: {b_data['commit_count']}") if b_data['last_commit_date']: print(f" Last commit: {b_data['last_commit_date']}") if len(b_list) > 10: print(f" ... and {len(b_list) - 10} more") print() print("=" * 80) print("MERGED BRANCHES (Completed Pull Requests)") print("=" * 80) print(f"\nTotal merged: {len(merged_branches)}") print("\nRecent merged branches:") # Sort merged branches by date (descending) merged_branches.sort(key=lambda x: x['last_commit_date'], reverse=True) for b_data in merged_branches[:20]: print(f" - {b_data['description']}") print("\n" + "=" * 80) print("REVIEW COMPLETE") print("=" * 80) print("\nNote: GitHub doesn't support 'pinning' pull requests directly.") print("Consider:") print("1. Creating a tracking issue for important PRs") print("2. Using labels to categorize PRs") print("3. Adding PRs to project boards") print("4. Creating a PR summary document") if __name__ == "__main__": main()