Tips and Tricks

(see also FAQ, HOWTOs, CategoryTipsAndTricks)

1. Undo an "hg add"

hg revert # take out of source control
hg rm -f # remove it

On Unix, to revert just the pending adds, you can use

hg status -an0 | xargs -r0 hg revert

2. Save a push URL so that you don't need to enter it each time

It is possible to store a default push URL that will be used when you type just "hg push". Edit hgrc and add something like:

[paths]
default-push = ssh://hg@example.com/path

3. Track changes to a repository with RSS

You can track changes to projects and individual files with RSS feeds from hgweb. Here are some examples:

If you want to create web links to tagged or tip versions of a repository or a file, you can do so like this:

5. Configuring Mercurial

See in .hgrc.

6. Abbreviate command options

It is possible to abbreviate command options:

hg revert --no-b
hg revert --no-backup

7. Ignore files from Emacs/XEmacs

Add the following to .hgignore:

syntax: glob
*~

syntax: regexp
(.*/)?\#[^/]*\#$

8. Ignore files in local working copy only

Add the following to the repo's .hg/hgrc:

[ui]
ignore = /path/to/repo/.hg/hgignore

and create a new file .hg/hgignore beside it. This new file will be untracked, but work the same as the versioned .hgignore file for this specific working copy. (The /path/to/repo bit is unfortunate but necessary to make it work when invoking hg from within a subdir of the repo.)

9. Make a clean copy of a source tree, like CVS export

hg clone source export
rm -rf export/.hg

or using the archive command

cd source
hg archive ../export

The same thing, but for a tagged release:

hg clone --noupdate source export-tagged
cd export-tagged
hg update mytag
rm -rf .hg

or using the archive command

cd source
hg archive -r mytag ../export-tagged

10. One liner to remove unknown files with a pattern

To make these work, replace the ls -l with the command you wish to execute (ie. rm). You can also tweak the parameters passed to hg status to filter by something other than unknown files (see hg help status).

hg status -nu0 | grep -z pattern | xargs -0r ls -l

The above command requires a current version of GNU grep. If you don't have one, you can use the following:

hg status -nu | grep pattern | tr '\n' '\0' | xargs -0r ls -l

11. Generating color diff output with extdiff and colordiff

Note as of Mercurial 1.1, you can just enable the ColorExtension instead of using ExtdiffExtension.

You can use the extdiff extension to get colorized diff output. If you've enabled the extension and have colordiff installed, the following hgrc snippet will create a new cdiff command:

[defaults]
# suppress noisy extdiff header message
cdiff = -q

[extdiff]
cmd.cdiff = colordiff
opts.cdiff = -uprN

12. Using config substitution and the [DEFAULT] section of hgrc

The hgrc manpage gives a passing description of the [DEFAULT] section header but gives no notion of how one might use this (or the possible caveats). Here's an example:

Here's an example of the usage:

13. Using FileMerge.app/opendiff as the diff program (OS X)

The Developer Tools for OS X provide the excellent graphical diff program "FileMerge.app". The provided command-line wrapper "opendiff" for "FileMerge.app" will not work with ExtdiffExtension. Instead, use the script fmdiff which wraps "FileMerge.app" so that it responds like the usual diff program. Once fmdiff is in your path, just add the below to your .hgrc file

[extensions]
hgext.extdiff =

[extdiff]
cmd.opendiff =  fmdiff

and use

$ hg opendiff ...

14. Using Vim as the filemerge program

The Vim text editor provides a graphical diff feature. To resolve Mercurial merge conflicts using Vim, add the below to your .hgrc file:

[merge-patterns]
** = filemerge

[merge-tools]
filemerge.executable = gvim
filemerge.args = -d $local $other
filemerge.checkchanged = true
filemerge.gui = true

15. Using RCS merge as the filemerge program

The merge program supplied with RCS gives more complete conflict markers than the default install if you give it the -A option. For your .hgrc:

[merge-tools]
filemerge.executable = /usr/bin/merge
filemerge.args = -A $local $base $other

merge just invokes diff3 but I couldn't make diff3 work directly. How do we tell hg that diff3 writes the merge result to stdout?

16. hg diff does not support -foo option like gnu diff does

I use the following bash function to put the diff options I like most

hgdi ()
{
  for i in `hg status -marn "$@"`
  do
    diff -ubwd <(hg cat "$i") "$i"
  done
}

You can also use the extdiff extension to call GNU diff from Mercurial.

17. Handling binary files

as stated in BinaryFiles, you need to have a tool which manages binary merge. Joachim Eibl's new kdiff3 version ships a version qt4 version (on windows called "kdiff3-QT4.exe") which recognizes binary files. Pressing "cancel" and "do not save" leaves you with the version of the file you have currently in the filesystem. See also on CvsConcepts.

18. Diagnose "abort: Error" messages

I get a cryptic "abort: Error" message while pushing to my server. This is not enough info to figure out the problem. I tried hg -v --debug push but I still don't get anything more informative. What can I do?

19. Removing the working directory of a repository

If you forgot to specify -U on "hg clone", doing

hg update null

will remove everything from the working directory of the repository. See also update. (reference)

20. Setting the default context for diff to something larger

hg diff outputs 3 lines of context per default (see "hg help diff"). To change the default to for example 8 lines, add

[defaults]
diff = --unified 8

to the defaults section of your .hgrc. However, this only affects the diff command itself. (reference)

