| 1 |
#!/usr/bin/env python3 |
| 2 |
""" |
| 3 |
Fenrir Release Validation Tool |
| 4 |
|
| 5 |
Comprehensive validation suite for Fenrir releases, including syntax validation, |
| 6 |
dependency checking, import testing, and basic functionality validation. |
| 7 |
|
| 8 |
Usage: |
| 9 |
python3 tools/validate_release.py # Full validation |
| 10 |
python3 tools/validate_release.py --quick # Skip slow tests |
| 11 |
python3 tools/validate_release.py --fix # Auto-fix issues where possible |
| 12 |
""" |
| 13 |
|
| 14 |
import ast |
| 15 |
import os |
| 16 |
import sys |
| 17 |
import argparse |
| 18 |
import subprocess |
| 19 |
import tempfile |
| 20 |
import importlib.util |
| 21 |
from pathlib import Path |
| 22 |
import time |
| 23 |
|
| 24 |
|
| 25 |
class ReleaseValidator: |
| 26 |
def __init__(self, verbose=True): |
| 27 |
self.verbose = verbose |
| 28 |
self.errors = [] |
| 29 |
self.warnings = [] |
| 30 |
self.fixes_applied = [] |
| 31 |
self.tests_run = 0 |
| 32 |
self.tests_passed = 0 |
| 33 |
|
| 34 |
def log(self, message, level="INFO"): |
| 35 |
"""Log a message with appropriate formatting.""" |
| 36 |
if not self.verbose and level == "INFO": |
| 37 |
return |
| 38 |
|
| 39 |
colors = { |
| 40 |
"INFO": "\033[0;36m", # Cyan |
| 41 |
"SUCCESS": "\033[0;32m", # Green |
| 42 |
"WARNING": "\033[1;33m", # Yellow |
| 43 |
"ERROR": "\033[0;31m", # Red |
| 44 |
"HEADER": "\033[1;34m", # Bold Blue |
| 45 |
} |
| 46 |
|
| 47 |
reset = "\033[0m" |
| 48 |
color = colors.get(level, "") |
| 49 |
|
| 50 |
if level == "HEADER": |
| 51 |
print(f"\n{color}{'='*60}") |
| 52 |
print(f"{message}") |
| 53 |
print(f"{'='*60}{reset}") |
| 54 |
else: |
| 55 |
symbol = { |
| 56 |
"SUCCESS": "✓", |
| 57 |
"ERROR": "✗", |
| 58 |
"WARNING": "⚠", |
| 59 |
"INFO": "•" |
| 60 |
}.get(level, "•") |
| 61 |
|
| 62 |
print(f"{color}{symbol} {message}{reset}") |
| 63 |
|
| 64 |
def run_test(self, name, test_func, *args, **kwargs): |
| 65 |
"""Run a test and track results.""" |
| 66 |
self.tests_run += 1 |
| 67 |
try: |
| 68 |
result = test_func(*args, **kwargs) |
| 69 |
if result: |
| 70 |
self.tests_passed += 1 |
| 71 |
self.log(f"{name}: PASSED", "SUCCESS") |
| 72 |
else: |
| 73 |
self.log(f"{name}: FAILED", "ERROR") |
| 74 |
return result |
| 75 |
except Exception as e: |
| 76 |
self.log(f"{name}: ERROR - {e}", "ERROR") |
| 77 |
self.errors.append(f"{name}: {e}") |
| 78 |
return False |
| 79 |
|
| 80 |
def validate_python_syntax(self, directory, fix_mode=False): |
| 81 |
"""Validate Python syntax across all files.""" |
| 82 |
python_files = list(Path(directory).rglob("*.py")) |
| 83 |
# Filter out cache and build directories |
| 84 |
python_files = [f for f in python_files if not any(part.startswith(('__pycache__', '.git', 'build', 'dist')) for part in f.parts)] |
| 85 |
|
| 86 |
syntax_errors = [] |
| 87 |
fixed_files = [] |
| 88 |
|
| 89 |
for filepath in python_files: |
| 90 |
try: |
| 91 |
with open(filepath, 'r', encoding='utf-8') as f: |
| 92 |
content = f.read() |
| 93 |
ast.parse(content, filename=str(filepath)) |
| 94 |
except SyntaxError as e: |
| 95 |
syntax_errors.append((filepath, e)) |
| 96 |
|
| 97 |
if fix_mode: |
| 98 |
# Try to fix common f-string issues |
| 99 |
fixed_content = self.fix_fstring_issues(content) |
| 100 |
if fixed_content != content: |
| 101 |
try: |
| 102 |
ast.parse(fixed_content, filename=str(filepath)) |
| 103 |
# Fix worked, write it back |
| 104 |
with open(filepath, 'w', encoding='utf-8') as f: |
| 105 |
f.write(fixed_content) |
| 106 |
fixed_files.append(filepath) |
| 107 |
syntax_errors.pop() # Remove from errors |
| 108 |
except SyntaxError: |
| 109 |
pass # Fix didn't work |
| 110 |
except Exception as e: |
| 111 |
syntax_errors.append((filepath, e)) |
| 112 |
|
| 113 |
if fixed_files: |
| 114 |
self.fixes_applied.extend([f"Fixed f-string syntax in {f}" for f in fixed_files]) |
| 115 |
|
| 116 |
if syntax_errors: |
| 117 |
for filepath, error in syntax_errors[:5]: # Show only first 5 |
| 118 |
if isinstance(error, SyntaxError): |
| 119 |
self.errors.append(f"Syntax error in {filepath}:{error.lineno}: {error.msg}") |
| 120 |
else: |
| 121 |
self.errors.append(f"Error in {filepath}: {error}") |
| 122 |
if len(syntax_errors) > 5: |
| 123 |
self.errors.append(f"... and {len(syntax_errors) - 5} more syntax errors") |
| 124 |
|
| 125 |
return len(syntax_errors) == 0 |
| 126 |
|
| 127 |
def fix_fstring_issues(self, content): |
| 128 |
"""Fix common f-string syntax issues.""" |
| 129 |
lines = content.split('\n') |
| 130 |
|
| 131 |
for i, line in enumerate(lines): |
| 132 |
# Look for f-strings that span multiple lines incorrectly |
| 133 |
if ('f"' in line and line.count('"') % 2 == 1 and |
| 134 |
i + 1 < len(lines) and lines[i + 1].strip()): |
| 135 |
|
| 136 |
next_line = lines[i + 1] |
| 137 |
# Common patterns to fix |
| 138 |
if (next_line.strip().endswith('}"') or |
| 139 |
'str(e)}' in next_line or |
| 140 |
next_line.strip().startswith(('fenrirVersion.', 'self.'))): |
| 141 |
|
| 142 |
# Merge the lines properly |
| 143 |
fixed_line = line.rstrip() + next_line.strip() |
| 144 |
lines[i] = fixed_line |
| 145 |
lines[i + 1] = '' |
| 146 |
|
| 147 |
return '\n'.join(line for line in lines if line.strip() or not line) |
| 148 |
|
| 149 |
def validate_dependencies(self): |
| 150 |
"""Run the existing dependency checker.""" |
| 151 |
try: |
| 152 |
result = subprocess.run([ |
| 153 |
sys.executable, "check-dependencies.py" |
| 154 |
], capture_output=True, text=True, timeout=30) |
| 155 |
|
| 156 |
if result.returncode == 0: |
| 157 |
return True |
| 158 |
else: |
| 159 |
self.errors.append(f"Dependency check failed: {result.stderr}") |
| 160 |
return False |
| 161 |
except subprocess.TimeoutExpired: |
| 162 |
self.errors.append("Dependency check timed out") |
| 163 |
return False |
| 164 |
except Exception as e: |
| 165 |
self.errors.append(f"Could not run dependency check: {e}") |
| 166 |
return False |
| 167 |
|
| 168 |
def validate_core_imports(self): |
| 169 |
"""Test importing core Fenrir modules.""" |
| 170 |
# Change to src directory for imports |
| 171 |
original_path = sys.path.copy() |
| 172 |
src_dir = Path.cwd() / "src" |
| 173 |
if src_dir.exists(): |
| 174 |
sys.path.insert(0, str(src_dir)) |
| 175 |
|
| 176 |
core_modules = [ |
| 177 |
"fenrirscreenreader.core.fenrirManager", |
| 178 |
"fenrirscreenreader.core.commandManager", |
| 179 |
"fenrirscreenreader.core.eventManager", |
| 180 |
"fenrirscreenreader.core.screenManager", |
| 181 |
"fenrirscreenreader.core.inputManager", |
| 182 |
"fenrirscreenreader.core.outputManager", |
| 183 |
] |
| 184 |
|
| 185 |
import_failures = [] |
| 186 |
|
| 187 |
for module_name in core_modules: |
| 188 |
try: |
| 189 |
importlib.import_module(module_name) |
| 190 |
except ImportError as e: |
| 191 |
import_failures.append(f"{module_name}: {e}") |
| 192 |
except Exception as e: |
| 193 |
import_failures.append(f"{module_name}: Unexpected error: {e}") |
| 194 |
|
| 195 |
# Restore path |
| 196 |
sys.path = original_path |
| 197 |
|
| 198 |
if import_failures: |
| 199 |
self.errors.extend(import_failures) |
| 200 |
return False |
| 201 |
return True |
| 202 |
|
| 203 |
def validate_command_structure(self): |
| 204 |
"""Validate command file structure and naming.""" |
| 205 |
commands_dir = Path("src/fenrirscreenreader/commands") |
| 206 |
if not commands_dir.exists(): |
| 207 |
self.errors.append("Commands directory not found") |
| 208 |
return False |
| 209 |
|
| 210 |
issues = [] |
| 211 |
|
| 212 |
# Check command directories |
| 213 |
expected_dirs = ["commands", "onHeartBeat", "onKeyInput", "onCursorChange", |
| 214 |
"onScreenUpdate", "onScreenChanged", "vmenu-profiles"] |
| 215 |
|
| 216 |
for expected_dir in expected_dirs: |
| 217 |
if not (commands_dir / expected_dir).exists(): |
| 218 |
issues.append(f"Missing expected directory: {expected_dir}") |
| 219 |
|
| 220 |
# Check for critical issues only (skip template files and base classes) |
| 221 |
for py_file in commands_dir.rglob("*.py"): |
| 222 |
if (py_file.name.startswith("__") or |
| 223 |
"template" in py_file.name.lower() or |
| 224 |
"base" in py_file.name.lower()): |
| 225 |
continue |
| 226 |
|
| 227 |
try: |
| 228 |
with open(py_file, 'r', encoding='utf-8') as f: |
| 229 |
content = f.read() |
| 230 |
|
| 231 |
# Critical structure checks only |
| 232 |
if "class command" not in content: |
| 233 |
issues.append(f"{py_file}: Missing 'class command' definition") |
| 234 |
|
| 235 |
# Skip method checks for files that inherit from base classes |
| 236 |
if ("super().__init__" in content or |
| 237 |
"importlib.util" in content or |
| 238 |
"_base.py" in content): |
| 239 |
continue # These inherit methods from base classes |
| 240 |
|
| 241 |
# Only check direct implementations |
| 242 |
# Special case: Application profile commands use load/unload instead of run |
| 243 |
if "onSwitchApplicationProfile" in str(py_file): |
| 244 |
if "def load" not in content and "def unload" not in content: |
| 245 |
issues.append(f"{py_file}: Missing 'load' or 'unload' method") |
| 246 |
else: |
| 247 |
critical_methods = ["run"] # Focus on the most critical method |
| 248 |
for method in critical_methods: |
| 249 |
if (f"def {method}" not in content and |
| 250 |
"super()" not in content): # Skip if uses inheritance |
| 251 |
issues.append(f"{py_file}: Missing '{method}' method") |
| 252 |
|
| 253 |
except Exception as e: |
| 254 |
issues.append(f"{py_file}: Could not validate structure: {e}") |
| 255 |
|
| 256 |
# Only report critical issues, not template/base class warnings |
| 257 |
critical_issues = [issue for issue in issues if not any(skip in issue.lower() |
| 258 |
for skip in ["template", "base", "missing 'initialize'", "missing 'shutdown'"])] |
| 259 |
|
| 260 |
if critical_issues: |
| 261 |
self.warnings.extend(critical_issues[:5]) # Limit warnings |
| 262 |
if len(critical_issues) > 5: |
| 263 |
self.warnings.append(f"... and {len(critical_issues) - 5} more critical command structure issues") |
| 264 |
|
| 265 |
# Return success if no critical issues (warnings are acceptable) |
| 266 |
return len(critical_issues) == 0 |
| 267 |
|
| 268 |
def validate_configuration_files(self): |
| 269 |
"""Validate configuration file structure.""" |
| 270 |
config_dir = Path("config") |
| 271 |
if not config_dir.exists(): |
| 272 |
self.errors.append("Config directory not found") |
| 273 |
return False |
| 274 |
|
| 275 |
required_configs = [ |
| 276 |
"settings/settings.conf", |
| 277 |
"keyboard/desktop.conf", |
| 278 |
"punctuation/default.conf" |
| 279 |
] |
| 280 |
|
| 281 |
missing_configs = [] |
| 282 |
for config_file in required_configs: |
| 283 |
if not (config_dir / config_file).exists(): |
| 284 |
missing_configs.append(config_file) |
| 285 |
|
| 286 |
if missing_configs: |
| 287 |
self.errors.extend([f"Missing config file: {f}" for f in missing_configs]) |
| 288 |
return False |
| 289 |
|
| 290 |
return True |
| 291 |
|
| 292 |
def validate_installation_scripts(self): |
| 293 |
"""Validate installation and setup scripts.""" |
| 294 |
required_scripts = ["setup.py", "install.sh", "uninstall.sh"] |
| 295 |
missing_scripts = [] |
| 296 |
|
| 297 |
for script in required_scripts: |
| 298 |
if not Path(script).exists(): |
| 299 |
missing_scripts.append(script) |
| 300 |
|
| 301 |
if missing_scripts: |
| 302 |
self.warnings.extend([f"Missing installation script: {s}" for s in missing_scripts]) |
| 303 |
|
| 304 |
# Check setup.py syntax if it exists |
| 305 |
if Path("setup.py").exists(): |
| 306 |
try: |
| 307 |
with open("setup.py", 'r') as f: |
| 308 |
content = f.read() |
| 309 |
ast.parse(content, filename="setup.py") |
| 310 |
except SyntaxError as e: |
| 311 |
self.errors.append(f"setup.py syntax error: {e}") |
| 312 |
return False |
| 313 |
|
| 314 |
return len(missing_scripts) == 0 |
| 315 |
|
| 316 |
def validate_repository_cleanliness(self): |
| 317 |
"""Check for cache files and other artifacts that shouldn't be in git.""" |
| 318 |
# Check for Python cache files in git tracking |
| 319 |
try: |
| 320 |
result = subprocess.run([ |
| 321 |
"git", "ls-files", "--cached" |
| 322 |
], capture_output=True, text=True, timeout=10) |
| 323 |
|
| 324 |
if result.returncode == 0: |
| 325 |
tracked_files = result.stdout.strip().split('\n') |
| 326 |
cache_files = [f for f in tracked_files if '__pycache__' in f or f.endswith('.pyc')] |
| 327 |
|
| 328 |
if cache_files: |
| 329 |
self.errors.extend([f"Python cache file tracked in git: {f}" for f in cache_files[:5]]) |
| 330 |
if len(cache_files) > 5: |
| 331 |
self.errors.append(f"... and {len(cache_files) - 5} more cache files in git") |
| 332 |
return False |
| 333 |
else: |
| 334 |
return True |
| 335 |
else: |
| 336 |
self.warnings.append("Could not check git tracked files") |
| 337 |
return True |
| 338 |
|
| 339 |
except subprocess.TimeoutExpired: |
| 340 |
self.warnings.append("Git check timed out") |
| 341 |
return True |
| 342 |
except Exception as e: |
| 343 |
self.warnings.append(f"Could not check repository cleanliness: {e}") |
| 344 |
return True |
| 345 |
|
| 346 |
def generate_report(self): |
| 347 |
"""Generate final validation report.""" |
| 348 |
self.log("FENRIR RELEASE VALIDATION REPORT", "HEADER") |
| 349 |
|
| 350 |
# Test Summary |
| 351 |
success_rate = (self.tests_passed / self.tests_run * 100) if self.tests_run > 0 else 0 |
| 352 |
self.log(f"Tests run: {self.tests_run}") |
| 353 |
self.log(f"Tests passed: {self.tests_passed}") |
| 354 |
self.log(f"Success rate: {success_rate:.1f}%") |
| 355 |
|
| 356 |
# Fixes Applied |
| 357 |
if self.fixes_applied: |
| 358 |
self.log("\nAUTO-FIXES APPLIED:", "HEADER") |
| 359 |
for fix in self.fixes_applied: |
| 360 |
self.log(fix, "SUCCESS") |
| 361 |
|
| 362 |
# Errors |
| 363 |
if self.errors: |
| 364 |
self.log(f"\nERRORS ({len(self.errors)}):", "HEADER") |
| 365 |
for error in self.errors: |
| 366 |
self.log(error, "ERROR") |
| 367 |
|
| 368 |
# Warnings |
| 369 |
if self.warnings: |
| 370 |
self.log(f"\nWARNINGS ({len(self.warnings)}):", "HEADER") |
| 371 |
for warning in self.warnings: |
| 372 |
self.log(warning, "WARNING") |
| 373 |
|
| 374 |
# Final Status |
| 375 |
if not self.errors and success_rate >= 80: |
| 376 |
self.log("\n🎉 RELEASE VALIDATION PASSED", "SUCCESS") |
| 377 |
self.log("The codebase appears ready for release", "SUCCESS") |
| 378 |
return True |
| 379 |
elif not self.errors: |
| 380 |
self.log("\n⚠️ RELEASE VALIDATION PASSED WITH WARNINGS", "WARNING") |
| 381 |
self.log("Release is possible but issues should be addressed", "WARNING") |
| 382 |
return True |
| 383 |
else: |
| 384 |
self.log("\n❌ RELEASE VALIDATION FAILED", "ERROR") |
| 385 |
self.log("Critical issues must be fixed before release", "ERROR") |
| 386 |
return False |
| 387 |
|
| 388 |
|
| 389 |
def main(): |
| 390 |
parser = argparse.ArgumentParser(description='Comprehensive Fenrir release validation') |
| 391 |
parser.add_argument('--quick', action='store_true', |
| 392 |
help='Skip slow tests (dependency checking)') |
| 393 |
parser.add_argument('--fix', action='store_true', |
| 394 |
help='Attempt to fix issues automatically where possible') |
| 395 |
parser.add_argument('--quiet', action='store_true', |
| 396 |
help='Reduce output verbosity') |
| 397 |
|
| 398 |
args = parser.parse_args() |
| 399 |
|
| 400 |
# Ensure we're in the project root |
| 401 |
if not Path("src/fenrirscreenreader").exists(): |
| 402 |
print("Error: Must be run from Fenrir project root directory") |
| 403 |
sys.exit(1) |
| 404 |
|
| 405 |
validator = ReleaseValidator(verbose=not args.quiet) |
| 406 |
|
| 407 |
validator.log("FENRIR RELEASE VALIDATION STARTING", "HEADER") |
| 408 |
start_time = time.time() |
| 409 |
|
| 410 |
# Run validation tests |
| 411 |
validator.run_test( |
| 412 |
"Python syntax validation", |
| 413 |
validator.validate_python_syntax, |
| 414 |
"src/fenrirscreenreader", |
| 415 |
args.fix |
| 416 |
) |
| 417 |
|
| 418 |
if not args.quick: |
| 419 |
validator.run_test( |
| 420 |
"Dependency validation", |
| 421 |
validator.validate_dependencies |
| 422 |
) |
| 423 |
|
| 424 |
validator.run_test( |
| 425 |
"Core module imports", |
| 426 |
validator.validate_core_imports |
| 427 |
) |
| 428 |
|
| 429 |
validator.run_test( |
| 430 |
"Command structure validation", |
| 431 |
validator.validate_command_structure |
| 432 |
) |
| 433 |
|
| 434 |
validator.run_test( |
| 435 |
"Configuration files validation", |
| 436 |
validator.validate_configuration_files |
| 437 |
) |
| 438 |
|
| 439 |
validator.run_test( |
| 440 |
"Installation scripts validation", |
| 441 |
validator.validate_installation_scripts |
| 442 |
) |
| 443 |
|
| 444 |
validator.run_test( |
| 445 |
"Repository cleanliness validation", |
| 446 |
validator.validate_repository_cleanliness |
| 447 |
) |
| 448 |
|
| 449 |
# Generate final report |
| 450 |
elapsed_time = time.time() - start_time |
| 451 |
validator.log(f"\nValidation completed in {elapsed_time:.1f} seconds") |
| 452 |
|
| 453 |
success = validator.generate_report() |
| 454 |
|
| 455 |
sys.exit(0 if success else 1) |
| 456 |
|
| 457 |
|
| 458 |
if __name__ == '__main__': |
| 459 |
main() |