Moving Already Committed Work To A Branch - Test-More/test-more GitHub Wiki

Let's say you've already done some work in master (or Test-Builder1.5) and you realize it really should have been in a branch. Here's how you can get that into a branch.

Let's say you've done two commits to master. Your repository looks something like this...

 C - master
 |
 B
 |
 A - origin/master
 |
...

You want it to look like this

 C - mybranch
 |
 B
 |
 A - origin/master & master
 |
...

You can see visualizations like the above with git log --pretty=format:'%h %s %d' --graph.

Step zero: backup your repository

We're going to be doing some light history manipulation here and there's a chance it could screw up your repository. If you haven't done this before, it would be wise to backup your repository. Since your git repository is stored in the .git directory of your checkout, just make a copy of your entire working directory.

  • cp -r path/to/my/checkout path/to/my/checkout.bak

If anything goes wrong, blow away your checkout and replace it with a fresh copy of the backup.

Step one: create the branch

The new branch is where master currently is, so make a branch there.

  • git checkout master
  • git branch mybranch

Now your repo should look like this.

 C - master & mybranch
 |
 B
 |
 A - origin/master
 |
...

Step two: move master back to origin/master

Now you need to move the master branch so it matches the main repository. That label is origin/master. git reset is all about moving labels (branches are just labels).

  • git reset --hard origin/master

Now your repo should look like this.

 C - mybranch
 |
 B
 |
 A - origin/master & master
 |
...

--hard tells reset to do a fresh checkout at the new location and clear your staging area. Otherwise it leaves all the code from your previous commits in your working directory.

Step three: checkout your new branch and work

Your new branch is ready! Check it out and commit to it as normal.

  • git checkout mybranch

Do a git log to make sure your commits are there.