1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
import os
import subprocess
import json
from loguru import logger
# 读取配置的 JSON 文件
def load_config(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
return json.load(f)
# 将操作结果写入到 JSON 文件
def write_result_to_json(results, output_file):
with open(output_file, 'w+', encoding='utf-8') as f:
json.dump(results, f, indent=4, ensure_ascii=False)
# 推送裸仓库到新远端
def push_bare_repo_to_remote(project, results):
absolute_path = project["absolute_path"]
new_ssh_url_to_repo = project["new_ssh_url_to_repo"]
# 检查仓库路径是否合法
if not os.path.isdir(absolute_path) or not os.path.exists(os.path.join(absolute_path, "HEAD")):
logger.error(f"Invalid bare repository path: {absolute_path}")
results.append({
"project": project,
"status": "failed",
"message": f"Invalid bare repository path: {absolute_path}"
})
return
try:
# 进入原始仓库目录
logger.info(f"Accessing local bare repository: {absolute_path}")
os.chdir(absolute_path)
# 确保是裸仓库
subprocess.run(["git", "rev-parse", "--is-bare-repository"], check=True)
# 设置新的远端地址
logger.info(f"Setting new remote URL: {new_ssh_url_to_repo}")
subprocess.run(["git", "remote", "add", "new-origin", new_ssh_url_to_repo], check=True)
# 推送所有分支到新远端
logger.info("Pushing all branches to the new remote repository")
subprocess.run(["git", "push", "new-origin", "--all","-f"], check=True)
# 推送所有标签到新远端
logger.info("Pushing all tags to the new remote repository")
subprocess.run(["git", "push", "new-origin", "--tags"], check=True)
results.append({
"project": project,
"status": "success",
"message": f"Successfully pushed to {new_ssh_url_to_repo}"
})
except subprocess.CalledProcessError as e:
logger.error(f"Error during git operations: {e}")
results.append({
"project": project,
"status": "failed",
"message": f"Error during git operations: {str(e)}"
})
except Exception as e:
logger.exception("Unexpected error occurred")
results.append({
"project": project,
"status": "failed",
"message": f"Unexpected error: {str(e)}"
})
finally:
# 移除新远端配置以保持原始仓库清洁
try:
subprocess.run(["git", "remote", "remove", "new-origin"], check=True)
except subprocess.CalledProcessError:
logger.warning("Failed to remove new-origin remote, please check manually.")
# 主函数
def main():
config_file = 'old_all_projects.json'
output_file = 'old_all_projects_result_2024.json'
projects = load_config(config_file)
logger.add("all_projects_operation_log_2024.log", rotation="500 MB", level="INFO", compression="zip")
results = []
for project in projects:
logger.info(f"Processing project: {project['name']}")
push_bare_repo_to_remote(project, results)
write_result_to_json(results, output_file)
logger.info(f"Operation results saved to {output_file}")
if __name__ == "__main__":
main()
|