Использование шаблонов
""""""""""""""""""""""
Mercurial позволяет вам настраивать вывод команд с помощью шаблонов.
Вы можете либо передать шаблон,
либо выбрать существующий шаблон-стиль в командной строке с помощью
параметра --template.
Можно настроить вывод для любой команды, похожей на log: log,
outgoing, incoming, tip, parents и heads.
Некоторые встроенные стили поставляются с Mercurial. Их можно посмотреть
с помощью :hg:`log --template list`. Пример использования::
$ hg log -r1.0::1.1 --template changelog
Шаблон - это текст с разметкой, позволяющей выполнять подстановку
переменных::
$ hg log -r1 --template "{node}\n"
b56ce7b07c52de7d5fd79fb89701ea538af65746
Keywords
========
Строки в фигурных скобках называются ключевыми словами. Ключевые
слова доступны в зависимости от контекста, в котором применяется
шаблон. Эти ключевые слова как правило доступны в шаблонах для
команд, похожих на log:
:_fast_rank: the rank of a changeset if cached
The rank of a revision is the size of the sub-graph it defines as a head.
Equivalently, the rank of a revision `r` is the size of the set
`ancestors(r)`, `r` included.
:activebookmark: String. The active bookmark, if it is associated with the changeset.
:author: Alias for ``{user}``
:bisect: Строка. Состояние поиска делением пополам (bisect) набора изменений.
: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
committed.
:branches: List of strings. The name of the branch on which the
changeset was committed. Will be empty if the branch name was
default. (DEPRECATED)
:changessincelatesttag: Integer. All ancestors not in the latest tag.
:children: Список строк. Дочерние ревизии набора изменений.
:currentbookmark: String. The active bookmark, if it is associated with the changeset.
(DEPRECATED)
:date: Информация о дате. Дата фиксации набора изменений.
:desc: Строка. Текст описания набора изменений.
:diffstat: String. Statistics of changes with the following format:
"modified files: +added/-removed lines"
:envvars: A dictionary of environment variables. (EXPERIMENTAL)
:extras: List of dicts with key, value entries of the 'extras'
field of this changeset.
:file_adds: Список строк. Файлы, добавленные этим набором изменений.
: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: Список строк. Файлы, удаленные этим набором изменений.
:file_mods: Список строк. Файлы, измененные этим набором изменений.
: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)
:instabilities: List of strings. Evolution instabilities affecting the changeset.
(EXPERIMENTAL)
: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: Целое число. Самый длинный путь до последней
метки.
:namespaces: Dict of lists. Names attached to this changeset per
namespace.
:negrev: Integer. The repository-local changeset negative revision number,
which counts in the opposite direction.
:node: String. The changeset identification hash, as a 40 hexadecimal
digit string.
:obsolete: String. Whether the changeset is obsolete. (EXPERIMENTAL)
:onelinesummary: String. A one-line summary for the ctx (not including trailing newline).
The default template be overridden in command-templates.oneline-summary.
:p1: Changeset. The changeset's first parent. ``{p1.rev}`` for the revision
number, and ``{p1.node}`` for the identification hash.
:p1node: String. The identification hash of the changeset's first parent,
as a 40 digit hexadecimal string. If the changeset has no parents, all
digits are 0. (DEPRECATED)
:p1rev: Integer. The repository-local revision number of the changeset's
first parent, or -1 if the changeset has no parents. (DEPRECATED)
:p2: Changeset. The changeset's second parent. ``{p2.rev}`` for the revision
number, and ``{p2.node}`` for the identification hash.
:p2node: String. The identification hash of the changeset's second
parent, as a 40 digit hexadecimal string. If the changeset has no second
parent, all digits are 0. (DEPRECATED)
:p2rev: Integer. The repository-local revision number of the changeset's
second parent, or -1 if the changeset has no second parent. (DEPRECATED)
:parents: List of strings. The parents of the changeset in "rev:node"
format. If the changeset has only one "natural" parent (the predecessor
revision) nothing is shown.
:path: String. Repository-absolute path of the current file. (EXPERIMENTAL)
:peerurls: A dictionary of repository locations defined in the [paths] section
of your configuration file.
:phase: Строка. Имя фазы набора изменений.
:phaseidx: Integer. The changeset phase index. (ADVANCED)
:predecessors: Returns the list of the closest visible predecessors. (EXPERIMENTAL)
:reporoot: String. The root directory of the current repository.
:rev: Целое число. Локальный номер ревизии в этом хранилище.
:size: Integer. Size of the current file in bytes. (EXPERIMENTAL)
:status: String. Status code of the current file. (EXPERIMENTAL)
:subrepos: Список строк. Подхранилища, обнавленные в наборе изменений.
:successorssets: Returns a string of sets of successors for a changectx. Format used
is: [ctx1, ctx2], [ctx3] if ctx has been split into ctx1 and ctx2
while also diverged into ctx3. (EXPERIMENTAL)
:succsandmarkers: Returns a list of dict for each final successor of ctx. The dict
contains successors node id in "successors" keys and the list of
obs-markers from ctx to the set of successors in "markers".
(EXPERIMENTAL)
:tags: Список строк. Все метки, ассоциированные с набором изменений.
: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', 'verbose',
or ''.
:whyunstable: List of dicts explaining all instabilities of a changeset.
(EXPERIMENTAL)
Ключевое слово "date" не создает читаемого вывода. Если вы хотите
использовать дату в выходном тексте, можно использовать для этого
фильтр. Фильтры - это функции, которые возвращают строку, основанную
на входной переменной. Убедитесь, что сначала используется фильтр,
преобразующий входные значения в строки, если вы хотите применить
фильтр, принимающий на вход строку, к входной переменной типа список.
Можно также использовать цепочку фильтров для получения желаемого
результата::
$ hg tip --template "{date|isodate}\n"
2008-08-21 18:22 +0000
Filters
=======
Список фильтров (вход, описание):
:addbreaks: Any text. Add an XHTML "<br />" 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
component of the path after splitting by the path separator.
For example, "foo/bar/baz" becomes "baz" and "foo/bar//" becomes "".
:cbor: Any object. Serializes the object to CBOR bytes.
: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 ignored.
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
component of the path after splitting by the path separator.
:domain: Any text. Finds the first string that looks like an email
address, and extracts just the domain component. Example: ``User
<user@example.com>`` becomes ``example.com``.
:email: Any text. Extracts the first string that looks like an email
address. Example: ``User <user@example.com>`` becomes
``user@example.com``.
:emailuser: Произвольный текст. Возвращает пользователя из email-адреса.
:escape: Any text. Replaces the special XML/XHTML characters "&", "<"
and ">" with XML entities, and filters out NUL characters.
:fill68: Произвольный текст. Делает строки не длиннее 68 символов.
:fill76: Произвольный текст. Делает строки не длиннее 76 символов.
:firstline: Произвольный текст. Возвращает первую строку текста.
: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: Произвольный текст. Возвращает '(none)' если входная
строка пуста.
: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.
:reverse: List. Reverses the order of list items.
:revescape: Any text. Escapes all "special" characters, except @.
Forward slashes are escaped twice to prevent web servers from prematurely
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
headers: "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 single-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: Дата. Возвращает дату в виде "2006-09-18".
:slashpath: Any text. Replaces the native path separator with slash.
:splitlines: Произвольный текст. Разбивает текст в список строк.
: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.
Обратите внимание, что фильтр это просто вызов функции, т.е.
``expr|filter`` эквивалентно ``filter(expr)``.
Functions
=========
В дополнение к фильтрам, существует несколько встроенных функций:
:config(section, name[, default]): Returns the requested hgrc config option as a string.
:configbool(section, name[, default]): Returns the requested hgrc config option as a boolean.
:configint(section, name[, default]): Returns the requested hgrc config option as an integer.
:date(date[, fmt]): Format a date. The format string uses the Python strftime format.
The default 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.
:extdata(source): Show a text read from the specified extdata source. (EXPERIMENTAL)
: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.
:formatnode(node): Obtain the preferred form of a changeset hash. (DEPRECATED)
: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
attribute 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 indentchars 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 colorization. In order to receive effects, labels must
have a dot, such as `log.secret` or `branch.active`.
:latesttag([pattern]): The global tags matching the given pattern on the
most recent globally tagged ancestor of this changeset.
If no such tags exist, 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
:obsfatedate(markers): Compute obsfate related information based on markers (EXPERIMENTAL)
:obsfateoperations(markers): Compute obsfate related information based on markers (EXPERIMENTAL)
:obsfateusers(markers): Compute obsfate related information based on markers (EXPERIMENTAL)
:obsfateverb(successors, markers): Compute obsfate related information based on successors (EXPERIMENTAL)
: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 relative 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.
:subsetparents(rev, revset): Look up parents of the rev in the sub graph given by the revset.
: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``
returns 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.
Например,
::
[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
``templates`` section. The syntax used is the general template string syntax.
Например,
::
[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
another 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
========
Примеры шаблонов в командной строке:
- Форматирование списков, например, файлов::
$ hg log -r 0 --template "files:\n{files % ' {file}\n'}"
- Объединить список файлов символами ", "::
$ 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"
- Изменить каждую строку описания ревизии::
$ hg log --template "{splitlines(desc) % '**** {line}\n'}"
- Форматирование даты::
$ hg log -r 0 --template "{date(date, '%Y')}\n"
- Display date in UTC::
$ hg log -r 0 --template "{localdate(date, 'UTC')|date}\n"
- Выводить описание так, чтобы оно занимало 30 символов::
$ hg log -r 0 --template "{fill(desc, 30)}"
- Использование условия для проверки, является ли ветка основной::
$ hg log -r 0 --template "{ifeq(branch, 'default', 'on the main branch',
'on branch {branch}')}\n"
- Добавить перенос строки, если значение не пустое::
$ hg tip --template "{if(author, '{author}\n')}"
- Пометить вывод для использования с расширением color::
$ hg log -r 0 --template "{label('changeset.{phase}', node|short)}\n"
- Инвертировать фильтр первой строки, т.е. все, кроме первой строки::
$ hg log -r 0 --template "{sub(r'^.*\n?\n?', '', desc)}\n"
- Показать содержимое поля 'extra', по одному на строку::
$ 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"
- Пометить рабочую копию родителя собакой '@'::
$ hg log --template "{ifcontains(rev, revset('.'), '@')}\n"
- Show details of parent revisions::
$ hg log --template "{revset('parents(%d)', rev) % '{desc|firstline}\n'}"
- Показывать только описания ревизий, начинающиеся с "шаблона"::
$ hg log --template "{startswith('template', firstline(desc))}\n"
- Напечатать первое слово каждой строки сообщения фиксации::
$ hg log --template "{word(0, desc)}\n"