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

如何合并两个含对应版本标签的依赖Git仓库A和B?

将两个依赖Git仓库合并为单一仓库并保留对应版本标签

需求背景

现有两个Git仓库A和B,B依赖于A,二者拥有完全一致的版本标签集合,且标签/版本呈线性排序。构建B的V版本时必须匹配A的V版本。现在需要将它们合并为单一仓库C,满足以下要求:

  • 仓库C拥有与A、B完全相同的标签
  • 每个标签V对应的C仓库状态中,A目录下是仓库A的V版本内容,B目录下是仓库B的V版本内容
  • 保留两个仓库的完整提交历史

实现方案:交错重放提交并打标签

核心思路是按版本线性顺序,依次将A、B对应版本的提交重放到新仓库的指定目录下,完成后打上对应标签,重复此过程直至所有标签处理完毕。

具体操作步骤

  1. 准备本地仓库副本
    先克隆A、B仓库到本地,同时初始化新仓库C:

    # 克隆仓库A和B
    git clone <仓库A的远程地址> repo-a
    git clone <仓库B的远程地址> repo-b
    
    # 创建并初始化仓库C
    mkdir repo-c && cd repo-c
    git init
    
  2. 获取有序标签列表
    在仓库A中按创建时间导出线性排序的标签列表(A、B标签一致,用任意一个的即可):

    cd ../repo-a
    git tag --sort=creatordate > tags.txt
    # 将标签列表复制到仓库C目录
    cp tags.txt ../repo-c/
    cd ../repo-c
    
  3. 遍历处理每个标签版本
    按标签列表顺序,逐个处理每个版本V:

    # 读取标签列表,逐个处理
    while read -r tag; do
        echo "Processing tag: $tag"
    
        # 1. 导入仓库A的$tag版本提交,将内容移动到A/目录
        git remote add -f repo-a ../repo-a
        git checkout -b temp-a repo-a/$tag
        # 使用git filter-repo将所有文件重定向到A/目录
        git filter-repo --to-subdirectory-filter A
        # 合并到主分支
        git checkout main
        git merge temp-a --allow-unrelated-histories -m "Merge repo-a $tag version into A/"
        # 清理临时分支和远程
        git branch -D temp-a
        git remote remove repo-a
    
        # 2. 导入仓库B的$tag版本提交,将内容移动到B/目录
        git remote add -f repo-b ../repo-b
        git checkout -b temp-b repo-b/$tag
        git filter-repo --to-subdirectory-filter B
        git checkout main
        git merge temp-b --allow-unrelated-histories -m "Merge repo-b $tag version into B/"
        git branch -D temp-b
        git remote remove repo-b
    
        # 3. 给仓库C打上对应标签
        git tag $tag
    done < tags.txt
    
  4. 验证与推送
    处理完成后,可通过git tag确认所有标签已存在,用git show <标签名>查看对应版本的目录结构是否符合要求,最后推送到远程仓库:

    git remote add origin <仓库C的远程地址>
    git push origin main --tags
    

注意事项

  • git filter-repo是Git官方推荐的历史重写工具,比旧的git filter-branch更高效稳定,若未安装可通过pip安装:pip install git-filter-repo
  • 若使用git filter-branch替代,重定向目录的命令为:git filter-branch --tree-filter 'mkdir -p A && git ls-files -z | xargs -0 mv -t A/' HEAD(仅适用于小仓库,大仓库推荐filter-repo)
  • 合并时使用--allow-unrelated-histories是因为两个仓库初始提交无关联,属于正常操作

内容的提问来源于stack exchange,提问作者kaba

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:40:45