Moving Commits into a new branch

October 24, 2017
San Francisco, CA

Sometimes I make the mistake of not starting a new branch before I start editing code, especially if i'm the only one working on a repository and there is only the master branch.

To fix this I looked it up on stackoverflow and this is the best answer I have found.


Step 1: How many commits in are we?

User$ git log

This allows us to check how many commits we want to move. You can read the comment on the commit to see how far back you want to roll

commit 0b2b5b47b9c540....
Author: Eric Tsai
Date: Tue Oct 24 20:00:44 2017 -0700
I want to roll this commit back

commit 0b2b235x333540....
Author: Eric Tsai
Date: Tue Oct 24 19:59:44 2017 -0700
This is fine, leave this in master


Step 2: Discarding the commits temporarily

User$ git reset --keep HEAD~3

This discards the "3" most recent commits temporarily because it doesn't "throw away" the changes, change this number to the number of commits you want to roll back


Step 3: Creating a new branch

User$ git checkout -t -b newbranchname

This creates and switches to a new branch based off of the new master branch that has been rolled back


Step 4: Cherry pick it

User$ git cherry-pick ..HEAD@{2}

This is the magical step that moves the temporarily discarded commits into the new branch we moved to, It's important to only use {2} because this denotes the action that happen 2 steps ago, not the number of commites we're bringing back

And if all goes well you should have a new branch that is x commits ahead of the master

User$ git status
On branch newbranch
Your branch is ahead of 'master' by 1 commit.
(use "git push" to publish your local commits)


And that's all there is to it. A simple 4 step process!
To read more about this go to the stackoverflow page.