Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Traditional Branching in Mercurial

📅 2010-Mar-11 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ branching, mercurial ⬩ 📚 Archive

Despite the allure of working in a distributed fashion in separate repositories and later merging the changes together, there are genuine cases when working in isolation in a separate branch is necessary. This kind of traditional branching is just as easy as everything else in Mercurial.


Assume we are working on a Car project. It has only one branch, the default. At some point in time we decide to spin off a separate project from the car to work on a fuel efficient car. This project may or may not ever merge back to the main Car project. Hence, branching instead of cloning is the better option for this.

First we clone the existing repository:

$ hg clone Car EfficientCar

To see the current branch in the new repository:

$ cd EfficientCar
$ hg branch

To create a branch for the fuel efficient car from the default branch:

$ hg branch EfficientCar

We need to commit this new branch before we do anything else:

$ hg commit

We can now work on the EfficientCar branch independent of changes happening in the default branch. When we decide to push changes in this branch (or repository) to the parent (central) repository, it aborts with an error:

$ hg push
pushing to Car
searching for changes
abort: push creates new remote branches: EfficientCar!
(use 'hg push --new-branch' to create new remote branches)

This push introduces a new branch in the parent repository, so Mercurial is warning the user about this addition. We are okay with this, so we push again, this time with force:

$ hg push --new-branch

Any number of branches can be created at any level like this easily in Mercurial. For example to experiment on a solar car we branch off from EfficientCar:

$ hg branch
$ hg branch SolarCar

© 2023 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 Mastodon📧 Email