gitlab备份代码
这是ChatGPT帮我写的,还没测试,先记录一下吧
要实现的功能:
- 获取所有 GitLab 仓库地址
- 首次使用
git clone --mirror
完整备份所有内容(包括所有分支和标签) - 后续自动使用
git remote update
拉取所有分支和最新提交 - 支持配置 GitLab 地址、私钥 Token、本地备份目录等
- 可用于定时任务执行(如每日自动备份)
代码如下:
import os
import subprocess
import requests
# ==== 配置区域 ====
GITLAB_URL = "https://gitlab.example.com"
PRIVATE_TOKEN = "your_private_token"
BACKUP_DIR = "/data/gitlab_backup"
USE_SSH = True # True 使用 SSH 地址, False 使用 HTTP 地址
PER_PAGE = 100 # 每页项目数
MAX_PAGES = 10 # 最大页数限制
# ===================
HEADERS = {"PRIVATE-TOKEN": PRIVATE_TOKEN}
REPO_KEY = "ssh_url_to_repo" if USE_SSH else "http_url_to_repo"
os.makedirs(BACKUP_DIR, exist_ok=True)
def run(cmd, cwd=None):
result = subprocess.run(cmd, shell=True, cwd=cwd,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return result.returncode, result.stdout.decode(), result.stderr.decode()
def get_projects():
repos = []
for page in range(1, MAX_PAGES + 1):
url = f"{GITLAB_URL}/api/v4/projects?per_page={PER_PAGE}&page={page}&simple=true&order_by=id&sort=asc"
response = requests.get(url, headers=HEADERS)
if response.status_code != 200:
print(f"[ERROR] Failed to fetch projects: {response.status_code}")
break
data = response.json()
if not data:
break
repos.extend([project[REPO_KEY] for project in data])
return repos
def backup():
repos = get_projects()
print(f"🔍 发现 {len(repos)} 个仓库")
for repo_url in repos:
repo_name = os.path.basename(repo_url).replace(".git", "")
repo_dir = os.path.join(BACKUP_DIR, f"{repo_name}.git")
if os.path.exists(repo_dir):
print(f"🔄 更新 {repo_name} ...")
cmd = "git remote update --prune"
code, out, err = run(cmd, cwd=repo_dir)
else:
print(f"📥 克隆 {repo_name} ...")
cmd = f"git clone --mirror {repo_url} {repo_dir}"
code, out, err = run(cmd)
if code != 0:
print(f"❌ [{repo_name}] 错误:\n{err}")
else:
print(f"✅ [{repo_name}] 完成")
if __name__ == "__main__":
backup()