tags:

views:

43

answers:

2

Hi all,

I started working on my master branch thinking that my task would be easy. After a while I realised it would take more work and I want to do all this work in a new branch.

So how can I create a new branch and take all these changes with me without dirtying master?

Thanks

+2  A: 

as mentioned in the git reset man page:

$ git branch topic/wip     (1)
$ git reset --hard HEAD~3  (2)
$ git checkout topic/wip   (3)
  1. You have made some commits, but realize they were premature to be in the "master" branch. You want to continue polishing them in a topic branch, so create "topic/wip" branch off of the current HEAD.
  2. Rewind the master branch to get rid of those three commits.
  3. Switch to "topic/wip" branch and keep working.

Note: due to the "destructive" effect of a git reset --hard command (it does resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded), I would rather go with a:

$ git reset --soft HEAD~3 (2)

, to make sure I'm not loosing any private file (not added to the index).
The --soft option won't touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do).


Note bis, if you hadn't made any commit yet, only (1) and (3) would be enough!
(or, in one command: git checkout -b newBranch)

VonC
It's probably also worth noting that this wouldn't be a good idea if you have committed topic material to your master branch in a repository that other people pull from. Or at least, if you do need to do a reset you'll need to tell people that's what you are doing so the warnings from their next pull aren't too much of a shock.
Andrew Walker
@VonC - I actually had not made any commits yet. So really easy, thanks mate
willcodejavaforfood
+1  A: 

Since you haven't made any commits yet, you can save all your changes to the stash, create and switch to a new branch, then pop those changes back into your working tree:

git stash push
git checkout -b topic/newbranch
git stash pop
Ether
@Ether - or as VonC pointed out 'git checkout -b newbranch' and skip the stash
willcodejavaforfood
@will: I was thinking that creating a new branch would overwrite any uncommitted changes you had, but if this is not the case, yes you can skip the stash.
Ether
@Ether - I tried it and it worked fine, git is very thoughtful and wont overwrite any local changes
willcodejavaforfood