21. Find repositories with GNU find

Users with access to GNU find may find these one-liners useful for managing all their repositories at once. They can of course be added to shell scripts to do more interesting things.

Print a list of directories which have repositories (a directory called ".hg" exists):

find ~/ -name ".hg" -type d -execdir pwd \;

Print a list of tracked files too:

find ~/ -name ".hg" -type d -printf "\t" -execdir pwd \; -execdir hg status -c -m -a -d \; -printf "\n"

22. Change temporary directory used on remote when pushing

See description of a hook for changing tmp directory on remote when pushing.

23. Keep "My" or "Their" files when doing a merge

Occasionally you want to merge two heads, but you want to throw away all changes from one of the heads, a so-called dummy merge. You can override the merge by using the HGMERGE environment variable:

HGMERGE=internal:local hg merge  #keep my files
HGMERGE=internal:other hg merge  #keep their files

This will leave out updates from the other head. But note that files added in the other head wont count as a conflict, and therefore no merging will be done. To exclude them first look at hg parents and decide which parent you want to keep. Call that revision X, then do

hg revert --all --rev X

This will ensure that only changes from X are committed when you commit the merge.

Using internal:fail will fail the merge - this is useful if you want to prevent Mercurial from starting a merge tool after a merge with conflicts.

24. Split a subdirectory into a separate project

Use ConvertExtension with --filemap option.

25. Use an extension only for one call (without editing hgrc)

You can enable an extension only for this call of hg by setting --config.

This enables the mq extension and calls its strip command to remove revision 111:

hg --config extensions.hgext.mq= strip 111

26. Convert a repo with mixed line endings to LF only

Enable the Win32TextExtension with encoding only.

Snippet of hgrc:

[extensions]
hgext.win32text=

#encode only => only LF in repo
[encode]
** = cleverencode:
[decode]
#** = cleverdecode:

Update the working directory. To force the update to all files do hg update null first and then hg update [rev]. The line endings in the working directory are still the same as in the repo.

Commit the changes. All the line endings are converted to LF before committing. To see the changes in the working dir do hg update null and hg update [tip] again.

(To convert all the line endings to CRLF, enable decode only).

27. Log all csets that would be merged (emulate `hg incoming` for merges)

To see which changesets would be merged into head tgt from src by

hg update tgt
hg merge src

you can do

hg log --follow --rev src:null --prune tgt

or, shorter,

hg log -fr src:null -P tgt

To omit merge csets, add -M.

28. Import all patches in a mbox file

The hg import command only accepts a single patch, but the formail tool (comes with procmail) can be used to split them:

formail -s hg import - < yourmailbox.mbox

This imports all emails with patches, skips those that don't, and works with inline or attachment patches.

29. Avoid merging autogenerated (binary) files (PDF)

Usecase: Writing in LaTeX, but always having an up to date pdf in the working dir.

There are two main options:

1. Not merging pdfs (UNTESTED):

For this you just choose a merge tool for pdfs which simply keeps either your or the other version.

Edit your .hg/hgrc to include the following section:

[merge-patterns]
**.pdf = internal:local #keep my files
**.pdf = internal:other #keep their files

(you should only use one of the lines)

This way all PDFs will always be either at your revision or the other revision and you won't have (real) merges.

- http://mercurial.selenic.com/wiki/MergeToolConfiguration

2. Creating pdfs on the fly

This assumes that you always want to have the PDFs you can use, but that you don't need to versiontrack tham - only their contents (and those are defined in the tex files).

For this you add an update hook which crates the pdf whenever you update to a revision.

Edit your .hg/hgrc to include the hooks section with an update hook:

[hooks]
update.create_pdfs = latex your_tex_file.tex

To make this still a bit easier, you can use a versioned script which creates all pdf. that way you can just call the script and don't need to worry about editing the .hg/hgrc when you add text files or change the call.

I use a python script for platform compatability:

parse_latex.py: 

from subprocess import call
for i in ["file1.tex", "file2.tex"]: 
  call(["latex", i])

.hg/hgrc: 

[hooks]
update.create = ./parse_latex.py

- http://hgbook.red-bean.com/read/handling-repository-events-with-hooks.html

30. Specify Explicit Ssh Connection Timeouts

If in an unattended script you want to explicitly timeout connection attempts in the case of a misbehaving server or network you can do:

hg push --ssh "/path/to/ssh -o ConnectTimeout=10"

Where the value for ConnectTimeout is in seconds. ConnectionAttempts is also available to specify a number of retries (default is none).

31. Fake A Commit Message Template In VIM

Presumably this can be done with any scriptable editor. Place this in your ~/.hgrc:

editor = /usr/bin/vim -c "r ~/.hgtemplate"

Create a template in ~/.hgtemplate. Example:

Bug: XXXX
Reviewed by: XXXX

32. Prevent a push that would create multiple heads

In many Mercurial work flows, teams may have a "stable" or "master" tree that is supposed to have only one head. While a plain 'hg push' will warn you if you're going to create new heads, that is merely a warning on the client side intended to help/remind users that they may have forgotten to merge first. However, 'hg push -f' will let you do a push that does create new heads (this is also very common usage for sharing changes via "working" or "review" or ... Mercurial repos). The only way to protect a repo from multiple heads is by using a hook that runs in the repo-to-be-protected. There are several existing hooks that do that which may be useful to copy and adapt: Netbeans, Mozilla, David Herron's (bash) hook.