Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git move single commit from feature_branch to master

What is the simplest way to achieve this?

from:

--A--B         
      \
       1--2--3 

to:

--A--B--2
         \
          1--3

I can't figure any simple way to achieve this (less than like 5 steps).

like image 507
svobol13 Avatar asked Jan 20 '14 11:01

svobol13


1 Answers

You left out the labels; let's put them back in. Here's "before":

--A--B          <-- master
      \
       1--2--3  <-- feature

and here is "after". I will mark these with a tick mark (or "prime" or whatever you like to call it) as they will be copies of the original commits, with new and different commit-IDs.

--A--B--2'      <-- master
         \
          1'-3' <-- feature

This cannot be done in a single step: it takes at least two.

First we have to re-order the 1--2--3 sequence so that 2 comes first. The easiest way is probably an interactive rebase (while on branch feature, using the git command git rebase -i master): just change the pick order and rebase will cherry-pick 2, then 1, then 3 and move the feature label:

--A--B          <-- master
      \
       2'-1'-3' <-- feature

Now we need only move the master label to point to commit 2'. Many commands will do this, but the simplest is git merge instructed to do a fast-forward merge (to avoid errors):

git checkout master; git merge --ff-only feature~2

To avoid checking out master we can use git branch -f as in VonC's answer (which appeared while I was editing this one), e.g.:

git branch -f master feature~2

(in both cases we need to name commit 2'; with git branch we must name the branch to move, while with git merge we have to be on the branch to be moved).


Just for completeness, here's a different but equivalent method (using four git commands). First let's get on branch master:

git checkout master

Now we can cherry-pick commit 2, creating a copy, 2':

git cherry-pick feature^     # or feature~1

which produces this graph:

--A--B--2'      <-- master
      \
       1--2--3  <-- feature

Now we can rebase feature interactively onto the new master, dropping commit 2:

git checkout feature
git rebase -i master

Change the pick lines to copy 1 and 3 and omit 2, as commit 2' is already there on master.

like image 52
torek Avatar answered Nov 08 '22 11:11

torek