轉自:合並兩個git倉庫
前提和期望:
- 有2個git倉庫:repo1、repo2;
- 想將repo1中的文件移入repo2;
- repo1的歷史日志要保留;
首先,快速創建2個倉庫。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
mkdir repo1 cd repo1 git init echo "repo1.txt" > repo1.txt git add repo1.txt git ci -m "init repo1" mkdir repo2 cd repo2 git init echo "repo2.txt" > repo2.txt git add repo2.txt git ci -m "init repo2" |
結果目錄路徑是:
1 2 3 4 5 6 7 |
repo1/ repo1/repo1.txt repo1/.git repo2/ repo2/repo2.txt repo2/.git |
再次注意,想要的效果是:
1 2 3 4 |
repo2/ repo2/repo1.txt repo2/repo2.txt repo2/.git |
然后,需要五步命令:
1 2 |
# 1、將repo1作為遠程倉庫,添加到repo2中,設置別名為other [jot@myhost repo2]$ git remote add other ../repo1/ |
1 2 3 4 5 6 7 8 |
# 2、從repo1倉庫中抓取數據到本倉庫 [jot@myhost repo2]$ git fetch other warning: no common commits remote: Counting objects: 3, done. remote: Total 3 (delta 0), reused 0 (delta 0) Unpacking objects: 100% (3/3), done. From ../repo1 * [new branch] master -> other/master |
1 2 3 4 |
# 3、將repo1倉庫抓去的master分支作為新分支checkout到本地,新分支名設定為repo1 [jot@myhost repo2]$ git checkout -b repo1 other/master Branch repo1 set up to track remote branch master from other. Switched to a new branch 'repo1' |
1 2 3 |
# 4、切換回repo2的master分支 [jot@myhost repo2]$ git checkout master Switched to branch 'master' |
1 2 3 4 5 6 |
# 5、將repo1合並入master分支 [jot@myhost repo2]$ git merge repo1 Merge made by recursive. repo1.txt | 1 + 1 files changed, 1 insertions(+), 0 deletions(-) create mode 100644 repo1.txt |
可以看到效果了,日志確實還在:

已經完成,可以push到服務器了。
可能遇到的問題:
1. 在合並時有可能兩個分支對同一個文件都做了修改,這時需要解決沖突,對文本文件來說很簡單,根據需要對沖突的位置進行處理就可以。對於二進制文件,需要用到如下命令。
git checkout --theirs YOUR_BINARY_FILES // 保留需要合並進來的分支的修改
//git checkout --ours YOUR_BINARY_FILES // 保留自己的修改
git add YOUR_BINARY_FILES
git comm
總結:
- 大致思路是偽造遠程的repo1倉庫為repo2的一個分支,然后合並進來;
- 若是文件有沖突、或要建立子目錄,建議在repo1中先解決,再進行如上操作。
如果報
------------------->$ git merge temp
fatal: refusing to merge unrelated histories
可執行:
------------------->$ git merge temp --allow-unrelated-histories