git同步代碼至github和gitee(碼雲)


我們有時候開發代碼需要把代碼同步到多個遠程庫中,如何操作才能做到呢?

我們知道,git是分布式版本控制系統,同步到多個遠程庫時,需要用不同的名稱來標識不同的遠程庫,而git給遠程庫起的默認名稱是origin。所以我們需要修改、配置名稱,以關聯不同遠程庫。有兩種方式!

為了方便舉例,我以GitHub和Gitee(碼雲)作為示例!

同步方式

命令方式同步

先刪除已關聯的名為origin的遠程庫:

git remote rm origin

然后,再關聯GitHub的遠程庫:

git remote add github git@github.com:chloneda/demo.git

接着,再關聯碼雲的遠程庫:

git remote add gitee git@gitee.com:chloneda/demo.git

配置方式同步

修改.git文件夾內的config文件:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    url = git@github.com:chloneda/demo.git
    fetch = +refs/heads/*:refs/remotes/github/*
[branch "master"]
    remote = origin
    merge = refs/heads/master

將上述文件內容[remote "origin"]內容復制,修改origin名稱,內容如下:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "github"]
    url = git@github.com:chloneda/demo.git
    fetch = +refs/heads/*:refs/remotes/github/*
[remote "gitee"]
    url = git@gitee.com:chloneda/demo.git
    fetch = +refs/heads/*:refs/remotes/gitee/*
[branch "master"]
    remote = origin
    merge = refs/heads/master

查看遠程庫

通過以上兩種方式的任一種方式配置完成后,我們用

git remote -v

 

查看遠程庫信息:

gitee   git@gitee.com:chloneda/demo.git (fetch)
gitee   git@gitee.com:chloneda/demo.git (push)
github  git@github.com:chloneda/demo.git (fetch)
github  git@github.com:chloneda/demo.git (push)

 

可以看到兩個遠程庫,說明配置生效了。

上傳代碼

git add .
git commit -m "update"

 

提交到github

git push github master

 

提交到碼雲

git push gitee master

 

更新代碼

# 從github拉取更新
git pull github

# 從gitee拉取更新
git pull gitee

 

踩到的坑

上述過程中,更新或提交代碼時可能會遇到fatal:refusing to merge unrelated histories (拒絕合並無關的歷史) 錯誤,解決辦法:

首先將遠程倉庫和本地倉庫關聯起來。

git branch --set-upstream-to=origin/remote_branch  your_branch

其中,origin/remote_branch是你本地分支對應的遠程分支,your_branch是你當前的本地分支。

然后使用git pull整合遠程倉庫和本地倉庫。

git pull --allow-unrelated-histories    //(忽略版本不同造成的影響)

 

重新更新、提交即可。

如遇到 Git沒有共同祖先的兩個分支合並 的情形請自行查詢!

 

注:本文出自博主 Chloneda https://zhuanlan.zhihu.com/p/71163868


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM