Git的本地倉庫遷移到遠程倉庫

本文主要介紹本地倉庫遷移到遠程倉庫

Part A

目標描述:本地倉庫已有log信息,但從未向遠程倉庫推送過。即:僅維護本地的git倉庫,但此時希望將本地倉庫推送至一個新建的遠程倉庫中進行協同管理。

step 1.  新建一個遠程倉庫,如圖:

step 2. 將遠程倉庫的指針添加到本地

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

step 3. 推送到遠程倉庫

git push origin master

 則此時本地倉庫成功遷移至新建立的遠程倉庫,且log信息同步保存,如圖

 

 

Part B

目標描述:若遠程分支不是新建的,而是已經存在的。即:將本地倉庫遷移至已經存在log信息的遠程倉庫。

step 1.將遠程倉庫的指針添加到同步到本地

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

這一步與Part A中的step 2是一致的。

step 2. 推送到遠程倉庫

如果再按照上述第三步進行推送,會報如下錯誤

Administrator@PC-201708231238 MINGW64 ~/Desktop/新建文件夾/Git_test (master)
$ git remote add origin https://github.com/zkhysz/Git_Examplr.git

Administrator@PC-201708231238 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到本地,效果如下圖:

則本地倉庫內多出了遠程倉庫的文件,查看gitk發現本地倉庫的commit記錄也被修改了

然後再向遠程倉庫推送

git push origin master

但是這樣做的不足之處在於:本地日誌被篡改了,相當於將遠程倉庫的日誌與本地倉庫的日誌按時間順序混編在了一起。

(2)方案二:強推本地倉庫到遠程倉庫

git push origin master -f

添加指令參數-f將本地倉庫強行推送到遠程,且本地日誌不會被改變。如圖:

但是此時遠程倉庫將被改寫,其之前的內容被清空,僅保留本次推送。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章