Differences between revisions 69 and 200 (spanning 131 versions)
Revision 69 as of 2007-03-25 05:06:36
Size: 20233
Editor: 4
Comment: Remove spam
Revision 200 as of 2016-11-03 03:05:50
Size: 20335
Comment: update links
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
(see also ["FAQ"])

[[TableOfContents]]

= Basic =

=== Search history for keywords ===

{{{hg log}}} has a keyword search feature that scans commit filenames, users, and descriptions:

{{{
$ hg log -k bug -k manifest.py
changeset: 2857:18cf5349a361
user: Alexis S. L. Carvalho <alexis@cecm.usp.br>
date: Sat Aug 12 08:53:23 2006 -0300
summary: Fix some bugs introduced during the manifest refactoring

changeset: 1650:f2ebd5251e88
user: Peter van Dijk <peter@dataloss.nl>
date: Sun Jan 29 00:18:52 2006 +0100
summary: changed template escape filter, added urlescape filter; audited all templates for insertion bugs; added note to manifest.py about newlines in filenames

changeset: 1451:54e4b187f69c
user: Matt Mackall <mpm@selenic.com>
date: Tue Oct 25 22:15:44 2005 -0700
summary: Remove old manifest diff code, it's now buggy

}}}

Note: hgweb's search box will also scan for keywords, tags, revisions, or changeset IDs.

=== Undo an "hg add" ===

{{{

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

}}}
#pragma section-numbers 3
= Tips and Tricks =
''(see also [[FAQ]], [[HOWTOs]], CategoryTipsAndTricks)''
||<<TableOfContents>> ||<<Include(/Index)>> ||




=== Undo an '`hg add`' ===
If you have accidentally `add`ed a file, the way to undo that (changing its status from `A` back to `?`, or unknown) is '`hg revert`'. For example, if you just ran '`hg add`' and realized that you do not want files ''`foo`'' or ''`bar`'' to be tracked by Mercurial:

{{{
hg revert foo bar
}}}
If you want to revert all pendings '`add`'s, at least on Unix you can use this trick:

{{{
hg status -an0 | xargs -0 hg revert
}}}
Line 42: Line 21:

It is possible to store a default push URL that will be used when you type just "hg push". Edit .hg/hgrc and add something like :
It is possible to store a default [[Push|push]] URL that will be used when you type just '`hg push`'. Edit [[.hgrc|hgrc]] and add something like:
Line 49: Line 27:
Line 51: Line 28:
Line 54: Line 30:
http://selenic.com/hg/rss-log/
http://selenic.com/hg/rss-log/tip/mercurial/hgweb/hgweb_mod.py
 * https://www.mercurial-scm.org/repo/hg/rss-log/
 * https://www.mercurial-scm.org/repo/hg/rss-log/tip/mercurial/hgweb/hgweb_mod.py
Line 58: Line 34:

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

 * http://selenic.com/hg/archive/tip.tar.gz
 * http://selenic.com/hg/archive/0.9.3.zip
 * http://selenic.com/hg/raw-file/tip/COPYING
 * http://selenic.com/hg/raw-file/0.9.3/COPYING

=== Create a bundle of all changes ===

The best way to create a compressed version of a repository is with a '''bundle'''. It will be significantly smaller than a tarball or a zip file. To include all revisions, simply specify the '''null''' base:

{{{
$ hg bundle --base null project.hg
}}}

=== Looking inside bundle files ===

Bundle files may contain either all or some of the changesets in a repository. To view a partial bundle, you must have a repository containing
the bundle's base changesets. Then you can ''overlay'' the bundle on top of the repo like so:

{{{
$ cd repo
$ hg in bundle.hg # view the changesets added by the bundle
$ hg -R bundle.hg log # view the log of repo+bundle
$ hg -R bundle.hg diff -R tip # compare the working dir to the bundle's tip
$ hg -R bundle.hg cat -r tip foo.txt # extract a particular file
}}}
If you want to create web links to [[Tag|tagged]] or [[Tip|tip]] versions of a [[Repository|repository]] or a file, you can do so like this:

 * https://www.mercurial-scm.org/repo/hg/archive/tip.tar.gz
 * https://www.mercurial-scm.org/repo/hg/archive/4.0.zip
 * https://www.mercurial-scm.org/repo/hg/raw-file/tip/COPYING
 * https://www.mercurial-scm.org/repo/hg/raw-file/4.0/COPYING

Be aware though that tarballs require some configuration to work; add this to ''`.hg/hgrc`'' of repository (or to your '`--webdir-conf`'):

{{{
[web]
allow_archive = gz zip
}}}
=== Configuring Mercurial ===
See in [[.hgrc]].

=== Abbreviate command options ===
It is possible to abbreviate command options:

{{{
hg revert --no-b
hg revert --no-backup
}}}
Line 88: Line 58:

Add the following to .hgignore:
Add the following to [[.hgignore]]:
Line 97: Line 66:

}}}
}}}
=== 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.)
Line 101: Line 77:
{{{
cd source
hg archive ../export
}}}
or you could simply clone the repository and remove the ''`.hg`'' folder:
Line 106: Line 87:
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
To export a [[Tag|tagged]] release:
Line 125: Line 93:
Line 127: Line 94:

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
}}}

= Intermediate =

=== using rsync to 'push' and 'pull' ===

This script will perform a pull from an rsync path:

