Mercurial move changes to a new branch

Casebash picture Casebash · Jan 12, 2011 · Viewed 34.3k times · Source

I have a number of changes that I committed to my local repository, but have not yet been pushed. Since on a feature is taking longer than expected, I want to swap these changes onto a named branch before I push. How can I do this?

Answer

Oben Sonne picture Oben Sonne · Jan 12, 2011

As suggested by Mark, the MqExtension is one solution for you problem. IMHO a simpler workflow is to use the rebase extension. Suppose you have a history like this:

@  changeset:   2:81b92083cb1d
|  tag:         tip
|  summary:     my new feature: edit file a
|
o  changeset:   1:8bdc4508ac7b
|  summary:     my new feature: add file b
|
o  changeset:   0:d554afd54164
   summary:     initial

This means, revision 0 is the base on which you started to work on your feature. Now you want to have revisions 1-2 on a named branch, let's say my-feature. Update to revision 0 and create that branch:

$ hg up 0
$ hg branch my-feature
$ hg ci -m "start new branch my-feature"

The history now looks like this:

@  changeset:   3:b5939750b911
|  branch:      my-feature
|  tag:         tip
|  parent:      0:d554afd54164
|  summary:     start new branch my-feature
|
| o  changeset:   2:81b92083cb1d
| |  summary:     my new feature: edit file a
| |
| o  changeset:   1:8bdc4508ac7b
|/   summary:     my new feature: add file b
|
o  changeset:   0:d554afd54164
   summary:     initial

Use the rebase command to move revisions 1-2 onto revision 3:

$ hg rebase -s 1 -d 3

This results in the following graph:

@  changeset:   3:88a90f9bbde7
|  branch:      my-feature
|  tag:         tip
|  summary:     my new feature: edit file a
|
o  changeset:   2:38f5adf2cf4b
|  branch:      my-feature
|  summary:     my new feature: add file b
|
o  changeset:   1:b5939750b911
|  branch:      my-feature
|  summary:     start new branch my-feature
|
o  changeset:   0:d554afd54164
   summary:     initial

That's it .. as mentioned in the comments to Mark's answer, moving around already pushed changesets generally is a bad idea, unless you work in a small team where you are able to communicate and enforce your history manipulation.