import subprocess import os from datetime import datetime # 新增:导入时间模块 def git_operations(repo_path, commit_message=None): """ 执行 Git 的 add、commit、pull、push 操作 Args: repo_path (str): Git 仓库的本地路径 commit_message (str): commit 提交信息,不传则使用带时间的默认备份信息 Returns: bool: 所有操作是否成功完成 """ # 处理默认提交信息(自动生成带当前时间的备份信息) if commit_message is None: # 获取当前时间并格式化为「年-月-日 时:分:秒」(也可根据需求调整格式) current_time = datetime.now().strftime("%Y年%m月%d日%H时%M分%S秒") commit_message = f"build(备份): {current_time}自动备份" # 切换到仓库目录 original_cwd = os.getcwd() try: os.chdir(repo_path) print(f"✅ 已切换到仓库目录: {repo_path}") # 1. 执行 git add . (添加所有变更文件) print("\n📤 执行 git add . ...") add_result = subprocess.run( ["git", "add", "."], capture_output=True, text=True, encoding="utf-8" # 解决中文乱码问题 ) if add_result.returncode != 0: raise Exception(f"git add 失败: {add_result.stderr}") print("✅ git add 执行成功") # 2. 执行 git commit print("\n📝 执行 git commit ...") commit_result = subprocess.run( ["git", "commit", "-m", commit_message], capture_output=True, text=True, encoding="utf-8" ) if commit_result.returncode != 0: # 处理没有变更需要提交的情况(这是正常情况,不是错误) if "nothing to commit" in commit_result.stderr or "nothing to commit" in commit_result.stdout: print("ℹ️ 没有变更需要提交,跳过 commit") else: raise Exception(f"git commit 失败: {commit_result.stderr}") else: print(f"✅ git commit 执行成功: {commit_message}") # 3. 执行 git pull (拉取远程最新代码,避免冲突) print("\n⬇️ 执行 git pull ...") pull_result = subprocess.run( ["git", "pull"], capture_output=True, text=True, encoding="utf-8" ) if pull_result.returncode != 0: raise Exception(f"git pull 失败: {pull_result.stderr}") print("✅ git pull 执行成功") # 4. 执行 git push (推送到远程仓库) print("\n⬆️ 执行 git push ...") push_result = subprocess.run( ["git", "push"], capture_output=True, text=True, encoding="utf-8" ) if push_result.returncode != 0: raise Exception(f"git push 失败: {push_result.stderr}") print("✅ git push 执行成功") print("\n🎉 所有 Git 操作执行完成!") return True except Exception as e: print(f"\n❌ 操作失败: {str(e)}") return False finally: # 切回原来的工作目录 os.chdir(original_cwd) # ------------------- 使用示例 ------------------- if __name__ == "__main__": # 替换为你的 Git 仓库本地路径 REPO_PATH = "d:\BaiduSyncdisk\Obsidian\juechafun" # 无需手动传 commit 信息,会自动生成带当前时间的备份信息 # 执行 Git 操作 git_operations(repo_path=REPO_PATH)