Issue with including changes from a previous branch in the current pull request after merging another branch in Git

50 Views Asked by At

I'm facing an issue while working with Git. I followed these steps:

  1. Create a new brunch B1 git switch -c B1 changing a file in the project git add . && git commit -m "B1" git push origin B1. Create pull request in GitHub(B1)

  2. Create a new brunch B2 git switch -c B2 changing a file in the project git add . && git commit -m "B2" git push origin B2. Create pull request in GitHub(B2)

  3. Merged the pull request of branch B1. On GitHub I click "create a merge commit" HEAD is on the last commit in B2

  4. Pulled changes into branch B2 using rebase: git pull origin main --rebase or git rebase main. Head pointer pointer is set to commit in B2

  5. Pushed my branch to the remote server: git push origin B2

    ![rejected] B2 -> B2 (non-fast-forward)

    error: failed to push some refs

If I follow the instructions git pull origin B2 and git push origin B2. I noticed that commits from branch B1 are included in my pull request for branch B2. How can I avoid including changes from B1 in the pull request for B2 after merging B1 into main?

The idea is to understand how to use git with a rebase strategy.

[upd]: as an option I can use git push origin B2 --force in this article https://git-scm.com/book/en/v2/Git-Branching-Rebasing

Any advice or guidance on resolving this issue would be greatly appreciated!

1

There are 1 best solutions below

4
matt On BEST ANSWER

The problem is that your step 4 was wrong. You should have said pull without --rebase (this code assumes your HEAD is B2):

git pull origin main

Or even better, you could have rebased B2 onto main (this code assumes your HEAD is B2):

git fetch
git rebase main

Basically what you did was to rebase the new part of main onto B2. That's exactly backwards. The new part of main is the commits from B1, so now you've added B1 onto the end of B2, as you have rightly observed.

Another possibility, best of all in my opinion, would be to omit step 4 entirely. That's what I would have done. If you are about to push B2 into a pull request and you do not anticipate any merge conflicts, your step 4 gains you exactly nothing.