The user wants a CODEOWNERS drift detector. This is a tool to analyze a CODEOWNERS file and the repository it belongs to (conceptually, since I can't actually clone repos) to identify:
- Coverage Gaps: Files or directories that aren't covered by any rule in CODEOWNERS.
- Risk Scoring: Assigning a risk value to files/directories based on factors like sensitivity, recent changes (churn), or lack of coverage.
- PR Guidance: Providing actionable advice on how to fix the CODEOWNERS file to close gaps or improve ownership structure.
Since I am an AI text model and not a script running in a live CI/CD environment with access to a specific repository's file system or git history, I need to provide a tool or script that the user can run to perform this analysis.
Key Components of the Solution:
- Language: Python is the standard for this type of DevOps/Analysis tooling. It handles file paths and pattern matching well.
- Inputs:
- The path to the repository root.
- The path to the CODEOWNERS file (usually
.github/CODEOWNERS).
- Logic Flow:
- Parse CODEOWNERS: Read the file, extract patterns (paths/globs) and owners.
- Walk Repository: List all files in the repository (respecting
.gitignore is a nice-to-have, but strict file walking is easier for a prototype).
- Match: For every file, check if it matches a CODEOWNERS pattern.
- Analyze:
- Coverage: If no match -> Gap.
- Risk: Calculate based on depth, extension, or simulated "churn" (since I can't access git history easily without the
git CLI, I will simulate a risk score based on path heuristics for the MVP, or add a dependency on GitPython for real history).
- Guidance: Generate suggested lines for the CODEOWNERS file.
Detailed Implementation Steps:
-
Step 1: Parsing CODEOWNERS.
- Ignore comments (
#).
- Handle lines with
pattern @owner.
- Handle optional sections
[Section].
- Crucial: CODEOWNERS globbing is similar to
.gitignore but has quirks. Using Python's pathspec or fnmatch is necessary. pathspec is better for gitignore-style matching.
-
Step 2: Scanning the Repo.
- Use
os.walk.
- Filter out
.git directory.
-
Step 3: Logic - Coverage Gaps.
- A file is "uncovered" if no pattern matches it.
- Edge case: The order matters. The last matching pattern wins. However, for coverage, we just need any pattern to match. If no pattern matches, it's a gap.
-
Step 4: Logic - Risk Scoring.
- I need a heuristic.
- High Risk: Sensitive files (
credentials, .env), CI config (.github/workflows), root files.
- Medium Risk: Source code.
- Low Risk: Docs, assets.
- Drift Risk: Uncovered files are inherently higher risk.
-
Step 5: Logic - PR Guidance.
- Group uncovered files by directory.
- Suggest a wildcard rule for that directory.
- Ask the user to assign an owner.
Refining the Output:
I will structure this as a complete Python script. I'll add a CLI interface using argparse or click. I'll stick to standard libraries as much as possible to make it portable, but pathspec is essential for accurate matching (pip install).
Drafting the Code Structure:
class CodeownersDriftDetector:
def __init__(self, repo_path, codeowners_path):
...
def parse_codeowners(self):
# Returns a list of (pattern, owners)
# Needs to handle the specific syntax
pass
def scan_repo(self):
# Returns list of all relative file paths
pass
def analyze(self):
# The core loop
for file in files:
# Check against pathspec
# If no match -> GAP
pass
def calculate_risk(self, file_path):
# Heuristics
pass
def generate_report(self):
# Print table of gaps
# Print PR suggestions
pass
Enhancements for "Drift":
Usually, "drift" implies that the repo has changed but CODEOWNERS hasn't. This specifically means "New files exist that aren't covered."
I will implement a "Smart Suggestion" engine. If src/new_feature/foo.py is uncovered, suggest src/new_feature/ @team-backend.
Dependencies:
pathspec: Essential for correct globbing.
rich (optional but good for pretty output): Maybe stick to standard print to ensure it runs everywhere, or use basic formatting. Let's use standard output for portability.
Risk Scoring Logic (Heuristics):
- Is it in
.github/workflows? Score 100 (Security/Infra risk).
- Is it
package.json or requirements.txt? Score 80 (Dependency risk).
- Is it a generic source file? Score 50.
- Is it a doc? Score 10.
PR Guidance Logic:
- Aggregate gaps.
- Find the deepest common directory.
- Propose a rule:
directory/** @<suggest-owner>.
Self-Correction during thought process:
- Issue: Real CODEOWNERS support is complex (escaping, optional owners).
- Resolution: Implement a simplified parser for the demo that handles standard
pattern @user @team. It won't be perfect for edge cases (like spaces in filenames without escaping), but sufficient for a robust tool demo.
Let's write the solution. I will provide a Python script that is ready to run.
Structure of the response:
- Introduction: What the tool does.
- Prerequisites:
pip install pathspec.
- The Script: The complete Python code.
- How to Run: CLI usage examples.
- Output Explanation: Understanding the results.
Code specifics:
- I need to mimic
gitignore logic for CODEOWNERS.
- If a directory is ignored, stop walking.
Let's refine the Risk Algorithm.
- Critical: CI/CD configs, Dockerfiles, dependency manifests.
- High: Core application logic (
.py, .go, .js).
- Medium: Configs, utilities.
- Low: Markdown, Images.
Let's build the tool.
This is a complete Python tool designed to be run locally or in CI to detect "drift" between your repository structure and your CODEOWNERS file.
It identifies orphans (files with no owner), scores them based on risk (sensitivity + complexity), and generates pull request guidance to fix the gaps.
Prerequisites
You will need Python 3 and the pathspec library (for accurate .gitignore style matching used by CODEOWNERS).
pip install pathspec
The Tool: codeowners_drift.py
Save the following code into a file named codeowners_drift.py.
import os
import sys
import re
import argparse
from dataclasses import dataclass, field
from typing import List, Dict, Optional
import pathspec
# ==========================================
# Configuration & Risk Heuristics
# ==========================================
# High-risk file patterns (Security, CI/CD, Infrastructure)
CRITICAL_PATTERNS = [
r'\.github/workflows/', r'\.gitlab-ci\.yml', r'Jenkinsfile',
r'Dockerfile', r'docker-compose', r'\.tf$', # Terraform
r'ansible/', r'kubernetes/', r'charts/', # Helm/K8s
r'^(Cargo\.toml|go\.mod|package\.json|requirements\.txt)$',
r'^(main|app|index)\.(py|go|js|rs|ts)$' # Core entry points
]
# Medium-risk patterns (Configuration, Logic)
MEDIUM_PATTERNS = [
r'\.env\.', r'config\.', r'\.ya?ml$', r'\.json$',
r'schema\.sql', r'migrations/'
]
@dataclass
class FileRisk:
path: str
risk_score: int
risk_reason: str
suggested_owner: Optional[str] = None
@dataclass
class DriftReport:
total_files: int = 0
covered_files: int = 0
coverage_pct: float = 0.0
gaps: List[FileRisk] = field(default_factory=list)
suggestions: Dict[str, List[str]] = field(default_factory=dict)
# ==========================================
# Core Logic
# ==========================================
class CodeownersDriftDetector:
def __init__(self, repo_root: str, codeowners_path: str):
self.repo_root = repo_root
self.codeowners_path = codeowners_path
self.spec = self._load_codeowners()
self.critical_regex = [re.compile(p) for p in CRITICAL_PATTERNS]
self.medium_regex = [re.compile(p) for p in MEDIUM_PATTERNS]
def _load_codeowners(self) -> pathspec.PathSpec:
"""Parses CODEOWNERS file into a PathSpec for matching."""
if not os.path.exists(self.codeowners_path):
raise FileNotFoundError(f"CODEOWNERS file not found at {self.codeowners_path}")
patterns = []
with open(self.codeowners_path, 'r') as f:
for line in f:
line = line.strip()
# Ignore comments and empty lines
if line and not line.startswith('#'):
# Pathspec expects patterns relative to root
patterns.append(line.split()[0]) # Take only the path pattern
return pathspec.PathSpec.from_lines("gitwildmatch", patterns)
def _calculate_risk(self, rel_path: str) -> FileRisk:
"""
Heuristic Risk Scoring:
1. Is it a critical system file? (CI, Docker, Entry points) -> Score 80-100
2. Is it configuration? -> Score 50
3. Default -> Score 10
"""
score = 10
reason = "General Code"
# Check Critical
for regex in self.critical_regex:
if regex.search(rel_path):
score = 90
reason = "Critical Infrastructure/Entry Point"
break
# Check Medium (if not already critical)
if score < 90:
for regex in self.medium_regex:
if regex.search(rel_path):
score = 60
reason = "Configuration/Data"
break
# Specific logic for root files (often overlooked)
if os.path.dirname(rel_path) == "" and score < 50:
score = 40
reason = "Root Configuration"
return FileRisk(path=rel_path, risk_score=score, risk_reason=reason)
def _generate_pr_guidance(self, gaps: List[FileRisk]) -> Dict[str, List[str]]:
"""
Groups gaps by directory to suggest wildcards.
e.g., if 5 files in /src/lib are uncovered, suggest /src/lib/ @team
"""
dir_map = {}
for gap in gaps:
parent = os.path.dirname(gap.path)
if parent == "":
parent = "/"
if parent not in dir_map:
dir_map[parent] = []
dir_map[parent].append(gap.path)
suggestions = {}
for directory, files in dir_map.items():
# If a folder has > 2 uncovered files, suggest a directory rule
if len(files) > 2:
rule = f"{directory}/*" if directory != "/" else "/*"
suggestions[f"Rule: {rule}"] = files[:3] + [f"... and {len(files)-3} more" if len(files)>3 else ""]
else:
# Suggest individual files
for f in files:
suggestions[f"Rule: {f}"] = [f"Uncovered ({gaps[0].risk_reason})"]
return suggestions
def scan(self) -> DriftReport:
report = DriftReport()
for root, dirs, files in os.walk(self.repo_root):
# Skip hidden directories and common non-code dirs
dirs[:] = [d for d in dirs if not d.startswith('.') and d not in ['node_modules', 'vendor', 'venv', '__pycache__']]
for f in files:
full_path = os.path.join(root, f)
rel_path = os.path.relpath(full_path, self.repo_root)
report.total_files += 1
# Check coverage
if self.spec.match_file(rel_path):
report.covered_files += 1
else:
# It's a gap! Analyze risk.
risk_obj = self._calculate_risk(rel_path)
report.gaps.append(risk_obj)
if report.total_files > 0:
report.coverage_pct = (report.covered_files / report.total_files) * 100
report.suggestions = self._generate_pr_guidance(report.gaps)
return report
# ==========================================
# CLI & Output Formatting
# ==========================================
def print_report(report: DriftReport):
print(f"\n📊 CODEOWNERS DRIFT REPORT")
print(f"==========================")
print(f"✅ Coverage: {report.coverage_pct:.2f}% ({report.covered_files}/{report.total_files} files)")
print(f"🚨 Gaps: {len(report.gaps)} uncovered files")
# Sort gaps by risk (descending)
report.gaps.sort(key=lambda x: x.risk_score, reverse=True)
print(f"\n🔥 TOP RISKS (Uncovered Critical Assets)")
print(f"----------------------------------------")
for gap in report.gaps[:10]:
if gap.risk_score >= 50: # Only show significant risks
print(f"[{gap.risk_score:3d}] {gap.path}")
print(f" Reason: {gap.risk_reason}")
print(f"\n💡 PR GUIDANCE (Suggestions to fix gaps)")
print(f"----------------------------------------")
print("Add the following lines to your CODEOWNERS file:\n")
count = 0
for suggestion, examples in report.suggestions.items():
if count >= 5: break # Limit output noise
print(f"# Covers: {', '.join([x for x in examples if x])}")
print(f"{suggestion} @YourTeamName")
print("")
count += 1
def main():
parser = argparse.ArgumentParser(description="Detect CODEOWNERS drift, risk, and coverage gaps.")
parser.add_argument("--repo", default=".", help="Path to repository root")
parser.add_argument("--file", default=".github/CODEOWNERS", help="Path to CODEOWNERS file relative to repo root")
args = parser.parse_args()
full_co_path = os.path.join(args.repo, args.file)
try:
detector = CodeownersDriftDetector(args.repo, full_co_path)
report = detector.scan()
print_report(report)
# Exit code for CI: Fail if coverage is below 100% (optional, or if high risk exists)
# sys.exit(1 if len(report.gaps) > 0 else 0)
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
How to Use It
-
Local Scan:
Run the script from the root of your repository.
python codeowners_drift.py
-
Specific Path:
If your CODEOWNERS file is in a non-standard location:
python codeowners_drift.py --repo /path/to/repo --file docs/CODEOWNERS
Key Features
-
Risk Scoring Engine:
Instead of just listing files, this tool parses file paths to detect "Risk."
- High Risk (90): CI/CD workflows, Dockerfiles, dependency manifests (
package.json), and main entry points (main.go). Unowned infrastructure code is a security risk.
- Medium Risk (60): Config files, environment files, schemas.
- Low Risk (10): General source code, docs, assets.
-
Drift Detection (Coverage Gaps):
It uses the pathspec library (the same logic used by Git) to match your CODEOWNERS patterns against the actual file system. If a file isn't matched, it's a gap.
-
PR Guidance:
Instead of giving you a list of 500 uncovered files, it attempts to aggregate them.
- Example: If
src/utils/helpers.js and src/utils/math.js are uncovered, it suggests adding a rule for src/utils/* instead of two separate file rules. This keeps your CODEOWNERS file clean.
-
CI/CD Integration:
You can uncomment the sys.exit line at the bottom to make the script fail (exit code 1) if there are uncovered files, preventing code from being merged without ownership.