Git branching - pull request on HEAD branch takes also prior branch commits

好久不见. 提交于 2019-12-06 09:12:07

I'm really surprised it's not a duplicate... It turns out I already answered almost the same question. Commit-wise it is a duplicate (i.e. there is a branch with 2 unnecessary commits). However, the problem is stated in quite a different way (e.g. the other question doesn't mention pull requests), and I wouldn't find it if it wasn't my answer there.

Use git rebase --onto.

In your local repository:

git checkout newbranch
git rebase master --onto origin/master
git push origin +newbranch  # May look slightly different for you; The point is, you need to force push (the + does that).

NB, in the second line, master could be replaced by HEAD~ or other reference to commit-2.

Short explanation: git takes commits between the one pointed to it (in this case master) and current commit, and replicates them one-by-one at the point defined be --onto. If some commits cannot be applied automatically, the process is suspended and you have to resolve conflicts manually.

Caveat: do not force-push unless you are sure it's safe. If you push to your own fork repository and can assume no one else uses it, you are probably fine (even if it's technically public). It is your private branch, which sometimes may be enough to mean it's fine. But it's important to know risks related to deleting the history (or attempting to).

Alternatives (cherry-pick): my answer to the other question details some alternatives. The situation there is essentially the same, branch F1 contains unnecessary commits.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!