{{{
#!/bin/sh
cd `hg root`
rm -rf .hg/rsync
hg clone -U . .hg/rsync # make an approximate copy to rsync over
rsync -ae ssh $1/.hg .hg/rsync # rsync over our copy
hg pull .hg/rsync # pull from our copy
rm -rf .hg/rsync
}}}

Use like this:

{{{
$ rsyncpull user@server:repo/foo
pulling from .hg/rsync
searching for changes
adding changesets
adding manifests
adding file changes
added 57 changesets with 153 changes to 65 files
(run 'hg update' to get a working copy)
}}}

Similarly, we can push with a script like this:

{{{
#!/bin/sh
cd `hg root`
rm -rf .hg/rsync
hg clone -U . .hg/rsync
rsync -ae ssh $1/.hg .hg/rsync
hg push .hg/rsync
rsync -ae ssh .hg/rsync $1/.hg
rm -rf .hg/rsync
}}}

<!> This push script ignores locking issues - don't use it for pushing to a repository with multiple writers!

=== pruning dead branches ===

If you've got a dead branch you'd like to eliminate from the list of heads, you can do a 'no-op merge' to remove it:

{{{
$ hg update -C tip # jump to one head
$ hg merge otherhead # merge in the other head
$ hg revert -a -r tip # undo all the changes from the merge
$ hg commit -m "eliminate other head" # create new tip identical to the old
}}}

=== generate a diff between two repositories ===

Usually, you can use the {{{-p}}} option to either {{{incoming}}} or {{{outgoing}}}. Example:

{{{
cd /path/to/repo1
hg incoming -p /path/to/repo2
}}}

Sometimes you may want a single diff. There are a number of ways to do this. We'll describe two:

a) The clone method

The basic idea is to use a cheap temporary clone to do the work. If the diff is agreeable, you can then pull from your temporary clone.

{{{
MYTIP=`hg tip --template "rev"`
hg clone -U . tmp # make a temporary clone with no working directory
hg -R tmp pull http://remoterepo # pull the remote changes into the temporary repo
hg -R tmp diff -r $MYTIP -r tip #
rm -rf tmp
}}}

b) The bundle method

{{{
MYTIP=`hg tip --template "{rev}"`
hg in -q --bundle tmp.hg http://remoterepo && hg -R tmp.hg diff -r $MYTIP -r tip
}}}

This grabs a bundle of incoming changes then overlays the bundle on your current repo to generate the diff.
If the diff is agreeable, you can unbundle the repo to make the changes permanent.

=== Adding a commit message template ===

Mercurial calls a user-defined program to edit commit messages. If
that program returns false, the commit is aborted.

Here's an example patch for hgeditor that adds a user-defined template to the commit message:

{{{
diff -r 33988aaa1652 hgeditor
--- a/hgeditor Sun Dec 17 22:16:57 2006 -0600
+++ b/hgeditor Tue Dec 19 08:08:57 2006 -0600
@@ -39,6 +39,7 @@ HGTMP="${TMPDIR-/tmp}/hgeditor.$RANDOM.$
     done
 )

-cat "$1" > "$HGTMP/msg"
+cat `hg root`/.commit-template > "$HGTMP/msg"
+cat "$1" >> "$HGTMP/msg"

 MD5=$(which md5sum 2>/dev/null) || \
}}}

Validating that the commit message is correct can either be done by hgeditor or enforced by a precommit hook.
Mercurial ships with the PurgeExtension for that purpose:

{{{
hg purge -p pattern
}}}
lists the files that will be removed. Remove the '`-p`' option to really removed the matched files.

If you need finer control, you can pipe the output of '`hg st -un`' through your favorite commands.

=== Customize diff behavior ===
==== Generating color diff output ====
You can just enable the ColorExtension to colorize command outputs. It has been bundled with Mercurial since 1.1

==== Use a custom diff program ====
To get colors for pre-1.1 Mercurial, you can use the [[ExtdiffExtension|extdiff extension]] with the '`colordiff`' tool to get colorized diff output. If you've enabled the extension and have '`colordiff`' installed, the following [[.hgrc|hgrc]] snippet will create a new '`hg cdiff`' command:

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

[extdiff]
cmd.cdiff = colordiff
opts.cdiff = -uprN
}}}
Similarly, on OSX if you want to use '`FileMerge.app`' for your diffs, you can use the ExtdiffExtension. The provided command-line wrapper '`opendiff`' for '`FileMerge.app`' will not work directly with the extension, but you can instead use the script [[http://ssel.vub.ac.be/ssel/internal:fmdiff|fmdiff]] which wraps '`FileMerge.app`' so that it responds like the usual diff program. Once '`fmdiff`' is in your path, just add the following to your ''`.hgrc`'' file

{{{
[extensions]
hgext.extdiff =

[extdiff]
cmd.opendiff = fmdiff
}}}
and use

{{{
$ hg opendiff ...
}}}
=== Using environment variables in hgrc files ===
You can use environment variables in filenames read from hgrc files with Mercurial 1.4. This applies to paths used to enable extensions and the paths used to load ignore files:

{{{
[extensions]
foo = $MYEXTENSIONS/foo.py

[ui]
ignore = $MYIGNORE
}}}
=== Using Vim as the filemerge program ===
The Vim text editor provides a [[http://vimdoc.sourceforge.net/htmldoc/diff.html|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
}}}
=== 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
}}}
See also MergingManuallyInEditor.
Line 252: Line 167:
Line 264: Line 178:

