#!/usr/bin/env python3
"""
Code Generation Quality Gate
A robust quality gate for auto-generated code diffs. It applies the diff in an isolated Git worktree,
runs contract tests (e.g., pytest), static analysis (e.g., mypy, pylint), and human review heuristics
(e.g., complexity checks, security scans, custom patterns).
Usage:
python code_gen_quality_gate.py --diff-path /path/to/generated.diff [options]
Requirements:
- Git (with worktree support)
- Python 3.8+
- pip install GitPython radon bandit (or run in a virtualenv with these)
- Project-specific tools: pytest, mypy, pylint, black, flake8 (install via pip/requirements)
Configurable via CLI args or a `quality-gate.json` file in repo root.
Example quality-gate.json:
{
"test_cmd": "pytest tests/ -v --cov=src --cov-fail-under=90",
"static_analysis_cmds": [
"mypy src/",
"pylint src/",
"black --check src/",
"flake8 src/"
],
"heuristics_cmds": [
"radon cc src/ --total-average -s",
"bandit -r src/ -ll",
"vulture src/ --min-confidence 80" // optional: pip install vulture
],
"custom_heuristics": {
"max_function_length": 50,
"max_complexity": 10,
"forbidden_patterns": ["eval\\(", "exec\\(", "os\\.system", "TODO", "FIXME", "HACK"],
"max_diff_hunk_size": 100
}
}
"""
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import List, Dict, Any
try:
import git
except ImportError:
print("ERROR: Install GitPython: pip install GitPython", file=sys.stderr)
sys.exit(1)
try:
import radon.complexity
import bandit # for security heuristics
except ImportError:
print("WARNING: Install radon & bandit for heuristics: pip install radon bandit", file=sys.stderr)
class QualityGateError(Exception):
pass
class QualityGate:
def __init__(self, base_dir: str, config: Dict[str, Any]):
self.base_dir = Path(base_dir).resolve()
self.config = config
self.repo = git.Repo(self.base_dir)
self.temp_worktree = None
def run_command(self, cmd: str, cwd: Path, env: Dict[str, str] = None) -> str:
"""Run a shell command and return stdout if success, raise on failure."""
try:
env = env or os.environ.copy()
result = subprocess.run(
cmd, shell=True, cwd=cwd, env=env, capture_output=True, text=True, check=True
)
return result.stdout
except subprocess.CalledProcessError as e:
raise QualityGateError(
f"Command failed: {cmd}\nstdout: {e.stdout}\nstderr: {e.stderr}"
)
def setup_temp_worktree(self) -> Path:
"""Create a Git worktree for isolated diff application."""
temp_base = Path(tempfile.mkdtemp(prefix="quality-gate-"))
worktree_path = temp_base / "worktree"
self.repo.git.worktree("add", str(worktree_path), "HEAD")
self.temp_worktree = worktree_path
return worktree_path
def cleanup(self):
"""Clean up temp worktree."""
if self.temp_worktree:
self.repo.git.worktree("remove", str(self.temp_worktree), force=True)
shutil.rmtree(self.temp_worktree.parent, ignore_errors=True)
def apply_diff(self, diff_path: Path):
"""Apply the generated diff in the worktree."""
self.run_command(f"git apply --check {diff_path}", self.temp_worktree)
self.run_command(f"git apply {diff_path}", self.temp_worktree)
print(f"✓ Diff applied successfully: {diff_path}")
def run_contract_tests(self) -> bool:
"""Run contract/integration tests."""
cmd = self.config.get("test_cmd", "pytest . -v")
print(f"Running contract tests: {cmd}")
self.run_command(cmd, self.temp_worktree)
print("✓ Contract tests passed")
return True
def run_static_analysis(self) -> bool:
"""Run static analysis tools."""
cmds = self.config.get("static_analysis_cmds", [
"mypy .",
"pylint src/ tests/",
"black --check .",
"flake8 ."
])
print("Running static analysis...")
for cmd in cmds:
self.run_command(cmd, self.temp_worktree)
print("✓ Static analysis passed")
return True
def run_human_review_heuristics(self) -> bool:
"""Run heuristics mimicking human review."""
print("Running human review heuristics...")
# 1. Tool-based heuristics
heuristics_cmds = self.config.get("heuristics_cmds", [
"radon cc src/ --total-average --maxcc=10", # Fail if >10
"bandit -r src/ --format json", # Will fail on high severity if customized
# Add "vulture src/" if installed
])
for cmd in heuristics_cmds:
self.run_command(cmd, self.temp_worktree)
# 2. Custom heuristics on diff
self._check_diff_heuristics()
# 3. Code metrics (e.g., function length via radon raw)
self._check_code_metrics()
# 4. Forbidden patterns scan
self._check_forbidden_patterns()
print("✓ Human review heuristics passed")
return True
def _check_diff_heuristics(self):
"""Check diff for size, hunks, etc."""
diff_output = self.run_command("git diff HEAD~1", self.temp_worktree)
hunks = re.findall(r'@@ -(\d+)(,\d+)? \+(\d+)(,\d+)? @@', diff_output)
max_hunk = self.config.get("custom_heuristics", {}).get("max_diff_hunk_size", 100)
for hunk in hunks:
if int(hunk[3].split(',')[0]) > max_hunk if len(hunk[3].split(',')) > 1 else False:
raise QualityGateError(f"Diff hunk too large (> {max_hunk} lines): {hunk}")
added_lines = len([l for l in diff_output.splitlines() if l.startswith('+') and not l.startswith('++')])
if added_lines > 1000: # Arbitrary large change limit
raise QualityGateError(f"Too many added lines: {added_lines}")
def _check_code_metrics(self):
"""Check complexity and length using radon."""
custom = self.config.get("custom_heuristics", {})
max_cc = custom.get("max_complexity", 10)
max_length = custom.get("max_function_length", 50)
# Radon CC
cc_results = radon.complexity.cc_visit(self.temp_worktree / "src")
for block in cc_results:
if block.complexity > max_cc:
raise QualityGateError(f"High complexity in {block.name}: {block.complexity}")
# Raw for length (radon raw gives loc)
raw_results = radon.complexity.visitor.analyze(self.temp_worktree / "src")
for block in raw_results.blocks:
if block.endline - block.startline + 1 > max_length:
raise QualityGateError(f"Function too long {block.name}: {block.endline - block.startline + 1} lines")
def _check_forbidden_patterns(self):
"""Scan for forbidden patterns in added code."""
diff_output = self.run_command("git diff HEAD~1", self.temp_worktree)
added_code = [line[1:] for line in diff_output.splitlines() if line.startswith('+') and not line.startswith('+++')]
patterns = self.config.get("custom_heuristics", {}).get("forbidden_patterns", [])
for pattern in patterns:
if re.search(pattern, ' '.join(added_code), re.IGNORECASE):
raise QualityGateError(f"Forbidden pattern '{pattern}' found in diff")
def run(self, diff_path: Path) -> bool:
"""Run the full quality gate."""
try:
self.temp_worktree = self.setup_temp_worktree()
self.apply_diff(diff_path)
self.run_contract_tests()
self.run_static_analysis()
self.run_human_review_heuristics()
print("🎉 QUALITY GATE PASSED! Diff is approved for merge.")
return True
except QualityGateError as e:
print(f"❌ QUALITY GATE FAILED: {e}", file=sys.stderr)
return False
finally:
self.cleanup()
def load_config(base_dir: Path) -> Dict[str, Any]:
config_path = base_dir / "quality-gate.json"
default_config = {
"test_cmd": "pytest tests/ -v",
"static_analysis_cmds": ["mypy src/", "pylint src/", "black --check .", "flake8 src/"],
"heuristics_cmds": ["radon cc src/ --total-average --maxcc=10"],
"custom_heuristics": {
"max_diff_hunk_size": 100,
"max_complexity": 10,
"max_function_length": 50,
"forbidden_patterns": [r"eval\(", r"exec\(", r"os\.system", r"TODO", r"FIXME", r"HACK"]
}
}
if config_path.exists():
with open(config_path) as f:
user_config = json.load(f)
default_config.update(user_config)
return default_config
def main():
parser = argparse.ArgumentParser(description="Code Gen Quality Gate")
parser.add_argument("--diff-path", "-d", required=True, help="Path to auto-generated diff")
parser.add_argument("--base-dir", "-b", default=".", help="Git repo base dir")
args = parser.parse_args()
base_dir = Path(args.base_dir).resolve()
if not base_dir.exists():
print("ERROR: Base dir not found", file=sys.stderr)
sys.exit(1)
diff_path = Path(args.diff_path).resolve()
if not diff_path.exists():
print("ERROR: Diff path not found", file=sys.stderr)
sys.exit(1)
config = load_config(base_dir)
gate = QualityGate(str(base_dir), config)
success = gate.run(diff_path)
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()
How to Use
-
Save the script: code_gen_quality_gate.py in your repo root (make executable: chmod +x code_gen_quality_gate.py).
-
Install dependencies:
pip install GitPython radon bandit pylint mypy black flake8 pytest pytest-cov
# Optional: pip install vulture # for dead code detection
-
Configure (optional): Create quality-gate.json as shown in the docstring. Customize commands and thresholds for your project.
-
Generate diff: Your code gen tool outputs generated.diff (use git diff --cached > generated.diff or equivalent).
-
Run the gate:
python code_gen_quality_gate.py --diff-path generated.diff
- Passes: All checks green → Safe to
git apply generated.diff && git commit.
- Fails: Detailed error → Review/fix generated code.
-
In CI/CD (e.g., GitHub Actions):
- name: Run Quality Gate
run: python code_gen_quality_gate.py --diff-path ${{ github.event.pull_request.head.sha }}.diff
Fetch diff via API or artifact.
-
Adapt for other langs:
- JS/TS: Swap cmds to
npm test, tsc --noEmit, eslint ., prettier --check ..
- Update
quality-gate.json accordingly.
Features
- Isolated: Uses Git worktree—no pollution of main branch.
- Contract Tests: Full test suite run post-diff.
- Static Analysis: Type checking, linting, formatting.
- Heuristics:
- Diff size/hunk limits.
- Cyclomatic complexity & function length (radon).
- Security (bandit).
- Forbidden patterns (regex).
- Extensible: JSON config, custom cmds.
- Robust: Cleans up always, detailed errors.
This gate ensures generated code is production-ready without manual review overhead! 🔒