#!/usr/bin/env python3 """ Complete application reset script Removes database, clears cache files, and reinitializes everything """ import os import sys import shutil import logging import importlib from pathlib import Path # Configure logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger("app-reset") # Application paths DB_FILES = ["app.db", "instance/app.db"] UPLOADS_FOLDER = "uploads" PYCACHE_PATTERN = "**/__pycache__" def confirm_reset(): """Get user confirmation before proceeding""" print("\nāš ļø WARNING: This will completely reset the application āš ļø") print("šŸ“¢ All data will be lost, including:") print(" - Database and all its tables") print(" - All uploaded files") print(" - Cache files and temporary data") print("\nAre you absolutely sure you want to continue?") return input("Type 'yes' to confirm: ").lower() == 'yes' def remove_database_files(): """Remove all database files""" success = True for db_file in DB_FILES: if os.path.exists(db_file): try: logger.info(f"Removing database file: {db_file}") os.remove(db_file) except Exception as e: logger.error(f"Failed to remove {db_file}: {e}") success = False return success def clear_uploads_directory(): """Clear all uploaded files but keep the directory""" if not os.path.exists(UPLOADS_FOLDER): logger.info(f"Creating uploads folder: {UPLOADS_FOLDER}") os.makedirs(UPLOADS_FOLDER, exist_ok=True) return True try: logger.info(f"Clearing uploads folder: {UPLOADS_FOLDER}") for item in os.listdir(UPLOADS_FOLDER): path = os.path.join(UPLOADS_FOLDER, item) if os.path.isfile(path): os.remove(path) elif os.path.isdir(path): shutil.rmtree(path) return True except Exception as e: logger.error(f"Failed to clear uploads directory: {e}") return False def clear_pycache_files(): """Clear all __pycache__ directories""" try: logger.info("Clearing Python cache files...") count = 0 for cache_dir in Path('.').glob(PYCACHE_PATTERN): if cache_dir.is_dir(): shutil.rmtree(cache_dir) count += 1 logger.info(f"Removed {count} __pycache__ directories") return True except Exception as e: logger.error(f"Failed to clear cache files: {e}") return False def initialize_application(create_admin=False): """Initialize the application with fresh database""" try: logger.info("Initializing Flask application...") # Force reload the app module if 'app' in sys.modules: importlib.reload(sys.modules['app']) # Import and create app from app import create_app, db app = create_app() with app.app_context(): logger.info("Creating database tables...") db.create_all() # Create admin user if requested if create_admin: from app.models import User, Share if User.query.filter_by(username='admin').first() is None: admin = User(username='admin', email='admin@example.com', is_admin=True) admin.password = 'adminpassword' db.session.add(admin) db.session.commit() logger.info("Created admin user (username: admin, password: adminpassword)") else: logger.info("Admin user already exists") else: logger.info("Skipping admin user creation as requested") logger.info("Application initialized successfully") return True except Exception as e: logger.error(f"Failed to initialize application: {e}") return False def main(): """Main reset procedure""" print("\nšŸ”„ Flask Files Application Reset Tool šŸ”„\n") if not confirm_reset(): print("\nāŒ Reset cancelled by user") return False create_admin = input("\nCreate admin user? (yes/no): ").lower() == 'yes' print("\nšŸš€ Starting reset process...\n") # Step 1: Remove database files if remove_database_files(): logger.info("āœ… Database files removed successfully") else: logger.error("āŒ Failed to remove some database files") # Step 2: Clear uploads directory if clear_uploads_directory(): logger.info("āœ… Uploads directory cleared successfully") else: logger.error("āŒ Failed to clear uploads directory") # Step 3: Clear cache files if clear_pycache_files(): logger.info("āœ… Python cache files cleared successfully") else: logger.error("āŒ Failed to clear cache files") # Step 4: Initialize application if initialize_application(create_admin): logger.info("āœ… Application initialized successfully") else: logger.error("āŒ Failed to initialize application") return False print("\n✨ Reset completed successfully! ✨") print("\nYou can now start the application with 'python run.py'") if create_admin: print("Default admin credentials: username=admin, password=adminpassword") return True if __name__ == "__main__": sys.exit(0 if main() else 1)