在日常开发过程中,可能会遇到需要将两个不同的仓库合并成到一个仓库的场景。
这里介绍一下怎么将两个不同的仓库合并到一个仓库中。
思路:添加两个远程仓库,将两个代码作为两个分支,然后手动合并。
譬如想将 https://github.com/CollegesChat/university-information 和 https://github.com/Reoger/PracticeCode 合并到 PracticeCode 仓库中。
1.clone PracticeCode 项目
$ git clone git@github.com:Reoger/PracticeCode.git
2.添加要合并仓库的远程地址
- $ git remote add merge_branch git@github.com:CollegesChat/university-information.git
- // 为了方便,这里将其命名为 merge_branch
这里时候,查看远程地址,应该已经有两个地址了

3.从远程仓库下载第二个仓库的代码:
$ git fetch merge_branch

4.将从 university-information 仓库下载的 master 分支作为要合入到项目 PracticeCode 项目,需要先将其分支 checkout 到一个新分支上
$ git checkout -b dev merge_branch/master

这里没有冲突。实际项目中可能会有一些冲突,譬如有些文件提示无法删除,subModule 提示问题等等。按照提示解决即可(手动删除或者修改,用 git status 查看冲突位置)。
5.切换原来的分支,
$ git checkout master
6.合并 master 分支和 dev 分支
- $ git merge --no-ff --allow-unrelated-histories dev
- CONFLICT (add/add): Merge conflict in README.md
- Auto-merging README.md
- CONFLICT (add/add): Merge conflict in .gitignore
- Auto-merging .gitignore
- Automatic merge failed; fix conflicts and then commit the result.
7.处理冲突
- $ git status
- On branch master
- Your branch is up to date with 'origin/master'.
-
- You have unmerged paths.
- (fix conflicts and run "git commit")
- (use "git merge --abort" to abort the merge)
-
- Changes to be committed:
- new file: .github/pull_request_template.md
- new file: .github/workflows/generate-data.yml
- new file: questionnaires/.gitignore
- new file: questionnaires/README.md
- new file: questionnaires/README_template.md
- new file: questionnaires/alias.txt
- new file: questionnaires/blacklist.txt
- new file: questionnaires/colleges.csv
- new file: questionnaires/history.txt
- new file: questionnaires/main.py
- new file: questionnaires/requirements.txt
- new file: questionnaires/results_desensitized.csv
- new file: questionnaires/whitelist.txt
-
- Unmerged paths:
- (use "git add
..." to mark resolution) - both added: .gitignore
- both added: README.md
- $ vim .gitignore
- $ git add .gitignore
- $ vim README.md
- $ git add README.md
- $ git commit
8.合并完成~
看 log,两个仓库的代码完美合并到一个仓库中了

有时候,我们会需要将仓库中 submodule 的代码直接合并到主工程中来。相关操作如下:
首先从主工程将 submodule 删除:
- 1. rm -rf {suModule-path}
- // 删除 submodule 目录和文件
- 2. vim .gitmodules
- // 删除项目目录下 .gitmodules 文件中子模块相关条目
- 3. vim .git/config
- // 删除配置相中子模块相关条目
- 4. rm .git/module/{subModule-path}/*
- // 删除模块下的子模块目录,每个子模块对应一个目录,注意只删除对应的子模块目录即可
- 5. git rm --cached {subModule-path}
- // 如果还有报错的话,把缓存也删除