Git 与上游合并代码

164 阅读1分钟

1. 首先添加上游仓库作为远程仓库(如果尚未添加)

git remote add upstream <上游仓库URL>

例如:

git remote add upstream https://github.com/example/repo.git

2. 获取上游仓库的最新变更

git fetch upstream

3. 切换到你的本地分支(通常是main或master)

git checkout main  # 或你的分支名

4. 将上游分支合并到本地分支

git merge upstream/main  # 假设上游主分支是main

如果是master分支:

git merge upstream/master

5. 解决可能的合并冲突(如果有)

如果有冲突,Git会提示你。你需要:

  • 手动编辑冲突文件
  • 使用git add <文件>标记已解决的文件
  • 完成合并:
git commit

6. 将合并后的更改推送到你的远程仓库

git push origin main  # 或你的分支名

完整流程示例:

git remote add upstream https://github.com/example/repo.git
git fetch upstream
git checkout main
git merge upstream/main
# 解决冲突(如果有)
git push origin main

替代方案:使用rebase(保持线性历史)

如果你更喜欢干净的提交历史,可以用rebase代替merge:

git fetch upstream
git checkout main
git rebase upstream/main
# 解决冲突(如果有)
git push origin main -f  # 需要强制推送

注意:强制推送(-f)会重写历史,只应在个人分支或团队同意的情况下使用。