Saturday, February 5, 2011

Experimental branches in Mercurial

Branching in Mercurial is easy, it’s so easy that most of the times you’re branching you don’t even know that you’re doing it. Have you ever had to merge? I guess you have, well guess what, when you’re merging, you’re merging two branches! Ever got an error when pushing stating that a push would create two heads in the remote repository? Head == branch.

I had a conversation the other day with a fellow developer about Git, I asked him what the main benefits of Git was. The thing is I’m pretty much Git illiterate. One of the things he said was the ease of branching and how local “throw away” branches can’t be done in Mercurial. First of all, I don’t know exactly how easy this is in Git so it might be harder in Mercurial but it’s definitely not hard. Let me show you!

I’ll use TortoiseHG in this example since it’s visual and makes for better examples but it is just as easy to do it from the command line.

Let’s start with a repository that contains a code file:


Now, this class is boring, it only writes hello to the console and I’d like to spice it up a little, so I’ll do a spike. Let’s make it say “Hello Europe!”. Said and done, I edit the file and commit, now my repository looks like this:


Now the thing is, while “Hello Europe!” is good I’d like to explore something differnt, let’s make it say “Hello World!” that’s so much more international. Let’s go back to before the change:


Now, I change the code again, this time to “Hello World!” then I commit, now the repo looks like this:


See, two branches, I could have backed to any point back in the revision history to branch from there. Now I’ve decided to go with the “Hello World!”-change and I want to push it to a central repo, I don’t want to include the “Hello Europe!” spike.

Go into the repository explorer and click the “Determine and mark outgoing changesets”-button. This will mark change sets not already in the repository you’re pushing to with arrows:


Right click the head of the branch you want to push and select “Push to here”. Now the repository you were pushing to will contain the following changesets:


That’s pretty much all there is to it! One more thing though, what about deleting local branches that you don’t want to keep? This can be done with the strip command in the MqExtensions for Mercurial.

Happy branching!

No comments:

Post a Comment