Last Updated: February 25, 2016
·
2.166K
· copenhas

I committed to the wrong branch?

WARNING: This does modify local history

Using Mercurial and committed to the wrong branch locally? Have no fear. You can very carefully graft then strip your commit to produce a clean history.

First get the revision number of your commit (-l5 is to limit the number of log entries:

hg log -b <branch you committed to mistakenly> -l5

Now basically this sequence:

hg update <branch you wanted> 
hg graft -r <commit revision>
# resolve and commit merge if needed
hg strip -r <original commit revision>

I would highly recommend doing the strip in a GUI tool to help visualize what you are stripping out. Also if you have multiple revisions you need to copy over then you can specify multiple -r <revision> arguments to the graft command. Only your root commit will need to be stripped, but strip removes everything after that commit. You can pull any in between changes (if you were pull/merging as you went along) just fine.

Remember the most important part is that all the work is on a local branch. Once you push commits out you need to use something else such as backout to undo your mistaken commits.

2 Responses
Add your response

Why no hg rebase/histedit?

over 1 year ago ·

Good call. I believe at the time when I wrote this pro-tip I had not used rebase.

The only advantage that this has is the 2 step process allows someone unfamiliar a chance to see what they did. Also if you had already pushed up the bad commit I believe rebase is not preferred. Of course in that scenario you wouldn't want to strip either (you'll just get the history back when you pull).

over 1 year ago ·