这篇文章的指令主要是用来合并两个代码库的,更具体的,是把一个代码库整历史的全部搬至另一个代码库中,作为一个子目录存在,并且不丢失原来的提交历史。
简单总结一下,其实就是在要插入代码的库中新加一个远程服务器,然后拉入待合并的代码,再把待合入的代码checkout到一个本地分支上,然后用git mv命令搬运要合入的代码到指定的位置或目录,完了提交。那么到此为止,待插入代码的库中其实有了至少两个分支,一个分支上就是另一个代码库的完整代码,这时只要把要合入的代码库的分支合并到待插入代码的库的分支上就可以了。之后再清理一下库就完事了。
Merge one git repository into another repository as a sub-directory
# based on the following:
# http://saintgimp.org/2013/01/22/merging-two-git-repositories-into-one-repository-without-losing-file-history/
# http://blog.caplin.com/2013/09/18/merging-two-git-repositories/
# repo_main就是待插入的代码库,是被插的角色
git clone repo_main
# repo_sub是要插入的代码库,是插入的角色
git clone repo_sub
cd repo_main
# 将要插的代码库拉入被插的代码库
git remote add repo_sub ../repo_sub
git fetch repo_sub
# 签出要插的代码库到本地新分支上
git checkout -b repo_sub repo_sub/master
mkdir dir_repo_sub
# 这个地方其实就是调整目录结构,也可以不调整
# '*' will cause git mv to fail because it cannot move dir_repo_sub into itself
git mv <list all files>
git commit -m"Moves all repo_sub files into a single directory for merging back into repo_main"
# 回到被插入的代码库本地分支上
git checkout master
# 合并要插入的代码分支
git merge repo_sub --allow-unrelated-histories
# 做些清理工作,也可以不做
git remote remove repo_sub
git branch -D repo_sub
# commit and push, and you're finished