=== See diffs when editing commit message with VIM ===

Make a private copy of the 'hgeditor' script provided with mercurial and replace the call to the editor with following command:

{{{
vim "+e $HGTMP/diff" '+set buftype=help filetype=diff' "+vsplit $HGTMP/msg" || exit $?
}}}

This will start up VIM in vertical split mode with commit message in the left pane and diff in the right pane. The {{{buftype=help}}} setting for diff window tells vim to exit when all other windows are closed, so when you write and quit the log with {{{:x}}} ({{{:wq}}} - they are equivalent), vim exits. If you have syntax highlight set up, the diff will be properly highlighted.

This setting is suitable for wide terminals. If you have a narrow terminal, you may want to replace the {{{+vsplit}}} above with {{{+split}}} or add {{{nowrap}}} to the {{{+set}}}.

=== See diffstat of pulled changes ===

Place the following script (named "pull-diffstat" here) somewhere in your $PATH:

{{{
#!/bin/sh
test -n "$HG_NODE" || exit 0
TIP=`hg tip --template '{node|short}'`
REV=`hg log -r $HG_NODE --template '{rev}'`
test -n "$REV" -a $REV -ne 0 || exit 0
PREV=`expr $REV - 1`
PARENT=`hg log -r $PREV --template '{node|short}'`
echo "diffstat for $PARENT to $TIP"
hg diff -r $PARENT -r tip | diffstat
}}}

Add a changegroup entry to the [hooks] section of hgrc:
You can also use the ExtdiffExtension to call GNU '`diff`' from Mercurial.

=== Handling binary files ===
As stated in BinaryFiles, you need to have a tool which manages binary merge. Newer versions of Joachim Eibl's [[http://kdiff3.sourceforge.net/|KDiff3]] program (using Qt 4, known on Windows as '`kdiff3-QT4.exe`') recognize 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.

=== 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?

 * disable cgitb in hgweb on the server
 * run with '`--debug --traceback`' on the client
 * check the error logs on the server

=== 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 [[WorkingDirectory|working directory]] of the [[Repository|repository]]. See also [[Update|update]]. ~-([[https://www.mercurial-scm.org/pipermail/mercurial/2008-March/018332.html|reference]])-~

=== 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. ~-(Issue:1076)-~

=== 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"
}}}
=== Change temporary directory used on remote when pushing ===
See description of a [[Hook#tmpdirhook|hook for changing tmp directory]] on remote when pushing.

<<Anchor(mergemineortheir)>>

=== 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. The {{{internal:local}}} and {{{internal:other}}} merge tools look like they do that, but only work if both branches have changed the content of the file. If the '`other`' branch changes the file and '`local`' does not, a merge using the {{{internal:local}}} tool will include that change, and vice versa. File renames, attribute changes and files added also suffer from this problem.

So to safely merge `X` into the current revision without letting ''any'' of the changes from `X` come through, do:

{{{
hg -y merge --tool=internal:fail X
hg revert --all --rev .
hg resolve -a -m
}}}
This will ensure that only changes from the current working copy parent revision 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. The `-y` option causes any questions that may come up to be answered in the affirmative, which is harmless since any changes will be reverted in the next step.

=== Split a subdirectory into a separate project ===
Use ConvertExtension with --filemap option.

=== Use an extension only for one call (without editing hgrc) ===
You can enable an [[UsingExtensions|extension]] only for this call of '`hg`' by setting '`--config`'.

This enables the [[MqExtension|mq extension]] and calls its strip command to remove revision 111:

{{{
hg --config extensions.hgext.mq= strip 111
}}}
=== 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).

=== Log all csets that would be merged (emulate '`hg incoming`' for merges) ===
Say you are considering merging from `source` to `dest` and you want to know which changesets will be involved, i.e. what's in `source` that's not in `dest`. In graph terms, you want to see all the ancestors of `source` (including `source` itself) that are not also ancestors of `dest`. (If `source` is already an ancestor of `dest`, then there is nothing to merge.)

This command will work on all versions of Mercurial, although it's slow with large repositories:

{{{
hg log -r 0::source --prune dest
}}}
(To omit merge csets, add `-M`.)

A faster way, using a command alias, assuming the source and dest are named branches:

{{{
[alias]
mlog = log -r "children(ancestor($1,$2)):: and branch($1)"
}}}

and then

{{{
hg mlog source dest
}}}

In Mercurial 1.4, '`merge`' grew a '`--preview`' option that was intended to do the same thing more conveniently. The 1.4 version of '`merge --preview`' doesn't actually show all the changesets that will be merged, but that bug was fixed in 1.5. So if you are using Mercurial 1.5 or later, you can get the same answer faster with

{{{
hg update dest
hg merge --preview source
}}}
(There is no way to omit merges with '`merge --preview`'.)

=== 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.

=== 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.

- 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 track them - 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:
Line 297: Line 342:
changegroup = pull-diffstat
}}}

Now you will see a diffstat of the new changes to your repo every time you do "hg pull".

=== Accessing ssh controlled repositories from a Windows Client ===

