Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move certain commits to be based on another branch in git?

Tags:

git

commit

patch

The situation:

  • master is at X
  • quickfix1 is at X + 2 commits

Such that:

o-o-X (master HEAD)      \       q1a--q1b (quickfix1 HEAD) 

Then I started working on quickfix2, but by accident took quickfix1 as the source branch to copy, not the master. Now quickfix2 is at X + 2 commits + 2 relevant commits.

o-o-X (master HEAD)      \       q1a--q1b (quickfix1 HEAD)               \                q2a--q2b (quickfix2 HEAD) 

Now I want to have a branch with quickfix2, but without the 2 commits that belong to quickfix1.

      q2a'--q2b' (quickfix2 HEAD)      / o-o-X (master HEAD)      \        q1a--q1b (quickfix1 HEAD) 

I tried to create a patch from a certain revision in quickfix2, but the patch doesn't preserve the commit history. Is there a way to save my commit history, but have a branch without changes in quickfix1?

like image 839
Alex Yarmula Avatar asked Mar 03 '10 07:03

Alex Yarmula


People also ask

How do you move a commit from one branch to another branch in git?

If we want to move a commit to an existing branch, we can follow a similar process using merge. In step (1) we make sure we are on the branch where we want the commit to end up. We then merge in the source branch in step (2). At this point, our target branch should have the work we want transferred.

How do I move multiple commits from one branch to another?

You can do this with multiple commits too, just cherry pick several, then reset back to the last commit you want to keep. The process is the same if you have committed to local master by mistake - just cherry-pick to a branch, then reset master. Only ever do this if you haven't pushed the commits to origin.


1 Answers

This is a classic case of rebase --onto:

 # let's go to current master (X, where quickfix2 should begin)  git checkout master   # replay every commit *after* quickfix1 up to quickfix2 HEAD.  git rebase --onto master quickfix1 quickfix2  

So you should go from

o-o-X (master HEAD)      \        q1a--q1b (quickfix1 HEAD)               \                q2a--q2b (quickfix2 HEAD) 

to:

      q2a'--q2b' (new quickfix2 HEAD)      / o-o-X (master HEAD)      \        q1a--q1b (quickfix1 HEAD) 

This is best done on a clean working tree.
See git config --global rebase.autostash true, especially after Git 2.10.

like image 79
VonC Avatar answered Oct 09 '22 06:10

VonC