python
#!/usr/bin/env python3
# .github/scripts/drift_detector.py
"""
CODEOWNERS Drift Detector
=========================
Detects coverage gaps in CODEOWNERS file, assigns risk scores, and provides PR guidance.
Features:
- Parses .github/CODEOWNERS (or CODEOWNERS).
- Identifies uncovered files/directories.
- Risk scoring: Based on file count, LOC, sensitivity (src/high-risk dirs), recent changes.
- PR guidance: Suggests patterns/owners for gaps; comments on PR if changed files uncovered.
- Outputs Markdown report; posts PR comment if applicable.
"""
import os
import sys
import json
import re
import subprocess
import fnmatch
from pathlib import Path
from typing import List, Dict, Set, Tuple, Optional
import git # gitpython
import requests # For GitHub API
from pathspec import PathSpec
from pathspec.patterns.gitwildmatch import GitWildMatchPattern
CODEOWNERS_PATHS = ['.github/CODEOWNERS', 'CODEOWNERS', 'docs/CODEOWNERS']
def run_cmd(cmd: List[str], cwd: Optional[Path] = None) -> str:
"""Run shell command and return stdout."""
result = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, check=True)
return result.stdout.strip()
def get_codeowners_path() -> Optional[Path]:
"""Find CODEOWNERS file."""
for path in CODEOWNERS_PATHS:
if Path(path).exists():
return Path(path)
return None
def parse_codeowners(codeowners_path: Path) -> List[Tuple[str, List[str]]]:
"""Parse CODEOWNERS into (pattern, owners) tuples."""
rules = []
with open(codeowners_path) as f:
for line_num, line in enumerate(f, 1):
line = line.strip()
if not line or line.startswith('#'):
continue
parts = line.split()
if len(parts) < 2:
print(f"Warning: Invalid line {line_num} in {codeowners_path}: {line}", file=sys.stderr)
continue
pattern = parts[0]
owners = parts[1:]
rules.append((pattern, owners))
return rules
def get_all_files(repo_root: Path) -> Set[Path]:
"""Get all tracked files (git ls-files)."""
files = run_cmd(['git', 'ls-files', '--cached', '--exclude-standard', '-z'], repo_root).split('\x00')
return {repo_root / f for f in files if f}
def build_pathspecs(rules: List[Tuple[str, List[str]]]) -> Dict[str, PathSpec]:
"""Build pathspec for each unique pattern."""
pattern_to_spec = {}
for pattern, _ in rules:
if pattern not in pattern_to_spec:
pattern_to_spec[pattern] = PathSpec.from_lines('gitwildmatch', [pattern])
return pattern_to_spec
def find_coverage_gaps(all_files: Set[Path], pathspecs: Dict[str, PathSpec], rules: List[Tuple[str, List[str]]]) -> Dict[str, Dict]:
"""
Find gaps: uncovered files grouped by inferred directory gaps.
Returns {gap_dir: {'files': [...], 'owners': None, 'pattern': inferred_pattern}}.
"""
covered = set()
file_to_rule = {} # For later use in PR guidance
for pattern, owners in rules:
spec = pathspecs[pattern]
matched = spec.match([f.relative_to(Path.cwd()) for f in all_files])
for rel_path in matched:
abs_path = Path.cwd() / rel_path
covered.add(abs_path)
if abs_path not in file_to_rule:
file_to_rule[abs_path] = (pattern, owners)
gaps = all_files - covered
gap_groups = {} # Group by common prefix dir
for gap in sorted(gaps):
rel = gap.relative_to(Path.cwd()).as_posix()
# Find deepest uncovered dir
parts = rel.split('/')
for i in range(1, len(parts) + 1):
dir_path = '/'.join(parts[:i])
if dir_path not in gap_groups:
gap_groups[dir_path] = {'files': [], 'owners': None, 'pattern': f"{dir_path}/*"}
gap_groups[parts[0]]['files'].append(rel) # At least group by top-level
# Dedup and prioritize deepest dirs
prioritized_gaps = {}
for gap_dir, data in gap_groups.items():
if any(gap_dir.startswith(d) and d != gap_dir for d in gap_groups):
continue # Skip if subdir of another
prioritized_gaps[gap_dir] = data
return prioritized_gaps, file_to_rule
def count_loc(file_path: Path) -> int:
"""Count lines of code in file (non-empty, non-comment)."""
try:
with open(file_path) as f:
return sum(1 for line in f if line.strip() and not line.strip().startswith('#'))
except:
return 0
def risk_score(gap_data: Dict, repo_root: Path, recent_days: int = 30) -> Dict[str, float]:
"""
Risk score (0-100):
- files_count: 20% (log scale)
- total_loc: 30%
- sensitivity: 30% (src=high, tests/docs=low)
- recent_changes: 20% (commits in last N days)
"""
files = [repo_root / f for f in gap_data['files']]
file_count = len(files)
total_loc = sum(count_loc(f) for f in files)
# Sensitivity multipliers
sensitivity = 1.0
high_risk_dirs = {'src', 'app', 'lib', 'backend', 'api', 'crypto', 'secrets'}
low_risk_dirs = {'tests', 'docs', 'examples', '.github'}
top_dir = gap_data['pattern'].split('/')[0]
if top_dir in high_risk_dirs:
sensitivity = 2.0
elif top_dir in low_risk_dirs:
sensitivity = 0.5
# Recent changes
since = run_cmd(['git', 'log', f'--since={recent_days}.days.ago', '--oneline', '--', gap_data['pattern']])
recent_commits = len(since.splitlines())
# Normalized scores
sc_file = min(20 * (1 + (file_count / 10).log() / 2.3), 20) # log10(10)=1 ->20
sc_loc = min(30 * (total_loc / 10000), 30) # Cap at 10k loc
sc_sens = 30 * sensitivity / 2 # 0-30
sc_recent = min(20 * (recent_commits / 10), 20)
score = sc_file + sc_loc + sc_sens + sc_recent
return {
'score': round(score, 1),
'components': {
'file_count': file_count,
'total_loc': total_loc,
'sensitivity': sensitivity,
'recent_commits': recent_commits
}
}
def get_changed_files(pr_number: Optional[int], token: str) -> List[str]:
"""Get files changed in PR via GitHub API."""
if not pr_number or not token:
return []
url = f"https://api.github.com/repos/{os.getenv('GITHUB_REPOSITORY')}/pulls/{pr_number}/files"
resp = requests.get(url, headers={'Authorization': f'token {token}'})
if resp.status_code == 200:
return [f.filename for f in resp.json()]
return []
def generate_pr_guidance(changed_files: List[str], gaps: Dict[str, Dict], file_to_rule: Dict[Path, Tuple]):
"""Guidance for PR: Warn if changed uncovered files; suggest fixes."""
changed_gaps = set()
for cf in changed_files:
p = Path.cwd() / cf
if p not in file_to_rule: # Uncovered
rel_dir = '/'.join(str(p).split('/')[:2]) # Top 2 levels
changed_gaps.add(rel_dir)
if not changed_gaps:
return None
suggestions = []
for gap_dir in changed_gaps:
if gap_dir in gaps:
gap = gaps[gap_dir]
owners = '@your-team' # TODO: Infer from similar patterns or repo teams
suggestions.append(f"- Add `{gap['pattern']} {owners}` to CODEOWNERS")
return f"""
## 🚨 CODEOWNERS Coverage Issue in PR
Changed files in uncovered areas: {', '.join(changed_gaps)}.
**Risk:** High - Update CODEOWNERS before merge.
**Suggested fixes:**
{suggestions}
"""
def post_pr_comment(pr_number: Optional[int], token: str, message: str):
"""Post comment to PR."""
if not pr_number or not token:
return
url = f"https://api.github.com/repos/{os.getenv('GITHUB_REPOSITORY')}/issues/{pr_number}/comments"
requests.post(url, headers={'Authorization': f'token {token}'}, json={'body': message})
def main():
repo_root = Path.cwd()
codeowners_path = get_codeowners_path()
if not codeowners_path:
print("No CODEOWNERS file found. ✅ Full coverage (trivially).")
sys.exit(0)
print(f"Parsing {codeowners_path}...")
rules = parse_codeowners(codeowners_path)
all_files = get_all_files(repo_root)
pathspecs = build_pathspecs(rules)
gaps, file_to_rule = find_coverage_gaps(all_files, pathspecs, rules)
# Compute risks
for gap_dir, gap_data in gaps.items():
gaps[gap_dir]['risk'] = risk_score(gap_data, repo_root)
# Sort by risk descending
sorted_gaps = dict(sorted(gaps.items(), key=lambda x: x[1]['risk']['score'], reverse=True))
# Generate report
report = ["# CODEOWNERS Drift Report\n"]
total_score = 0
high_risk = []
for gap_dir, data in sorted_gaps.items():
r = data['risk']
total_score += r['score']
status = "🔴 HIGH" if r['score'] > 50 else "🟡 MEDIUM" if r['score'] > 20 else "🟢 LOW"
report.append(f"### {status} {gap_dir} (Score: {r['score']})")
report.append(f"- Files: {len(data['files'])}")
report.append(f"- LOC: {r['components']['total_loc']:,}")
report.append(f"- Recent commits: {r['components']['recent_commits']}")
report.append(f"- Suggested pattern: `{data['pattern']} @your-team`") # Customize owner inference
report.append("\nFiles:\n" + "\n".join(f" - {f}" for f in data['files'][:10]) + ("\n ... (more)" if len(data['files']) > 10 else "") + "\n")
if r['score'] > 50:
high_risk.append(gap_dir)
report.append(f"\n## Summary")
report.append(f"- Total gaps: {len(sorted_gaps)}")
report.append(f"- Avg risk score: {total_score / max(len(sorted_gaps), 1):.1f}")
if high_risk:
report.append(f"- **High-risk gaps:** {', '.join(high_risk)}")
else:
report.append("- ✅ No high-risk gaps!")
report_md = "\n".join(report)
# Save report
with open("drift-report.md", "w") as f:
f.write(report_md)
# CI status
if high_risk:
print("::error::High-risk CODEOWNERS gaps found! See report.")
sys.exit(1)
else:
print("✅ No high-risk gaps.")
# PR guidance
token = os.getenv('GITHUB_TOKEN')
pr_number = os.getenv('PR_NUMBER')
event_name = os.getenv('GITHUB_EVENT_NAME')
if event_name == 'pull_request' and pr_number:
changed_files = get_changed_files(int(pr_number), token)
guidance = generate_pr_guidance(changed_files, gaps, file_to_rule)
if guidance:
post_pr_comment(int(pr_number), token, guidance)
print("Posted PR guidance comment.")
if __name__ == '__main__':
main()