mercurialtortoisehgmercurial-commit

Mercurial undo last commit


How can I undo my last accidentally commited (not pushed) change in Mercurial?

If possible, a way to do so with TortoiseHg would be prefered.

Update

In my concrete case I commited a changeset (not pushed). Then I pulled and updated from the server. With these new updates I decided, that my last commit is obsolete and I don't want to sync it. So it seems, that hg rollback is not exactly what I'm searching for, because it would rollback the pull instead of my commit.


Solution

  • One way would be hg rollback (deprecated as of Hg2.7, August 2013)

    Please use hg commit --amend instead of rollback to correct mistakes in the last commit.

    Roll back the last transaction in a repository.

    When committing or merging, Mercurial adds the changeset entry last.
    Mercurial keeps a transaction log of the name of each file touched and its length prior to the transaction. On abort, it truncates each file to its prior length. This simplicity is one benefit of making revlogs append-only. The transaction journal also allows an undo operation.

    See TortoiseHg Recovery section:

    alt text

    This thread also details the difference between hg rollback and hg strip:
    (written by Martin Geisler who also contributes on SO)

    • 'hg rollback' will remove the last transaction. Transactions are a concept often found in databases. In Mercurial we start a transaction when certain operations are run, such as commit, push, pull...
      When the operation finishes succesfully, the transaction is marked as complete. If an error occurs, the transaction is "rolled back" and the repository is left in the same state as before.
      You can manually trigger a rollback with 'hg rollback'. This will undo the last transactional command. If a pull command brought 10 new changesets into the repository on different branches, then 'hg rollback' will remove them all. Please note: there is no backup when you rollback a transaction!

    • 'hg strip' will remove a changeset and all its descendants. The changesets are saved as a bundle, which you can apply again if you need them back.

    ForeverWintr suggests in the comments (in 2016, 5 years later)

    You can 'un-commit' files by first hg forgetting them, e.g.: hg forget filea; hg commit --amend, but that seems unintuitive.
    hg strip --keep is probably a better solution for modern hg.