外观
开源仓库 A (upstream) ──► 本地 B仓库 ──► 私有仓库 C (origin) ↑_________________________________│ (你定期拉取最新代码)
核心概念:本地仓库 B 同时连接两个远程仓库:
origin→ 私有仓库 C(推送修改到这里)upstream→ 开源仓库 A(只从这里拉取更新)
第一步:初始化设置
假设已经克隆了开源仓库到本地:
bash
# 1. 克隆开源仓库(这会创建本地仓库 B)
git clone https://github.com/xx/仓库A.git
cd 仓库A(仓库B)
# 2. 把仓库地址改成私有仓库 C(这样默认推送到私有仓库)
git remote set-url origin https://github.com/自己/仓库C.git
# 3. 添加开源仓库作为 "upstream"(上游)
git remote add upstream https://github.com/xx/仓库A.git
#验证一下:
git remote -v
# 应该显示:
origin https://github.com/自己/仓库C.git (fetch/push)
upstream https://github.com/xx/仓库A.git (fetch/push)第二步:日常开发工作流
情况 A:写自己的代码
bash
# 确保在主分支(或自己的分支)
git checkout main
# 写代码、修改文件...
# 提交修改
git add .
git commit -m "我添加了某某功能"
# 推送到私有仓库 C
git push origin main情况 B:开源仓库 A 更新了,需要同步
bash
# 1. 从开源仓库拉取最新代码(下载到本地,但不合并)
git fetch upstream
# 2. 切换到自己的主分支
git checkout main
# 3. 把别人的更新合并到自己的分支
git merge upstream/main
# Git 自动合并成功
git push origin main