周五整理机器人线上监控脚本,忽然想起这个脚本还是放在github上管理呀,免费用户在github上的代码都是公开的,谁都可以看。我和一些同事的工作邮箱还在脚本里配置着呢,要是被爬虫抓到就烦人了。
最近才找到一个私有的git仓库,于是想把github上的原有数据移过去,但又要保存以前的commit记录,所以不是简单的mv那么简单了,要折腾一下了。
结果嘛,当然是终于成功了,所以发此博文分享并记录。
为了让大家看的明白,我重新描述下case如下:
- 有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到服务器了。
总结:
- 大致思路是伪造远程的repo1仓库为repo2的一个分支,然后合并进来;
- 若是文件有冲突、或要建立子目录,建议在repo1中先解决,再进行如上操作。
参考资料:
- http://stackoverflow.com/questions/1683531/how-to-import-existing-git-repository-into-another
- http://progit.org/book/zh/ch2-5.html (推荐阅读)
