Search code examples
mercurial

How do I copy commits from one branch to another?


I have a branch with a few revisions in it. I want to try making some code changes that require reordering and patching those commits with histedit, but I want to keep the original branch around in case it doesn't go well. How can I do that?

Example

Before:

master -> change 1 -> change 2 (branch A)

After:

master -> change 1 -> change 2 (branch A)
       -> change 1 -> change 2 (branch B)

Solution

  • The integrated and recommended way to copy or cherry-pick commits from one branch to another is using

    hg graft -r XX YY ZZ.

    where XX YY ZZ etc. are the revisions to copy to your currently checked-out branch. By default they are committed, but you can also use the --no-commit flag so that you can edit changes. Or do it one-by-one and make additions using hg commit --amend.

    Compared to exporting and importing it has the added benefit of using the configured merge programme, should a merge be required - but it will NOT be a merge, so no line of ancestors is established from the current commit to the one you copy from.