有时候会需要提交部分内容回源,额~主要是我会遇到这种需求,然后我记不住,所以记录一下
用到的仓库
完整操作步骤
一、 本地添加两个远程仓库地址
# 如果你还没克隆过
git clone https://${host}/${warehouse}/yami-anime.git
cd yami-anime
# 确保有两个 remote 配置
git remote add upstream https://${host}/${warehouse}/tkt.git
# 验证git
git remote -v输出应该类似:
origin https://${host}/${warehouse}/yami-anime.git (fetch)
origin https://${host}/${warehouse}/yami-anime.git (push)
upstream https://${host}/${warehouse}/tkt.git (fetch)
upstream https://${host}/${warehouse}/tkt.git (push)二、列出 Fork 中相对于上游新增/修改的 commits
先同步上游最新代码,再看看你的 fork 有哪些额外的 commit:
git fetch upstream
git fetch origin
# 查看你的 fork 比上游多出了哪些 commits
git log --oneline origin/main ^upstream/main
# 或者如果你的默认分支名不同
git log --oneline origin/master ^upstream/master
git log --oneline origin/main ^upstream/master三、根据你的需求选择方式
方式 A — 想挑特定的几个 commits 提 PR(推荐)
# 基于上游最新代码建一个新分支
git checkout -b my-contribution upstream/main
# 只 cherry-pick 你想要的 commits(从 fork 中挑)
git cherry-pick <你想提交的commit-hash>
# 推送到你的 fork,然后通过 ${host} 提 PR
git push origin my-contribution去 https://${host}/${warehouse}/yami-anime 点 Pull Request,选分支 my-contribution,目标选 ${warehouse}/tkt 的 main 分支。
方式 B — 只想提交部分文件的改动
git checkout -b file-only-update upstream/main
# 只从你的 fork 中拿特定文件
git checkout origin/main -- src/某个文件.py docs/某个文档.md
git add .
git commit -m "feat: 合并部分文件改动到上游"
git push origin file-only-update然后同样提 PR。
方式 C — 连文件内的改动都想精细挑选
git checkout -b partial-hunk upstream/main
# 交互式地从 fork 逐块挑选某个文件的改动
git checkout -p origin/main -- src/some-file.ts
# 按 y/n/s 逐块决定是否应用
git add .
git commit -m "feat: 部分合并改动到上游"
git push origin partial-hunk四、在 ${host} 上创建 Pull Request
浏览器打开你的 fork 仓库:
https://${host}/${warehouse}/yami-anime点击 Pull Request → 新建 PR:
源分支:你刚刚推送的分支(如
my-contribution)目标仓库:
${warehouse}/tkt目标分支:
main(或仓库的默认分支)
填写标题和描述,说明你只提交了部分改动,然后提交 PR。
五、后续清理
PR 合并后,同步你的本地仓库:
git checkout main
git fetch upstream
git rebase upstream/main
git push origin main