fork 开源项目后,上游仓库新增了分支,如何同步
当你 fork 了一个仓库,如果 上游(upstream)新增了分支,你需要先同步 upstream,再把分支拉到本地。
完整步骤如下:
1️⃣ 查看当前远程仓库
git remote -v
一般会看到:
origin https://github.com/你的用户名/repo.git
如果没有 upstream,需要添加。
2️⃣ 添加 upstream(上游仓库)
git remote add upstream https://github.com/原作者/repo.git
例如:
git remote add upstream https://github.com/openai/example.git
确认:
git remote -v
应该看到:
origin https://github.com/你/repo.git
upstream https://github.com/原作者/repo.git
3️⃣ 获取 upstream 最新信息
git fetch upstream
这一步会把 所有 upstream 分支信息拉下来。
例如会出现:
upstream/main
upstream/dev
upstream/new-branch
4️⃣ 查看 upstream 所有分支
git branch -r
输出示例:
origin/main
origin/dev
upstream/main
upstream/new-feature
5️⃣ 拉取上游新增分支到本地
例如 upstream 新增了:
new-feature
执行:
git checkout -b new-feature upstream/new-feature
或者新版 git:
git switch -c new-feature upstream/new-feature
这样:
本地 new-feature
↑
跟踪 upstream/new-feature
6️⃣ 如果想推到自己的 fork
git push origin new-feature
这样你的 GitHub fork 里也会出现这个分支。
🔑 一套完整命令(最常用)
git remote add upstream https://github.com/原仓库/repo.git
git fetch upstream
git checkout -b new-branch upstream/new-branch
git push origin new-branch
🧠 推荐 fork 仓库的标准结构
你的仓库 (origin)
│
├── main
├── dev
└── feature
原仓库 (upstream)
│
├── main
├── dev
└── new-feature
平时同步:
git fetch upstream
git merge upstream/main

浙公网安备 33010602011771号