Rebasing to a New Branch with Mercurial
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 command to move all my local commits to a new branch before pushing. It worked, and here’s how I did it.
hg clone localrepo temp-localrepo. I always try crazy ideas in another local clone in case I trash the repo.hg upto the revision before my local commits that I want to put in a branch.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.- Now for the rebase. I needed to rebase the first changeset in my series of local changes onto the
newbranchnamechangeset. Something likehg 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 as an exercise for the reader.
July 9th, 2010 at 11:10 am
Or, you could have just pushed to default and merged (or not) later. But (sigh) I guess that would’ve required a month-long campaign of television ads and flyers dropped from Zeppelins to educate your huge team to work off rev 95 instead of tip. Too much work.
July 9th, 2010 at 3:03 pm
Well, the point is this is a way to handle situations where you wish you would have branched at some point in the past. It makes your wish come true. And all your wildest dreams too.