git合并多个仓库

之前因为考虑不得当,没有采用分支的方法管理同一个工程。在github上建立了多个仓库,强迫症发作了,想合并这些仓库到同一个git中,并保留所有的git记录。具体来说,假设我们有如下几个仓库:

  1. OldA:要合并的仓库A
  2. OldB:要合并的仓库B
  3. C:将OldA和OldB两个仓库合并到该git中

具体操作过程如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
mkdir C
cd C
# Assume the current directory is where we want the new repository to be created, Create the new repository
git init

# Before we do a merge, we have to have an initial commit, so we’ll make a dummy commit
dir > deleteme.txt
git add .
git commit -m "Initial dummy commit"

# Add a remote for and fetch the old repo
git remote add -f old_a <OldA repo URL>

# Merge the files from old_a/master into new/master
git merge old_a/master
# if occurs "fatal: refusing to merge unrelated histories"
git merge old_a/master --allow-unrelated-histories

# Clean up our dummy file because we don’t need it any more
git rm .\deleteme.txt
git commit -m "Clean up initial file"

# Move the old_a repo files and folders into a subdirectory so they don’t collide with the other repo coming later
mkdir old_a
dir -exclude old_a | %{git mv $_.Name old_a}

# Commit the move
git commit -m "Move old_a files into subdir"

接着合并其余仓库,如OldB

1
2
3
4
5
6
7
8
# Do the same thing for old_b
git remote add -f old_b <OldB repo URL>
git merge old_b/master
# if occurs "fatal: refusing to merge unrelated histories"
git merge old_b/master --allow-unrelated-histories
mkdir old_b
dir -exclude old_a,old_b | %{git mv $_.Name old_b}
git commit -m "Move old_b files into subdir"

这个时候仓库A和B都合并到了仓库C中,并且保留了所有的git记录。此时若想查看某个文件的提交记录,需要使用git log --follow old_b/readme.md

old_a仓库有多个分支,则可以采用如下方式继续合并:

1
2
3
# Bring over a feature branch from one of the old repos
git checkout -b feature-in-progress
git merge -s recursive -Xsubtree=old_a old_a/feature-in-progress

参考

Merging Two Git Repositories Into One Repository Without Losing File History
How to merge two or multiple git repositories into one

------ 本文结束------
坚持原创技术分享,您的支持将鼓励我继续创作!

欢迎关注我的其它发布渠道