當我們想在 Github 上的某個開源倉庫中貢獻自己的代碼時,通常會先 Fork 這個開源代碼倉庫,然后clone到本地,提交自己的修改,最后 Pull Request 進行合并,
由于開源倉庫通常會有很多人一起貢獻代碼,要持續與這些專案貢獻者保持協作,我們就會遇到一個很常見的問題:如何與源倉庫保持同步?
參考以下步驟即可與 Fork 的源倉庫保持同步,
配置遠程倉庫
-
先查看當前配置的遠程倉庫,
YOUR_USERNAME為你的 Github 用戶名,YOUR_FORK為 Fork 的倉庫名,$ git remote -v > origin https://github.com/YOUR_USERNAME/YOUR_FORK.git (fetch) > origin https://github.com/YOUR_USERNAME/YOUR_FORK.git (push) -
配置需要同步的上游倉庫(即Fork的源倉庫),
ORIGINAL_OWNER為源倉庫作者用戶名,ORIGINAL_REPOSITORY為源倉庫名,$ git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git -
驗證配置,
upstream開頭的即是遠程倉庫$ git remote -v > origin https://github.com/YOUR_USERNAME/YOUR_FORK.git (fetch) > origin https://github.com/YOUR_USERNAME/YOUR_FORK.git (push) > upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git (fetch) > upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git (push)
同步Fork分支
-
從上游倉庫獲取分支及其各自的提交,對
BRANCHNAME的提交將存盤在本地分支upstream/BRANCHNAME中,$ git fetch upstream > remote: Counting objects: 75, done. > remote: Compressing objects: 100% (53/53), done. > remote: Total 62 (delta 27), reused 44 (delta 9) > Unpacking objects: 100% (62/62), done. > From https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY > * [new branch] main -> upstream/main -
切換本地默認分支,本例中即
main分支,$ git checkout main > Switched to branch 'main' -
將上游默認分支 - 本例中為
upstream/main- 的更改合并到本地默認分支,$ git merge upstream/main > Updating a422352..5fdff0f > Fast-forward > README | 9 ------- > README.md | 7 ++++++ > 2 files changed, 7 insertions(+), 9 deletions(-) > delete mode 100644 README > create mode 100644 README.md這個操作會使本地的默認分支與上游倉庫同步,而不會丟失本地更改,
如果你本地沒有任何單獨的提交,Git會直接進行"fast-forward"操作:
$ git merge upstream/main > Updating 34e91da..16c56ad > Fast-forward > README.md | 5 +++-- > 1 file changed, 3 insertions(+), 2 deletions(-)
推送同步
上述步驟僅僅同步了倉庫的本地副本,要在 GitHub 上同步更新,還需要將本地更改推送到 Github 在線倉庫:
git push origin main
有時,推送本地副本到在線倉庫會遇到如下錯誤:
$ git push origin main
To https://github.com/YOUR_USERNAME/YOUR_FORK.git
! [rejected] main -> main (fetch first)
error: 推送一些參考到 'https://github.com/YOUR_USERNAME/YOUR_FORK.git' 失敗
提示:更新被拒絕,因為遠程倉庫包含您本地尚不存在的提交,這通常是因為另外
提示:一個倉庫已向該參考進行了推送,再次推送前,您可能需要先整合遠程變更
提示:(如 'git pull ...'),
提示:詳見 'git push --help' 中的 'Note about fast-forwards' 小節,
這說明你的遠程倉庫有本地副本中不包含的提交,只需要執行如下操作即可:
$ git pull origin main
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/264195.html
標籤:其他
