#!/usr/bin/env python3 """ 旧代码清理脚本 此脚本用于安全地删除已废弃的旧代码。 在运行此脚本之前,请确保: 1. 新代码已经过充分测试 2. 所有导入引用已更新 3. 已创建数据备份 警告:此操作不可逆! """ import os import shutil from pathlib import Path from typing import List import argparse # 要删除的旧代码目录 OLD_CODE_DIRS = [ 'src/api/sdk', 'src/api/db', 'src/api/dataset', 'src/api/mcp', ] # 要保留的文件(用于向后兼容) KEEP_FILES = [ 'src/api/__init__.py', # 包含废弃警告 'src/api/DEPRECATED.md', # 废弃说明文档 ] def list_files_to_delete(dirs: List[str]) -> List[Path]: """ 列出将要删除的文件 Args: dirs: 要删除的目录列表 Returns: 文件路径列表 """ files_to_delete = [] for dir_path in dirs: path = Path(dir_path) if path.exists() and path.is_dir(): for file_path in path.rglob('*'): if file_path.is_file(): files_to_delete.append(file_path) return files_to_delete def calculate_size(files: List[Path]) -> int: """ 计算文件总大小 Args: files: 文件路径列表 Returns: 总大小(字节) """ total_size = 0 for file_path in files: try: total_size += file_path.stat().st_size except Exception: pass return total_size def format_size(size_bytes: int) -> str: """ 格式化文件大小 Args: size_bytes: 字节数 Returns: 格式化的大小字符串 """ for unit in ['B', 'KB', 'MB', 'GB']: if size_bytes < 1024.0: return f"{size_bytes:.2f} {unit}" size_bytes /= 1024.0 return f"{size_bytes:.2f} TB" def preview_deletion(dry_run: bool = True): """ 预览将要删除的内容 Args: dry_run: 是否为演练模式 """ print("=" * 60) print("Old Code Cleanup Script") print("=" * 60) print() if dry_run: print("🔍 DRY RUN MODE - No files will be deleted") else: print("⚠️ DELETION MODE - Files will be permanently deleted!") print() print("Directories to clean:") for dir_path in OLD_CODE_DIRS: status = "✓ exists" if Path(dir_path).exists() else "✗ not found" print(f" - {dir_path} ({status})") print() print("Files to keep:") for file_path in KEEP_FILES: status = "✓ exists" if Path(file_path).exists() else "✗ not found" print(f" - {file_path} ({status})") print() # 列出将要删除的文件 files_to_delete = list_files_to_delete(OLD_CODE_DIRS) # 过滤掉要保留的文件 files_to_delete = [ f for f in files_to_delete if str(f) not in KEEP_FILES ] if not files_to_delete: print("✅ No files to delete") return total_size = calculate_size(files_to_delete) print(f"Files to delete: {len(files_to_delete)}") print(f"Total size: {format_size(total_size)}") print() # 显示前 10 个文件 print("Sample files (first 10):") for file_path in files_to_delete[:10]: size = format_size(file_path.stat().st_size) print(f" - {file_path} ({size})") if len(files_to_delete) > 10: print(f" ... and {len(files_to_delete) - 10} more files") print() if not dry_run: # 确认删除 response = input("⚠️ Are you sure you want to delete these files? (yes/no): ") if response.lower() != 'yes': print("❌ Deletion cancelled") return print() print("Deleting files...") deleted_count = 0 for dir_path in OLD_CODE_DIRS: path = Path(dir_path) if path.exists() and path.is_dir(): try: shutil.rmtree(path) deleted_count += 1 print(f" ✓ Deleted {dir_path}") except Exception as e: print(f" ✗ Error deleting {dir_path}: {e}") print() print(f"✅ Cleanup complete! Deleted {deleted_count} directories") print() print("Next steps:") print(" 1. Run tests to ensure everything still works") print(" 2. Commit the changes") print(" 3. Update documentation if needed") def main(): """主函数""" parser = argparse.ArgumentParser( description='Clean up old deprecated code', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: # Preview what will be deleted (safe) python scripts/cleanup_old_code.py --dry-run # Actually delete the files (dangerous!) python scripts/cleanup_old_code.py --delete Warning: Deletion is permanent! Make sure you have backups. """ ) parser.add_argument( '--dry-run', action='store_true', default=True, help='Preview what will be deleted without actually deleting (default)' ) parser.add_argument( '--delete', action='store_true', help='Actually delete the files (use with caution!)' ) args = parser.parse_args() # 如果指定了 --delete,则不是 dry run dry_run = not args.delete preview_deletion(dry_run=dry_run) if __name__ == '__main__': main()