The Occasional Occurence

Rebasing to a New Branch with Mercurial

July 09, 2010 at 08:53 AM | categories: Python, Software, work, computing, General

I had a situation at work the other day where I had made a number of local commits to the default branch of my repo. I wanted to push them upstream to our central server but the feature was incomplete and I didn't want to break anything in case someone needed to make a tweak to the current code in the default branch.

I had the idea to use the `hg rebase <http://mercurial.selenic.com/wiki/RebaseProject>`_ command to move all my local commits to a new branch before pushing. It worked, and here's how I did it.

  1. hg clone localrepo temp-localrepo. I always try crazy ideas in another local clone in case I trash the repo.
  2. hg up to the revision before my local commits that I want to put in a branch.
  3. hg branch newbranchname && hg ci -m "Branching for reason foo." This creates a new branch and head that can be used as a rebase destination.
  4. Now for the rebase. I needed to rebase the first changeset in my series of local changes onto the newbranchname changeset. Something like hg rebase --source 94 --dest 105.

That's about it. After verifying that it did what I wanted all that was left was to repeat the steps in my main local repo and push to the central server.*

cw

* Of course what I actually did was push these changes to my main local repo and then to the central repo. Woops. That left me with the changes both in ``default`` and in ``newbranchname``.

Don't do that. Repeat the steps after you've tried them in another local clone. I leave recovering from such a situation with ```hg strip <http://mercurial.selenic.com/wiki/Strip>`_`` as an exercise for the reader.