| 1 |
#!/usr/bin/env python3 |
| 2 |
""" |
| 3 |
Fenrir Syntax Validation Tool |
| 4 |
|
| 5 |
Validates Python syntax across the entire Fenrir codebase without writing |
| 6 |
cache files. Designed to catch syntax errors before packaging or releases. |
| 7 |
|
| 8 |
Usage: |
| 9 |
python3 tools/validate_syntax.py # Validate all Python files |
| 10 |
python3 tools/validate_syntax.py --fix # Fix common issues automatically |
| 11 |
python3 tools/validate_syntax.py --check-only # Exit with non-zero if errors found |
| 12 |
""" |
| 13 |
|
| 14 |
import ast |
| 15 |
import os |
| 16 |
import re |
| 17 |
import sys |
| 18 |
import argparse |
| 19 |
import tempfile |
| 20 |
from pathlib import Path |
| 21 |
|
| 22 |
|
| 23 |
class SyntaxValidator: |
| 24 |
def __init__(self): |
| 25 |
self.errors = [] |
| 26 |
self.warnings = [] |
| 27 |
self.fixed = [] |
| 28 |
|
| 29 |
def check_fstring_issues(self, content): |
| 30 |
"""Check for common f-string formatting issues that cause syntax errors.""" |
| 31 |
issues = [] |
| 32 |
lines = content.split('\n') |
| 33 |
|
| 34 |
for i, line in enumerate(lines, 1): |
| 35 |
# Check for f-strings that appear to be broken across lines |
| 36 |
# Pattern: f"some text { |
| 37 |
if re.search(r'f"[^"]*{[^}]*$', line.strip()): |
| 38 |
issues.append(f"Line {i}: Potential broken multiline f-string") |
| 39 |
|
| 40 |
return issues |
| 41 |
|
| 42 |
def validate_file(self, filepath): |
| 43 |
"""Validate syntax of a single Python file.""" |
| 44 |
try: |
| 45 |
with open(filepath, 'r', encoding='utf-8') as f: |
| 46 |
content = f.read() |
| 47 |
|
| 48 |
# Check for specific f-string issues before AST parsing |
| 49 |
fstring_issues = self.check_fstring_issues(content) |
| 50 |
if fstring_issues: |
| 51 |
# Create a synthetic syntax error for f-string issues |
| 52 |
error_msg = f"F-string issues: {'; '.join(fstring_issues)}" |
| 53 |
self.errors.append((filepath, SyntaxError(error_msg), content)) |
| 54 |
return False, content |
| 55 |
|
| 56 |
# Parse with AST (catches syntax errors) |
| 57 |
ast.parse(content, filename=str(filepath)) |
| 58 |
return True, content |
| 59 |
|
| 60 |
except SyntaxError as e: |
| 61 |
error_msg = f"{filepath}:{e.lineno}: {e.msg}" |
| 62 |
self.errors.append((filepath, e, content)) |
| 63 |
return False, content |
| 64 |
|
| 65 |
except UnicodeDecodeError as e: |
| 66 |
error_msg = f"{filepath}: Unicode decode error: {e}" |
| 67 |
self.errors.append((filepath, e, None)) |
| 68 |
return False, None |
| 69 |
|
| 70 |
except Exception as e: |
| 71 |
error_msg = f"{filepath}: Unexpected error: {e}" |
| 72 |
self.errors.append((filepath, e, None)) |
| 73 |
return False, None |
| 74 |
|
| 75 |
def fix_common_issues(self, filepath, content): |
| 76 |
"""Attempt to fix common syntax issues automatically.""" |
| 77 |
if not content: |
| 78 |
return False, content |
| 79 |
|
| 80 |
original_content = content |
| 81 |
fixed_issues = [] |
| 82 |
|
| 83 |
# Fix unterminated f-strings (the main issue from the email) |
| 84 |
lines = content.split('\n') |
| 85 |
modified = False |
| 86 |
|
| 87 |
for i, line in enumerate(lines): |
| 88 |
# Look for f-strings that span multiple lines incorrectly |
| 89 |
if 'f"' in line and line.count('"') % 2 == 1: |
| 90 |
# Check if this looks like a broken multi-line f-string |
| 91 |
indent = len(line) - len(line.lstrip()) |
| 92 |
|
| 93 |
# Look ahead for continuation |
| 94 |
j = i + 1 |
| 95 |
while j < len(lines) and lines[j].strip(): |
| 96 |
next_line = lines[j] |
| 97 |
next_indent = len(next_line) - len(next_line.lstrip()) |
| 98 |
|
| 99 |
# If next line is indented more and has closing brace/quote |
| 100 |
if (next_indent > indent and |
| 101 |
('"' in next_line or '}' in next_line)): |
| 102 |
|
| 103 |
# Try to fix by joining lines properly |
| 104 |
combined_line = line.rstrip() |
| 105 |
continuation = next_line.strip() |
| 106 |
|
| 107 |
if continuation.startswith(('"', '}', 'str(e)', 'self.', 'fenrirVersion.')): |
| 108 |
# Fix common patterns |
| 109 |
if 'str(e)}' in continuation: |
| 110 |
fixed_line = line.replace('f"', 'f"').rstrip() + '{' + continuation.replace('"', '') + '}' |
| 111 |
elif continuation.startswith('"'): |
| 112 |
fixed_line = line + continuation |
| 113 |
else: |
| 114 |
fixed_line = line.rstrip() + continuation |
| 115 |
|
| 116 |
lines[i] = fixed_line |
| 117 |
lines[j] = '' # Remove the continuation line |
| 118 |
modified = True |
| 119 |
fixed_issues.append(f"Line {i+1}: Fixed multi-line f-string") |
| 120 |
break |
| 121 |
j += 1 |
| 122 |
|
| 123 |
if modified: |
| 124 |
content = '\n'.join(lines) |
| 125 |
# Clean up empty lines that were created |
| 126 |
content = '\n'.join(line for line in content.split('\n') if line.strip() or not line) |
| 127 |
|
| 128 |
# Verify the fix worked |
| 129 |
try: |
| 130 |
ast.parse(content, filename=str(filepath)) |
| 131 |
self.fixed.append((filepath, fixed_issues)) |
| 132 |
return True, content |
| 133 |
except SyntaxError: |
| 134 |
# Fix didn't work, return original |
| 135 |
return False, original_content |
| 136 |
|
| 137 |
return False, content |
| 138 |
|
| 139 |
def scan_directory(self, directory, fix_mode=False): |
| 140 |
"""Scan directory for Python files and validate them.""" |
| 141 |
python_files = [] |
| 142 |
|
| 143 |
# Find all Python files |
| 144 |
for root, dirs, files in os.walk(directory): |
| 145 |
# Skip cache and build directories |
| 146 |
dirs[:] = [d for d in dirs if not d.startswith(('__pycache__', '.git', 'build', 'dist'))] |
| 147 |
|
| 148 |
for file in files: |
| 149 |
if file.endswith('.py'): |
| 150 |
python_files.append(Path(root) / file) |
| 151 |
|
| 152 |
print(f"Validating {len(python_files)} Python files...") |
| 153 |
|
| 154 |
valid_count = 0 |
| 155 |
fixed_count = 0 |
| 156 |
|
| 157 |
for filepath in sorted(python_files): |
| 158 |
is_valid, content = self.validate_file(filepath) |
| 159 |
|
| 160 |
if is_valid: |
| 161 |
valid_count += 1 |
| 162 |
print(f"ā {filepath}") |
| 163 |
else: |
| 164 |
print(f"ā {filepath}") |
| 165 |
|
| 166 |
if fix_mode and content: |
| 167 |
# Try to fix the file |
| 168 |
was_fixed, fixed_content = self.fix_common_issues(filepath, content) |
| 169 |
if was_fixed: |
| 170 |
# Write the fixed content back |
| 171 |
with open(filepath, 'w', encoding='utf-8') as f: |
| 172 |
f.write(fixed_content) |
| 173 |
print(f" ā Fixed automatically") |
| 174 |
fixed_count += 1 |
| 175 |
|
| 176 |
# Re-validate |
| 177 |
is_valid_now, _ = self.validate_file(filepath) |
| 178 |
if is_valid_now: |
| 179 |
valid_count += 1 |
| 180 |
|
| 181 |
return valid_count, len(python_files), fixed_count |
| 182 |
|
| 183 |
def print_summary(self, valid_count, total_count, fixed_count=0): |
| 184 |
"""Print validation summary.""" |
| 185 |
print(f"\n{'='*60}") |
| 186 |
print(f"SYNTAX VALIDATION SUMMARY") |
| 187 |
print(f"{'='*60}") |
| 188 |
print(f"Valid files: {valid_count}/{total_count}") |
| 189 |
print(f"Invalid files: {total_count - valid_count}") |
| 190 |
if fixed_count > 0: |
| 191 |
print(f"Auto-fixed: {fixed_count}") |
| 192 |
|
| 193 |
if self.errors: |
| 194 |
print(f"\nERRORS ({len(self.errors)}):") |
| 195 |
for filepath, error, _ in self.errors: |
| 196 |
if isinstance(error, SyntaxError): |
| 197 |
print(f" {filepath}:{error.lineno}: {error.msg}") |
| 198 |
else: |
| 199 |
print(f" {filepath}: {error}") |
| 200 |
|
| 201 |
if self.fixed: |
| 202 |
print(f"\nAUTO-FIXES APPLIED ({len(self.fixed)}):") |
| 203 |
for filepath, fixes in self.fixed: |
| 204 |
print(f" {filepath}:") |
| 205 |
for fix in fixes: |
| 206 |
print(f" - {fix}") |
| 207 |
|
| 208 |
success_rate = (valid_count / total_count) * 100 if total_count > 0 else 0 |
| 209 |
print(f"\nSuccess rate: {success_rate:.1f}%") |
| 210 |
|
| 211 |
return len(self.errors) == 0 |
| 212 |
|
| 213 |
|
| 214 |
def main(): |
| 215 |
parser = argparse.ArgumentParser(description='Validate Python syntax in Fenrir codebase') |
| 216 |
parser.add_argument('--fix', action='store_true', |
| 217 |
help='Attempt to fix common syntax issues automatically') |
| 218 |
parser.add_argument('--check-only', action='store_true', |
| 219 |
help='Exit with non-zero code if syntax errors found') |
| 220 |
parser.add_argument('--directory', default='src/fenrirscreenreader', |
| 221 |
help='Directory to scan (default: src/fenrirscreenreader)') |
| 222 |
|
| 223 |
args = parser.parse_args() |
| 224 |
|
| 225 |
# Find project root |
| 226 |
script_dir = Path(__file__).parent |
| 227 |
project_root = script_dir.parent |
| 228 |
target_dir = project_root / args.directory |
| 229 |
|
| 230 |
if not target_dir.exists(): |
| 231 |
print(f"Error: Directory {target_dir} does not exist") |
| 232 |
sys.exit(1) |
| 233 |
|
| 234 |
print(f"Fenrir Syntax Validator") |
| 235 |
print(f"Target directory: {target_dir}") |
| 236 |
print(f"Fix mode: {'ON' if args.fix else 'OFF'}") |
| 237 |
print() |
| 238 |
|
| 239 |
validator = SyntaxValidator() |
| 240 |
valid_count, total_count, fixed_count = validator.scan_directory(target_dir, fix_mode=args.fix) |
| 241 |
|
| 242 |
all_valid = validator.print_summary(valid_count, total_count, fixed_count) |
| 243 |
|
| 244 |
if args.check_only and not all_valid: |
| 245 |
print(f"\nValidation failed: {total_count - valid_count} files have syntax errors") |
| 246 |
sys.exit(1) |
| 247 |
elif not all_valid: |
| 248 |
print(f"\nWarning: {total_count - valid_count} files have syntax errors") |
| 249 |
if not args.fix: |
| 250 |
print("Run with --fix to attempt automatic fixes") |
| 251 |
sys.exit(1) |
| 252 |
else: |
| 253 |
print(f"\nā All {total_count} files have valid syntax") |
| 254 |
sys.exit(0) |
| 255 |
|
| 256 |
|
| 257 |
if __name__ == '__main__': |
| 258 |
main() |