Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rebase only last two commits without the whole branch?

Tags:

git

I accidentally committed to a wrong branch. The graph looks like this

----o--o-----o (master)
     \
      \
       A--B--C--D (feature)

I want to move C and D to master without the changes in A and B. I want the graph to look like this

----o--o-----o (master)
     \        \
      \        C--D (other_feature)
       \
        A--B (feature)

is this possible? and how to do it also on remote?

Changes in A and B are not going to be merged so I don't care if the commits will be lost

like image 793
Zygro Avatar asked Aug 22 '16 17:08

Zygro


People also ask

How do you rebase without going through each commit?

If you don't want rebase to stop at each commit if you get any merge conflicts and want it to stop only once during the rebase process, you can squash all the commits into one in your fix/align-div-vertically branch by squashing them using interactive rebase before rebasing with the master.

How do you skip rebasing?

You can run git rebase --abort to completely undo the rebase. Git will return you to your branch's state as it was before git rebase was called. You can run git rebase --skip to completely skip the commit.


2 Answers

Warning: The following git commands will rewrite the history of the feature branch. git rebase and git reset are dangerous because it can wreak havoc for anyone else who is using the feature branch.

First create the branch other_feature at the same commit as feature.

git checkout -b other_feature feature

Rebase the previous two commits onto master.

git rebase --onto master HEAD~2

Checkout feature.

git checkout feature

Reset feature to the commit where you want it.

git reset --hard HEAD~2
like image 131
Code-Apprentice Avatar answered Oct 13 '22 09:10

Code-Apprentice


The following answer presumes that your feature branch is already published to the remote. I would just cherry pick commits C and D from the feature branch onto the master branch, and then revert these two commits on feature:

git checkout master
git checkout -b other_feature
git cherry-pick <SHA-1 for C>
git cherry-pick <SHA-1 for D>

git checkout feature
git revert <SHA-1 for C>
git revert <SHA-1 for D>
like image 21
Tim Biegeleisen Avatar answered Oct 13 '22 08:10

Tim Biegeleisen