🚀 如何同步 Fork 倉庫:處理一般更新與原始倉庫重寫歷史的情況
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/1180
前言
當你在 GitHub 上 Fork 了別人的倉庫後,原始作者(上游倉庫)可能會持續更新,而你的 Fork 並不會自動同步。
那麼問題來了:
-
原始倉庫有了新提交,怎麼更新我的 Fork?
-
如果原始倉庫 刪除了很多 commit 或強制推送(force push) 呢?我還能更新嗎?
本文就針對這兩種情況進行完整講解與對應解法。
🧩 情況一:原始倉庫只新增 commit(沒重寫歷史)
這是最常見的情況,步驟如下:
1. 添加 upstream(原始倉庫)
git remote add upstream https://github.com/原始作者帳號/原始倉庫名.git
確認是否成功添加:
git remote -v
你會看到:
origin https://github.com/你的帳號/倉庫名.git (fetch)
upstream https://github.com/原始作者帳號/倉庫名.git (fetch)
2. 從 upstream 抓取最新變更
git fetch upstream
3. 合併 upstream 的分支到你的分支
以 main
為例:
git checkout main
git merge upstream/main
或者使用 rebase
(保持線性歷史):
git rebase upstream/main
4. 將同步後的結果推送到 GitHub
git push origin main
💥 情況二:原始倉庫重寫歷史(刪除 commit、rebase、強制推送)
如果對方重寫了歷史,你再用上面的方法是沒用的,因為 Git 會認為你們的歷史分歧了。這時必須採用 強制同步策略:
1. 抓取 upstream
git fetch upstream
2. 用 reset --hard
強制對齊 upstream 分支
git checkout main
git reset --hard upstream/main
這會讓你的本地分支完全等同於原始倉庫的狀態,包括刪除的 commit 也會一起消失。
⚠️ 警告:這會刪除你本地尚未提交的更改,請提前備份!
3. 強制推送到你自己的 Fork
git push origin main --force
🎯 總結:各情況對應做法
狀況 | 操作方式 |
---|---|
原始倉庫只新增 commit | fetch + merge 或 rebase |
原始倉庫重寫歷史(刪除 commit / force push) | fetch + reset --hard + push --force |
🧪 額外補充:不使用 Git 命令,只在 GitHub 上同步的方法
-
打開你 Fork 的倉庫頁面。
-
點選
Sync fork
或Fetch upstream
按鈕。 -
點
Update branch
。
這種方法方便但功能有限,無法處理複雜情況如歷史重寫或衝突。
結語
同步 Fork 倉庫時,千萬別只用 pull
,先判斷對方是否有重寫歷史,再決定同步策略。只要選對方法,就能讓你的 Fork 永遠保持與上游一致。
→返回目錄:GitBash使用手冊
This article was last edited at