Search code examples
gitgithubgit-mergegit-rebasegit-merge-conflict

git rebase and reset commits to source branch


I want to rebase my my-branch to staging-branch

A---B---C---D---E                  staging-branch
         \
          A5---A4---A3---A2---A1   my-branch

After rebasing, I want to get all their commits and then mine.

A---B---C---D---E                            staging-branch
         
A---B---C---D---E---A5---A4---A3---A2---A1   my-branch

Then I want to combine all commits as two commits.

A---B---C---D---E---A11---A22   my-branch

I could group all my commits as one using following commands below but not sure how I can split into two.

git reset --soft HEAD~5
git commit --edit -m"A11"
git push origin my-branch

Thank you


Solution

  • Use interactive rebase and edit the todo list accordingly:

    git rebase -i staging-branch my-branch
    

    This will open a text editor with a todo list, which defines which commits should be rebased and what action to take with each of the commits. By default, all actions are pick:

    pick A5 commit message 5
    pick A4 commit message 4
    pick A3 commit message 3
    pick A2 commit message 2
    pick A1 commit message 1
    

    You can now replace the pick action with fixup/f (combines two commits into one) or squash/s (combines two commits and lets you edit the commit message). For instance:

    pick A5 commit message 5
    f A4 commit message 4
    f A3 commit message 3
    pick A2 commit message 2
    f A1 commit message 1
    

    This instructs git rebase to combine commits 5, 4 and 3; and combine commits 2 and 1.

    Once you are satisfied with your todo list, save and exit the editor and rebase will do its work. If there are conflicts, you have to resolve them manually and then run git rebase --continue.

    With above's todo list, you will eventually end up with the following history:

    A---B---C---D---E              < staging-branch
                     \
                      A543---A21   < my-branch