Mercurial: how to amend the last commit?

mstrap picture mstrap · Nov 18, 2011 · Viewed 102.5k times · Source

I'm looking for a counter-part of git commit --amend in Mercurial, i.e. a way to modify the commit which my working copy is linked to. I'm only interested in the last commit, not an arbitrary earlier commit.

The requirements for this amend-procedure are:

  • if possible, it should not require any extensions. It must not require non-default extensions, i.e. extensions which do not come with an official Mercurial installation.

  • if the commit to amend is one head of my current branch, no new head should be created. If the commit is not head, a new head may be created.

  • the procedure should be safe in a way that if for whatever reasons the amending fails, I want to have the same working copy and repository state restored as before the amending. With other words, if the amending itself can fail, there should be a fail-safe procedure to restore the working copy and repository state. I'm referring to "failures" which lie in the nature of the amend-procedure (like e.g. conflicts), not to file-system-related problems (like access restrictions, not being able to lock a file for writing, ...)

Update (1):

  • the procedure must be automatable, so it can be performed by a GUI client without any user interaction required.

Update (2):

  • files in the working directory must not be touched (there may be file system locks on certain modified files). This especially means, that a possible approach may at no point require a clean working directory.

Answer

Chris Phillips picture Chris Phillips · May 2, 2012

With the release of Mercurial 2.2, you can use the --amend option with hg commit to update the last commit with the current working directory

From the command line reference:

The --amend flag can be used to amend the parent of the working directory with a new commit that contains the changes in the parent in addition to those currently reported by hg status, if there are any. The old commit is stored in a backup bundle in .hg/strip-backup (see hg help bundle and hg help unbundle on how to restore it).

Message, user and date are taken from the amended commit unless specified. When a message isn't specified on the command line, the editor will open with the message of the amended commit.

The great thing is that this mechanism is "safe", because it relies on the relatively new "Phases" feature to prevent updates that would change history that's already been made available outside of the local repository.