iOSGeek iOSGeek - 1 year ago 50
Git Question

Reorganise pushed commits, remove from brach to apply in other one

I have two feature branches, I made the mistake of committing and pushing some commits to a wrong branch here is the situation:

Branch1: commit1 -> commit2 -> commit3 -> commit4

All commits pushed to Branch1.

I want to remove
from the local and remote branches and from history. I don't want to touch master or any other branch, just remove two non-consecutive PUSHED commits from a SPECIFIC branch

Answer Source

You cannot remove commits from a branch. But you can recreate a branch from selected commits.

One simple way is to rebase in interactive mode (thanks @Steve!):

git rebase -i SHA_commit1

This will give you a list of commits, something like:

pick SHA_commit2 log msg of commit 2
pick SHA_commit3 log msg of commit 3
pick SHA_commit4 log msg of commit 4

Remove the commits you don't want. The commits after the first removed will be replayed.

Another way is to recreate a branch without the commits you don't want, for example:

# switch to branch1 (if not already on it)
git checkout branch1

# rename it -> it will become the backup
git branch -m branch1-bak

# recreate branch1 from the good point, at commit1
git checkout -b branch1 commit1_SHA

# replay commit3
git cherry-pick commit3_SHA

Now, branch1 has commit1 and commit3, the other two commits are not in it.