| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184 |
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- """
- Git 推送自动化脚本
- 自动执行 Git 初始化、提交和推送操作
- """
- import subprocess
- import sys
- import os
- def run_command(cmd, description):
- """执行命令并显示结果"""
- print(f"\n{'='*50}")
- print(f"执行: {description}")
- print(f"命令: {cmd}")
- print(f"{'='*50}")
-
- try:
- result = subprocess.run(
- cmd,
- shell=True,
- capture_output=True,
- text=True,
- encoding='utf-8',
- errors='ignore'
- )
-
- if result.stdout:
- print(result.stdout)
- if result.stderr:
- print(result.stderr, file=sys.stderr)
-
- return result.returncode == 0, result.stdout, result.stderr
- except Exception as e:
- print(f"错误: {e}")
- return False, "", str(e)
- def main():
- print("="*50)
- print("Git 推送自动化脚本")
- print("="*50)
-
- # 切换到项目目录
- os.chdir(r"D:\线稿图")
- print(f"当前目录: {os.getcwd()}")
-
- # 1. 检查 Git 仓库
- print("\n[1/7] 检查 Git 仓库...")
- if not os.path.exists(".git"):
- print("Git 仓库不存在,正在初始化...")
- success, _, _ = run_command("git init", "初始化 Git 仓库")
- if not success:
- print("❌ Git 初始化失败")
- return
- else:
- print("✅ Git 仓库已存在")
-
- # 2. 检查远程仓库配置
- print("\n[2/7] 检查远程仓库配置...")
- success, output, _ = run_command("git remote -v", "查看远程仓库")
- if "origin" not in output:
- print("添加远程仓库...")
- run_command(
- "git remote add origin http://git.gloria.com.cn:10080/AI/AI_design_agent.git",
- "添加远程仓库"
- )
- else:
- print("✅ 远程仓库已配置")
- # 更新远程 URL(如果需要)
- run_command(
- "git remote set-url origin http://git.gloria.com.cn:10080/AI/AI_design_agent.git",
- "更新远程仓库 URL"
- )
-
- # 3. 检查当前分支
- print("\n[3/7] 检查当前分支...")
- success, branch_output, _ = run_command("git branch", "查看分支")
- current_branch = None
-
- # 尝试获取当前分支
- success, branch_output, _ = run_command("git branch --show-current", "获取当前分支")
- if success and branch_output.strip():
- current_branch = branch_output.strip()
- else:
- # 备用方法
- success, branch_output, _ = run_command("git branch", "查看所有分支")
- for line in branch_output.split('\n'):
- if '*' in line:
- current_branch = line.replace('*', '').strip()
- break
-
- if not current_branch:
- # 如果没有分支,创建 master 分支
- print("没有分支,创建 master 分支...")
- run_command("git checkout -b master", "创建并切换到 master 分支")
- current_branch = "master"
-
- print(f"当前分支: {current_branch}")
-
- # 4. 添加所有文件
- print("\n[4/7] 添加所有文件到暂存区...")
- run_command("git add .", "添加所有文件")
-
- # 5. 检查是否有未提交的更改
- print("\n[5/7] 检查未提交的更改...")
- success, status_output, _ = run_command("git status --short", "检查状态")
-
- has_changes = bool(status_output.strip())
-
- # 检查是否有已暂存但未提交的文件
- success, diff_output, _ = run_command("git diff --cached --quiet", "检查已暂存文件")
- has_staged = not success # diff --quiet 返回非0表示有差异
-
- if has_changes or has_staged:
- print("有未提交的更改,创建提交...")
- commit_message = "Update: 更新代码"
- success, _, _ = run_command(
- f'git commit -m "{commit_message}"',
- "创建提交"
- )
- if success:
- print("✅ 提交成功")
- else:
- print("⚠️ 提交可能失败或没有需要提交的内容")
- else:
- print("没有需要提交的更改")
-
- # 6. 检查提交历史
- print("\n[6/7] 检查提交历史...")
- run_command("git log --oneline -3", "查看最近3次提交")
-
- # 7. 推送到远程
- print("\n[7/7] 推送到远程仓库...")
- print(f"尝试推送到: origin/{current_branch}")
-
- # 先尝试推送
- success, output, error = run_command(
- f"git push -u origin {current_branch}",
- f"推送到远程 {current_branch} 分支"
- )
-
- if not success:
- print("\n⚠️ 推送失败,尝试其他方法...")
-
- # 尝试 main 分支
- if current_branch != "main":
- print("尝试推送到 main 分支...")
- run_command("git branch -M main", "重命名分支为 main")
- success, _, _ = run_command(
- "git push -u origin main",
- "推送到远程 main 分支"
- )
- if success:
- print("✅ 推送到 main 分支成功")
- return
-
- # 如果还是失败,提示用户
- print("\n❌ 推送失败,可能的原因:")
- print("1. 远程仓库需要认证")
- print("2. 远程仓库已有内容,需要先拉取")
- print("3. 网络连接问题")
- print("\n建议手动执行:")
- print(f" git pull origin {current_branch} --allow-unrelated-histories")
- print(f" git push -u origin {current_branch}")
- else:
- print("✅ 推送成功!")
-
- print("\n" + "="*50)
- print("完成!")
- print("="*50)
- if __name__ == "__main__":
- try:
- main()
- except KeyboardInterrupt:
- print("\n\n操作已取消")
- sys.exit(1)
- except Exception as e:
- print(f"\n❌ 发生错误: {e}")
- import traceback
- traceback.print_exc()
- sys.exit(1)
|