大家好,我是程序员柏风,AI 最全的 Vibecoding 学习地图 http://coderoadmap.cn 作者。
远程与 Fork
远程(remote) 是本地仓库与 GitHub 服务器之间的桥梁;Fork 是在自己账号下复制他人仓库,开源贡献的标准入口。本课对应 git-github 路线图 的 managing-remotes、forking-vs-cloning、pr-from-a-fork。
git push / git pull 基础在 git-essentials;这里讲多 remote、upstream 同步与 fork 工作流。
学习目标
- 管理多个 remote(
origin、upstream) - 区分 clone 与 fork 的使用场景
- 完成从 fork 开 PR 的完整同步流程
查看与配置 remote
git remote -v
git remote add upstream git@github.com:original-owner/project.git
git remote rename origin old-origin # 少用
git remote remove upstream
典型 fork 布局:
| remote | 指向 | 用途 |
|---|---|---|
| origin | 你的 fork | push 你的分支 |
| upstream | 上游原仓 | pull 最新 main,保持同步 |
同步 upstream 到 fork
git fetch upstream
git switch main
git merge upstream/main
# 或 git rebase upstream/main
git push origin main
在 feature 分支开发前,先更新 main,减少 PR 冲突。
Fork vs Clone
| 操作 | 结果 |
|---|---|
| Clone | 本地副本;需对原仓有读权限(public 可读) |
| Fork | GitHub 上在你账号建新仓 + 可选 clone 到本地 |
开源贡献:Fork → clone 你的 fork → 分支 → push origin → PR 到 upstream。
git clone git@github.com:you/forked-project.git
cd forked-project
git remote add upstream git@github.com:upstream-owner/forked-project.git
git switch -c fix/typo-in-readme
# 修改、commit
git push -u origin fix/typo-in-readme
然后在 GitHub:Compare & pull request 到 upstream-owner/forked-project 的 main。
HTTPS 与 SSH
# 查看当前 remote URL
git remote get-url origin
# 切换为 SSH
git remote set-url origin git@github.com:you/repo.git
公司代理环境可能限制 SSH;HTTPS + credential manager 亦可。
常见错误
- rejected (non-fast-forward):远程有你本地没有的 commit → 先
git pull --rebase - Permission denied:SSH 密钥未加到 GitHub,或 push 到了无权限的 upstream(应对 origin push)
练习
- Fork 一个开源 docs 仓,添加
upstreamremote -
git fetch upstream && git merge upstream/main同步 main - 推一条小改动到 origin,准备下一课开 PR
小结
origin 写自己,upstream 读上游;Fork 是开源 PR 的第一步。 下一课 Pull Request 规范、Review 与 diff 阅读。