You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何批量单向同步104个Gitlab仓库至Github?

批量Gitlab到Github单向同步方案

准备工作

  • 生成访问令牌:分别为三台Gitlab实例创建带仓库只读权限的个人访问令牌,为Github创建带仓库写入权限的个人访问令牌。
  • 整理仓库列表:将104个仓库按格式整理成文本文件(如repos_list.txt),每行用|分隔三个字段:
    Gitlab实例地址|Gitlab仓库路径|Github目标仓库地址
    
    示例:
    https://gitlab.teamA.com|backend/api-service|https://github.com/our-org/api-service
    https://gitlab.teamB.com|frontend/web-app|https://github.com/our-org/web-app
    
  • 本地环境配置:确保安装git,通过环境变量配置令牌(避免硬编码泄露):
    export GITLAB_TOKEN_TEAMA="your-gitlab-teama-token"
    export GITLAB_TOKEN_TEAMB="your-gitlab-teamb-token"
    export GITLAB_TOKEN_TEAMC="your-gitlab-teamc-token"
    export GITHUB_TOKEN="your-github-token"
    

批量同步脚本(Bash)

创建脚本sync_repos.sh,实现批量克隆、同步逻辑:

#!/bin/bash

if [ $# -ne 1 ]; then
    echo "用法: $0 <仓库列表文件>"
    exit 1
fi

REPO_LIST=$1
SYNC_DIR="./git_sync_mirrors"
mkdir -p $SYNC_DIR

while IFS='|' read -r GITLAB_URL REPO_PATH GITHUB_URL; do
    [[ -z "$GITLAB_URL" || "$GITLAB_URL" =~ ^# ]] && continue

    case $GITLAB_URL in
        https://gitlab.teamA.com*)
            GITLAB_TOKEN=$GITLAB_TOKEN_TEAMA
            ;;
        https://gitlab.teamB.com*)
            GITLAB_TOKEN=$GITLAB_TOKEN_TEAMB
            ;;
        https://gitlab.teamC.com*)
            GITLAB_TOKEN=$GITLAB_TOKEN_TEAMC
            ;;
        *)
            echo "未知Gitlab实例: $GITLAB_URL,跳过该仓库"
            continue
            ;;
    esac

    GITLAB_CLONE_URL="${GITLAB_URL%/}/${REPO_PATH}.git"
    GITLAB_AUTH_URL="https://oauth2:${GITLAB_TOKEN}@${GITLAB_CLONE_URL#https://}"
    REPO_NAME=$(basename $REPO_PATH)
    LOCAL_REPO="${SYNC_DIR}/${REPO_NAME}_mirror"

    echo "开始同步仓库: $REPO_PATH"

    if [ -d "$LOCAL_REPO" ]; then
        cd $LOCAL_REPO
        git fetch --all --prune
    else
        git clone --mirror $GITLAB_AUTH_URL $LOCAL_REPO
        cd $LOCAL_REPO
    fi

    if ! git remote | grep -q "github"; then
        GITHUB_AUTH_URL="https://${GITHUB_TOKEN}@${GITHUB_URL#https://}.git"
        git remote add github $GITHUB_AUTH_URL
    fi

    git push --mirror github

    if [ $? -eq 0 ]; then
        echo "仓库 $REPO_PATH 同步成功"
    else
        echo "[$(date)] 仓库 $REPO_PATH 同步失败" >> sync_errors.log
    fi

    cd ../..
done < $REPO_LIST

echo "批量同步完成,失败仓库请查看 sync_errors.log"

执行与验证

  1. 给脚本添加执行权限:
    chmod +x sync_repos.sh
    
  2. 运行脚本:
    ./sync_repos.sh repos_list.txt
    
  3. 验证同步结果:
    • 手动抽查部分仓库,确认分支、标签与Gitlab完全一致
    • 检查sync_errors.log文件,单独处理同步失败的仓库

后续维护

  • 定时自动同步:通过crontab设置每日自动同步(示例:凌晨2点执行):
    0 2 * * * /path/to/sync_repos.sh /path/to/repos_list.txt >> /path/to/sync_cron.log 2>&1
    
  • 仓库变更:直接修改repos_list.txt即可添加或移除同步仓库
  • 令牌更新:更新对应环境变量后,重启脚本或定时任务生效

内容的提问来源于stack exchange,提问作者Marco Meyer-Conde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 02:45:20