NOTE: The following works for cases when the private keys are not Password phrase encrypted.

 1. Grab {{{putty.exe}}} and {{{plink.exe}}} from [http://www.chiark.greenend.org.uk/~sgtatham/putty/ PuTTY] website.
 2. Connect to remote ssh host over ssh using PuTTY once and have PuTTY save it's key as a known host.
 3. Add the following to the {{{[ui]}}} section of your {{{~/Mercurial.ini}}} file {{{
ssh=/path/to/plink.exe -ssh -i "/path/to/your/private/key"
}}}
 4. Profit!!!

''This didn't work for me with the latest windows version, maybe because I'm using key authentication with a passphrase. I got cygwin ssh to work though. Follow the instructions for this on [wiki:Self:WindowsInstall#head-f68270c2de0d123382f73ef2fa702084831bffb6 WindowsInstall ssh help].'' -- krupan [[DateTime(2006-12-15T22:13:42Z)]]

''I got this to work with my passphrase-locked ssh keys by following the directions below, but the Mercurial.ini syntax above seemed to be very sensitive. It didn't work when I put quotes around /path/to/plink. That took a while to figure out :-('' -- krupan

''Also observed the effect above: no attempts to quote plink path worked - very ugly errors, like {{{remote: Incorrect file name, directory name, or volume label. abort: no suitable response from remote hg!}}} and unquoted path like {{{C:\Program Files\Putty\plink.exe}}} resulted in attempts to run {{{C:\Program}}}. I ended up creating {{{C:\Bin}}} and copying plink.exe there. Interesting that path to key could be quoted.'' -- Marcin.Kasperski

To get your passphrase-locked SSH keys to work properly under PuTTY, you'll need to go through the following steps.

 1. Download {{{putty.exe}}}, {{{puttygen.exe}}}, {{{pageant.exe}}}, and {{{plink.exe}}} from the [http://www.chiark.greenend.org.uk/~sgtatham/putty/ PuTTY website]. You may want {{{pscp.exe}}} as well if you plan to do SCP, but it's not necessary for running Mercurial.
 2. Copy your SSH private key onto your Windows machine.
 3. PuTTY uses its own private format for SSH private keys, so you'll need to convert your private key. Run {{{puttygen.exe}}} and choose {{{Import key}}} from the {{{Conversions}}} menu.
 4. Import your private key; enter its passphrase when prompted.
 5. Change the key comment to something meaningful.
 6. Click the {{{Save private key}}} button and save the .PPK file somewhere.
 7. Run {{{pageant.exe}}}. The pageant icon (a computer wearing a hat) will show up in the status tray.
 8. Right-click the pageant icon and choose {{{Add Key}}}.
 9. Choose the .PPK file you saved earlier and type in its passphrase.
 10. Follow steps 2 & 3 above: connect to the remote host, save its key, and edit your {{{Mercurial.ini}}} file.
 11. Enjoy your newly-secure SSH authentication on Windows!

  -- RobinMunn

Note that {{{pageant.exe}}} caches your unlocked key in memory, which could conceivably make its way into your swap file. Be aware of the security implications of that fact. (For example, if your computer is ever stolen, it would be wise to consider that SSH key compromised and change it as soon as possible).

= Advanced =

=== Keyword expansion according to file revision ===

(also see KeywordPlan and KeywordExpansionExtension)

This is an example on how you can achieve filewise keyword expansion (similar
to CVS) with an [encode] filter and the pretxncommit-hook. Comes in handy
when you want to keep track of different file revisions in the same
repository.

For demonstration we use just one keyword: "Hg".

 * {{{$Hg$}}}

It will be expanded by the script "hgpretxncommit.sh" (see below) to:

 * {{{$Hg: <basename of file>,v <short hash> <date> $}}}

You need an [encode] filter that "reverts" the expansion in your hgrc.

Simple example hgrc for a repository containing python files:

{{{
[encode]
*.py = sed 's/[$]Hg[^$]*[$]/\$Hg\$/'
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 compatibility:

''`parse_latex.py`'':

{{{#!python
#!/usr/bin/env python
from subprocess import call
for i in ("file1.tex", "file2.tex"):
  call(["latex", i])
}}}
''`.hg/hgrc`'':

{{{
Line 364: Line 360:
pretxncommit = hgpretxncommit.sh
}}}

In "hgpretxncommit.sh" you have to tweak the $excl variable according
to your needs. The script doesn't look at files matching $excl.

{{{
#!/bin/sh
set -e
test $? -eq 0 -a -n "$HG_NODE" || exit 1
excl='^\.hg\|\.\(p\(df\|ng\)\|jpg\)$'
cset="${HG_NODE:0:12}"
isodate=`hg tip --template='{date|isodate}'`
for f in `hg status --modified --added --no-status \
    | grep --invert-match "$excl" 2>/dev/null`; do
    bn="${f##*/}"
    sed -i~ -e "s!\([$]Hg\)[^$]*[$]!\1: $bn,v $cset $isodate \$!" "$f"
done
exit $?
}}}

=== upgrading a repository to revlogng in place ===

Here's a quick and dirty script to upgrade a mercurial repository in place.
Note: the current undo information will be lost.

{{{
function upgradehg () (
  if test -n "$1"
  then
    local repo="$1"
    local tmprepo="$1".tmp
update.create = ./parse_latex.py
}}}
- http://hgbook.red-bean.com/read/handling-repository-events-with-hooks.html

=== 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).

=== 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
}}}
=== 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: [[http://hg.netbeans.org/nb-hooks/file/tip/forbid_2head.py|Netbeans]], [[http://hg.mozilla.org/users/bsmedberg_mozilla.com/hghooks/file/tip/mozhghooks/single_head_per_branch.py|Mozilla]], [[http://davidherron.com/blog/topics/961-forbidding-multiple-heads-shared-mercurial-repository|David Herron's (bash) hook]], [[https://bitbucket.org/dgc/headcount/|the Headcount hook]], [[https://bitbucket.org/haard/autohook|autohook]].

=== Check If One revision Is A Descendant Of Another ===
{{{
function isKid() {
  if [ $(hg debugancestor $1 $2 | cut -d : -f 1) == "$1" ] ; then
    echo $2 is a decendent of $1;
Line 397: Line 393:
    local repo="."
    local tmprepo="../hgupgrade.tmp"
   echo $2 is NOT a descendent of $1;
Line 400: Line 395:

  set -e
  hg clone --pull -U "$repo" "$tmprepo"
  cp "$repo"/.hg/{hgrc,dirstate} "$tmprepo"/.hg
  mv "$repo"/.hg "$repo"/.hg.orig
  mv "$tmprepo"/.hg "$repo"/.hg
  rmdir "$tmprepo"
  echo "Upgrade complete. A backup of your original repository is now in $repo/\.hg.orig"
)
}}}

=== Concatenating multiple changeset into one changeset. ===

Suppose you have a repository with a number of changesets which you
want to combine into a single changeset.

This can be done as follows using only the basic operations of
mercurial, namely clone, push, pull.

For simplicity, let us assume that the repository in question has a
single head, and you want to combine the last k revisions into a
single revision.

For concreteness, let us call the base revision R, and the ending
revision R+k.

Let us furthermore assume the repository has no local changes.

The strategy is to take advantage of mercurial's support for
repositories with more than one head. What we do is create a branch
whose root revision is R and which consists of just one changeset
(actually it can be multiple changesets, the principle is the same,
but for simplicity let us assume one).

Diagramatically, this looks like:

{{{#!dot
digraph {
  rankdir = BT;
  node [shape=box];
  "working directory" -> R [label="1. update"];
  R -> "R+1" -> "R+2";
  "R+2" -> "R+k" [style=dashed];
  "working directory" -> "R+k" [color=red label="2. revert"];
  "working directory" [shape=ellipse];
}}}

{{{#!dot
digraph {
  rankdir = BT;
  node [shape=box];
  "working directory" -> "R+k (concatenated)" [color=red label="3. commit"];
  "working directory" -> R [style=invis];
  R -> "R+k (concatenated)";
  R -> "R+1" -> "R+2";
  "R+2" -> "R+k" [style=dashed];
  "working directory" [shape=ellipse];
}}}

{{{#!dot
digraph {
  rankdir = BT;
  node [shape=box];
  "working directory" -> R [style=invis];
  "working directory" -> "R+k (concatenated)" [color=red label="4. clone -r tip"]
  R -> "R+k (concatenated)"
  "working directory" [shape=ellipse label="cloned working directory"]
}}}


The procedure is as follows.

 1. hg update R
    This updates the working directory to revision R. Specifically, this
    means that the contents of the working directory are changed to that
    of revision R, and that R becomes the parent of the working directory.

 2. hg revert -r tip
    This reverts the working directory revert to its contents at tip.
    Since the parent of the working directory is still R, this means that
    the combined contents of all changesets between R and R+k show up as
    the modifications in the working directory.

 3. hg ci -m "Combined changesets between R and R+k"
    At this point, committing these modifications will create a changeset
    containing all combined changesets between revisions R and R+k.

 4. hg clone -r tip oldrepo newrepo
    This assumes you want to get rid of your individual changesets
    (which are a dangling branch in oldrepo) and just keep the combined
    changeset. newrepo will now just have the combined changeset.

=== Recreate hardlinks between two mercurial repositories ===

When repositories are cloned locally, their data files will be hardlinked so that they only use the space of a single repository. Unfortunately, subsequent pulls into either repository will break hardlinks for any files touched by the new changesets, even if both repositories end up pulling the same changes. Here's a quick and dirty way to recreate those hardlinks and reclaim that wasted space:

{{{
#!/usr/bin/env python

import os, sys

class ConfigError(Exception): pass

def usage():
    print """relink <source> <destination>
    Hard-link files from source to destination"""

class Config:
    def __init__(self, args):
        if len(args) != 3:
            raise ConfigError("wrong number of arguments")
        self.src = os.path.abspath(args[1])
        self.dst = os.path.abspath(args[2])
        for d in (self.src, self.dst):
            if not os.path.exists(os.path.join(d, '.hg')):
                raise ConfigError("%s: not a mercurial repository" % d)

try:
    cfg = Config(sys.argv)
except ConfigError, inst:
    print str(inst)
    usage()
    sys.exit(1)

relinked = 0
savedbytes = 0
CHUNKLEN = 4096

def collect(src):
    seplen = len(os.path.sep)
    candidates = []
    for dirpath, dirnames, filenames in os.walk(src):
        relpath = dirpath[len(src) + seplen:]
        for filename in filenames:
            if not (filename.endswith('.i') or filename.endswith('.d')):
                continue
            st = os.stat(os.path.join(dirpath, filename))
            candidates.append((os.path.join(relpath, filename), st))

    return candidates

def prune(candidates, dst):
    targets = []
    for fn, st in candidates:
        tgt = os.path.join(dst, fn)
        try:
            ts = os.stat(tgt)
        except OSError:
            # Destination doesn't have this file?
            continue
        if st.st_ino == ts.st_ino:
            continue
        if st.st_dev != ts.st_dev:
            raise Exception('Source and destination are on different devices')
        if st.st_size != ts.st_size:
            continue
        targets.append((fn, ts.st_size))

    return targets

def relink(src, dst, files):
    CHUNKLEN = 65536
    relinked = 0
    savedbytes = 0

    for f, sz in files:
        source = os.path.join(src, f)
        tgt = os.path.join(dst, f)
        sfp = file(source)
        dfp = file(tgt)
        sin = sfp.read(CHUNKLEN)
        while sin:
            din = dfp.read(CHUNKLEN)
            if sin != din:
                break
            sin = sfp.read(CHUNKLEN)
        if sin:
            continue
        try:
            os.rename(tgt, tgt + '.bak')
            try:
                os.link(source, tgt)
            except OSError:
                os.rename(tgt + '.bak', tgt)
                raise
            print 'Relinked %s' % f
            relinked += 1
            savedbytes += sz
            os.remove(tgt + '.bak')
        except OSError, inst:
            print '%s: %s' % (tgt, str(inst))

    print 'Relinked %d files (%d bytes reclaimed)' % (relinked, savedbytes)

src = os.path.join(cfg.src, '.hg')
dst = os.path.join(cfg.dst, '.hg')
candidates = collect(src)
targets = prune(candidates, dst)
relink(src, dst, targets)
}}}
}
}}}
Example:

{{{
$ isKid 70 72
72 is a decendent of 70

$ isKid 72 70
70 is NOT a descendent of 72
}}}
=== Merge or rebase with uncommitted changes ===
It is not possible to merge or rebase when there are uncommited local changes in the working copy. Some recommend using the shelve extension or mq to handle that, but there is an even easier way. First put your local changes in a patch file, then revert the changes in the working copy.

{{{
hg diff > somefile # save local changes

hg revert -a # nuke 'em
}}}
Now you can do your merge or rebase in your clean working copy.

When you're done you reapply the changes again:

{{{
hg import --no-commit somefile
}}}
Originally described by [[http://thread.gmane.org/gmane.comp.version-control.mercurial.general/19704/focus=19725|Matt on the users list]].

=== Remove files that are matched by .hgignore but were added in error ===
If there are only a few files they can easily `hg remove`ed manually. If many files were already added to the repository before e.g. ''`.hgignore`'' is changed then the following trick might help.

The files matched in ''`.hgignore`'' already added to the repository will not show in a '`hg status -i`' since only files not already in the repository are ignored. Solution is to have a temporary pristine repository to find all ignored files:

{{{
hg clone source temp
cd temp
rm -rf .hg
hg init
}}}
In ''`temp/`'' we have now a tree of all files in the ''`source/`'' repository but not being added to the newly created empty repository.

{{{
hg status -i
}}}
will show now all files ignored by ''`.hgignore`'' but in the original repository. This list can be massaged in a editor to create a bunch of '`hg remove`' lines. This can be further automated by using

{{{
cd temp
hg status -in0 | xargs -0 hg --cwd ../source remove
}}}
Explanation: '`hg status -in0` 'produces a zero delimited list of all ignored files without the `I` prefix. This list is consumed by '`xargs -0`' calling '`hg remove`' in the original repository ('`--cwd ../source`').

The directory ''`temp`'' can then be discarded.

This trick was the idea of MartinGeisler on #mercurial

=== Check for tabs or trailing whitespace before commit ===
Check out the [[https://bitbucket.org/marcusl/ml-hgext/src/tip/checkfiles.py|checkfiles extension]] which installs a hook to do just that.

Given --verbose, it also points out where on each line tabs or trailing whitespace is.

The file extensions to check is configurable in your hgrc, as well as a list specific files to exclude from the check.

=== Restore file history after file move without rename ===

Steps:
 1. Update your working directory to before you did the rename
 2. Do an actual "hg rename" which will create a new head
 3. Merge that new head into the revision where you did the "manual" rename (not the head revision!)
 4. Then finally merge the head revision into this merge result.

Advice:
 1. Make a clone first and work on that, just in case!
 2. After finishing the steps, use a file compare tool to check that the original and the clone are identical
 3. Check the file history of any moved file to make sure it is now restored


=== View differences between a feature branch and latest ancestor of default ===
 1. hg update feature_branch
 2. hg diff -r 'ancestor(default,.)'

=== list files which might be affected by a merge ===

{{{
hg diff -r "ancestor(.,other) -r . --stat | cut -d "|" -f 1 | sed "s/ *$//" > /tmp/1
hg diff -r "ancestor(.,other) -r other --stat | cut -d "|" -f 1 | sed "s/ *$//" > /tmp/2
comm -12 <(sort /tmp/1) <(sort /tmp/2)
}}}

=== Beware of plain copying a Repo from Windows to Linux ===
In some cases, when no hg upstream server is present, one may copy e.g. an existing repository from Windows to Linux. However, Mercurial is sensitive to permissions. Any file that has been copied over from e.g. an NTFS drive gets its Executable attrribute set. Mercurial then treats such files as completely "new" in TortoiseHg (file view window, but 'M'-tagged) or via hg stat (however, a hg diff sees no difference between files in repo without 'x'-attribute and with 'x'-attribute in the workspace.
A workaround is to update to tip (without backing up). This yields the desired state of all files.

Tips and Tricks

(see also FAQ, HOWTOs, CategoryTipsAndTricks)

Contents

  1. Undo an '`hg add`'
  2. Save a push URL so that you don't need to enter it each time
  3. Track changes to a repository with RSS
  4. Create links to snapshots of files and tarballs
  5. Configuring Mercurial
  6. Abbreviate command options
  7. Ignore files from Emacs/XEmacs
  8. Ignore files in local working copy only
  9. Make a clean copy of a source tree, like CVS export
  10. One liner to remove unknown files with a pattern
  11. Customize diff behavior
    1. Generating color diff output
    2. Use a custom diff program
  12. Using environment variables in hgrc files
  13. Using Vim as the filemerge program
  14. Using RCS merge as the filemerge program
  15. hg diff does not support -foo option like gnu diff does
  16. Handling binary files
  17. Diagnose "abort: Error" messages
  18. Removing the working directory of a repository
  19. Setting the default context for diff to something larger
  20. Find repositories with GNU find
  21. Change temporary directory used on remote when pushing
  22. Keep "My" or "Their" files when doing a merge
  23. Split a subdirectory into a separate project
  24. Use an extension only for one call (without editing hgrc)
  25. Convert a repo with mixed line endings to LF only
  26. Log all csets that would be merged (emulate '`hg incoming`' for merges)
  27. Import all patches in a mbox file
  28. Avoid merging autogenerated (binary) files (PDF)
  29. Specify Explicit Ssh Connection Timeouts
  30. Fake A Commit Message Template In VIM
  31. Prevent a push that would create multiple heads
  32. Check If One revision Is A Descendant Of Another
  33. Merge or rebase with uncommitted changes
  34. Remove files that are matched by .hgignore but were added in error
  35. Check for tabs or trailing whitespace before commit
  36. Restore file history after file move without rename
  37. View differences between a feature branch and latest ancestor of default
  38. list files which might be affected by a merge
  39. Beware of plain copying a Repo from Windows to Linux

1. Undo an '`hg add`'

If you have accidentally added a file, the way to undo that (changing its status from A back to ?, or unknown) is 'hg revert'. For example, if you just ran 'hg add' and realized that you do not want files foo or bar to be tracked by Mercurial:

hg revert foo bar

If you want to revert all pendings 'add's, at least on Unix you can use this trick:

hg status -an0 | xargs -0 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:

Be aware though that tarballs require some configuration to work; add this to .hg/hgrc of repository (or to your '--webdir-conf'):

[web]
allow_archive = gz zip

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

cd source
hg archive ../export

or you could simply clone the repository and remove the .hg folder:

hg clone source export
rm -rf export/.hg

To export a tagged release:

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

10. One liner to remove unknown files with a pattern

Mercurial ships with the PurgeExtension for that purpose:

hg purge -p pattern

lists the files that will be removed. Remove the '-p' option to really removed the matched files.

If you need finer control, you can pipe the output of 'hg st -un' through your favorite commands.

11. Customize diff behavior

11.1. Generating color diff output

You can just enable the ColorExtension to colorize command outputs. It has been bundled with Mercurial since 1.1

11.2. Use a custom diff program

To get colors for pre-1.1 Mercurial, you can use the extdiff extension with the 'colordiff' tool to get colorized diff output. If you've enabled the extension and have 'colordiff' installed, the following hgrc snippet will create a new 'hg cdiff' command:

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

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

Similarly, on OSX if you want to use 'FileMerge.app' for your diffs, you can use the ExtdiffExtension. The provided command-line wrapper 'opendiff' for 'FileMerge.app' will not work directly with the extension, but you can 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 following to your .hgrc file

[extensions]
hgext.extdiff =

[extdiff]
cmd.opendiff = fmdiff

and use

$ hg opendiff ...

12. Using environment variables in hgrc files

You can use environment variables in filenames read from hgrc files with Mercurial 1.4. This applies to paths used to enable extensions and the paths used to load ignore files:

[extensions]
foo = $MYEXTENSIONS/foo.py

[ui]
ignore = $MYIGNORE

13. 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

14. 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

See also MergingManuallyInEditor.

15. 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 ExtdiffExtension to call GNU 'diff' from Mercurial.

16. Handling binary files

As stated in BinaryFiles, you need to have a tool which manages binary merge. Newer versions of Joachim Eibl's KDiff3 program (using Qt 4, known on Windows as 'kdiff3-QT4.exe') recognize 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.

17. 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?

  • disable cgitb in hgweb on the server
  • run with '--debug --traceback' on the client

  • check the error logs on the server

18. 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)

19. 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. (1076)

20. 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"

21. Change temporary directory used on remote when pushing

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

22. 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. The internal:local and internal:other merge tools look like they do that, but only work if both branches have changed the content of the file. If the 'other' branch changes the file and 'local' does not, a merge using the internal:local tool will include that change, and vice versa. File renames, attribute changes and files added also suffer from this problem.

So to safely merge X into the current revision without letting any of the changes from X come through, do:

hg -y merge --tool=internal:fail X
hg revert --all --rev .
hg resolve -a -m

This will ensure that only changes from the current working copy parent revision 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. The -y option causes any questions that may come up to be answered in the affirmative, which is harmless since any changes will be reverted in the next step.

23. Split a subdirectory into a separate project

Use ConvertExtension with --filemap option.

24. 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

25. 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).

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

Say you are considering merging from source to dest and you want to know which changesets will be involved, i.e. what's in source that's not in dest. In graph terms, you want to see all the ancestors of source (including source itself) that are not also ancestors of dest. (If source is already an ancestor of dest, then there is nothing to merge.)

This command will work on all versions of Mercurial, although it's slow with large repositories:

hg log -r 0::source --prune dest

(To omit merge csets, add -M.)

A faster way, using a command alias, assuming the source and dest are named branches:

[alias]
mlog = log -r "children(ancestor($1,$2)):: and branch($1)"

and then

hg mlog source dest

In Mercurial 1.4, 'merge' grew a '--preview' option that was intended to do the same thing more conveniently. The 1.4 version of 'merge --preview' doesn't actually show all the changesets that will be merged, but that bug was fixed in 1.5. So if you are using Mercurial 1.5 or later, you can get the same answer faster with

hg update dest
hg merge --preview source

(There is no way to omit merges with 'merge --preview'.)

27. 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.

28. 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.

- 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 track them - 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 compatibility:

parse_latex.py:

   1 #!/usr/bin/env python
   2 from subprocess import call
   3 for i in ("file1.tex", "file2.tex"):
   4   call(["latex", i])

.hg/hgrc:

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

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

29. 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).

30. 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

31. 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, the Headcount hook, autohook.

32. Check If One revision Is A Descendant Of Another

function isKid() {
  if [ $(hg debugancestor $1 $2 | cut -d : -f 1) == "$1" ] ; then
    echo $2 is a decendent of $1;
  else
   echo $2 is NOT a descendent of $1;
  fi
}

Example:

$ isKid 70 72
72 is a decendent of 70

$ isKid 72 70
70 is NOT a descendent of 72

33. Merge or rebase with uncommitted changes

It is not possible to merge or rebase when there are uncommited local changes in the working copy. Some recommend using the shelve extension or mq to handle that, but there is an even easier way. First put your local changes in a patch file, then revert the changes in the working copy.

hg diff > somefile # save local changes

hg revert -a       # nuke 'em

Now you can do your merge or rebase in your clean working copy.

When you're done you reapply the changes again:

hg import --no-commit somefile

Originally described by Matt on the users list.

34. Remove files that are matched by .hgignore but were added in error

If there are only a few files they can easily hg removeed manually. If many files were already added to the repository before e.g. .hgignore is changed then the following trick might help.

The files matched in .hgignore already added to the repository will not show in a 'hg status -i' since only files not already in the repository are ignored. Solution is to have a temporary pristine repository to find all ignored files:

hg clone source temp
cd temp
rm -rf .hg
hg init

In temp/ we have now a tree of all files in the source/ repository but not being added to the newly created empty repository.

hg status -i

will show now all files ignored by .hgignore but in the original repository. This list can be massaged in a editor to create a bunch of 'hg remove' lines. This can be further automated by using

cd temp
hg status -in0 | xargs -0 hg --cwd ../source remove

Explanation: 'hg status -in0 'produces a zero delimited list of all ignored files without the I prefix. This list is consumed by 'xargs -0' calling 'hg remove' in the original repository ('--cwd ../source').

The directory temp can then be discarded.

This trick was the idea of MartinGeisler on #mercurial

35. Check for tabs or trailing whitespace before commit

Check out the checkfiles extension which installs a hook to do just that.

Given --verbose, it also points out where on each line tabs or trailing whitespace is.

The file extensions to check is configurable in your hgrc, as well as a list specific files to exclude from the check.

36. Restore file history after file move without rename

Steps:

  1. Update your working directory to before you did the rename
  2. Do an actual "hg rename" which will create a new head
  3. Merge that new head into the revision where you did the "manual" rename (not the head revision!)
  4. Then finally merge the head revision into this merge result.

Advice:

  1. Make a clone first and work on that, just in case!
  2. After finishing the steps, use a file compare tool to check that the original and the clone are identical
  3. Check the file history of any moved file to make sure it is now restored

37. View differences between a feature branch and latest ancestor of default

  1. hg update feature_branch
  2. hg diff -r 'ancestor(default,.)'

38. list files which might be affected by a merge

hg diff -r "ancestor(.,other) -r . --stat | cut -d "|" -f 1 | sed "s/ *$//" > /tmp/1
hg diff -r "ancestor(.,other) -r other --stat | cut -d "|" -f 1 | sed "s/ *$//" > /tmp/2
comm -12 <(sort /tmp/1) <(sort /tmp/2)

39. Beware of plain copying a Repo from Windows to Linux

In some cases, when no hg upstream server is present, one may copy e.g. an existing repository from Windows to Linux. However, Mercurial is sensitive to permissions. Any file that has been copied over from e.g. an NTFS drive gets its Executable attrribute set. Mercurial then treats such files as completely "new" in TortoiseHg (file view window, but 'M'-tagged) or via hg stat (however, a hg diff sees no difference between files in repo without 'x'-attribute and with 'x'-attribute in the workspace. A workaround is to update to tip (without backing up). This yields the desired state of all files.

TipsAndTricks (last edited 2016-12-05 11:14:36 by ArneBab)