sirus / backend /core /scripts /clean_pycache.py
ranilmukesh's picture
Deploy SiRUS SQL Agent backend
b8277c4
#!/usr/bin/env python3
"""
🧹 PYTHON CACHE CLEANER
Removes all __pycache__ folders and .pyc files from the backend directory
"""
import os
import shutil
import sys
from pathlib import Path
from typing import List, Tuple
def find_pycache_dirs(root_dir: str) -> List[str]:
"""Find all __pycache__ directories recursively"""
pycache_dirs = []
for root, dirs, files in os.walk(root_dir):
if '__pycache__' in dirs:
pycache_path = os.path.join(root, '__pycache__')
pycache_dirs.append(pycache_path)
return pycache_dirs
def find_pyc_files(root_dir: str) -> List[str]:
"""Find all .pyc files recursively"""
pyc_files = []
for root, dirs, files in os.walk(root_dir):
for file in files:
if file.endswith('.pyc'):
pyc_path = os.path.join(root, file)
pyc_files.append(pyc_path)
return pyc_files
def delete_pycache_dirs(pycache_dirs: List[str]) -> Tuple[int, List[str]]:
"""Delete __pycache__ directories and return count and any errors"""
deleted_count = 0
errors = []
for pycache_dir in pycache_dirs:
try:
shutil.rmtree(pycache_dir)
print(f"βœ… Deleted: {pycache_dir}")
deleted_count += 1
except Exception as e:
error_msg = f"❌ Failed to delete {pycache_dir}: {str(e)}"
print(error_msg)
errors.append(error_msg)
return deleted_count, errors
def delete_pyc_files(pyc_files: List[str]) -> Tuple[int, List[str]]:
"""Delete .pyc files and return count and any errors"""
deleted_count = 0
errors = []
for pyc_file in pyc_files:
try:
os.remove(pyc_file)
print(f"βœ… Deleted: {pyc_file}")
deleted_count += 1
except Exception as e:
error_msg = f"❌ Failed to delete {pyc_file}: {str(e)}"
print(error_msg)
errors.append(error_msg)
return deleted_count, errors
def get_directory_size(root_dir: str) -> int:
"""Calculate total size of __pycache__ directories in bytes"""
total_size = 0
for root, dirs, files in os.walk(root_dir):
if '__pycache__' in dirs:
pycache_path = os.path.join(root, '__pycache__')
try:
for dirpath, dirnames, filenames in os.walk(pycache_path):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
try:
total_size += os.path.getsize(filepath)
except (OSError, FileNotFoundError):
pass
except (OSError, FileNotFoundError):
pass
return total_size
def format_size(size_bytes: int) -> str:
"""Format size in human readable format"""
if size_bytes == 0:
return "0 B"
size_names = ["B", "KB", "MB", "GB"]
i = 0
size = float(size_bytes)
while size >= 1024.0 and i < len(size_names) - 1:
size /= 1024.0
i += 1
return f"{size:.1f} {size_names[i]}"
def main():
"""Main function to clean Python cache files"""
print("🧹 PYTHON CACHE CLEANER")
print("=" * 50)
# Get the backend directory (current script's directory)
backend_dir = os.path.dirname(os.path.abspath(__file__))
print(f"πŸ“ Scanning directory: {backend_dir}")
# Calculate cache size before deletion
print("\nπŸ“Š Analyzing cache files...")
cache_size = get_directory_size(backend_dir)
print(f"πŸ’Ύ Total cache size: {format_size(cache_size)}")
# Find all cache files and directories
pycache_dirs = find_pycache_dirs(backend_dir)
pyc_files = find_pyc_files(backend_dir)
print(f"\nπŸ” Found:")
print(f" πŸ“‚ __pycache__ directories: {len(pycache_dirs)}")
print(f" πŸ“„ .pyc files: {len(pyc_files)}")
if len(pycache_dirs) == 0 and len(pyc_files) == 0:
print("\n✨ No cache files found! Directory is already clean.")
return
# Show what will be deleted
print(f"\nπŸ“‹ Cache directories to delete:")
for pycache_dir in pycache_dirs:
rel_path = os.path.relpath(pycache_dir, backend_dir)
print(f" πŸ—‚οΈ {rel_path}")
if pyc_files:
print(f"\nπŸ“‹ .pyc files to delete:")
for pyc_file in pyc_files[:10]: # Show first 10
rel_path = os.path.relpath(pyc_file, backend_dir)
print(f" πŸ“„ {rel_path}")
if len(pyc_files) > 10:
print(f" ... and {len(pyc_files) - 10} more")
# Ask for confirmation
print(f"\n⚠️ This will permanently delete {len(pycache_dirs)} directories and {len(pyc_files)} files")
print(f"πŸ’Ύ Total space to be freed: {format_size(cache_size)}")
try:
confirm = input("\nπŸ€” Proceed with deletion? (y/N): ").strip().lower()
if confirm not in ['y', 'yes']:
print("❌ Operation cancelled by user")
return
except KeyboardInterrupt:
print("\n❌ Operation cancelled by user")
return
print(f"\n🧹 Starting cleanup...")
# Delete __pycache__ directories
dirs_deleted, dir_errors = delete_pycache_dirs(pycache_dirs)
# Delete .pyc files
files_deleted, file_errors = delete_pyc_files(pyc_files)
# Summary
print(f"\nπŸ“Š CLEANUP SUMMARY")
print("=" * 30)
print(f"βœ… Directories deleted: {dirs_deleted}/{len(pycache_dirs)}")
print(f"βœ… Files deleted: {files_deleted}/{len(pyc_files)}")
print(f"πŸ’Ύ Space freed: {format_size(cache_size)}")
if dir_errors or file_errors:
print(f"\n⚠️ ERRORS ENCOUNTERED:")
for error in dir_errors + file_errors:
print(f" {error}")
print(f"\n❌ {len(dir_errors + file_errors)} errors occurred during cleanup")
else:
print(f"\nπŸŽ‰ Cleanup completed successfully!")
# Final verification
remaining_pycache = find_pycache_dirs(backend_dir)
remaining_pyc = find_pyc_files(backend_dir)
if remaining_pycache or remaining_pyc:
print(f"\n⚠️ Warning: {len(remaining_pycache)} __pycache__ dirs and {len(remaining_pyc)} .pyc files still remain")
else:
print(f"\n✨ All Python cache files have been successfully removed!")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\n❌ Cleanup interrupted by user")
sys.exit(1)
except Exception as e:
print(f"\n\nπŸ’₯ Unexpected error: {str(e)}")
sys.exit(1)