git_push.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Git 推送自动化脚本
  5. 自动执行 Git 初始化、提交和推送操作
  6. """
  7. import subprocess
  8. import sys
  9. import os
  10. def run_command(cmd, description):
  11. """执行命令并显示结果"""
  12. print(f"\n{'='*50}")
  13. print(f"执行: {description}")
  14. print(f"命令: {cmd}")
  15. print(f"{'='*50}")
  16. try:
  17. result = subprocess.run(
  18. cmd,
  19. shell=True,
  20. capture_output=True,
  21. text=True,
  22. encoding='utf-8',
  23. errors='ignore'
  24. )
  25. if result.stdout:
  26. print(result.stdout)
  27. if result.stderr:
  28. print(result.stderr, file=sys.stderr)
  29. return result.returncode == 0, result.stdout, result.stderr
  30. except Exception as e:
  31. print(f"错误: {e}")
  32. return False, "", str(e)
  33. def main():
  34. print("="*50)
  35. print("Git 推送自动化脚本")
  36. print("="*50)
  37. # 切换到项目目录
  38. os.chdir(r"D:\线稿图")
  39. print(f"当前目录: {os.getcwd()}")
  40. # 1. 检查 Git 仓库
  41. print("\n[1/7] 检查 Git 仓库...")
  42. if not os.path.exists(".git"):
  43. print("Git 仓库不存在,正在初始化...")
  44. success, _, _ = run_command("git init", "初始化 Git 仓库")
  45. if not success:
  46. print("❌ Git 初始化失败")
  47. return
  48. else:
  49. print("✅ Git 仓库已存在")
  50. # 2. 检查远程仓库配置
  51. print("\n[2/7] 检查远程仓库配置...")
  52. success, output, _ = run_command("git remote -v", "查看远程仓库")
  53. if "origin" not in output:
  54. print("添加远程仓库...")
  55. run_command(
  56. "git remote add origin http://git.gloria.com.cn:10080/AI/AI_design_agent.git",
  57. "添加远程仓库"
  58. )
  59. else:
  60. print("✅ 远程仓库已配置")
  61. # 更新远程 URL(如果需要)
  62. run_command(
  63. "git remote set-url origin http://git.gloria.com.cn:10080/AI/AI_design_agent.git",
  64. "更新远程仓库 URL"
  65. )
  66. # 3. 检查当前分支
  67. print("\n[3/7] 检查当前分支...")
  68. success, branch_output, _ = run_command("git branch", "查看分支")
  69. current_branch = None
  70. # 尝试获取当前分支
  71. success, branch_output, _ = run_command("git branch --show-current", "获取当前分支")
  72. if success and branch_output.strip():
  73. current_branch = branch_output.strip()
  74. else:
  75. # 备用方法
  76. success, branch_output, _ = run_command("git branch", "查看所有分支")
  77. for line in branch_output.split('\n'):
  78. if '*' in line:
  79. current_branch = line.replace('*', '').strip()
  80. break
  81. if not current_branch:
  82. # 如果没有分支,创建 master 分支
  83. print("没有分支,创建 master 分支...")
  84. run_command("git checkout -b master", "创建并切换到 master 分支")
  85. current_branch = "master"
  86. print(f"当前分支: {current_branch}")
  87. # 4. 添加所有文件
  88. print("\n[4/7] 添加所有文件到暂存区...")
  89. run_command("git add .", "添加所有文件")
  90. # 5. 检查是否有未提交的更改
  91. print("\n[5/7] 检查未提交的更改...")
  92. success, status_output, _ = run_command("git status --short", "检查状态")
  93. has_changes = bool(status_output.strip())
  94. # 检查是否有已暂存但未提交的文件
  95. success, diff_output, _ = run_command("git diff --cached --quiet", "检查已暂存文件")
  96. has_staged = not success # diff --quiet 返回非0表示有差异
  97. if has_changes or has_staged:
  98. print("有未提交的更改,创建提交...")
  99. commit_message = "Update: 更新代码"
  100. success, _, _ = run_command(
  101. f'git commit -m "{commit_message}"',
  102. "创建提交"
  103. )
  104. if success:
  105. print("✅ 提交成功")
  106. else:
  107. print("⚠️ 提交可能失败或没有需要提交的内容")
  108. else:
  109. print("没有需要提交的更改")
  110. # 6. 检查提交历史
  111. print("\n[6/7] 检查提交历史...")
  112. run_command("git log --oneline -3", "查看最近3次提交")
  113. # 7. 推送到远程
  114. print("\n[7/7] 推送到远程仓库...")
  115. print(f"尝试推送到: origin/{current_branch}")
  116. # 先尝试推送
  117. success, output, error = run_command(
  118. f"git push -u origin {current_branch}",
  119. f"推送到远程 {current_branch} 分支"
  120. )
  121. if not success:
  122. print("\n⚠️ 推送失败,尝试其他方法...")
  123. # 尝试 main 分支
  124. if current_branch != "main":
  125. print("尝试推送到 main 分支...")
  126. run_command("git branch -M main", "重命名分支为 main")
  127. success, _, _ = run_command(
  128. "git push -u origin main",
  129. "推送到远程 main 分支"
  130. )
  131. if success:
  132. print("✅ 推送到 main 分支成功")
  133. return
  134. # 如果还是失败,提示用户
  135. print("\n❌ 推送失败,可能的原因:")
  136. print("1. 远程仓库需要认证")
  137. print("2. 远程仓库已有内容,需要先拉取")
  138. print("3. 网络连接问题")
  139. print("\n建议手动执行:")
  140. print(f" git pull origin {current_branch} --allow-unrelated-histories")
  141. print(f" git push -u origin {current_branch}")
  142. else:
  143. print("✅ 推送成功!")
  144. print("\n" + "="*50)
  145. print("完成!")
  146. print("="*50)
  147. if __name__ == "__main__":
  148. try:
  149. main()
  150. except KeyboardInterrupt:
  151. print("\n\n操作已取消")
  152. sys.exit(1)
  153. except Exception as e:
  154. print(f"\n❌ 发生错误: {e}")
  155. import traceback
  156. traceback.print_exc()
  157. sys.exit(1)