Search code examples
gitgit-rebase

How to rebase this branch?


The image below consists of two parts: the first part is the repository sample model, the second part is the repository state that I want to get using the git rebase.

I didn't forget anything in the second part. This is exactly what I want.

enter image description here


Solution

  • If the number of commits you want to manipulate is as small as in the picture : use cherry-pick

    git checkout tmp1
    # make sure you have a clean working directory before running reset --hard :
    git reset --hard <e>
    git cherry-pick <h> <i>
    

    git rebase has a syntax to select a range of commits :

    git checkout tmp1
    # you need to mention <g>, the *parent* of the first commit you
    # want to replay, not <h>
    git rebase --onto <e> <g> tmp1
    
    git checkout tmp2
    git reset --hard <k>
    git rebase --onto <e> <g> tmp2
    

    a note about git reset --hard :

    git reset --hard <target> is one of the few dangerous git commands, that can delete modifications from your disk without saving them somewhere first.

    It sets the active commit to <target>, and discards any modifications on all tracked files (that's the dangerous part).

    You should at least know the effects before using it.

    Some easy ways to avoid loosing your un-committed work are :

    • git stash your work before using git reset --hard,
    • commit your work before using it (even after a git reset, the commit will still be available through git reflog),