Mercurial source code management system


Execute Mercurial command

>_ hg [command]

Call general help

>_ hg help

Call help on a command

>_ hg help [command]

Check the Mercurial version

>_ hg --version


hg command [option]... [argument]...


Mercurial colorizes output from several commands. For example, the diff command shows additions in green and deletions in red, while the status command shows modified files in magenta. Many other commands have analogous colors. It is possible to customize these colors. To enable color (default) whenever possible use: [ui] color = yes To disable color use: [ui] color = no See hg help config.ui.color for details. The default pager on Windows does not support color, so enabling the pager will effectively disable color. See hg help config.ui.paginate to disable the pager. Alternately, MSYS and Cygwin shells provide less as a pager, which can be configured to support ANSI color mode. Win‐ dows 10 natively supports ANSI color mode. Mode Mercurial can use various systems to display color. The supported modes are ansi, win32, and terminfo. See hg help config.color for details about how to control the mode. Effects Other effects in addition to color, like bold and underlined text, are also available. By default, the terminfo database is used to find the terminal codes used to change color and effect. If terminfo is not available, then effects are rendered with the ECMA-48 SGR control func‐ tion (aka ANSI escape codes). The available effects in terminfo mode are 'blink', 'bold', 'dim', 'in‐ verse', 'invisible', 'italic', 'standout', and 'underline'; in ECMA-48 mode, the options are 'bold', 'inverse', 'italic', and 'underline'. How each is rendered depends on the terminal emulator. Some may not be available for a given terminal type, and will be silently ignored. If the terminfo entry for your terminal is missing codes for an effect or has the wrong codes, you can add or override those codes in your configuration: [color] terminfo.dim = \E[2m where 'E' is substituted with an escape character. Labels Text receives color effects depending on the labels that it has. Many default Mercurial commands emit labelled text. You can also define your own labels in templates using the label function, see hg help templates . A single portion of text may have more than one label. In that case, effects given to the last label will override any other effects. This includes the special "none" effect, which nullifies other effects. Labels are normally invisible. In order to see these labels and their position in the text, use the global --color=debug option. The same an‐ chor text may be associated to multiple labels, e.g. [log.changeset changeset.secret|changeset: 22611:6f0a53c8f587] The following are the default effects for some default labels. Default effects may be overridden from your configuration file: [color] status.modified = blue bold underline red_background status.added = green bold status.removed = red bold blue_background status.deleted = cyan bold underline status.unknown = magenta bold underline status.ignored = black bold # 'none' turns off all effects status.clean = none status.copied = none qseries.applied = blue bold underline qseries.unapplied = black bold qseries.missing = red bold diff.diffline = bold diff.extended = cyan bold diff.file_a = red bold diff.file_b = green bold diff.hunk = magenta diff.deleted = red diff.inserted = green diff.changed = white diff.tab = diff.trailingwhitespace = bold red_background # Blank so it inherits the style of the surrounding label changeset.public = changeset.draft = changeset.secret = resolve.unresolved = red bold resolve.resolved = green bold bookmarks.active = green branches.active = none branches.closed = black bold branches.current = green branches.inactive = none tags.normal = green tags.local = black bold rebase.rebased = blue rebase.remaining = red bold shelve.age = cyan shelve.newest = green bold shelve.name = blue bold histedit.remaining = red bold Custom colors Because there are only eight standard colors, Mercurial allows you to define color names for other color slots which might be available for your terminal type, assuming terminfo mode. For instance: color.brightblue = 12 color.pink = 207 color.orange = 202 to set 'brightblue' to color slot 12 (useful for 16 color terminals that have brighter colors defined in the upper eight) and, 'pink' and 'orange' to colors in 256-color xterm's default color cube. These de‐ fined colors may then be used as any of the pre-defined eight, includ‐ ing appending '_background' to set the background to that color.


Some commands allow the user to specify a date, e.g.: • backout, commit, import, tag: Specify the commit date. • log, revert, update: Select revision(s) by date. Many date formats are valid. Here are some examples: • Wed Dec 6 13:18:29 2006 (local timezone assumed) • Dec 6 13:18 -0600 (year assumed, time offset provided) • Dec 6 13:18 UTC (UTC and GMT are aliases for +0000) • Dec 6 (midnight) • 13:18 (today assumed) • 3:39 (3:39AM assumed) • 3:39pm (15:39) • 2006-12-06 13:18:29 (ISO 8601 format) • 2006-12-6 13:18 • 2006-12-6 • 12-6 • 12/6 • 12/6/6 (Dec 6 2006) • today (midnight) • yesterday (midnight) • now - right now Lastly, there is Mercurial's internal format: • 1165411109 0 (Wed Dec 6 13:18:29 2006 UTC) This is the internal representation format for dates. The first number is the number of seconds since the epoch (1970-01-01 00:00 UTC). The second is the offset of the local timezone, in seconds west of UTC (negative if the timezone is east of UTC). The log command also accepts date ranges: • DATE - on or after a given date/time • DATE to DATE - a date range, inclusive • -DAYS - within a given number of days of today


Mercurial evolves over time, some features, options, commands may be replaced by better and more secure alternatives. This topic will help you migrating your existing usage and/or configuration to newer fea‐ tures. Commands The following commands are still available but their use are not recom‐ mended: locate This command has been replaced by hg files. parents This command can be replaced by hg summary or hg log with appropriate revsets. See hg help revsets for more information. tip The recommended alternative is hg heads. Options web.allowpull Renamed to allow-pull. web.allow_push Renamed to allow-push.


What are phases? Phases are a system for tracking which changesets have been or should be shared. This helps prevent common mistakes when modifying history (for instance, with the mq or rebase extensions). Each changeset in a repository is in one of the following phases: • public : changeset is visible on a public server • draft : changeset is not yet published • secret : changeset should not be pushed, pulled, or cloned These phases are ordered (public < draft < secret) and no changeset can be in a lower phase than its ancestors. For instance, if a changeset is public, all its ancestors are also public. Lastly, changeset phases should only be changed towards the public phase. How are phases managed? For the most part, phases should work transparently. By default, a changeset is created in the draft phase and is moved into the public phase when it is pushed to another repository. Once changesets become public, extensions like mq and rebase will refuse to operate on them to prevent creating duplicate changesets. Phases can also be manually manipulated with the hg phase command if needed. See hg help -v phase for examples. To make your commits secret by default, put this in your configuration file: [phases] new-commit = secret Phases and servers Normally, all servers are publishing by default. This means: - all draft changesets that are pulled or cloned appear in phase public on the client - all draft changesets that are pushed appear as public on both client and server - secret changesets are neither pushed, pulled, or cloned Note Pulling a draft changeset from a publishing server does not mark it as public on the server side due to the read-only nature of pull. Sometimes it may be desirable to push and pull changesets in the draft phase to share unfinished work. This can be done by setting a reposi‐ tory to disable publishing in its configuration file: [phases] publish = False See hg help config for more information on configuration files. Note Servers running older versions of Mercurial are treated as pub‐ lishing. Note Changesets in secret phase are not exchanged with the server. This applies to their content: file names, file contents, and changeset metadata. For technical reasons, the identifier (e.g. d825e4025e39) of the secret changeset may be communicated to the server. Examples • list changesets in draft or secret phase: hg log -r "not public()" • change all secret changesets to draft: hg phase --draft "secret()" • forcibly move the current changeset and descendants from public to draft: hg phase --force --draft . • show a list of changeset revisions and each corresponding phase: hg log --template "{rev} {phase}\n" • resynchronize draft changesets relative to a remote repository: hg phase -fd "outgoing(URL)" See hg help phase for more information on manually manipulating phases.


Mercurial supports several ways to specify revisions. Specifying single revisions A plain integer is treated as a revision number. Negative integers are treated as sequential offsets from the tip, with -1 denoting the tip, -2 denoting the revision prior to the tip, and so forth. A 40-digit hexadecimal string is treated as a unique revision identi‐ fier. A hexadecimal string less than 40 characters long is treated as a unique revision identifier and is referred to as a short-form identi‐ fier. A short-form identifier is only valid if it is the prefix of ex‐ actly one full-length identifier. Any other string is treated as a bookmark, tag, or branch name. A book‐ mark is a movable pointer to a revision. A tag is a permanent name as‐ sociated with a revision. A branch name denotes the tipmost open branch head of that branch - or if they are all closed, the tipmost closed head of the branch. Bookmark, tag, and branch names must not contain the ":" character. The reserved name "tip" always identifies the most recent revision. The reserved name "null" indicates the null revision. This is the revi‐ sion of an empty repository, and the parent of revision 0. The reserved name "." indicates the working directory parent. If no working directory is checked out, it is equivalent to null. If an un‐ committed merge is in progress, "." is the revision of the first par‐ ent. Finally, commands that expect a single revision (like hg update) also accept revsets (see below for details). When given a revset, they use the last revision of the revset. A few commands accept two single revi‐ sions (like hg diff). When given a revset, they use the first and the last revisions of the revset. Specifying multiple revisions Mercurial supports a functional language for selecting a set of revi‐ sions. Expressions in this language are called revsets. The language supports a number of predicates which are joined by infix operators. Parenthesis can be used for grouping. Identifiers such as branch names may need quoting with single or double quotes if they contain characters like - or if they match one of the predefined predicates. Special characters can be used in quoted identifiers by escaping them, e.g., \n is interpreted as a newline. To prevent them from being inter‐ preted, strings can be prefixed with r, e.g. r'...'. Operators There is a single prefix operator: not x Changesets not in x. Short form is ! x. These are the supported infix operators: x::y A DAG range, meaning all changesets that are descendants of x and ancestors of y, including x and y themselves. If the first endpoint is left out, this is equivalent to ancestors(y), if the second is left out it is equivalent to descendants(x). An alternative syntax is x..y. x:y All changesets with revision numbers between x and y, both in‐ clusive. Either endpoint can be left out, they default to 0 and tip. x and y The intersection of changesets in x and y. Short form is x & y. x or y The union of changesets in x and y. There are two alternative short forms: x | y and x + y. x - y Changesets in x but not in y. x % y Changesets that are ancestors of x but not ancestors of y (i.e. ::x - ::y). This is shorthand notation for only(x, y) (see be‐ low). The second argument is optional and, if left out, is equivalent to only(x). x^n The nth parent of x, n == 0, 1, or 2. For n == 0, x; for n == 1, the first parent of each changeset in x; for n == 2, the sec‐ ond parent of changeset in x. x~n The nth first ancestor of x; x~0 is x; x~3 is x^^^. For n < 0, the nth unambiguous descendent of x. x ## y Concatenate strings and identifiers into one string. All other prefix, infix and postfix operators have lower prior‐ ity than ##. For example, a1 ## a2~2 is equivalent to (a1 ## a2)~2. For example: [revsetalias] issue(a1) = grep(r'\bissue[ :]?' ## a1 ## r'\b|\bbug\(' ## a1 ## r'\)') issue(1234) is equivalent to grep(r'\bissue[ :]?1234\b|\bbug\(1234\)') in this case. This matches against all of "issue 1234", "issue:1234", "issue1234" and "bug(1234)". There is a single postfix operator: x^ Equivalent to x^1, the first parent of each changeset in x. Patterns Where noted, predicates that perform string matching can accept a pat‐ tern string. The pattern may be either a literal, or a regular expres‐ sion. If the pattern starts with re:, the remainder of the pattern is treated as a regular expression. Otherwise, it is treated as a literal. To match a pattern that actually starts with re:, use the prefix lit‐ eral:. Matching is case-sensitive, unless otherwise noted. To perform a case- insensitive match on a case-sensitive predicate, use a regular expres‐ sion, prefixed with (?i). For example, tag(r're:(?i)release') matches "release" or "RELEASE" or "Release", etc. Predicates The following predicates are supported: adds(pattern) Changesets that add a file matching pattern. The pattern without explicit kind like glob: is expected to be relative to the current directory and match against a file or a directory. all() All changesets, the same as 0:tip. ancestor(*changeset) A greatest common ancestor of the changesets. Accepts 0 or more changesets. Will return empty list when passed no args. Greatest common ancestor of a single changeset is that changeset. ancestors(set[, depth]) Changesets that are ancestors of changesets in set, including the given changesets themselves. If depth is specified, the result only includes changesets up to the specified generation. author(string) Alias for user(string). bisect(string) Changesets marked in the specified bisect status: • good, bad, skip: csets explicitly marked as good/bad/skip • goods, bads : csets topologically good/bad • range : csets taking part in the bisection • pruned : csets that are goods, bads or skipped • untested : csets whose fate is yet unknown • ignored : csets ignored due to DAG topology • current : the cset currently being bisected bookmark([name]) The named bookmark or all bookmarks. Pattern matching is supported for name. See hg help revi‐ sions.patterns. branch(string or set) All changesets belonging to the given branch or the branches of the given changesets. Pattern matching is supported for string. See hg help revi‐ sions.patterns. branchpoint() Changesets with more than one child. bundle() Changesets in the bundle. Bundle must be specified by the -R option. children(set) Child changesets of changesets in set. closed() Changeset is closed. commonancestors(set) Changesets that are ancestors of every changeset in set. contains(pattern) The revision's manifest contains a file matching pattern (but might not modify it). See hg help patterns for information about file patterns. The pattern without explicit kind like glob: is expected to be relative to the current directory and match against a file ex‐ actly for efficiency. converted([id]) Changesets converted from the given identifier in the old repos‐ itory if present, or all converted changesets if no identifier is specified. date(interval) Changesets within the interval, see hg help dates. desc(string) Search commit message for string. The match is case-insensitive. Pattern matching is supported for string. See hg help revi‐ sions.patterns. descendants(set[, depth]) Changesets which are descendants of changesets in set, including the given changesets themselves. If depth is specified, the result only includes changesets up to the specified generation. destination([set]) Changesets that were created by a graft, transplant or rebase operation, with the given revisions specified as the source. Omitting the optional set is the same as passing all(). draft() Changeset in draft phase. extinct() Obsolete changesets with obsolete descendants only. extra(label, [value]) Changesets with the given label in the extra metadata, with the given optional value. Pattern matching is supported for value. See hg help revi‐ sions.patterns. file(pattern) Changesets affecting files matched by pattern. For a faster but less accurate result, consider using filelog() instead. This predicate uses glob: as the default kind of pattern. filelog(pattern) Changesets connected to the specified filelog. For performance reasons, visits only revisions mentioned in the file-level filelog, rather than filtering through all changesets (much faster, but doesn't include deletes or duplicate changes). For a slower, more accurate result, use file(). The pattern without explicit kind like glob: is expected to be relative to the current directory and match against a file ex‐ actly for efficiency. If some linkrev points to revisions filtered by the current re‐ poview, we'll work around it to return a non-filtered value. first(set, [n]) An alias for limit(). follow([file[, startrev]]) An alias for ::. (ancestors of the working directory's first parent). If file pattern is specified, the histories of files matching given pattern in the revision given by startrev are followed, including copies. followlines(file, fromline:toline[, startrev=., descend=False]) Changesets modifying file in line range ('fromline', 'toline'). Line range corresponds to 'file' content at 'startrev' and should hence be consistent with file size. If startrev is not specified, working directory's parent is used. By default, ancestors of 'startrev' are returned. If 'descend' is True, descendants of 'startrev' are returned though renames are (currently) not followed in this direction. grep(regex) Like keyword(string) but accepts a regex. Use grep(r'...') to ensure special escape characters are handled correctly. Unlike keyword(string), the match is case-sensitive. head() Changeset is a named branch head. heads(set) Members of set with no children in set. hidden() Hidden changesets. id(string) Revision non-ambiguously specified by the given hex string pre‐ fix. keyword(string) Search commit message, user name, and names of changed files for string. The match is case-insensitive. For a regular expression or case sensitive search of these fields, use grep(regex). last(set, [n]) Last n members of set, defaulting to 1. limit(set[, n[, offset]]) First n members of set, defaulting to 1, starting from offset. matching(revision [, field]) Changesets in which a given set of fields match the set of fields in the selected revision or set. To match more than one field pass the list of fields to match separated by spaces (e.g. author description). Valid fields are most regular revision fields and some special fields. Regular revision fields are description, author, branch, date, files, phase, parents, substate, user and diff. Note that au‐ thor and user are synonyms. diff refers to the contents of the revision. Two revisions matching their diff will also match their files. Special fields are summary and metadata: summary matches the first line of the description. metadata is equivalent to match‐ ing description user date (i.e. it matches the main metadata fields). metadata is the default field which is used when no fields are specified. You can match more than one field at a time. max(set) Changeset with highest revision number in set. merge() Changeset is a merge changeset. min(set) Changeset with lowest revision number in set. modifies(pattern) Changesets modifying files matched by pattern. The pattern without explicit kind like glob: is expected to be relative to the current directory and match against a file or a directory. named(namespace) The changesets in a given namespace. Pattern matching is supported for namespace. See hg help revi‐ sions.patterns. none() No changesets. obsolete() Mutable changeset with a newer version. only(set, [set]) Changesets that are ancestors of the first set that are not an‐ cestors of any other head in the repo. If a second set is speci‐ fied, the result is ancestors of the first set that are not an‐ cestors of the second set (i.e. :: - ::). origin([set]) Changesets that were specified as a source for the grafts, transplants or rebases that created the given revisions. Omit‐ ting the optional set is the same as passing all(). If a changeset created by these operations is itself specified as a source for one of these operations, only the source changeset for the first operation is selected. outgoing([path]) Changesets not found in the specified destination repository, or the default push location. p1([set]) First parent of changesets in set, or the working directory. p2([set]) Second parent of changesets in set, or the working directory. parents([set]) The set of all parents for all changesets in set, or the working directory. present(set) An empty set, if any revision in set isn't found; otherwise, all revisions in set. If any of specified revisions is not present in the local repos‐ itory, the query is normally aborted. But this predicate allows the query to continue even in such cases. public() Changeset in public phase. remote([id [,path]]) Local revision that corresponds to the given identifier in a re‐ mote repository, if present. Here, the '.' identifier is a syn‐ onym for the current local branch. removes(pattern) Changesets which remove files matching pattern. The pattern without explicit kind like glob: is expected to be relative to the current directory and match against a file or a directory. rev(number) Revision with the given numeric identifier. reverse(set) Reverse order of set. revset(set) Strictly interpret the content as a revset. The content of this special predicate will be strictly inter‐ preted as a revset. For example, revset(id(0)) will be inter‐ preted as "id(0)" without possible ambiguity with a "id(0)" bookmark or tag. roots(set) Changesets in set with no parent changeset in set. secret() Changeset in secret phase. sort(set[, [-]key... [, ...]]) Sort set by keys. The default sort order is ascending, specify a key as -key to sort in descending order. The keys can be: • rev for the revision number, • branch for the branch name, • desc for the commit message (description), • user for user name (author can be used as an alias), • date for the commit date • topo for a reverse topographical sort The topo sort order cannot be combined with other sort keys. This sort takes one optional argument, topo.firstbranch, which takes a revset that specifies what topographical branches to prioritize in the sort. subrepo([pattern]) Changesets that add, modify or remove the given subrepo. If no subrepo pattern is named, any subrepo changes are returned. successors(set) All successors for set, including the given set themselves tag([name]) The specified tag by name, or all tagged revisions if no name is given. Pattern matching is supported for name. See hg help revi‐ sions.patterns. user(string) User name contains string. The match is case-insensitive. Pattern matching is supported for string. See hg help revi‐ sions.patterns. Aliases New predicates (known as "aliases") can be defined, using any combina‐ tion of existing predicates or other aliases. An alias definition looks like: = in the revsetalias section of a Mercurial configuration file. Arguments of the form a1, a2, etc. are substituted from the alias into the defi‐ nition. For example, [revsetalias] h = heads() d(s) = sort(s, date) rs(s, k) = reverse(sort(s, k)) defines three aliases, h, d, and rs. rs(0:tip, author) is exactly equivalent to reverse(sort(0:tip, author)). Equivalents Command line equivalents for hg log: -f -> ::. -d x -> date(x) -k x -> keyword(x) -m -> merge() -u x -> user(x) -b x -> branch(x) -P x -> !::x -l x -> limit(expr, x) Examples Some sample queries: • Changesets on the default branch: hg log -r "branch(default)" • Changesets on the default branch since tag 1.5 (excluding merges): hg log -r "branch(default) and 1.5:: and not merge()" • Open branch heads: hg log -r "head() and not closed()" • Changesets between tags 1.3 and 1.5 mentioning "bug" that affect hgext/*: hg log -r "1.3::1.5 and keyword(bug) and file('hgext/*')" • Changesets committed in May 2008, sorted by user: hg log -r "sort(date('May 2008'), user)" • Changesets mentioning "bug" or "issue" that are not in a tagged re‐ lease: hg log -r "(keyword(bug) or keyword(issue)) and not ancestors(tag())" • Update to the commit that bookmark @ is pointing to, without activat‐ ing the bookmark (this works because the last revision of the revset is used): hg update :@ • Show diff between tags 1.3 and 1.5 (this works because the first and the last revisions of the revset are used): hg diff -r 1.3::1.5


It is common for machines (as opposed to humans) to consume Mercurial. This help topic describes some of the considerations for interfacing machines with Mercurial. Choosing an Interface Machines have a choice of several methods to interface with Mercurial. These include: • Executing the hg process • Querying a HTTP server • Calling out to a command server Executing hg processes is very similar to how humans interact with Mer‐ curial in the shell. It should already be familiar to you. hg serve can be used to start a server. By default, this will start a "hgweb" HTTP server. This HTTP server has support for machine-readable output, such as JSON. For more, see hg help hgweb. hg serve can also start a "command server." Clients can connect to this server and issue Mercurial commands over a special protocol. For more details on the command server, including links to client libraries, see https://www.mercurial-scm.org/wiki/CommandServer. hg serve based interfaces (the hgweb and command servers) have the ad‐ vantage over simple hg process invocations in that they are likely more efficient. This is because there is significant overhead to spawn new Python processes. Tip If you need to invoke several hg processes in short order and/or performance is important to you, use of a server-based interface is highly recommended. Environment Variables As documented in hg help environment, various environment variables in‐ fluence the operation of Mercurial. The following are particularly rel‐ evant for machines consuming Mercurial: HGPLAIN If not set, Mercurial's output could be influenced by configura‐ tion settings that impact its encoding, verbose mode, localiza‐ tion, etc. It is highly recommended for machines to set this variable when invoking hg processes. HGENCODING If not set, the locale used by Mercurial will be detected from the environment. If the determined locale does not support dis‐ play of certain characters, Mercurial may render these character sequences incorrectly (often by using "?" as a placeholder for invalid characters in the current locale). Explicitly setting this environment variable is a good practice to guarantee consistent results. "utf-8" is a good choice on UNIX-like environments. HGRCPATH If not set, Mercurial will inherit config options from config files using the process described in hg help config. This in‐ cludes inheriting user or system-wide config files. When utmost control over the Mercurial configuration is desired, the value of HGRCPATH can be set to an explicit file with known good configs. In rare cases, the value can be set to an empty file or the null device (often /dev/null) to bypass loading of any user or system config files. Note that these approaches can have unintended consequences, as the user and system config files often define things like the username and extensions that may be required to interface with a repository. Command-line Flags Mercurial's default command-line parser is designed for humans, and is not robust against malicious input. For instance, you can start a de‐ bugger by passing --debugger as an option value: $ REV=--debugger sh -c 'hg log -r "$REV"' This happens because several command-line flags need to be scanned without using a concrete command table, which may be modified while loading repository settings and extensions. Since Mercurial 4.4.2, the parsing of such flags may be restricted by setting HGPLAIN=+strictflags. When this feature is enabled, all early options (e.g. -R/--repository, --cwd, --config) must be specified first amongst the other global options, and cannot be injected to an arbi‐ trary location: $ HGPLAIN=+strictflags hg -R "$REPO" log -r "$REV" In earlier Mercurial versions where +strictflags isn't available, you can mitigate the issue by concatenating an option value with its flag: $ hg log -r"$REV" --keyword="$KEYWORD" Consuming Command Output It is common for machines to need to parse the output of Mercurial com‐ mands for relevant data. This section describes the various techniques for doing so. Parsing Raw Command Output Likely the simplest and most effective solution for consuming command output is to simply invoke hg commands as you would as a user and parse their output. The output of many commands can easily be parsed with tools like grep, sed, and awk. A potential downside with parsing command output is that the output of commands can change when Mercurial is upgraded. While Mercurial does generally strive for strong backwards compatibility, command output does occasionally change. Having tests for your automated interactions with hg commands is generally recommended, but is even more important when raw command output parsing is involved. Using Templates to Control Output Many hg commands support templatized output via the -T/--template argu‐ ment. For more, see hg help templates. Templates are useful for explicitly controlling output so that you get exactly the data you want formatted how you want it. For example, log -T {node}\n can be used to print a newline delimited list of changeset nodes instead of a human-tailored output containing authors, dates, de‐ scriptions, etc. Tip If parsing raw command output is too complicated, consider using templates to make your life easier. The -T/--template argument allows specifying pre-defined styles. Mer‐ curial ships with the machine-readable styles json and xml, which pro‐ vide JSON and XML output, respectively. These are useful for producing output that is machine readable as-is. Important The json and xml styles are considered experimental. While they may be attractive to use for easily obtaining machine-readable output, their behavior may change in subsequent versions. These styles may also exhibit unexpected results when dealing with certain encodings. Mercurial treats things like filenames as a series of bytes and normalizing certain byte sequences to JSON or XML with certain encoding settings can lead to sur‐ prises. Command Server Output If using the command server to interact with Mercurial, you are likely using an existing library/API that abstracts implementation details of the command server. If so, this interface layer may perform parsing for you, saving you the work of implementing it yourself. Output Verbosity Commands often have varying output verbosity, even when machine read‐ able styles are being used (e.g. -T json). Adding -v/--verbose and --debug to the command's arguments can increase the amount of data ex‐ posed by Mercurial. An alternate way to get the data you need is by explicitly specifying a template. Other Topics revsets Revisions sets is a functional query language for selecting a set of revisions. Think of it as SQL for Mercurial repositories. Revsets are useful for querying repositories for specific data. See hg help revsets for more. share extension The share extension provides functionality for sharing reposi‐ tory data across several working copies. It can even automati‐ cally "pool" storage for logically related repositories when cloning. Configuring the share extension can lead to significant resource utilization reduction, particularly around disk space and the network. This is especially true for continuous integration (CI) environments. See hg help -e share for more.


Subrepositories let you nest external repositories or projects into a parent Mercurial repository, and make commands operate on them as a group. Mercurial currently supports Mercurial, Git, and Subversion subreposi‐ tories. Subrepositories are made of three components: 1. Nested repository checkouts. They can appear anywhere in the parent working directory. 2. Nested repository references. They are defined in .hgsub, which should be placed in the root of working directory, and tell where the subrepository checkouts come from. Mercurial subrepositories are referenced like: path/to/nested = https://example.com/nested/repo/path Git and Subversion subrepos are also supported: path/to/nested = [git]git://example.com/nested/repo/path path/to/nested = [svn]https://example.com/nested/trunk/path where path/to/nested is the checkout location relatively to the par‐ ent Mercurial root, and https://example.com/nested/repo/path is the source repository path. The source can also reference a filesystem path. Note that .hgsub does not exist by default in Mercurial reposito‐ ries, you have to create and add it to the parent repository before using subrepositories. 3. Nested repository states. They are defined in .hgsubstate, which is placed in the root of working directory, and capture whatever infor‐ mation is required to restore the subrepositories to the state they were committed in a parent repository changeset. Mercurial automati‐ cally record the nested repositories states when committing in the parent repository. Note The .hgsubstate file should not be edited manually. Adding a Subrepository If .hgsub does not exist, create it and add it to the parent reposi‐ tory. Clone or checkout the external projects where you want it to live in the parent repository. Edit .hgsub and add the subrepository entry as described above. At this point, the subrepository is tracked and the next commit will record its state in .hgsubstate and bind it to the committed changeset. Synchronizing a Subrepository Subrepos do not automatically track the latest changeset of their sources. Instead, they are updated to the changeset that corresponds with the changeset checked out in the top-level changeset. This is so developers always get a consistent set of compatible code and libraries when they update. Thus, updating subrepos is a manual process. Simply check out target subrepo at the desired revision, test in the top-level repo, then com‐ mit in the parent repository to record the new combination. Deleting a Subrepository To remove a subrepository from the parent repository, delete its refer‐ ence from .hgsub, then remove its files. Interaction with Mercurial Commands add add does not recurse in subrepos unless -S/--subrepos is speci‐ fied. However, if you specify the full path of a file in a sub‐ repo, it will be added even without -S/--subrepos specified. Subversion subrepositories are currently silently ignored. addremove addremove does not recurse into subrepos unless -S/--subrepos is specified. However, if you specify the full path of a directory in a subrepo, addremove will be performed on it even without -S/--subrepos being specified. Git and Subversion subreposito‐ ries will print a warning and continue. archive archive does not recurse in subrepositories unless -S/--subrepos is specified. cat Git subrepositories only support exact file matches. Subversion subrepositories are currently ignored. commit commit creates a consistent snapshot of the state of the entire project and its subrepositories. If any subrepositories have been modified, Mercurial will abort. Mercurial can be made to instead commit all modified subrepositories by specifying -S/--subrepos, or setting "ui.commitsubrepos=True" in a configu‐ ration file (see hg help config). After there are no longer any modified subrepositories, it records their state and finally commits it in the parent repository. The --addremove option also honors the -S/--subrepos option. However, Git and Subver‐ sion subrepositories will print a warning and abort. diff diff does not recurse in subrepos unless -S/--subrepos is speci‐ fied. Changes are displayed as usual, on the subrepositories el‐ ements. Subversion subrepositories are currently silently ig‐ nored. files files does not recurse into subrepos unless -S/--subrepos is specified. However, if you specify the full path of a file or directory in a subrepo, it will be displayed even without -S/--subrepos being specified. Git and Subversion subreposito‐ ries are currently silently ignored. forget forget currently only handles exact file matches in subrepos. Git and Subversion subrepositories are currently silently ig‐ nored. incoming incoming does not recurse in subrepos unless -S/--subrepos is specified. Git and Subversion subrepositories are currently silently ignored. outgoing outgoing does not recurse in subrepos unless -S/--subrepos is specified. Git and Subversion subrepositories are currently silently ignored. pull pull is not recursive since it is not clear what to pull prior to running hg update. Listing and retrieving all subrepositories changes referenced by the parent repository pulled changesets is expensive at best, impossible in the Subversion case. push Mercurial will automatically push all subrepositories first when the parent repository is being pushed. This ensures new sub‐ repository changes are available when referenced by top-level repositories. Push is a no-op for Subversion subrepositories. serve serve does not recurse into subrepositories unless -S/--subrepos is specified. Git and Subversion subrepositories are currently silently ignored. status status does not recurse into subrepositories unless -S/--subre‐ pos is specified. Subrepository changes are displayed as regular Mercurial changes on the subrepository elements. Subversion sub‐ repositories are currently silently ignored. remove remove does not recurse into subrepositories unless -S/--subre‐ pos is specified. However, if you specify a file or directory path in a subrepo, it will be removed even without -S/--subre‐ pos. Git and Subversion subrepositories are currently silently ignored. update update restores the subrepos in the state they were originally committed in target changeset. If the recorded changeset is not available in the current subrepository, Mercurial will pull it in first before updating. This means that updating can require network access when using subrepositories. Remapping Subrepositories Sources A subrepository source location may change during a project life, in‐ validating references stored in the parent repository history. To fix this, rewriting rules can be defined in parent repository hgrc file or in Mercurial configuration. See the [subpaths] section in hgrc(5) for more details.


Valid URLs are of the form: local/filesystem/path[#revision] file://local/filesystem/path[#revision] http://[user[:pass]@]host[:port]/[path][#revision] https://[user[:pass]@]host[:port]/[path][#revision] ssh://[user@]host[:port]/[path][#revision] Paths in the local filesystem can either point to Mercurial reposito‐ ries or to bundle files (as created by hg bundle or hg incoming --bun‐ dle). See also hg help paths. An optional identifier after # indicates a particular branch, tag, or changeset to use from the remote repository. See also hg help revisions . Some features, such as pushing to http:// and https:// URLs are only possible if the feature is explicitly enabled on the remote Mercurial server. Note that the security of HTTPS URLs depends on proper configuration of web.cacerts. Some notes about using SSH with Mercurial: • SSH requires an accessible shell account on the destination machine and a copy of hg in the remote path or specified with remotecmd. • path is relative to the remote user's home directory by default. Use an extra slash at the start of a path to specify an absolute path: ssh://example.com//tmp/repository • Mercurial doesn't use its own compression via SSH; the right thing to do is to configure it in your ~/.ssh/config, e.g.: Host *.mylocalnetwork.example.com Compression no Host * Compression yes Alternatively specify "ssh -C" as your ssh command in your configura‐ tion file or with the --ssh command line option. These URLs can all be stored in your configuration file with path aliases under the [paths] section like so: [paths] alias1 = URL1 alias2 = URL2 ... You can then use the alias for any command that uses a URL (for example hg pull alias1 will be treated as hg pull URL1). Two path aliases are special because they are used as defaults when you do not provide the URL to a command: default: When you create a repository with hg clone, the clone command saves the location of the source repository as the new reposi‐ tory's 'default' path. This is then used when you omit path from push- and pull-like commands (including incoming and outgoing). default-push: The push command will look for a path named 'default-push', and prefer it over 'default' if both are defined.


Mercurial allows you to customize output of commands through templates. You can either pass in a template or select an existing template-style from the command line, via the --template option. You can customize output for any "log-like" command: log, outgoing, in‐ coming, tip, parents, and heads. Some built-in styles are packaged with Mercurial. These can be listed with hg log --template list. Example usage: $ hg log -r1.0::1.1 --template changelog A template is a piece of text, with markup to invoke variable expan‐ sion: $ hg log -r1 --template "{node}\n" b56ce7b07c52de7d5fd79fb89701ea538af65746 Keywords Strings in curly braces are called keywords. The availability of key‐ words depends on the exact context of the templater. These keywords are usually available for templating a log-like command: activebookmark String. The active bookmark, if it is associated with the changeset. author Alias for {user} bisect String. The changeset bisection status. bookmarks List of strings. Any bookmarks associated with the changeset. Also sets 'active', the name of the active bookmark. branch String. The name of the branch on which the changeset was com‐ mitted. changessincelatesttag Integer. All ancestors not in the latest tag. children List of strings. The children of the changeset. date Date information. The date when the changeset was committed. desc String. The text of the changeset description. diffstat String. Statistics of changes with the following format: "modi‐ fied files: +added/-removed lines" extras List of dicts with key, value entries of the 'extras' field of this changeset. file_adds List of strings. Files added by this changeset. file_copies List of strings. Files copied in this changeset with their sources. file_copies_switch List of strings. Like "file_copies" but displayed only if the --copied switch is set. file_dels List of strings. Files removed by this changeset. file_mods List of strings. Files modified by this changeset. files List of strings. All files modified, added, or removed by this changeset. graphnode String. The character representing the changeset node in an ASCII revision graph. graphwidth Integer. The width of the graph drawn by 'log --graph' or zero. index Integer. The current iteration of the loop. (0 indexed) latesttag List of strings. The global tags on the most recent globally tagged ancestor of this changeset. If no such tags exist, the list consists of the single string "null". latesttagdistance Integer. Longest path to the latest tag. namespaces Dict of lists. Names attached to this changeset per namespace. node String. The changeset identification hash, as a 40 hexadecimal digit string. p1 Changeset. The changeset's first parent. {p1.rev} for the revi‐ sion number, and {p1.node} for the identification hash. p2 Changeset. The changeset's second parent. {p2.rev} for the revi‐ sion number, and {p2.node} for the identification hash. parents List of strings. The parents of the changeset in "rev:node" for‐ mat. If the changeset has only one "natural" parent (the prede‐ cessor revision) nothing is shown. peerurls A dictionary of repository locations defined in the [paths] sec‐ tion of your configuration file. phase String. The changeset phase name. reporoot String. The root directory of the current repository. rev Integer. The repository-local changeset revision number. subrepos List of strings. Updated subrepositories in the changeset. tags List of strings. Any tags associated with the changeset. termwidth Integer. The width of the current terminal. user String. The unmodified author of the changeset. verbosity String. The current output verbosity in 'debug', 'quiet', 'ver‐ bose', or ''. The "date" keyword does not produce human-readable output. If you want to use a date in your output, you can use a filter to process it. Fil‐ ters are functions which return a string based on the input variable. Be sure to use the stringify filter first when you're applying a string-input filter to a list-like input variable. You can also use a chain of filters to get the desired output: $ hg tip --template "{date|isodate}\n" 2008-08-21 18:22 +0000 Filters List of filters: addbreaks Any text. Add an XHTML "
" tag before the end of every line except the last. age Date. Returns a human-readable date/time difference between the given date/time and the current date/time. basename Any text. Treats the text as a path, and returns the last compo‐ nent of the path after splitting by the path separator. For ex‐ ample, "foo/bar/baz" becomes "baz" and "foo/bar//" becomes "". commondir List of text. Treats each list item as file name with / as path separator and returns the longest common directory prefix shared by all list items. Returns the empty string if no common prefix exists. The list items are not normalized, i.e. "foo/../bar" is handled as file "bar" in the directory "foo/..". Leading slashes are ig‐ nored. For example, ["foo/bar/baz", "foo/baz/bar"] becomes "foo" and ["foo/bar", "baz"] becomes "". count List or text. Returns the length as an integer. dirname Any text. Treats the text as a path, and strips the last compo‐ nent of the path after splitting by the path separator. domain Any text. Finds the first string that looks like an email ad‐ dress, and extracts just the domain component. Example: User becomes example.com. email Any text. Extracts the first string that looks like an email ad‐ dress. Example: User becomes user@exam‐ ple.com. emailuser Any text. Returns the user portion of an email address. escape Any text. Replaces the special XML/XHTML characters "&", "<" and ">" with XML entities, and filters out NUL characters. fill68 Any text. Wraps the text to fit in 68 columns. fill76 Any text. Wraps the text to fit in 76 columns. firstline Any text. Returns the first line of text. hex Any text. Convert a binary Mercurial node identifier into its long hexadecimal representation. hgdate Date. Returns the date as a pair of numbers: "1157407993 25200" (Unix timestamp, timezone offset). isodate Date. Returns the date in ISO 8601 format: "2009-08-18 13:00 +0200". isodatesec Date. Returns the date in ISO 8601 format, including seconds: "2009-08-18 13:00:13 +0200". See also the rfc3339date filter. json Any object. Serializes the object to a JSON formatted text. lower Any text. Converts the text to lowercase. nonempty Any text. Returns '(none)' if the string is empty. obfuscate Any text. Returns the input text rendered as a sequence of XML entities. person Any text. Returns the name before an email address, interpreting it as per RFC 5322. revescape Any text. Escapes all "special" characters, except @. Forward slashes are escaped twice to prevent web servers from prema‐ turely unescaping them. For example, "@foo bar/baz" becomes "@foo%20bar%252Fbaz". rfc3339date Date. Returns a date using the Internet date format specified in RFC 3339: "2009-08-18T13:00:13+02:00". rfc822date Date. Returns a date using the same format used in email head‐ ers: "Tue, 18 Aug 2009 13:00:13 +0200". short Changeset hash. Returns the short form of a changeset hash, i.e. a 12 hexadecimal digit string. shortbisect Any text. Treats label as a bisection status, and returns a sin‐ gle-character representing the status (G: good, B: bad, S: skipped, U: untested, I: ignored). Returns single space if text is not a valid bisection status. shortdate Date. Returns a date like "2006-09-18". slashpath Any text. Replaces the native path separator with slash. splitlines Any text. Split text into a list of lines. stringify Any type. Turns the value into text by converting values into text and concatenating them. stripdir Treat the text as path and strip a directory level, if possible. For example, "foo" and "foo/bar" becomes "foo". tabindent Any text. Returns the text, with every non-empty line except the first starting with a tab character. upper Any text. Converts the text to uppercase. urlescape Any text. Escapes all "special" characters. For example, "foo bar" becomes "foo%20bar". user Any text. Returns a short representation of a user name or email address. utf8 Any text. Converts from the local character encoding to UTF-8. Note that a filter is nothing more than a function call, i.e. expr|filter is equivalent to filter(expr). Functions In addition to filters, there are some basic built-in functions: date(date[, fmt]) Format a date. See hg help dates for formatting strings. The de‐ fault is a Unix date format, including the timezone: "Mon Sep 04 15:13:13 2006 0700". dict([[key=]value...]) Construct a dict from key-value pairs. A key may be omitted if a value expression can provide an unambiguous name. diff([includepattern [, excludepattern]]) Show a diff, optionally specifying files to include or exclude. files(pattern) All files of the current changeset matching the pattern. See hg help patterns. fill(text[, width[, initialident[, hangindent]]]) Fill many paragraphs with optional indentation. See the "fill" filter. filter(iterable[, expr]) Remove empty elements from a list or a dict. If expr specified, it's applied to each element to test emptiness. get(dict, key) Get an attribute/key from an object. Some keywords are complex types. This function allows you to obtain the value of an attri‐ bute on these types. if(expr, then[, else]) Conditionally execute based on the result of an expression. ifcontains(needle, haystack, then[, else]) Conditionally execute based on whether the item "needle" is in "haystack". ifeq(expr1, expr2, then[, else]) Conditionally execute based on whether 2 items are equivalent. indent(text, indentchars[, firstline]) Indents all non-empty lines with the characters given in the in‐ dentchars string. An optional third parameter will override the indent for the first line only if present. join(list, sep) Join items in a list with a delimiter. label(label, expr) Apply a label to generated content. Content with a label applied can result in additional post-processing, such as automatic col‐ orization. latesttag([pattern]) The global tags matching the given pattern on the most recent globally tagged ancestor of this changeset. If no such tags ex‐ ist, the "{tag}" template resolves to the string "null". See hg help revisions.patterns for the pattern syntax. localdate(date[, tz]) Converts a date to the specified timezone. The default is local date. mailmap(author) Return the author, updated according to the value set in the .mailmap file max(iterable) Return the max of an iterable min(iterable) Return the min of an iterable mod(a, b) Calculate a mod b such that a / b + a mod b == a pad(text, width[, fillchar=' '[, left=False[, truncate=False]]]) Pad text with a fill character. relpath(path) Convert a repository-absolute path into a filesystem path rela‐ tive to the current working directory. revset(query[, formatargs...]) Execute a revision set query. See hg help revset. rstdoc(text, style) Format reStructuredText. search(pattern, text) Look for the first text matching the regular expression pattern. Groups are accessible as {1}, {2}, ... in %-mapped template. separate(sep, args...) Add a separator between non-empty arguments. shortest(node, minlength=4) Obtain the shortest representation of a node. startswith(pattern, text) Returns the value from the "text" argument if it begins with the content from the "pattern" argument. strip(text[, chars]) Strip characters from a string. By default, strips all leading and trailing whitespace. sub(pattern, replacement, expression) Perform text substitution using regular expressions. word(number, text[, separator]) Return the nth word from a string. Operators We provide a limited set of infix arithmetic operations on integers: + for addition - for subtraction * for multiplication / for floor division (division rounded to integer nearest -infinity) Division fulfills the law x = x / y + mod(x, y). Also, for any expression that returns a list, there is a list operator: expr % "{template}" As seen in the above example, {template} is interpreted as a template. To prevent it from being interpreted, you can use an escape character \{ or a raw string prefix, r'...'. The dot operator can be used as a shorthand for accessing a sub item: • expr.member is roughly equivalent to expr % '{member}' if expr re‐ turns a non-list/dict. The returned value is not stringified. • dict.key is identical to get(dict, 'key'). Aliases New keywords and functions can be defined in the templatealias section of a Mercurial configuration file: = Arguments of the form a1, a2, etc. are substituted from the alias into the definition. For example, [templatealias] r = rev rn = "{r}:{node|short}" leftpad(s, w) = pad(s, w, ' ', True) defines two symbol aliases, r and rn, and a function alias leftpad(). It's also possible to specify complete template strings, using the tem‐ plates section. The syntax used is the general template string syntax. For example, [templates] nodedate = "{node|short}: {date(date, "%Y-%m-%d")}\n" defines a template, nodedate, which can be called like: $ hg log -r . -Tnodedate A template defined in templates section can also be referenced from an‐ other template: $ hg log -r . -T "{rev} {nodedate}" but be aware that the keywords cannot be overridden by templates. For example, a template defined as templates.rev cannot be referenced as {rev}. A template defined in templates section may have sub templates which are inserted before/after/between items: [templates] myjson = ' {dict(rev, node|short)|json}' myjson:docheader = '\{\n' myjson:docfooter = '\n}\n' myjson:separator = ',\n' Examples Some sample command line templates: • Format lists, e.g. files: $ hg log -r 0 --template "files:\n{files % ' {file}\n'}" • Join the list of files with a ", ": $ hg log -r 0 --template "files: {join(files, ', ')}\n" • Join the list of files ending with ".py" with a ", ": $ hg log -r 0 --template "pythonfiles: {join(files('**.py'), ', ')}\n" • Separate non-empty arguments by a " ": $ hg log -r 0 --template "{separate(' ', node, bookmarks, tags}\n" • Modify each line of a commit description: $ hg log --template "{splitlines(desc) % '**** {line}\n'}" • Format date: $ hg log -r 0 --template "{date(date, '%Y')}\n" • Display date in UTC: $ hg log -r 0 --template "{localdate(date, 'UTC')|date}\n" • Output the description set to a fill-width of 30: $ hg log -r 0 --template "{fill(desc, 30)}" • Use a conditional to test for the default branch: $ hg log -r 0 --template "{ifeq(branch, 'default', 'on the main branch', 'on branch {branch}')}\n" • Append a newline if not empty: $ hg tip --template "{if(author, '{author}\n')}" • Label the output for use with the color extension: $ hg log -r 0 --template "{label('changeset.{phase}', node|short)}\n" • Invert the firstline filter, i.e. everything but the first line: $ hg log -r 0 --template "{sub(r'^.*\n?\n?', '', desc)}\n" • Display the contents of the 'extra' field, one per line: $ hg log -r 0 --template "{join(extras, '\n')}\n" • Mark the active bookmark with '*': $ hg log --template "{bookmarks % '{bookmark}{ifeq(bookmark, active, '*')} '}\n" • Find the previous release candidate tag, the distance and changes since the tag: $ hg log -r . --template "{latesttag('re:^.*-rc$') % '{tag}, {changes}, {distance}'}\n" • Mark the working copy parent with '@': $ hg log --template "{ifcontains(rev, revset('.'), '@')}\n" • Show details of parent revisions: $ hg log --template "{revset('parents(%d)', rev) % '{desc|firstline}\n'}" • Show only commit descriptions that start with "template": $ hg log --template "{startswith('template', firstline(desc))}\n" • Print the first word of each line of a commit message: $ hg log --template "{word(0, desc)}\n"


Some Mercurial commands can produce a lot of output, and Mercurial will attempt to use a pager to make those commands more pleasant. To set the pager that should be used, set the application variable: [pager] pager = less -FRX If no pager is set in the user or repository configuration, Mercurial uses the environment variable $PAGER. If $PAGER is not set, pager.pager from the default or system configuration is used. If none of these are set, a default pager will be used, typically less on Unix and more on Windows. On Windows, more is not color aware, so using it effectively disables color. MSYS and Cygwin shells provide less as a pager, which can be configured to support ANSI color codes. See hg help con‐ fig.color.pagermode to configure the color mode when invoking a pager. You can disable the pager for certain commands by adding them to the pager.ignore list: [pager] ignore = version, help, update To ignore global commands like hg version or hg help, you have to spec‐ ify them in your user configuration file. To control whether the pager is used at all for an individual command, you can use --pager=: • use as needed: auto. • require the pager: yes or on. • suppress the pager: no or off (any unrecognized value will also work). To globally turn off all attempts to use a pager, set: [ui] paginate = never which will prevent the pager from running.


Mercurial accepts several notations for identifying one or more files at a time. By default, Mercurial treats filenames as shell-style extended glob patterns. Alternate pattern notations must be specified explicitly. Note Patterns specified in .hgignore are not rooted. Please see hg help hgignore for details. To use a plain path name without any pattern matching, start it with path:. These path names must completely match starting at the current repository root, and when the path points to a directory, it is matched recursively. To match all files in a directory non-recursively (not in‐ cluding any files in subdirectories), rootfilesin: can be used, speci‐ fying an absolute path (relative to the repository root). To use an extended glob, start a name with glob:. Globs are rooted at the current directory; a glob such as *.c will only match files in the current directory ending with .c. rootglob: can be used instead of glob: for a glob that is rooted at the root of the repository. The supported glob syntax extensions are ** to match any string across path separators and {a,b} to mean "a or b". To use a Perl/Python regular expression, start a name with re:. Regexp pattern matching is anchored at the root of the repository. To read name patterns from a file, use listfile: or listfile0:. The latter expects null delimited patterns while the former expects line feeds. Each string read from the file is itself treated as a file pat‐ tern. To read a set of patterns from a file, use include: or subinclude:. include: will use all the patterns from the given file and treat them as if they had been passed in manually. subinclude: will only apply the patterns against files that are under the subinclude file's direc‐ tory. See hg help hgignore for details on the format of these files. All patterns, except for glob: specified in command line (not for -I or -X options), can match also against directories: files under matched directories are treated as matched. For -I and -X options, glob: will match directories recursively. Plain examples: path:foo/bar a name bar in a directory named foo in the root of the repository path:path:name a file or directory named "path:name" rootfilesin:foo/bar the files in a directory called foo/bar, but not any files in its subdirectories and not a file bar in directory foo Glob examples: glob:*.c any name ending in ".c" in the current directory *.c any name ending in ".c" in the current directory **.c any name ending in ".c" in any subdirectory of the current directory including itself. foo/* any file in directory foo foo/** any file in directory foo plus all its subdirectories, recursively foo/*.c any name ending in ".c" in the directory foo foo/**.c any name ending in ".c" in any subdirectory of foo including itself. rootglob:*.c any name ending in ".c" in the root of the repository Regexp examples: re:.*\.c$ any name ending in ".c", anywhere in the repository File examples: listfile:list.txt read list from list.txt with one file pattern per line listfile0:list.txt read list from list.txt with null byte delimiters See also hg help filesets. Include examples: include:path/to/mypatternfile reads patterns to be applied to all paths subinclude:path/to/subignorefile reads patterns specifically for paths in the subdirectory


The hg command provides a command line interface to the Mercurial sys‐ tem.


files... indicates one or more filename or relative path filenames; see File Name Patterns for information on pattern matching path indicates a path on the local machine revision indicates a changeset which can be specified as a changeset re‐ vision number, a tag, or a unique substring of the changeset hash value repository path either the pathname of a local repository or the URI of a remote repository.


-R,--repository repository root directory or name of overlay bundle file --cwd

change working directory -y, --noninteractive do not prompt, automatically pick the first choice for all prompts -q, --quiet suppress output -v, --verbose enable additional output --color when to colorize (boolean, always, auto, never, or debug) --config set/override config option (use 'section.name=value') --debug enable debugging output --debugger start debugger --encoding set the charset encoding (default: UTF-8) --encodingmode set the charset encoding mode (default: strict) --traceback always print a traceback on exception --time time how long the command takes --profile print command execution profile --version output version information and exit -h, --help display help and exit --hidden consider hidden changesets --pager when to paginate (boolean, always, auto, or never) (default: auto) [+] marked option can be specified multiple times


Mercurial's default format for showing changes between two versions of a file is compatible with the unified format of GNU diff, which can be used by GNU patch and many other standard tools. While this standard format is often enough, it does not encode the fol‐ lowing information: • executable status and other permission bits • copy or rename information • changes in binary files • creation or deletion of empty files Mercurial also supports the extended diff format from the git VCS which addresses these limitations. The git diff format is not produced by de‐ fault because a few widespread tools still do not understand this for‐ mat. This means that when generating diffs from a Mercurial repository (e.g. with hg export), you should be careful about things like file copies and renames or other things mentioned above, because when applying a standard diff to a different repository, this extra information is lost. Mercurial's internal operations (like push and pull) are not af‐ fected by this, because they use an internal binary format for communi‐ cating changes. To make Mercurial produce the git extended diff format, use the --git option available for many commands, or set 'git = True' in the [diff] section of your configuration file. You do not need to set this option when importing diffs in this format or using them in the mq extension.


HG Path to the 'hg' executable, automatically passed when running hooks, extensions or external tools. If unset or empty, this is the hg executable's name if it's frozen, or an executable named 'hg' (with %PATHEXT% [defaulting to COM/EXE/BAT/CMD] extensions on Windows) is searched. HGEDITOR This is the name of the editor to run when committing. See EDI‐ TOR. (deprecated, see hg help config.ui.editor) HGENCODING This overrides the default locale setting detected by Mercurial. This setting is used to convert data including usernames, changeset descriptions, tag names, and branches. This setting can be overridden with the --encoding command-line option. HGENCODINGMODE This sets Mercurial's behavior for handling unknown characters while transcoding user input. The default is "strict", which causes Mercurial to abort if it can't map a character. Other settings include "replace", which replaces unknown characters, and "ignore", which drops them. This setting can be overridden with the --encodingmode command-line option. HGENCODINGAMBIGUOUS This sets Mercurial's behavior for handling characters with "am‐ biguous" widths like accented Latin characters with East Asian fonts. By default, Mercurial assumes ambiguous characters are narrow, set this variable to "wide" if such characters cause formatting problems. HGMERGE An executable to use for resolving merge conflicts. The program will be executed with three arguments: local file, remote file, ancestor file. (deprecated, see hg help config.ui.merge) HGRCPATH A list of files or directories to search for configuration files. Item separator is ":" on Unix, ";" on Windows. If HGRC‐ PATH is not set, platform default search path is used. If empty, only the .hg/hgrc from the current repository is read. For each element in HGRCPATH: • if it's a directory, all files ending with .rc are added • otherwise, the file itself will be added HGPLAIN When set, this disables any configuration settings that might change Mercurial's default output. This includes encoding, de‐ faults, verbose mode, debug mode, quiet mode, tracebacks, and localization. This can be useful when scripting against Mercu‐ rial in the face of existing user configuration. In addition to the features disabled by HGPLAIN=, the following values can be specified to adjust behavior: +strictflags Restrict parsing of command line flags. Equivalent options set via command line flags or environment variables are not overridden. See hg help scripting for details. HGPLAINEXCEPT This is a comma-separated list of features to preserve when HG‐ PLAIN is enabled. Currently the following values are supported: alias Don't remove aliases. color Don't disable colored output. i18n Preserve internationalization. revsetalias Don't remove revset aliases. templatealias Don't remove template aliases. progress Don't hide progress output. Setting HGPLAINEXCEPT to anything (even an empty string) will enable plain mode. HGUSER This is the string used as the author of a commit. If not set, available values will be considered in this order: • HGUSER (deprecated) • configuration files from the HGRCPATH • EMAIL • interactive prompt • LOGNAME (with @hostname appended) (deprecated, see hg help config.ui.username) EMAIL May be used as the author of a commit; see HGUSER. LOGNAME May be used as the author of a commit; see HGUSER. VISUAL This is the name of the editor to use when committing. See EDI‐ TOR. EDITOR Sometimes Mercurial needs to open a text file in an editor for a user to modify, for example when writing commit messages. The editor it uses is determined by looking at the environment vari‐ ables HGEDITOR, VISUAL and EDITOR, in that order. The first non-empty one is chosen. If all of them are empty, the editor defaults to 'sensible-editor'. PYTHONPATH This is used by Python to find imported modules and may need to be set appropriately if this Mercurial is not installed sys‐ tem-wide.


Mercurial has the ability to add new features through the use of exten‐ sions. Extensions may add new commands, add options to existing com‐ mands, change the default behavior of commands, or implement hooks. To enable the "foo" extension, either shipped with Mercurial or in the Python search path, create an entry for it in your configuration file, like this: [extensions] foo = You may also specify the full path to an extension: [extensions] myfeature = ~/.hgext/myfeature.py See hg help config for more information on configuration files. Extensions are not loaded by default for a variety of reasons: they can increase startup overhead; they may be meant for advanced usage only; they may provide potentially dangerous abilities (such as letting you destroy or modify history); they might not be ready for prime time; or they may alter some usual behaviors of stock Mercurial. It is thus up to the user to activate extensions as needed. To explicitly disable an extension enabled in a configuration file of broader scope, prepend its path with !: [extensions] # disabling extension bar residing in /path/to/extension/bar.py bar = !/path/to/extension/bar.py # ditto, but no path was supplied for extension baz baz = ! disabled extensions: acl hooks for controlling repository access blackbox log repository events to a blackbox for debugging bugzilla hooks for integrating with the Bugzilla bug tracker censor erase file content at a given revision churn command to display statistics about repository history clonebundles advertise pre-generated bundles to seed clones closehead close arbitrary heads without checking them out first convert import revisions from foreign VCS repositories into Mercurial eol automatically manage newlines in repository files extdiff command to allow external programs to compare revisions factotum http authentication with factotum githelp try mapping git commands to Mercurial commands gpg commands to sign and verify changesets hgk browse the repository in a graphical way highlight syntax highlighting for hgweb (requires Pygments) histedit interactive history editing keyword expand keywords in tracked files largefiles track large binary files mq manage a stack of patches notify hooks for sending email push notifications patchbomb command to send changesets as (a series of) patch emails purge command to delete untracked files from the working directory rebase command to move sets of revisions to a different ancestor relink recreates hardlinks between repository clones schemes extend schemes with shortcuts to repository swarms share share a common history between several working directories shelve save and restore changes to the working directory strip strip changesets and their descendants from history transplant command to transplant changesets from another branch win32mbcs allow the use of MBCS paths with problematic encodings zeroconf discover and advertise repositories on the local network


Mercurial supports a functional language for selecting a set of files. Like other file patterns, this pattern type is indicated by a prefix, 'set:'. The language supports a number of predicates which are joined by infix operators. Parenthesis can be used for grouping. Identifiers such as filenames or patterns must be quoted with single or double quotes if they contain characters outside of [.*{}[]?/\_a-zA-Z0-9\x80-\xff] or if they match one of the predefined predicates. This generally applies to file patterns other than globs and arguments for predicates. Pattern prefixes such as path: may be specified without quoting. Special characters can be used in quoted identifiers by escaping them, e.g., \n is interpreted as a newline. To prevent them from being inter‐ preted, strings can be prefixed with r, e.g. r'...'. See also hg help patterns. Operators There is a single prefix operator: not x Files not in x. Short form is ! x. These are the supported infix operators: x and y The intersection of files in x and y. Short form is x & y. x or y The union of files in x and y. There are two alternative short forms: x | y and x + y. x - y Files in x but not in y. Predicates The following predicates are supported: added() File that is added according to hg status. binary() File that appears to be binary (contains NUL bytes). clean() File that is clean according to hg status. copied() File that is recorded as being copied. deleted() Alias for missing(). encoding(name) File can be successfully decoded with the given character encod‐ ing. May not be useful for encodings other than ASCII and UTF-8. eol(style) File contains newlines of the given style (dos, unix, mac). Bi‐ nary files are excluded, files with mixed line endings match multiple styles. exec() File that is marked as executable. grep(regex) File contains the given regular expression. hgignore() File that matches the active .hgignore pattern. ignored() File that is ignored according to hg status. missing() File that is missing according to hg status. modified() File that is modified according to hg status. portable() File that has a portable name. (This doesn't include filenames with case collisions.) removed() File that is removed according to hg status. resolved() File that is marked resolved according to hg resolve -l. revs(revs, pattern) Evaluate set in the specified revisions. If the revset match multiple revs, this will return file matching pattern in any of the revision. size(expression) File size matches the given expression. Examples: • size('1k') - files from 1024 to 2047 bytes • size('< 20k') - files less than 20480 bytes • size('>= .5MB') - files at least 524288 bytes • size('4k - 1MB') - files from 4096 bytes to 1048576 bytes status(base, rev, pattern) Evaluate predicate using status change between base and rev. Ex‐ amples: • status(3, 7, added()) - matches files added from "3" to "7" subrepo([pattern]) Subrepositories whose paths match the given pattern. symlink() File that is marked as a symlink. tracked() File that is under Mercurial control. unknown() File that is unknown according to hg status. unresolved() File that is marked unresolved according to hg resolve -l. Examples Some sample queries: • Show status of files that appear to be binary in the working direc‐ tory: hg status -A "set:binary()" • Forget files that are in .hgignore but are already tracked: hg forget "set:hgignore() and not ignored()" • Find text files that contain a string: hg files "set:grep(magic) and not binary()" • Find C files in a non-standard encoding: hg files "set:**.c and not encoding('UTF-8')" • Revert copies of large binary files: hg revert "set:copied() and binary() and size('>1M')" • Revert files that were added to the working directory: hg revert "set:revs('wdir()', added())" • Remove files listed in foo.lst that contain the letter a or b: hg remove "set: listfile:foo.lst and (**a* or **b*)"


Most Mercurial commands accept various flags. Flag names Flags for each command are listed in hg help for that command. Addi‐ tionally, some flags, such as --repository, are global and can be used with any command - those are seen in hg help -v, and can be specified before or after the command. Every flag has at least a long name, such as --repository. Some flags may also have a short one-letter name, such as the equivalent -R. Using the short or long name is equivalent and has the same effect. Flags that have a short name can also be bundled together - for in‐ stance, to specify both --edit (short -e) and --interactive (short -i), one could use: hg commit -ei If any of the bundled flags takes a value (i.e. is not a boolean), it must be last, followed by the value: hg commit -im 'Message' Flag types Mercurial command-line flags can be strings, numbers, booleans, or lists of strings. Specifying flag values The following syntaxes are allowed, assuming a flag 'flagname' with short name 'f': --flagname=foo --flagname foo -f foo -ffoo This syntax applies to all non-boolean flags (strings, numbers or lists). Specifying boolean flags Boolean flags do not take a value parameter. To specify a boolean, use the flag name to set it to true, or the same name prefixed with 'no-' to set it to false: hg commit --interactive hg commit --no-interactive Specifying list flags List flags take multiple values. To specify them, pass the flag multi‐ ple times: hg files --include mercurial --include tests Setting flag defaults In order to set a default value for a flag in an hgrc file, it is rec‐ ommended to use aliases: [alias] commit = commit --interactive For more information on hgrc files, see hg help config. Overriding flags on the command line If the same non-list flag is specified multiple times on the command line, the latest specification is used: hg commit -m "Ignored value" -m "Used value" This includes the use of aliases - e.g., if one has: [alias] committemp = commit -m "Ignored value" then the following command will override that -m: hg committemp -m "Used value" Overriding flag defaults Every flag has a default value, and you may also set your own defaults in hgrc as described above. Except for list flags, defaults can be overridden on the command line simply by specifying the flag in that location. Hidden flags Some flags are not shown in a command's help by default - specifically, those that are deemed to be experimental, deprecated or advanced. To show all flags, add the --verbose flag for the help command: hg help --verbose commit


Ancestor Any changeset that can be reached by an unbroken chain of parent changesets from a given changeset. More precisely, the ancestors of a changeset can be defined by two properties: a parent of a changeset is an ancestor, and a parent of an ancestor is an an‐ cestor. See also: 'Descendant'. Bookmark Bookmarks are pointers to certain commits that move when commit‐ ting. They are similar to tags in that it is possible to use bookmark names in all places where Mercurial expects a changeset ID, e.g., with hg update. Unlike tags, bookmarks move along when you make a commit. Bookmarks can be renamed, copied and deleted. Bookmarks are lo‐ cal, unless they are explicitly pushed or pulled between reposi‐ tories. Pushing and pulling bookmarks allow you to collaborate with others on a branch without creating a named branch. Branch (Noun) A child changeset that has been created from a parent that is not a head. These are known as topological branches, see 'Branch, topological'. If a topological branch is named, it be‐ comes a named branch. If a topological branch is not named, it becomes an anonymous branch. See 'Branch, anonymous' and 'Branch, named'. Branches may be created when changes are pulled from or pushed to a remote repository, since new heads may be created by these operations. Note that the term branch can also be used infor‐ mally to describe a development process in which certain devel‐ opment is done independently of other development. This is some‐ times done explicitly with a named branch, but it can also be done locally, using bookmarks or clones and anonymous branches. Example: "The experimental branch." (Verb) The action of creating a child changeset which results in its parent having more than one child. Example: "I'm going to branch at X." Branch, anonymous Every time a new child changeset is created from a parent that is not a head and the name of the branch is not changed, a new anonymous branch is created. Branch, closed A named branch whose branch heads have all been closed. Branch, default The branch assigned to a changeset when no name has previously been assigned. Branch head See 'Head, branch'. Branch, inactive If a named branch has no topological heads, it is considered to be inactive. As an example, a feature branch becomes inactive when it is merged into the default branch. The hg branches com‐ mand shows inactive branches by default, though they can be hid‐ den with hg branches --active. NOTE: this concept is deprecated because it is too implicit. Branches should now be explicitly closed using hg commit --close-branch when they are no longer needed. Branch, named A collection of changesets which have the same branch name. By default, children of a changeset in a named branch belong to the same named branch. A child can be explicitly assigned to a dif‐ ferent branch. See hg help branch, hg help branches and hg com‐ mit --close-branch for more information on managing branches. Named branches can be thought of as a kind of namespace, divid‐ ing the collection of changesets that comprise the repository into a collection of disjoint subsets. A named branch is not necessarily a topological branch. If a new named branch is cre‐ ated from the head of another named branch, or the default branch, but no further changesets are added to that previous branch, then that previous branch will be a branch in name only. Branch tip See 'Tip, branch'. Branch, topological Every time a new child changeset is created from a parent that is not a head, a new topological branch is created. If a topo‐ logical branch is named, it becomes a named branch. If a topo‐ logical branch is not named, it becomes an anonymous branch of the current, possibly default, branch. Changelog A record of the changesets in the order in which they were added to the repository. This includes details such as changeset id, author, commit message, date, and list of changed files. Changeset A snapshot of the state of the repository used to record a change. Changeset, child The converse of parent changeset: if P is a parent of C, then C is a child of P. There is no limit to the number of children that a changeset may have. Changeset id A SHA-1 hash that uniquely identifies a changeset. It may be represented as either a "long" 40 hexadecimal digit string, or a "short" 12 hexadecimal digit string. Changeset, merge A changeset with two parents. This occurs when a merge is com‐ mitted. Changeset, parent A revision upon which a child changeset is based. Specifically, a parent changeset of a changeset C is a changeset whose node immediately precedes C in the DAG. Changesets have at most two parents. Checkout (Noun) The working directory being updated to a specific revi‐ sion. This use should probably be avoided where possible, as changeset is much more appropriate than checkout in this con‐ text. Example: "I'm using checkout X." (Verb) Updating the working directory to a specific changeset. See hg help update. Example: "I'm going to check out changeset X." Child changeset See 'Changeset, child'. Close changeset See 'Head, closed branch'. Closed branch See 'Branch, closed'. Clone (Noun) An entire or partial copy of a repository. The partial clone must be in the form of a revision and its ancestors. Example: "Is your clone up to date?" (Verb) The process of creating a clone, using hg clone. Example: "I'm going to clone the repository." Closed branch head See 'Head, closed branch'. Commit (Noun) A synonym for changeset. Example: "Is the bug fixed in your recent commit?" (Verb) The act of recording changes to a repository. When files are committed in a working directory, Mercurial finds the dif‐ ferences between the committed files and their parent changeset, creating a new changeset in the repository. Example: "You should commit those changes now." Cset A common abbreviation of the term changeset. DAG The repository of changesets of a distributed version control system (DVCS) can be described as a directed acyclic graph (DAG), consisting of nodes and edges, where nodes correspond to changesets and edges imply a parent -> child relation. This graph can be visualized by graphical tools such as hg log --graph. In Mercurial, the DAG is limited by the requirement for children to have at most two parents. Deprecated Feature removed from documentation, but not scheduled for re‐ moval. Default branch See 'Branch, default'. Descendant Any changeset that can be reached by a chain of child changesets from a given changeset. More precisely, the descendants of a changeset can be defined by two properties: the child of a changeset is a descendant, and the child of a descendant is a descendant. See also: 'Ancestor'. Diff (Noun) The difference between the contents and attributes of files in two changesets or a changeset and the current working directory. The difference is usually represented in a standard form called a "diff" or "patch". The "git diff" format is used when the changes include copies, renames, or changes to file at‐ tributes, none of which can be represented/handled by classic "diff" and "patch". Example: "Did you see my correction in the diff?" (Verb) Diffing two changesets is the action of creating a diff or patch. Example: "If you diff with changeset X, you will see what I mean." Directory, working The working directory represents the state of the files tracked by Mercurial, that will be recorded in the next commit. The working directory initially corresponds to the snapshot at an existing changeset, known as the parent of the working direc‐ tory. See 'Parent, working directory'. The state may be modified by changes to the files introduced manually or by a merge. The repository metadata exists in the .hg directory inside the work‐ ing directory. Draft Changesets in the draft phase have not been shared with publish‐ ing repositories and may thus be safely changed by history-modi‐ fying extensions. See hg help phases. Experimental Feature that may change or be removed at a later date. Graph See DAG and hg log --graph. Head The term 'head' may be used to refer to both a branch head or a repository head, depending on the context. See 'Head, branch' and 'Head, repository' for specific definitions. Heads are where development generally takes place and are the usual targets for update and merge operations. Head, branch A changeset with no descendants on the same named branch. Head, closed branch A changeset that marks a head as no longer interesting. The closed head is no longer listed by hg heads. A branch is consid‐ ered closed when all its heads are closed and consequently is not listed by hg branches. Closed heads can be re-opened by committing new changeset as the child of the changeset that marks a head as closed. Head, repository A topological head which has not been closed. Head, topological A changeset with no children in the repository. History, immutable Once committed, changesets cannot be altered. Extensions which appear to change history actually create new changesets that re‐ place existing ones, and then destroy the old changesets. Doing so in public repositories can result in old changesets being reintroduced to the repository. History, rewriting The changesets in a repository are immutable. However, exten‐ sions to Mercurial can be used to alter the repository, usually in such a way as to preserve changeset contents. Immutable history See 'History, immutable'. Merge changeset See 'Changeset, merge'. Manifest Each changeset has a manifest, which is the list of files that are tracked by the changeset. Merge Used to bring together divergent branches of work. When you up‐ date to a changeset and then merge another changeset, you bring the history of the latter changeset into your working directory. Once conflicts are resolved (and marked), this merge may be com‐ mitted as a merge changeset, bringing two branches together in the DAG. Named branch See 'Branch, named'. Null changeset The empty changeset. It is the parent state of newly-initialized repositories and repositories with no checked out revision. It is thus the parent of root changesets and the effective ancestor when merging unrelated changesets. Can be specified by the alias 'null' or by the changeset ID '000000000000'. Parent See 'Changeset, parent'. Parent changeset See 'Changeset, parent'. Parent, working directory The working directory parent reflects a virtual revision which is the child of the changeset (or two changesets with an uncom‐ mitted merge) shown by hg parents. This is changed with hg up‐ date. Other commands to see the working directory parent are hg summary and hg id. Can be specified by the alias ".". Patch (Noun) The product of a diff operation. Example: "I've sent you my patch." (Verb) The process of using a patch file to transform one changeset into another. Example: "You will need to patch that revision." Phase A per-changeset state tracking how the changeset has been or should be shared. See hg help phases. Public Changesets in the public phase have been shared with publishing repositories and are therefore considered immutable. See hg help phases. Pull An operation in which changesets in a remote repository which are not in the local repository are brought into the local repository. Note that this operation without special arguments only updates the repository, it does not update the files in the working directory. See hg help pull. Push An operation in which changesets in a local repository which are not in a remote repository are sent to the remote repository. Note that this operation only adds changesets which have been committed locally to the remote repository. Uncommitted changes are not sent. See hg help push. Repository The metadata describing all recorded states of a collection of files. Each recorded state is represented by a changeset. A repository is usually (but not always) found in the .hg subdi‐ rectory of a working directory. Any recorded state can be recre‐ ated by "updating" a working directory to a specific changeset. Repository head See 'Head, repository'. Revision A state of the repository at some point in time. Earlier revi‐ sions can be updated to by using hg update. See also 'Revision number'; See also 'Changeset'. Revision number This integer uniquely identifies a changeset in a specific repository. It represents the order in which changesets were added to a repository, starting with revision number 0. Note that the revision number may be different in each clone of a repository. To identify changesets uniquely between different clones, see 'Changeset id'. Revlog History storage mechanism used by Mercurial. It is a form of delta encoding, with occasional full revision of data followed by delta of each successive revision. It includes data and an index pointing to the data. Rewriting history See 'History, rewriting'. Root A changeset that has only the null changeset as its parent. Most repositories have only a single root changeset. Secret Changesets in the secret phase may not be shared via push, pull, or clone. See hg help phases. Tag An alternative name given to a changeset. Tags can be used in all places where Mercurial expects a changeset ID, e.g., with hg update. The creation of a tag is stored in the history and will thus automatically be shared with other using push and pull. Tip The changeset with the highest revision number. It is the changeset most recently added in a repository. Tip, branch The head of a given branch with the highest revision number. When a branch name is used as a revision identifier, it refers to the branch tip. See also 'Branch, head'. Note that because revision numbers may be different in different repository clones, the branch tip may be different in different cloned repositories. Update (Noun) Another synonym of changeset. Example: "I've pushed an update." (Verb) This term is usually used to describe updating the state of the working directory to that of a specific changeset. See hg help update. Example: "You should update." Working directory See 'Directory, working'. Working directory parent See 'Parent, working directory'.


Synopsis The Mercurial system uses a file called .hgignore in the root directory of a repository to control its behavior when it searches for files that it is not currently tracking. Description The working directory of a Mercurial repository will often contain files that should not be tracked by Mercurial. These include backup files created by editors and build products created by compilers. These files can be ignored by listing them in a .hgignore file in the root of the working directory. The .hgignore file must be created manu‐ ally. It is typically put under version control, so that the settings will propagate to other repositories with push and pull. An untracked file is ignored if its path relative to the repository root directory, or any prefix path of that path, is matched against any pattern in .hgignore. For example, say we have an untracked file, file.c, at a/b/file.c in‐ side our repository. Mercurial will ignore file.c if any pattern in .hgignore matches a/b/file.c, a/b or a. In addition, a Mercurial configuration file can reference a set of per-user or global ignore files. See the ignore configuration key on the [ui] section of hg help config for details of how to configure these files. To control Mercurial's handling of files that it manages, many commands support the -I and -X options; see hg help and hg help pat‐ terns for details. Files that are already tracked are not affected by .hgignore, even if they appear in .hgignore. An untracked file X can be explicitly added with hg add X, even if X would be excluded by a pattern in .hgignore. Syntax An ignore file is a plain text file consisting of a list of patterns, with one pattern per line. Empty lines are skipped. The # character is treated as a comment character, and the \ character is treated as an escape character. Mercurial supports several pattern syntaxes. The default syntax used is Python/Perl-style regular expressions. To change the syntax used, use a line of the following form: syntax: NAME where NAME is one of the following: regexp Regular expression, Python/Perl syntax. glob Shell-style glob. rootglob A variant of glob that is rooted (see below). The chosen syntax stays in effect when parsing all patterns that fol‐ low, until another syntax is selected. Neither glob nor regexp patterns are rooted. A glob-syntax pattern of the form *.c will match a file ending in .c in any directory, and a regexp pattern of the form \.c$ will do the same. To root a regexp pat‐ tern, start it with ^. To get the same effect with glob-syntax, you have to use rootglob. Subdirectories can have their own .hgignore settings by adding subin‐ clude:path/to/subdir/.hgignore to the root .hgignore. See hg help pat‐ terns for details on subinclude: and include:. Note Patterns specified in other than .hgignore are always rooted. Please see hg help patterns for details. Example Here is an example ignore file. # use glob syntax. syntax: glob *.elc *.pyc *~ # switch to regexp syntax. syntax: regexp ^\.pc/


Mercurial's internal web server, hgweb, can serve either a single repository, or a tree of repositories. In the second case, repository paths and global options can be defined using a dedicated configuration file common to hg serve, hgweb.wsgi, hgweb.cgi and hgweb.fcgi. This file uses the same syntax as other Mercurial configuration files but recognizes only the following sections: • web • paths • collections The web options are thoroughly described in hg help config. The paths section maps URL paths to paths of repositories in the filesystem. hgweb will not expose the filesystem directly - only Mercu‐ rial repositories can be published and only according to the configura‐ tion. The left hand side is the path in the URL. Note that hgweb reserves subpaths like rev or file, try using different names for nested reposi‐ tories to avoid confusing effects. The right hand side is the path in the filesystem. If the specified path ends with * or ** the filesystem will be searched recursively for repositories below that point. With * it will not recurse into the repositories it finds (except for .hg/patches). With ** it will also search inside repository working directories and possibly find sub‐ repositories. In this example: [paths] /projects/a = /srv/tmprepos/a /projects/b = c:/repos/b / = /srv/repos/* /user/bob = /home/bob/repos/** • The first two entries make two repositories in different directories appear under the same directory in the web interface • The third entry will publish every Mercurial repository found in /srv/repos/, for instance the repository /srv/repos/quux/ will appear as http://server/quux/ • The fourth entry will publish both http://server/user/bob/quux/ and http://server/user/bob/quux/testsubrepo/ The collections section is deprecated and has been superseded by paths. URLs and Common Arguments URLs under each repository have the form /{command}[/{arguments}] where {command} represents the name of a command or handler and {arguments} represents any number of additional URL parameters to that command. The web server has a default style associated with it. Styles map to a collection of named templates. Each template is used to render a spe‐ cific piece of data, such as a changeset or diff. The style for the current request can be overwritten two ways. First, if {command} contains a hyphen (-), the text before the hyphen defines the style. For example, /atom-log will render the log command handler with the atom style. The second way to set the style is with the style query string argument. For example, /log?style=atom. The hyphenated URL parameter is preferred. Not all templates are available for all styles. Attempting to use a style that doesn't have all templates defined may result in an error rendering the page. Many commands take a {revision} URL parameter. This defines the change‐ set to operate on. This is commonly specified as the short, 12 digit hexadecimal abbreviation for the full 40 character unique revision identifier. However, any value described by hg help revisions typically works. Commands and URLs The following web commands and their URLs are available: /annotate/{revision}/{path} Show changeset information for each line in a file. The ignorews, ignorewsamount, ignorewseol, and ignoreblanklines query string arguments have the same meaning as their [annotate] config equivalents. It uses the hgrc boolean parsing logic to interpret the value. e.g. 0 and false are false and 1 and true are true. If not de‐ fined, the server default settings are used. The fileannotate template is rendered. /archive/{revision}.{format}[/{path}] Obtain an archive of repository content. The content and type of the archive is defined by a URL path parameter. format is the file extension of the archive type to be generated. e.g. zip or tar.bz2. Not all archive types may be allowed by your server configuration. The optional path URL parameter controls content to include in the ar‐ chive. If omitted, every file in the specified revision is present in the archive. If included, only the specified file or contents of the specified directory will be included in the archive. No template is used for this handler. Raw, binary content is generated. /bookmarks Show information about bookmarks. No arguments are accepted. The bookmarks template is rendered. /branches Show information about branches. All known branches are contained in the output, even closed branches. No arguments are accepted. The branches template is rendered. /changelog[/{revision}] Show information about multiple changesets. If the optional revision URL argument is absent, information about all changesets starting at tip will be rendered. If the revision argument is present, changesets will be shown starting from the specified revi‐ sion. If revision is absent, the rev query string argument may be defined. This will perform a search for changesets. The argument for rev can be a single revision, a revision set, or a literal keyword to search for in changeset data (equivalent to hg log -k). The revcount query string argument defines the maximum numbers of changesets to render. For non-searches, the changelog template will be rendered. /changeset[/{revision}] Show information about a single changeset. A URL path argument is the changeset identifier to show. See hg help revisions for possible values. If not defined, the tip changeset will be shown. The changeset template is rendered. Contents of the changesettag, changesetbookmark, filenodelink, filenolink, and the many templates re‐ lated to diffs may all be used to produce the output. /comparison/{revision}/{path} Show a comparison between the old and new versions of a file from changes made on a particular revision. This is similar to the diff handler. However, this form features a split or side-by-side diff rather than a unified diff. The context query string argument can be used to control the lines of context in the diff. The filecomparison template is rendered. /diff/{revision}/{path} Show how a file changed in a particular commit. The filediff template is rendered. This handler is registered under both the /diff and /filediff paths. /diff is used in modern code. /file/{revision}[/{path}] Show information about a directory or file in the repository. Info about the path given as a URL parameter will be rendered. If path is a directory, information about the entries in that directory will be rendered. This form is equivalent to the manifest handler. If path is a file, information about that file will be shown via the filerevision template. If path is not defined, information about the root directory will be rendered. /diff/{revision}/{path} Show how a file changed in a particular commit. The filediff template is rendered. This handler is registered under both the /diff and /filediff paths. /diff is used in modern code. /filelog/{revision}/{path} Show information about the history of a file in the repository. The revcount query string argument can be defined to control the maxi‐ mum number of entries to show. The filelog template will be rendered. /graph[/{revision}] Show information about the graphical topology of the repository. Information rendered by this handler can be used to create visual rep‐ resentations of repository topology. The revision URL parameter controls the starting changeset. If it's ab‐ sent, the default is tip. The revcount query string argument can define the number of changesets to show information for. The graphtop query string argument can specify the starting changeset for producing jsdata variable that is used for rendering graph in Java‐ Script. By default it has the same value as revision. This handler will render the graph template. /help[/{topic}] Render help documentation. This web command is roughly equivalent to hg help. If a topic is de‐ fined, that help topic will be rendered. If not, an index of available help topics will be rendered. The help template will be rendered when requesting help for a topic. helptopics will be rendered for the index of help topics. /log[/{revision}[/{path}]] Show repository or file history. For URLs of the form /log/{revision}, a list of changesets starting at the specified changeset identifier is shown. If {revision} is not de‐ fined, the default is tip. This form is equivalent to the changelog handler. For URLs of the form /log/{revision}/{file}, the history for a specific file will be shown. This form is equivalent to the filelog handler. /manifest[/{revision}[/{path}]] Show information about a directory. If the URL path arguments are omitted, information about the root di‐ rectory for the tip changeset will be shown. Because this handler can only show information for directories, it is recommended to use the file handler instead, as it can handle both di‐ rectories and files. The manifest template will be rendered for this handler. /changeset[/{revision}] Show information about a single changeset. A URL path argument is the changeset identifier to show. See hg help revisions for possible values. If not defined, the tip changeset will be shown. The changeset template is rendered. Contents of the changesettag, changesetbookmark, filenodelink, filenolink, and the many templates re‐ lated to diffs may all be used to produce the output. /shortlog Show basic information about a set of changesets. This accepts the same parameters as the changelog handler. The only difference is the shortlog template will be rendered instead of the changelog template. /summary Show a summary of repository state. Information about the latest changesets, bookmarks, tags, and branches is captured by this handler. The summary template is rendered. /tags Show information about tags. No arguments are accepted. The tags template is rendered.


To access a subtopic, use "hg help internals.{subtopic-name}" bundle2 Bundle2 bundles Bundles cbor CBOR censor Censor changegroups Changegroups config Config Registrar extensions Extension API requirements Repository Requirements revlogs Revision Logs wireprotocol Wire Protocol wireprotocolrpc Wire Protocol RPC wireprotocolv2 Wire Protocol Version 2


To merge files Mercurial uses merge tools. A merge tool combines two different versions of a file into a merged file. Merge tools are given the two files and the greatest common an‐ cestor of the two file versions, so they can determine the changes made on both branches. Merge tools are used both for hg resolve, hg merge, hg update, hg back‐ out and in several extensions. Usually, the merge tool tries to automatically reconcile the files by combining all non-overlapping changes that occurred separately in the two different evolutions of the same initial base file. Furthermore, some interactive merge programs make it easier to manually resolve con‐ flicting merges, either in a graphical way, or by inserting some con‐ flict markers. Mercurial does not include any interactive merge pro‐ grams but relies on external tools for that. Available merge tools External merge tools and their properties are configured in the merge-tools configuration section - see hgrc(5) - but they can often just be named by their executable. A merge tool is generally usable if its executable can be found on the system and if it can handle the merge. The executable is found if it is an absolute or relative executable path or the name of an application in the executable search path. The tool is assumed to be able to handle the merge if it can handle symlinks if the file is a symlink, if it can handle binary files if the file is binary, and if a GUI is available if the tool requires a GUI. There are some internal merge tools which can be used. The internal merge tools are: :dump Creates three versions of the files to merge, containing the contents of local, other and base. These files can then be used to perform a merge manually. If the file to be merged is named a.txt, these files will accordingly be named a.txt.local, a.txt.other and a.txt.base and they will be placed in the same directory as a.txt. This implies premerge. Therefore, files aren't dumped, if pre‐ merge runs successfully. Use :forcedump to forcibly write files out. (actual capabilities: binary, symlink) :fail Rather than attempting to merge files that were modified on both branches, it marks them as unresolved. The resolve command must be used to resolve these conflicts. (actual capabilities: binary, symlink) :forcedump Creates three versions of the files as same as :dump, but omits premerge. (actual capabilities: binary, symlink) :local Uses the local p1() version of files as the merged version. (actual capabilities: binary, symlink) :merge Uses the internal non-interactive simple merge algorithm for merging files. It will fail if there are any conflicts and leave markers in the partially merged file. Markers will have two sec‐ tions, one for each side of merge. :merge-local Like :merge, but resolve all conflicts non-interactively in fa‐ vor of the local p1() changes. :merge-other Like :merge, but resolve all conflicts non-interactively in fa‐ vor of the other p2() changes. :merge3 Uses the internal non-interactive simple merge algorithm for merging files. It will fail if there are any conflicts and leave markers in the partially merged file. Marker will have three sections, one from each side of the merge and one for the base content. :other Uses the other p2() version of files as the merged version. (actual capabilities: binary, symlink) :prompt Asks the user which of the local p1() or the other p2() version to keep as the merged version. (actual capabilities: binary, symlink) :tagmerge Uses the internal tag merge algorithm (experimental). :union Uses the internal non-interactive simple merge algorithm for merging files. It will use both left and right sides for con‐ flict regions. No markers are inserted. Internal tools are always available and do not require a GUI but will by default not handle symlinks or binary files. See next section for detail about "actual capabilities" described above. Choosing a merge tool Mercurial uses these rules when deciding which merge tool to use: 1. If a tool has been specified with the --tool option to merge or re‐ solve, it is used. If it is the name of a tool in the merge-tools configuration, its configuration is used. Otherwise the specified tool must be executable by the shell. 2. If the HGMERGE environment variable is present, its value is used and must be executable by the shell. 3. If the filename of the file to be merged matches any of the patterns in the merge-patterns configuration section, the first usable merge tool corresponding to a matching pattern is used. 4. If ui.merge is set it will be considered next. If the value is not the name of a configured tool, the specified value is used and must be executable by the shell. Otherwise the named tool is used if it is usable. 5. If any usable merge tools are present in the merge-tools configura‐ tion section, the one with the highest priority is used. 6. If a program named hgmerge can be found on the system, it is used - but it will by default not be used for symlinks and binary files. 7. If the file to be merged is not binary and is not a symlink, then internal :merge is used. 8. Otherwise, :prompt is used. For historical reason, Mercurial treats merge tools as below while ex‐ amining rules above. ┌───────────┬────────────────┬────────┬─────────┐ │step │ specified via │ binary │ symlink │ ├───────────┼────────────────┼────────┼─────────┤ │ │ --tool │ o/o │ o/o │ │ 1. │ │ │ │ ├───────────┼────────────────┼────────┼─────────┤ │ │ HGMERGE │ o/o │ o/o │ │ 2. │ │ │ │ ├───────────┼────────────────┼────────┼─────────┤ │ │ merge-patterns │ o/o(*) │ x/?(*) │ │ 3. │ │ │ │ ├───────────┼────────────────┼────────┼─────────┤ │ │ ui.merge │ x/?(*) │ x/?(*) │ │ 4. │ │ │ │ └───────────┴────────────────┴────────┴─────────┘ Each capability column indicates Mercurial behavior for internal/exter‐ nal merge tools at examining each rule. • "o": "assume that a tool has capability" • "x": "assume that a tool does not have capability" • "?": "check actual capability of a tool" If merge.strict-capability-check configuration is true, Mercurial checks capabilities of merge tools strictly in (*) cases above (= each capability column becomes "?/?"). It is false by default for backward compatibility. Note After selecting a merge program, Mercurial will by default at‐ tempt to merge the files using a simple merge algorithm first. Only if it doesn't succeed because of conflicting changes will Mercurial actually execute the merge program. Whether to use the simple merge algorithm first can be controlled by the premerge setting of the merge tool. Premerge is enabled by default unless the file is binary or a symlink. See the merge-tools and ui sections of hgrc(5) for details on the con‐ figuration of merge tools.


add add the specified files on the next commit: hg add [OPTION]... [FILE]... Schedule files to be version controlled and added to the repository. The files will be added to the repository at the next commit. To undo an add before that, see hg forget. If no names are given, add all files to the repository (except files matching .hgignore). Examples: • New (unknown) files are added automatically by hg add: $ ls foo.c $ hg status ? foo.c $ hg add adding foo.c $ hg status A foo.c • Specific files to be added can be specified: $ ls bar.c foo.c $ hg status ? bar.c ? foo.c $ hg add bar.c $ hg status A bar.c ? foo.c Returns 0 if all files are successfully added. Options: -I,--include include names matching the given patterns -X,--exclude exclude names matching the given patterns -S, --subrepos recurse into subrepositories -n, --dry-run do not perform actions, just print output [+] marked option can be specified multiple times addremove add all new files, delete all missing files: hg addremove [OPTION]... [FILE]... Add all new files and remove all missing files from the repository. Unless names are given, new files are ignored if they match any of the patterns in .hgignore. As with add, these changes take effect at the next commit. Use the -s/--similarity option to detect renamed files. This option takes a percentage between 0 (disabled) and 100 (files must be identi‐ cal) as its parameter. With a parameter greater than 0, this compares every removed file with every added file and records those similar enough as renames. Detecting renamed files this way can be expensive. After using this option, hg status -C can be used to check which files were identified as moved or renamed. If not specified, -s/--similarity defaults to 100 and only renames of identical files are detected. Examples: • A number of files (bar.c and foo.c) are new, while foobar.c has been removed (without using hg remove) from the repository: $ ls bar.c foo.c $ hg status ! foobar.c ? bar.c ? foo.c $ hg addremove adding bar.c adding foo.c removing foobar.c $ hg status A bar.c A foo.c R foobar.c • A file foobar.c was moved to foo.c without using hg rename. Af‐ terwards, it was edited slightly: $ ls foo.c $ hg status ! foobar.c ? foo.c $ hg addremove --similarity 90 removing foobar.c adding foo.c recording removal of foobar.c as rename to foo.c (94% similar) $ hg status -C A foo.c foobar.c R foobar.c Returns 0 if all files are successfully added. Options: -s,--similarity guess renamed files by similarity (0<=s<=100) -S, --subrepos recurse into subrepositories -I,--include include names matching the given patterns -X,--exclude exclude names matching the given patterns -n, --dry-run do not perform actions, just print output [+] marked option can be specified multiple times annotate show changeset information by line for each file: hg annotate [-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE... List changes in files, showing the revision id responsible for each line. This command is useful for discovering when a change was made and by whom. If you include --file, --user, or --date, the revision number is sup‐ pressed unless you also include --number. Without the -a/--text option, annotate will avoid processing files it detects as binary. With -a, annotate will annotate the file anyway, al‐ though the results will probably be neither useful nor desirable. Template: The following keywords are supported in addition to the common template keywords and functions. See also hg help templates. lines List of lines with annotation data. path String. Repository-absolute path of the specified file. And each entry of {lines} provides the following sub-keywords in addi‐ tion to {date}, {node}, {rev}, {user}, etc. line String. Line content. lineno Integer. Line number at that revision. path String. Repository-absolute path of the file at that revision. See hg help templates.operators for the list expansion syntax. Returns 0 on success. Options: -r,--rev annotate the specified revision --follow follow copies/renames and list the filename (DEPRECATED) --no-follow don't follow copies and renames -a, --text treat all files as text -u, --user list the author (long with -v) -f, --file list the filename -d, --date list the date (short with -q) -n, --number list the revision number (default) -c, --changeset list the changeset -l, --line-number show line number at the first appearance --skip revision to not display (EXPERIMENTAL) -w, --ignore-all-space ignore white space when comparing lines -b, --ignore-space-change ignore changes in the amount of white space -B, --ignore-blank-lines ignore changes whose lines are all blank -Z, --ignore-space-at-eol ignore changes in whitespace at EOL -I,--include include names matching the given patterns -X,--exclude exclude names matching the given patterns -T,--template