| 1 |
#!/usr/bin/env python3 |
| 2 |
""" |
| 3 |
Fenrir PEP8 Validation and Auto-Fix Tool |
| 4 |
|
| 5 |
Validates Python code style using flake8 and applies safe automatic fixes. |
| 6 |
Designed to work with Fenrir's existing codebase while respecting timing-critical code. |
| 7 |
|
| 8 |
Usage: |
| 9 |
python3 tools/validate_pep8.py # Check all Python files |
| 10 |
python3 tools/validate_pep8.py --fix-safe # Auto-fix safe issues |
| 11 |
python3 tools/validate_pep8.py --check-only # Exit with error if issues found |
| 12 |
python3 tools/validate_pep8.py --staged # Check only staged files |
| 13 |
""" |
| 14 |
|
| 15 |
import os |
| 16 |
import sys |
| 17 |
import argparse |
| 18 |
import subprocess |
| 19 |
import tempfile |
| 20 |
from pathlib import Path |
| 21 |
|
| 22 |
|
| 23 |
class PEP8Validator: |
| 24 |
def __init__(self, verbose=True): |
| 25 |
self.verbose = verbose |
| 26 |
self.errors = [] |
| 27 |
self.warnings = [] |
| 28 |
self.fixes_applied = [] |
| 29 |
|
| 30 |
def log(self, message, level="INFO"): |
| 31 |
"""Log a message with appropriate formatting.""" |
| 32 |
if not self.verbose and level == "INFO": |
| 33 |
return |
| 34 |
|
| 35 |
colors = { |
| 36 |
"INFO": "\033[0;36m", # Cyan |
| 37 |
"SUCCESS": "\033[0;32m", # Green |
| 38 |
"WARNING": "\033[1;33m", # Yellow |
| 39 |
"ERROR": "\033[0;31m", # Red |
| 40 |
"HEADER": "\033[1;34m", # Bold Blue |
| 41 |
} |
| 42 |
|
| 43 |
reset = "\033[0m" |
| 44 |
color = colors.get(level, "") |
| 45 |
|
| 46 |
if level == "HEADER": |
| 47 |
print(f"\n{color}{'='*60}") |
| 48 |
print(f"{message}") |
| 49 |
print(f"{'='*60}{reset}") |
| 50 |
else: |
| 51 |
symbol = { |
| 52 |
"SUCCESS": "✓", |
| 53 |
"ERROR": "✗", |
| 54 |
"WARNING": "⚠", |
| 55 |
"INFO": "•" |
| 56 |
}.get(level, "•") |
| 57 |
|
| 58 |
print(f"{color}{symbol} {message}{reset}") |
| 59 |
|
| 60 |
def check_flake8_available(self): |
| 61 |
"""Check if flake8 is available.""" |
| 62 |
try: |
| 63 |
result = subprocess.run(["flake8", "--version"], |
| 64 |
capture_output=True, text=True, timeout=5) |
| 65 |
if result.returncode == 0: |
| 66 |
version = result.stdout.strip().split('\n')[0] |
| 67 |
self.log(f"Using flake8: {version}") |
| 68 |
return True |
| 69 |
else: |
| 70 |
return False |
| 71 |
except (subprocess.TimeoutExpired, FileNotFoundError): |
| 72 |
return False |
| 73 |
|
| 74 |
def get_python_files(self, directory=None, staged_only=False): |
| 75 |
"""Get list of Python files to check.""" |
| 76 |
if staged_only: |
| 77 |
try: |
| 78 |
result = subprocess.run([ |
| 79 |
"git", "diff", "--cached", "--name-only", "--diff-filter=ACM" |
| 80 |
], capture_output=True, text=True, timeout=10) |
| 81 |
|
| 82 |
if result.returncode == 0: |
| 83 |
files = [f for f in result.stdout.strip().split('\n') |
| 84 |
if f.endswith('.py') and Path(f).exists()] |
| 85 |
return [Path(f) for f in files if f] |
| 86 |
else: |
| 87 |
self.warnings.append("Could not get staged files, checking all files") |
| 88 |
staged_only = False |
| 89 |
except subprocess.TimeoutExpired: |
| 90 |
self.warnings.append("Git command timed out, checking all files") |
| 91 |
staged_only = False |
| 92 |
|
| 93 |
if not staged_only: |
| 94 |
directory = Path(directory or "src/fenrirscreenreader") |
| 95 |
if not directory.exists(): |
| 96 |
self.errors.append(f"Directory {directory} does not exist") |
| 97 |
return [] |
| 98 |
|
| 99 |
python_files = list(directory.rglob("*.py")) |
| 100 |
# Filter out cache and build directories |
| 101 |
python_files = [f for f in python_files if not any( |
| 102 |
part.startswith(('__pycache__', '.git', 'build', 'dist')) |
| 103 |
for part in f.parts)] |
| 104 |
return python_files |
| 105 |
|
| 106 |
return [] |
| 107 |
|
| 108 |
def run_flake8(self, files, select=None, ignore=None): |
| 109 |
"""Run flake8 on the given files.""" |
| 110 |
if not files: |
| 111 |
return True, "" |
| 112 |
|
| 113 |
cmd = ["flake8"] |
| 114 |
|
| 115 |
if select: |
| 116 |
cmd.extend(["--select", select]) |
| 117 |
if ignore: |
| 118 |
cmd.extend(["--ignore", ignore]) |
| 119 |
|
| 120 |
# Add files |
| 121 |
cmd.extend([str(f) for f in files]) |
| 122 |
|
| 123 |
try: |
| 124 |
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30) |
| 125 |
return result.returncode == 0, result.stdout |
| 126 |
except subprocess.TimeoutExpired: |
| 127 |
self.errors.append("flake8 command timed out") |
| 128 |
return False, "" |
| 129 |
except Exception as e: |
| 130 |
self.errors.append(f"Failed to run flake8: {e}") |
| 131 |
return False, "" |
| 132 |
|
| 133 |
def categorize_issues(self, flake8_output): |
| 134 |
"""Categorize flake8 issues by severity and safety for auto-fixing.""" |
| 135 |
lines = flake8_output.strip().split('\n') |
| 136 |
issues = {'critical': [], 'safe_fixable': [], 'manual': []} |
| 137 |
|
| 138 |
for line in lines: |
| 139 |
if not line.strip(): |
| 140 |
continue |
| 141 |
|
| 142 |
# Parse flake8 output: filename:line:col: code message |
| 143 |
parts = line.split(':', 3) |
| 144 |
if len(parts) < 4: |
| 145 |
continue |
| 146 |
|
| 147 |
filename = parts[0] |
| 148 |
line_num = parts[1] |
| 149 |
col = parts[2] |
| 150 |
code_msg = parts[3].strip() |
| 151 |
|
| 152 |
code = code_msg.split()[0] if code_msg else "" |
| 153 |
|
| 154 |
# Categorize by error code |
| 155 |
if code.startswith('E9') or code.startswith('F'): |
| 156 |
# Critical syntax/import errors |
| 157 |
issues['critical'].append(line) |
| 158 |
elif code in ['E111', 'E114', 'E117', 'E121', 'E122', 'E123', 'E124', |
| 159 |
'E125', 'E126', 'E127', 'E128', 'E129', 'E131', 'E133', |
| 160 |
'W291', 'W292', 'W293']: |
| 161 |
# Safe indentation and whitespace fixes |
| 162 |
# But skip timing-critical files |
| 163 |
if not any(critical in filename.lower() for critical in |
| 164 |
['evdevdriver', 'vcsadriver', 'screenmanager', 'inputmanager']): |
| 165 |
issues['safe_fixable'].append(line) |
| 166 |
else: |
| 167 |
issues['manual'].append(line) |
| 168 |
else: |
| 169 |
# Everything else needs manual review |
| 170 |
issues['manual'].append(line) |
| 171 |
|
| 172 |
return issues |
| 173 |
|
| 174 |
def apply_safe_fixes(self, files): |
| 175 |
"""Apply safe automatic fixes using autopep8.""" |
| 176 |
try: |
| 177 |
# Check if autopep8 is available |
| 178 |
result = subprocess.run(["autopep8", "--version"], |
| 179 |
capture_output=True, text=True, timeout=5) |
| 180 |
if result.returncode != 0: |
| 181 |
self.warnings.append("autopep8 not available for auto-fixing") |
| 182 |
return False |
| 183 |
except (subprocess.TimeoutExpired, FileNotFoundError): |
| 184 |
self.warnings.append("autopep8 not available for auto-fixing") |
| 185 |
return False |
| 186 |
|
| 187 |
fixed_count = 0 |
| 188 |
|
| 189 |
for file_path in files: |
| 190 |
# Skip timing-critical files |
| 191 |
if any(critical in str(file_path).lower() for critical in |
| 192 |
['evdevdriver', 'vcsadriver', 'screenmanager', 'inputmanager']): |
| 193 |
self.log(f"Skipping timing-critical file: {file_path}", "WARNING") |
| 194 |
continue |
| 195 |
|
| 196 |
try: |
| 197 |
# Apply safe fixes only |
| 198 |
cmd = [ |
| 199 |
"autopep8", |
| 200 |
"--in-place", |
| 201 |
"--select", "E111,E114,E117,E121,E122,E123,E124,E125,E126,E127,E128,E129,E131,E133,W291,W292,W293", |
| 202 |
str(file_path) |
| 203 |
] |
| 204 |
|
| 205 |
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10) |
| 206 |
if result.returncode == 0: |
| 207 |
self.fixes_applied.append(f"Applied safe PEP8 fixes to {file_path}") |
| 208 |
fixed_count += 1 |
| 209 |
else: |
| 210 |
self.warnings.append(f"Could not auto-fix {file_path}: {result.stderr}") |
| 211 |
|
| 212 |
except subprocess.TimeoutExpired: |
| 213 |
self.warnings.append(f"Auto-fix timed out for {file_path}") |
| 214 |
except Exception as e: |
| 215 |
self.warnings.append(f"Error auto-fixing {file_path}: {e}") |
| 216 |
|
| 217 |
return fixed_count > 0 |
| 218 |
|
| 219 |
def validate_files(self, files, fix_safe=False): |
| 220 |
"""Validate Python files for PEP8 compliance.""" |
| 221 |
if not files: |
| 222 |
self.log("No Python files to validate") |
| 223 |
return True |
| 224 |
|
| 225 |
self.log(f"Validating {len(files)} Python files") |
| 226 |
|
| 227 |
# Run comprehensive flake8 check |
| 228 |
success, output = self.run_flake8(files) |
| 229 |
|
| 230 |
if not output.strip(): |
| 231 |
self.log("All files pass PEP8 validation", "SUCCESS") |
| 232 |
return True |
| 233 |
|
| 234 |
# Categorize issues |
| 235 |
issues = self.categorize_issues(output) |
| 236 |
|
| 237 |
# Report critical issues |
| 238 |
if issues['critical']: |
| 239 |
self.log(f"Critical issues found ({len(issues['critical'])}):", "ERROR") |
| 240 |
for issue in issues['critical'][:10]: # Limit output |
| 241 |
self.log(f" {issue}", "ERROR") |
| 242 |
if len(issues['critical']) > 10: |
| 243 |
self.log(f" ... and {len(issues['critical']) - 10} more", "ERROR") |
| 244 |
|
| 245 |
# Handle safe fixable issues |
| 246 |
if issues['safe_fixable']: |
| 247 |
if fix_safe: |
| 248 |
self.log(f"Auto-fixing {len(issues['safe_fixable'])} safe issues...", "INFO") |
| 249 |
# Get unique files from safe_fixable issues |
| 250 |
fix_files = set() |
| 251 |
for issue in issues['safe_fixable']: |
| 252 |
filename = issue.split(':')[0] |
| 253 |
fix_files.add(Path(filename)) |
| 254 |
|
| 255 |
if self.apply_safe_fixes(fix_files): |
| 256 |
self.log("Safe auto-fixes applied", "SUCCESS") |
| 257 |
# Re-run flake8 to see remaining issues |
| 258 |
success, output = self.run_flake8(files) |
| 259 |
if output.strip(): |
| 260 |
remaining_issues = self.categorize_issues(output) |
| 261 |
issues = remaining_issues |
| 262 |
else: |
| 263 |
issues = {'critical': [], 'safe_fixable': [], 'manual': []} |
| 264 |
else: |
| 265 |
self.log(f"Safe fixable issues found ({len(issues['safe_fixable'])}):", "WARNING") |
| 266 |
for issue in issues['safe_fixable'][:5]: |
| 267 |
self.log(f" {issue}", "WARNING") |
| 268 |
if len(issues['safe_fixable']) > 5: |
| 269 |
self.log(f" ... and {len(issues['safe_fixable']) - 5} more", "WARNING") |
| 270 |
self.log("Run with --fix-safe to auto-fix these", "INFO") |
| 271 |
|
| 272 |
# Report manual issues |
| 273 |
if issues['manual']: |
| 274 |
self.log(f"Manual review needed ({len(issues['manual'])}):", "WARNING") |
| 275 |
for issue in issues['manual'][:5]: |
| 276 |
self.log(f" {issue}", "WARNING") |
| 277 |
if len(issues['manual']) > 5: |
| 278 |
self.log(f" ... and {len(issues['manual']) - 5} more", "WARNING") |
| 279 |
|
| 280 |
# Return success if only manual issues remain (non-critical) |
| 281 |
return len(issues['critical']) == 0 |
| 282 |
|
| 283 |
def generate_report(self): |
| 284 |
"""Generate final validation report.""" |
| 285 |
total_issues = len(self.errors) + len(self.warnings) |
| 286 |
|
| 287 |
if self.fixes_applied: |
| 288 |
self.log(f"\nAUTO-FIXES APPLIED ({len(self.fixes_applied)}):", "HEADER") |
| 289 |
for fix in self.fixes_applied: |
| 290 |
self.log(fix, "SUCCESS") |
| 291 |
|
| 292 |
if self.errors: |
| 293 |
self.log(f"\nERRORS ({len(self.errors)}):", "HEADER") |
| 294 |
for error in self.errors: |
| 295 |
self.log(error, "ERROR") |
| 296 |
|
| 297 |
if self.warnings: |
| 298 |
self.log(f"\nWARNINGS ({len(self.warnings)}):", "HEADER") |
| 299 |
for warning in self.warnings: |
| 300 |
self.log(warning, "WARNING") |
| 301 |
|
| 302 |
if len(self.errors) == 0: |
| 303 |
self.log("\n✅ PEP8 VALIDATION PASSED", "SUCCESS") |
| 304 |
if self.warnings: |
| 305 |
self.log("Non-critical style issues found - consider manual review", "INFO") |
| 306 |
return True |
| 307 |
else: |
| 308 |
self.log("\n❌ PEP8 VALIDATION FAILED", "ERROR") |
| 309 |
self.log("Critical issues must be fixed", "ERROR") |
| 310 |
return False |
| 311 |
|
| 312 |
|
| 313 |
def main(): |
| 314 |
parser = argparse.ArgumentParser(description='Validate and fix PEP8 compliance in Fenrir') |
| 315 |
parser.add_argument('--fix-safe', action='store_true', |
| 316 |
help='Apply safe automatic fixes (avoids timing-critical files)') |
| 317 |
parser.add_argument('--check-only', action='store_true', |
| 318 |
help='Exit with non-zero code if issues found') |
| 319 |
parser.add_argument('--staged', action='store_true', |
| 320 |
help='Check only staged files') |
| 321 |
parser.add_argument('--quiet', action='store_true', |
| 322 |
help='Reduce output verbosity') |
| 323 |
parser.add_argument('--directory', default='src/fenrirscreenreader', |
| 324 |
help='Directory to scan (default: src/fenrirscreenreader)') |
| 325 |
|
| 326 |
args = parser.parse_args() |
| 327 |
|
| 328 |
validator = PEP8Validator(verbose=not args.quiet) |
| 329 |
|
| 330 |
validator.log("FENRIR PEP8 VALIDATION", "HEADER") |
| 331 |
|
| 332 |
# Check if flake8 is available |
| 333 |
if not validator.check_flake8_available(): |
| 334 |
validator.log("flake8 is required but not available", "ERROR") |
| 335 |
validator.log("Install with: pip install flake8", "INFO") |
| 336 |
if args.fix_safe: |
| 337 |
validator.log("For auto-fixing, also install: pip install autopep8", "INFO") |
| 338 |
sys.exit(1) |
| 339 |
|
| 340 |
# Get files to validate |
| 341 |
files = validator.get_python_files( |
| 342 |
directory=args.directory if not args.staged else None, |
| 343 |
staged_only=args.staged |
| 344 |
) |
| 345 |
|
| 346 |
if not files: |
| 347 |
validator.log("No Python files found to validate") |
| 348 |
sys.exit(0) |
| 349 |
|
| 350 |
# Validate files |
| 351 |
success = validator.validate_files(files, fix_safe=args.fix_safe) |
| 352 |
|
| 353 |
# Generate report |
| 354 |
validation_passed = validator.generate_report() |
| 355 |
|
| 356 |
if args.check_only and not validation_passed: |
| 357 |
sys.exit(1) |
| 358 |
elif validation_passed: |
| 359 |
sys.exit(0) |
| 360 |
else: |
| 361 |
sys.exit(1) |
| 362 |
|
| 363 |
|
| 364 |
if __name__ == '__main__': |
| 365 |
main() |