diff --git a/patch_cursor_get_machine_id.py b/patch_cursor_get_machine_id.py index 9062aeb..7dd7d1c 100644 --- a/patch_cursor_get_machine_id.py +++ b/patch_cursor_get_machine_id.py @@ -150,6 +150,12 @@ def modify_main_js(main_path: str) -> bool: bool: 修改是否成功 """ try: + # 获取原始文件的权限和所有者信息 + original_stat = os.stat(main_path) + original_mode = original_stat.st_mode + original_uid = original_stat.st_uid + original_gid = original_stat.st_gid + with tempfile.NamedTemporaryFile(mode="w", delete=False) as tmp_file: with open(main_path, "r", encoding="utf-8") as main_file: content = main_file.read() @@ -169,6 +175,12 @@ def modify_main_js(main_path: str) -> bool: # 使用 shutil.copy2 保留文件权限 shutil.copy2(main_path, main_path + ".old") shutil.move(tmp_path, main_path) + + # 恢复原始文件的权限和所有者 + os.chmod(main_path, original_mode) + if os.name != "nt": # 在非Windows系统上设置所有者 + os.chown(main_path, original_uid, original_gid) + logger.info("文件修改成功") return True @@ -179,8 +191,63 @@ def modify_main_js(main_path: str) -> bool: return False -def patch_cursor_get_machine_id() -> None: - """主函数""" +def backup_files(pkg_path: str, main_path: str) -> bool: + """ + 备份原始文件 + + Args: + pkg_path: package.json 文件路径(未使用) + main_path: main.js 文件路径 + + Returns: + bool: 备份是否成功 + """ + try: + # 只备份 main.js + if os.path.exists(main_path): + backup_main = f"{main_path}.bak" + shutil.copy2(main_path, backup_main) + logger.info(f"已备份 main.js: {backup_main}") + + return True + except Exception as e: + logger.error(f"备份文件失败: {str(e)}") + return False + + +def restore_backup_files(pkg_path: str, main_path: str) -> bool: + """ + 恢复备份文件 + + Args: + pkg_path: package.json 文件路径(未使用) + main_path: main.js 文件路径 + + Returns: + bool: 恢复是否成功 + """ + try: + # 只恢复 main.js + backup_main = f"{main_path}.bak" + if os.path.exists(backup_main): + shutil.copy2(backup_main, main_path) + logger.info(f"已恢复 main.js") + return True + + logger.error("未找到备份文件") + return False + except Exception as e: + logger.error(f"恢复备份失败: {str(e)}") + return False + + +def patch_cursor_get_machine_id(restore_mode=False) -> None: + """ + 主函数 + + Args: + restore_mode: 是否为恢复模式 + """ logger.info("开始执行脚本...") try: @@ -191,6 +258,14 @@ def patch_cursor_get_machine_id() -> None: if not check_system_requirements(pkg_path, main_path): sys.exit(1) + if restore_mode: + # 恢复备份 + if restore_backup_files(pkg_path, main_path): + logger.info("备份恢复完成") + else: + logger.error("备份恢复失败") + return + # 获取版本号 try: with open(pkg_path, "r", encoding="utf-8") as f: @@ -207,6 +282,11 @@ def patch_cursor_get_machine_id() -> None: logger.info("版本检查通过,准备修改文件") + # 备份文件 + if not backup_files(pkg_path, main_path): + logger.error("文件备份失败,终止操作") + sys.exit(1) + # 修改文件 if not modify_main_js(main_path): sys.exit(1)