Search code examples
gitgithubterminalsourcetree

Git/source tree move specific commits at branch B to branch A


I have an accident when develop. I have two commits which need at branch A but I pushed to branch B. So now, I want to move those commit to branch A and then remove them from branch B. Please view image for detail:

enter image description here


Solution

  • First, go to branchA and cherry-pick the two commits you want to pick here.

    $ git checkout branchA
    $ git cherry-pick <commit1>       # commit1 = 0a18e0f   
    $ git cherry-pick <commit2>       # commit2 = e604ce4
    
    $ git push origin HEAD            # push to remote
    

    Now remove the two commits from branchB by revert or rebase. Revert is preferable because it does not change git history.

    Revert:

    $ git checkout branchB
    $ git revert <commit1>
    $ git revert <commit2>
    $ git push origin HEAD
    

    Rebase:

    $ git checkout branchB
    $ git rebase -i efb2443         # go back to the commit before the two commmits you want to remove
    
    Now comment out (adding `#` before the commit hash) the two commits you want to remove.
    
    $ git push -f origin HEAD       # you need to force(-f) push as history is changed here by rebasing