Monday 6 October 2008

Git tip: rewind master, keep head in a branch

Imagine that you just committed something on your master branch, and suddendly realize that you'll have to work a bit more on it. Wouldn't it be great to have committed this last patch on a branch instead?

Git allows you to do this. You can rewind the master by one patch, while retaining the current HEAD in a new branch.

First, create a new branch (let's call it newbranch) that points at your HEAD:

git branch newbranch
Then, rewind the master by one commit:
git reset --hard HEAD^
That's all. You just moved your last commit on its own branch. If you want to continue working on top of it, you just have to
git checkout newbranch
and start hacking.
(Now, this is a very entry-level git tip, but those kind of examples, that demonstrate what makes git different from centralized version control systems, have certainly a good pedagogical value. More to come when I have tuits.)

2 comments:

Gregory Benison said...

Very helpful post. This is a surprisingly common situation to get into ("wish I had been working on a branch.") I suppose this is the reason some never commit directly to "master" but only merge into it. It can be hard to maintain that discipline though, especially for smaller projects where you just want to work quickly.

Anonymous said...

Thanks, it helps me today :-)