| 1 |
#!/usr/bin/env python3 |
| 2 |
""" |
| 3 |
Fenrir Cache Cleanup Tool |
| 4 |
|
| 5 |
Removes Python cache files and directories from the repository. |
| 6 |
These files should never be committed and can cause issues. |
| 7 |
|
| 8 |
Usage: |
| 9 |
python3 tools/cleanup_cache.py # Show what would be removed |
| 10 |
python3 tools/cleanup_cache.py --remove # Actually remove cache files |
| 11 |
python3 tools/cleanup_cache.py --check # Exit with error if cache files found |
| 12 |
""" |
| 13 |
|
| 14 |
import os |
| 15 |
import sys |
| 16 |
import argparse |
| 17 |
import shutil |
| 18 |
from pathlib import Path |
| 19 |
|
| 20 |
|
| 21 |
class CacheCleanup: |
| 22 |
def __init__(self, verbose=True): |
| 23 |
self.verbose = verbose |
| 24 |
self.cache_dirs = [] |
| 25 |
self.cache_files = [] |
| 26 |
|
| 27 |
def log(self, message, level="INFO"): |
| 28 |
"""Log a message with appropriate formatting.""" |
| 29 |
if not self.verbose and level == "INFO": |
| 30 |
return |
| 31 |
|
| 32 |
colors = { |
| 33 |
"INFO": "\033[0;36m", # Cyan |
| 34 |
"SUCCESS": "\033[0;32m", # Green |
| 35 |
"WARNING": "\033[1;33m", # Yellow |
| 36 |
"ERROR": "\033[0;31m", # Red |
| 37 |
"HEADER": "\033[1;34m", # Bold Blue |
| 38 |
} |
| 39 |
|
| 40 |
reset = "\033[0m" |
| 41 |
color = colors.get(level, "") |
| 42 |
|
| 43 |
if level == "HEADER": |
| 44 |
print(f"\n{color}{'='*60}") |
| 45 |
print(f"{message}") |
| 46 |
print(f"{'='*60}{reset}") |
| 47 |
else: |
| 48 |
symbol = { |
| 49 |
"SUCCESS": "✓", |
| 50 |
"ERROR": "✗", |
| 51 |
"WARNING": "⚠", |
| 52 |
"INFO": "•" |
| 53 |
}.get(level, "•") |
| 54 |
|
| 55 |
print(f"{color}{symbol} {message}{reset}") |
| 56 |
|
| 57 |
def find_cache_files(self, directory): |
| 58 |
"""Find all Python cache files and directories.""" |
| 59 |
directory = Path(directory) |
| 60 |
|
| 61 |
for root, dirs, files in os.walk(directory): |
| 62 |
root_path = Path(root) |
| 63 |
|
| 64 |
# Skip .git directory entirely |
| 65 |
if '.git' in root_path.parts: |
| 66 |
continue |
| 67 |
|
| 68 |
# Find __pycache__ directories |
| 69 |
if '__pycache__' in dirs: |
| 70 |
cache_dir = root_path / '__pycache__' |
| 71 |
self.cache_dirs.append(cache_dir) |
| 72 |
# Don't traverse into __pycache__ directories |
| 73 |
dirs.remove('__pycache__') |
| 74 |
|
| 75 |
# Find .pyc files outside of __pycache__ |
| 76 |
for file in files: |
| 77 |
if file.endswith('.pyc'): |
| 78 |
cache_file = root_path / file |
| 79 |
self.cache_files.append(cache_file) |
| 80 |
|
| 81 |
def show_findings(self): |
| 82 |
"""Display what cache files were found.""" |
| 83 |
total_items = len(self.cache_dirs) + len(self.cache_files) |
| 84 |
|
| 85 |
if total_items == 0: |
| 86 |
self.log("No Python cache files found", "SUCCESS") |
| 87 |
return True |
| 88 |
|
| 89 |
self.log(f"Found {total_items} cache items:", "WARNING") |
| 90 |
|
| 91 |
if self.cache_dirs: |
| 92 |
self.log(f"\n__pycache__ directories ({len(self.cache_dirs)}):", "WARNING") |
| 93 |
for cache_dir in sorted(self.cache_dirs): |
| 94 |
# Show size of directory |
| 95 |
size = self.get_directory_size(cache_dir) |
| 96 |
self.log(f" {cache_dir} ({size} files)", "WARNING") |
| 97 |
|
| 98 |
if self.cache_files: |
| 99 |
self.log(f"\nLoose .pyc files ({len(self.cache_files)}):", "WARNING") |
| 100 |
for cache_file in sorted(self.cache_files): |
| 101 |
# Show file size |
| 102 |
try: |
| 103 |
size = cache_file.stat().st_size |
| 104 |
size_str = self.format_size(size) |
| 105 |
self.log(f" {cache_file} ({size_str})", "WARNING") |
| 106 |
except OSError: |
| 107 |
self.log(f" {cache_file} (size unknown)", "WARNING") |
| 108 |
|
| 109 |
return False |
| 110 |
|
| 111 |
def get_directory_size(self, directory): |
| 112 |
"""Get the number of files in a directory.""" |
| 113 |
try: |
| 114 |
return len(list(directory.rglob('*'))) |
| 115 |
except OSError: |
| 116 |
return 0 |
| 117 |
|
| 118 |
def format_size(self, size_bytes): |
| 119 |
"""Format file size in human-readable format.""" |
| 120 |
if size_bytes < 1024: |
| 121 |
return f"{size_bytes} B" |
| 122 |
elif size_bytes < 1024 * 1024: |
| 123 |
return f"{size_bytes // 1024} KB" |
| 124 |
else: |
| 125 |
return f"{size_bytes // (1024 * 1024)} MB" |
| 126 |
|
| 127 |
def remove_cache_files(self): |
| 128 |
"""Actually remove the cache files and directories.""" |
| 129 |
removed_count = 0 |
| 130 |
errors = [] |
| 131 |
|
| 132 |
# Remove __pycache__ directories |
| 133 |
for cache_dir in self.cache_dirs: |
| 134 |
try: |
| 135 |
if cache_dir.exists(): |
| 136 |
shutil.rmtree(cache_dir) |
| 137 |
self.log(f"Removed directory: {cache_dir}", "SUCCESS") |
| 138 |
removed_count += 1 |
| 139 |
except OSError as e: |
| 140 |
error_msg = f"Failed to remove {cache_dir}: {e}" |
| 141 |
errors.append(error_msg) |
| 142 |
self.log(error_msg, "ERROR") |
| 143 |
|
| 144 |
# Remove .pyc files |
| 145 |
for cache_file in self.cache_files: |
| 146 |
try: |
| 147 |
if cache_file.exists(): |
| 148 |
cache_file.unlink() |
| 149 |
self.log(f"Removed file: {cache_file}", "SUCCESS") |
| 150 |
removed_count += 1 |
| 151 |
except OSError as e: |
| 152 |
error_msg = f"Failed to remove {cache_file}: {e}" |
| 153 |
errors.append(error_msg) |
| 154 |
self.log(error_msg, "ERROR") |
| 155 |
|
| 156 |
if errors: |
| 157 |
self.log(f"Encountered {len(errors)} errors during cleanup", "ERROR") |
| 158 |
return False |
| 159 |
else: |
| 160 |
self.log(f"Successfully removed {removed_count} cache items", "SUCCESS") |
| 161 |
return True |
| 162 |
|
| 163 |
def check_gitignore(self): |
| 164 |
"""Check if .gitignore properly excludes cache files.""" |
| 165 |
gitignore_path = Path('.gitignore') |
| 166 |
if not gitignore_path.exists(): |
| 167 |
self.log("Warning: No .gitignore file found", "WARNING") |
| 168 |
return False |
| 169 |
|
| 170 |
try: |
| 171 |
with open(gitignore_path, 'r') as f: |
| 172 |
content = f.read() |
| 173 |
|
| 174 |
has_pycache = '__pycache__' in content or '__pycache__/' in content |
| 175 |
has_pyc = '*.pyc' in content |
| 176 |
|
| 177 |
if has_pycache and has_pyc: |
| 178 |
self.log("✓ .gitignore properly excludes Python cache files", "SUCCESS") |
| 179 |
return True |
| 180 |
else: |
| 181 |
missing = [] |
| 182 |
if not has_pycache: |
| 183 |
missing.append("__pycache__/") |
| 184 |
if not has_pyc: |
| 185 |
missing.append("*.pyc") |
| 186 |
|
| 187 |
self.log(f"Warning: .gitignore missing: {', '.join(missing)}", "WARNING") |
| 188 |
return False |
| 189 |
|
| 190 |
except OSError as e: |
| 191 |
self.log(f"Could not read .gitignore: {e}", "ERROR") |
| 192 |
return False |
| 193 |
|
| 194 |
def suggest_gitignore_additions(self): |
| 195 |
"""Suggest additions to .gitignore.""" |
| 196 |
self.log("\nRecommended .gitignore entries for Python:", "INFO") |
| 197 |
print(""" |
| 198 |
# Byte-compiled / optimized / DLL files |
| 199 |
__pycache__/ |
| 200 |
*.py[cod] |
| 201 |
*.so |
| 202 |
|
| 203 |
# Distribution / packaging |
| 204 |
.Python |
| 205 |
build/ |
| 206 |
develop-eggs/ |
| 207 |
dist/ |
| 208 |
downloads/ |
| 209 |
eggs/ |
| 210 |
.eggs/ |
| 211 |
lib/ |
| 212 |
lib64/ |
| 213 |
parts/ |
| 214 |
sdist/ |
| 215 |
var/ |
| 216 |
wheels/ |
| 217 |
*.egg-info/ |
| 218 |
.installed.cfg |
| 219 |
*.egg |
| 220 |
""") |
| 221 |
|
| 222 |
|
| 223 |
def main(): |
| 224 |
parser = argparse.ArgumentParser(description='Clean Python cache files from Fenrir repository') |
| 225 |
parser.add_argument('--remove', action='store_true', |
| 226 |
help='Actually remove cache files (default is dry-run)') |
| 227 |
parser.add_argument('--check', action='store_true', |
| 228 |
help='Exit with non-zero code if cache files found') |
| 229 |
parser.add_argument('--quiet', action='store_true', |
| 230 |
help='Reduce output verbosity') |
| 231 |
parser.add_argument('--directory', default='.', |
| 232 |
help='Directory to scan (default: current directory)') |
| 233 |
|
| 234 |
args = parser.parse_args() |
| 235 |
|
| 236 |
# Ensure we're in the project root |
| 237 |
if not Path("src/fenrirscreenreader").exists(): |
| 238 |
print("Error: Must be run from Fenrir project root directory") |
| 239 |
sys.exit(1) |
| 240 |
|
| 241 |
cleanup = CacheCleanup(verbose=not args.quiet) |
| 242 |
|
| 243 |
cleanup.log("FENRIR CACHE CLEANUP", "HEADER") |
| 244 |
cleanup.log(f"Scanning directory: {Path(args.directory).absolute()}") |
| 245 |
|
| 246 |
# Find cache files |
| 247 |
cleanup.find_cache_files(args.directory) |
| 248 |
|
| 249 |
# Show what we found |
| 250 |
no_cache_found = cleanup.show_findings() |
| 251 |
|
| 252 |
if no_cache_found: |
| 253 |
# Check .gitignore anyway |
| 254 |
cleanup.check_gitignore() |
| 255 |
cleanup.log("\n✅ Repository is clean of Python cache files", "SUCCESS") |
| 256 |
sys.exit(0) |
| 257 |
|
| 258 |
# Check .gitignore |
| 259 |
gitignore_ok = cleanup.check_gitignore() |
| 260 |
if not gitignore_ok: |
| 261 |
cleanup.suggest_gitignore_additions() |
| 262 |
|
| 263 |
# Handle different modes |
| 264 |
if args.remove: |
| 265 |
cleanup.log("\n🧹 REMOVING CACHE FILES", "HEADER") |
| 266 |
success = cleanup.remove_cache_files() |
| 267 |
if success: |
| 268 |
cleanup.log("\n✅ Cache cleanup completed successfully", "SUCCESS") |
| 269 |
sys.exit(0) |
| 270 |
else: |
| 271 |
cleanup.log("\n❌ Cache cleanup completed with errors", "ERROR") |
| 272 |
sys.exit(1) |
| 273 |
|
| 274 |
elif args.check: |
| 275 |
cleanup.log("\n❌ Cache files found - validation failed", "ERROR") |
| 276 |
cleanup.log("Run with --remove to clean up cache files", "INFO") |
| 277 |
sys.exit(1) |
| 278 |
|
| 279 |
else: |
| 280 |
# Dry run mode |
| 281 |
cleanup.log("\n💡 DRY RUN MODE", "HEADER") |
| 282 |
cleanup.log("Add --remove to actually delete these files", "INFO") |
| 283 |
cleanup.log("Add --check to fail if cache files are present", "INFO") |
| 284 |
sys.exit(0) |
| 285 |
|
| 286 |
|
| 287 |
if __name__ == '__main__': |
| 288 |
main() |