#!/usr/bin/env python3 """ Cursor自动化服务 - 设置脚本补丁 修复MySQL连接和添加虚拟环境支持 """ import os import sys import subprocess import shutil # 彩色输出 class Colors: GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' def print_title(title): """打印标题""" print(f"\n{Colors.BOLD}{Colors.GREEN}{'='*60}{Colors.ENDC}") print(f"{Colors.BOLD}{Colors.GREEN}{title.center(60)}{Colors.ENDC}") print(f"{Colors.BOLD}{Colors.GREEN}{'='*60}{Colors.ENDC}\n") def print_success(message): """打印成功信息""" print(f"{Colors.GREEN}✓ {message}{Colors.ENDC}") def print_warning(message): """打印警告信息""" print(f"{Colors.YELLOW}⚠ {message}{Colors.ENDC}") def print_error(message): """打印错误信息""" print(f"{Colors.RED}✗ {message}{Colors.ENDC}") def is_in_virtualenv(): """检查是否在虚拟环境中运行""" return hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix) def setup_virtualenv(): """设置虚拟环境""" print_title("虚拟环境设置") if is_in_virtualenv(): print_success("已在虚拟环境中运行") return True print_warning("当前不在虚拟环境中运行") create_venv = input("是否创建并使用虚拟环境? (推荐) (y/n, 默认: y): ").strip().lower() if create_venv == 'n': print_warning("跳过虚拟环境创建,将直接在系统Python环境中安装依赖") return True venv_path = input("请输入虚拟环境路径 (默认: ./venv): ").strip() or "./venv" try: # 检查venv模块 try: subprocess.check_call([sys.executable, "-m", "venv", "--help"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) has_venv = True except (subprocess.SubprocessError, ImportError): has_venv = False if not has_venv: print_warning("Python venv模块不可用,尝试安装...") if sys.platform.startswith('linux'): print("在Linux上安装venv模块...") try: subprocess.check_call(["sudo", "apt", "install", "-y", "python3-venv", "python3-full"], stdout=subprocess.DEVNULL) print_success("venv模块安装成功") except: try: subprocess.check_call(["sudo", "yum", "install", "-y", "python3-venv"], stdout=subprocess.DEVNULL) print_success("venv模块安装成功") except: print_error("无法自动安装venv模块,请手动安装后重试") print_warning("Ubuntu/Debian: sudo apt install python3-venv python3-full") print_warning("CentOS/RHEL: sudo yum install python3-venv") return False else: print_error("请安装Python venv模块后重试") return False # 创建虚拟环境 print("\n正在创建虚拟环境...") subprocess.check_call([sys.executable, "-m", "venv", venv_path]) # 计算激活脚本路径 if sys.platform.startswith('win'): activate_script = os.path.join(venv_path, "Scripts", "activate.bat") pip_path = os.path.join(venv_path, "Scripts", "pip.exe") python_path = os.path.join(venv_path, "Scripts", "python.exe") else: activate_script = os.path.join(venv_path, "bin", "activate") pip_path = os.path.join(venv_path, "bin", "pip") python_path = os.path.join(venv_path, "bin", "python") print_success(f"虚拟环境创建成功: {venv_path}") # 安装依赖 print("\n正在安装依赖包...") if os.path.exists("requirements.txt"): try: if sys.platform.startswith('win'): subprocess.check_call([pip_path, "install", "-r", "requirements.txt"]) else: script = f"""#!/bin/bash source "{activate_script}" pip install -r requirements.txt pip install cryptography echo "依赖安装完成,请运行以下命令启动设置向导:" echo "source {activate_script}" echo "python setup_environment.py" """ with open("setup_venv.sh", "w") as f: f.write(script) os.chmod("setup_venv.sh", 0o755) print_success("已创建安装脚本: setup_venv.sh") print("\n请运行以下命令完成安装并启动设置向导:") print(f" bash ./setup_venv.sh") except Exception as e: print_error(f"安装依赖失败: {str(e)}") print("\n请手动运行以下命令:") print(f" source {activate_script}") print(f" pip install -r requirements.txt") print(f" pip install cryptography") print(f" python setup_environment.py") else: print_warning("未找到requirements.txt文件") print("\n请手动运行以下命令:") print(f" source {activate_script}") print(f" pip install loguru pymysql aiomysql redis pyyaml cryptography") print(f" python setup_environment.py") return False except Exception as e: print_error(f"创建虚拟环境失败: {str(e)}") return False def patch_setup_script(): """修补setup_environment.py脚本""" print_title("修补设置脚本") if not os.path.exists("setup_environment.py"): print_error("未找到setup_environment.py文件") return False # 备份原始文件 backup_file = f"setup_environment.py.bak.{int(os.path.getmtime('setup_environment.py'))}" try: shutil.copy2("setup_environment.py", backup_file) print_success(f"已备份原始文件: {backup_file}") except Exception as e: print_error(f"备份文件失败: {str(e)}") return False # 修改required_packages列表 try: with open("setup_environment.py", "r", encoding="utf-8") as f: content = f.read() # 添加cryptography包 if "cryptography" not in content: content = content.replace( 'required_packages = [\n "loguru",\n "pymysql",\n "aiomysql",\n "redis",\n "pyyaml"', 'required_packages = [\n "loguru",\n "pymysql",\n "aiomysql",\n "redis",\n "pyyaml",\n "cryptography"' ) print_success("已添加cryptography包到依赖列表") # 修复MySQL字符串格式化问题 if "CREATE USER '{db_user}'@'%'" in content: content = content.replace( "cursor.execute(f\"CREATE USER '{db_user}'@'%' IDENTIFIED BY %s\", (db_password,))", "cursor.execute(\"CREATE USER %s@'%%' IDENTIFIED BY %s\", (db_user, db_password))" ) print_success("已修复MySQL用户创建语句的格式化问题") if "ALTER USER '{db_user}'@'%'" in content: content = content.replace( "cursor.execute(f\"ALTER USER '{db_user}'@'%' IDENTIFIED BY %s\", (db_password,))", "cursor.execute(\"ALTER USER %s@'%%' IDENTIFIED BY %s\", (db_user, db_password))" ) print_success("已修复MySQL用户更新语句的格式化问题") # 写回文件 with open("setup_environment.py", "w", encoding="utf-8") as f: f.write(content) print_success("设置脚本修补完成") return True except Exception as e: print_error(f"修补文件失败: {str(e)}") try: # 恢复备份 shutil.copy2(backup_file, "setup_environment.py") print_warning("已恢复原始文件") except: pass return False def main(): """主函数""" print_title("Cursor自动化服务 - 设置补丁工具") # 设置虚拟环境 if not setup_virtualenv(): return # 修补设置脚本 if not patch_setup_script(): return print_title("补丁应用完成") print("现在您可以安全地运行设置向导:") print(" python setup_environment.py") if __name__ == "__main__": try: main() except KeyboardInterrupt: print("\n\n操作已取消") sys.exit(1)