Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move some last Git commits currently on a branch, onto another branch?

I have a repository where I had been working on master branch having last added some 10 or so commits which I now wish were on another branch, as they describe work that I now consider experimental (I am still learning good Git practices).

In light of this consideration, I would now like to have these last 10 commits form their own branch so to speak, so that I can have master clean and reserved for "release" / "stable" commits only.

To illustrate, what I have is:

        b--b (feature B)
       /       
X--X--X--Z--Z--Z--Z--Z--Z (master)
    \
     a--a--a (feature A)

You can see that commits marked with X and Z are all on the master branch, while what I want is commits marked with Z (the now considered experimental "feature Z" work) to lie on their own branch and master ending with the rightmost X. To illustrate, the desired graph:

        b--b (feature B)
       /       
X--X--X (master)
    \  \
     \  Z--Z--Z--Z--Z--Z (feature Z - the new branch I want)
      \
       a--a--a (feature A)

That way I will have my master reserved for releases and otherwise stable commits, being able to merge in A, B and Z features as needed.

So how do I move the "Z" commits onto their own branch?

like image 558
amn Avatar asked Dec 30 '10 13:12

amn


3 Answers

git checkout master
git branch feature-Z
git reset <commit_id>

where commit_id is an identifier of that last X commit before b branches off.

like image 158
JB. Avatar answered Nov 07 '22 07:11

JB.


For completeness, the answer is here - http://git-scm.com/docs/git-reset - search for the text "Undo a commit, making it a topic branch" - the example shows making the last 3 commits a branch and resetting master to the commit previous to those 3 commits:

$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 3 commits.
#
nothing to commit (working directory clean)
$ git branch topic/wip
$ git reset --hard HEAD~3
$ git checkout topic/wip
Switched to branch topic/wip
like image 28
notbrain Avatar answered Nov 07 '22 09:11

notbrain


Simply rename master and start a new master at the last X:

git checkout master; git branch -m feature; git checkout -b master HEAD~6

like image 2
user502515 Avatar answered Nov 07 '22 07:11

user502515