天天看点

Git的本地仓库迁移到远程仓库

本文主要介绍本地仓库迁移到远程仓库

Part A

目标描述:本地仓库已有log信息,但从未向远程仓库推送过。即:仅维护本地的git仓库,但此时希望将本地仓库推送至一个新建的远程仓库中进行协同管理。

step 1.  新建一个远程仓库,如图:

Git的本地仓库迁移到远程仓库

step 2. 将远程仓库的指针添加到本地

git remote add origin https://github.com/zkhysz/Git_Examplr.git
           

step 3. 推送到远程仓库

git push origin master
           

 则此时本地仓库成功迁移至新建立的远程仓库,且log信息同步保存,如图

Git的本地仓库迁移到远程仓库

Part B

目标描述:若远程分支不是新建的,而是已经存在的。即:将本地仓库迁移至已经存在log信息的远程仓库。

step 1.将远程仓库的指针添加到同步到本地

git remote add origin https://github.com/zkhysz/Git_Examplr.git
           

这一步与Part A中的step 2是一致的。

step 2. 推送到远程仓库

如果再按照上述第三步进行推送,会报如下错误

[email protected] MINGW64 ~/Desktop/新建文件夹/Git_test (master)
$ git remote add origin https://github.com/zkhysz/Git_Examplr.git

[email protected] MINGW64 ~/Desktop/新建文件夹/Git_test (master)
$ git push origin master
To https://github.com/zkhysz/Git_Examplr.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/zkhysz/Git_Examplr.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
           

此处的解决方案有两种:

(1)方案一,遵循信息提示的操作,先将远程的信息pull到本地,再推送远程仓库。

git pull origin master --rebase
           

利用上述代码,将远程仓库pull到本地,效果如下图:

Git的本地仓库迁移到远程仓库

则本地仓库内多出了远程仓库的文件,查看gitk发现本地仓库的commit记录也被修改了

Git的本地仓库迁移到远程仓库

然后再向远程仓库推送

git push origin master
           

但是这样做的不足之处在于:本地日志被篡改了,相当于将远程仓库的日志与本地仓库的日志按时间顺序混编在了一起。

(2)方案二:强推本地仓库到远程仓库

git push origin master -f
           

添加指令参数-f将本地仓库强行推送到远程,且本地日志不会被改变。如图:

Git的本地仓库迁移到远程仓库

但是此时远程仓库将被改写,其之前的内容被清空,仅保留本次推送。

Git的本地仓库迁移到远程仓库