合并Git仓库时,如何添加已移除LFS文件的子树?
合并含Git LFS的多仓库为单体仓库并保留历史
方案一:彻底移除LFS后合并
若无需保留LFS,先清理目标仓库的LFS关联及占位符,再执行合并:
克隆裸仓库以确保干净环境
git clone --bare git@gitlab.com:org/third-party.git third-party-bare cd third-party-bare用git filter-repo清理LFS痕迹
确保已安装git filter-repo(Git 2.22+内置,或单独安装):# 移除.gitattributes中的LFS规则 git filter-repo --replace-text <(echo 'regex:\.gitattributes$==>') # 将LFS占位符替换为实际文件内容 git filter-repo --blob-callback ' import base64 if b"oid sha256:" in blob.data and b"size " in blob.data: try: oid_start = blob.data.find(b"oid sha256:") + len(b"oid sha256:") oid_end = blob.data.find(b"\n", oid_start) oid = blob.data[oid_start:oid_end].decode("utf-8") # 拉取LFS实际文件并替换占位符 import subprocess subprocess.run(["git", "lfs", "fetch", "--object-id", oid], check=True) lfs_path = f".git/lfs/objects/{oid[:2]}/{oid[2:4]}/{oid}" with open(lfs_path, "rb") as f: blob.data = f.read() except: pass '创建本地工作仓库并验证清理效果
mkdir ../third-party-clean && cd ../third-party-clean git init && git pull ../third-party-bare # 验证:无.gitattributes文件,LFS文件显示实际内容而非占位符 ls -la .gitattributes cat path/to/any-lfs-file合并到单体仓库
在单体仓库根目录执行:git subtree add -P third-party ../third-party-clean main重复以上步骤处理
asset仓库。
方案二:保留LFS的合并方式
若需保留LFS,通过重写历史调整目录结构后合并:
克隆并拉取所有LFS文件
git clone git@gitlab.com:org/third-party.git cd third-party git lfs pull重写历史,将所有文件迁移到目标子目录
git filter-repo --to-subdirectory-filter third-party合并到单体仓库
在单体仓库根目录:git remote add third-party-local ../third-party git fetch third-party-local git merge --allow-unrelated-histories third-party-local/main git remote remove third-party-local同理处理
asset仓库。
关键注意点
- 优先使用
git filter-repo:相比BFG,它对LFS的清理和历史重写更彻底,能避免残留远程关联。 - 合并时使用本地仓库路径:避免传入远程URL触发LFS远程请求,解决Smudge error类问题。
- 合并前务必验证:确认LFS占位符已替换、目录结构正确,再执行合并操作。
内容的提问来源于stack exchange,提问作者ndeubert
相关产品推荐
相关产品推荐

