view mercurial/templatekw.py @ 45892:06b64fabf91c

copies: cache the ancestor checking call when tracing copy A good share of the time spent in this function is spent doing ancestors checking. To avoid spending time in duplicated call, we cache the result of calls. In the slower case, this provide a quite significant performance boost. Below are the result for a set of selected pairs (many of them pathological): (And further down is another table that summarize the current state of filelog based vs changeset base copy tracing) The benchmark have been configured to be killed after 6 minutes of runtime, which mean that any detect slower than 2 minutes will be marked as "killed". This drop some useful information about how much slower these case are? but also prevent 99% of the benchmark time to be spent on case that can be labelled "very slow" anyway. Repo Case Source-Rev Dest-Rev Old-Time New-Time Difference Factor ------------------------------------------------------------------------------------------------------------------------------------ mercurial x_revs_x_added_0_copies ad6b123de1c7 39cfcef4f463 : 0.000044 s, 0.000044 s, +0.000000 s, ? 1.0000 mercurial x_revs_x_added_x_copies 2b1c78674230 0c1d10351869 : 0.000138 s, 0.000138 s, +0.000000 s, ? 1.0000 mercurial x000_revs_x000_added_x_copies 81f8ff2a9bf2 dd3267698d84 : 0.005067 s, 0.005052 s, -0.000015 s, ? 0.9970 pypy x_revs_x_added_0_copies aed021ee8ae8 099ed31b181b : 0.000218 s, 0.000219 s, +0.000001 s, ? 1.0046 pypy x_revs_x000_added_0_copies 4aa4e1f8e19a 359343b9ac0e : 0.000053 s, 0.000055 s, +0.000002 s, ? 1.0377 pypy x_revs_x_added_x_copies ac52eb7bbbb0 72e022663155 : 0.000125 s, 0.000128 s, +0.000003 s, ? 1.0240 pypy x_revs_x00_added_x_copies c3b14617fbd7 ace7255d9a26 : 0.001098 s, 0.001089 s, -0.000009 s, ? 0.9918 pypy x_revs_x000_added_x000_copies df6f7a526b60 a83dc6a2d56f : 0.017546 s, 0.017407 s, -0.000139 s, ? 0.9921 pypy x000_revs_xx00_added_0_copies 89a76aede314 2f22446ff07e : 0.096723 s, 0.094175 s, -0.002548 s, ? 0.9737 pypy x000_revs_x000_added_x_copies 8a3b5bfd266e 2c68e87c3efe : 0.271796 s, 0.238009 s, -0.033787 s, ? 0.8757 pypy x000_revs_x000_added_x000_copies 89a76aede314 7b3dda341c84 : 0.128602 s, 0.125876 s, -0.002726 s, ? 0.9788 pypy x0000_revs_x_added_0_copies d1defd0dc478 c9cb1334cc78 : 7.086742 s, 3.581556 s, -3.505186 s, ? 0.5054 pypy x0000_revs_xx000_added_0_copies bf2c629d0071 4ffed77c095c : 0.016634 s, 0.016721 s, +0.000087 s, ? 1.0052 pypy x0000_revs_xx000_added_x000_copies 08ea3258278e d9fa043f30c0 : 0.254225 s, 0.242367 s, -0.011858 s, ? 0.9534 netbeans x_revs_x_added_0_copies fb0955ffcbcd a01e9239f9e7 : 0.000166 s, 0.000165 s, -0.000001 s, ? 0.9940 netbeans x_revs_x000_added_0_copies 6f360122949f 20eb231cc7d0 : 0.000118 s, 0.000114 s, -0.000004 s, ? 0.9661 netbeans x_revs_x_added_x_copies 1ada3faf6fb6 5a39d12eecf4 : 0.000296 s, 0.000296 s, +0.000000 s, ? 1.0000 netbeans x_revs_x00_added_x_copies 35be93ba1e2c 9eec5e90c05f : 0.001137 s, 0.001124 s, -0.000013 s, ? 0.9886 netbeans x000_revs_xx00_added_0_copies eac3045b4fdd 51d4ae7f1290 : 0.014133 s, 0.013060 s, -0.001073 s, ? 0.9241 netbeans x000_revs_x000_added_x_copies e2063d266acd 6081d72689dc : 0.016988 s, 0.017112 s, +0.000124 s, ? 1.0073 netbeans x000_revs_x000_added_x000_copies ff453e9fee32 411350406ec2 : 0.676361 s, 0.660350 s, -0.016011 s, ? 0.9763 netbeans x0000_revs_xx000_added_x000_copies 588c2d1ced70 1aad62e59ddd : 12.515149 s, 10.032499 s, -2.482650 s, ? 0.8016 mozilla-central x_revs_x_added_0_copies 3697f962bb7b 7015fcdd43a2 : 0.000186 s, 0.000189 s, +0.000003 s, ? 1.0161 mozilla-central x_revs_x000_added_0_copies dd390860c6c9 40d0c5bed75d : 0.000459 s, 0.000462 s, +0.000003 s, ? 1.0065 mozilla-central x_revs_x_added_x_copies 8d198483ae3b 14207ffc2b2f : 0.000273 s, 0.000270 s, -0.000003 s, ? 0.9890 mozilla-central x_revs_x00_added_x_copies 98cbc58cc6bc 446a150332c3 : 0.001503 s, 0.001474 s, -0.000029 s, ? 0.9807 mozilla-central x_revs_x000_added_x000_copies 3c684b4b8f68 0a5e72d1b479 : 0.004862 s, 0.004806 s, -0.000056 s, ? 0.9885 mozilla-central x_revs_x0000_added_x0000_copies effb563bb7e5 c07a39dc4e80 : 0.088291 s, 0.085150 s, -0.003141 s, ? 0.9644 mozilla-central x000_revs_xx00_added_0_copies 6100d773079a 04a55431795e : 0.007113 s, 0.007064 s, -0.000049 s, ? 0.9931 mozilla-central x000_revs_x000_added_x_copies 9f17a6fc04f9 2d37b966abed : 0.004687 s, 0.004741 s, +0.000054 s, ? 1.0115 mozilla-central x000_revs_x000_added_x000_copies 7c97034feb78 4407bd0c6330 : 0.198710 s, 0.190133 s, -0.008577 s, ? 0.9568 mozilla-central x0000_revs_xx000_added_0_copies 9eec5917337d 67118cc6dcad : 0.036068 s, 0.035651 s, -0.000417 s, ? 0.9884 mozilla-central x0000_revs_xx000_added_x000_copies f78c615a656c 96a38b690156 : 0.465362 s, 0.440694 s, -0.024668 s, ? 0.9470 mozilla-central x00000_revs_x0000_added_x0000_copies 6832ae71433c 4c222a1d9a00 : 24.519684 s, 18.454163 s, -6.065521 s, ? 0.7526 mozilla-central x00000_revs_x00000_added_x000_copies 76caed42cf7c 1daa622bbe42 : 42.711897 s, 31.562719 s, -11.149178 s, ? 0.7390 mozilla-try x_revs_x_added_0_copies aaf6dde0deb8 9790f499805a : 0.001201 s, 0.001189 s, -0.000012 s, ? 0.9900 mozilla-try x_revs_x000_added_0_copies d8d0222927b4 5bb8ce8c7450 : 0.001216 s, 0.001204 s, -0.000012 s, ? 0.9901 mozilla-try x_revs_x_added_x_copies 092fcca11bdb 936255a0384a : 0.000595 s, 0.000586 s, -0.000009 s, ? 0.9849 mozilla-try x_revs_x00_added_x_copies b53d2fadbdb5 017afae788ec : 0.001856 s, 0.001845 s, -0.000011 s, ? 0.9941 mozilla-try x_revs_x000_added_x000_copies 20408ad61ce5 6f0ee96e21ad : 0.064936 s, 0.063822 s, -0.001114 s, ? 0.9828 mozilla-try x_revs_x0000_added_x0000_copies effb563bb7e5 c07a39dc4e80 : 0.090601 s, 0.088038 s, -0.002563 s, ? 0.9717 mozilla-try x000_revs_xx00_added_0_copies 6100d773079a 04a55431795e : 0.007510 s, 0.007389 s, -0.000121 s, ? 0.9839 mozilla-try x000_revs_x000_added_x_copies 9f17a6fc04f9 2d37b966abed : 0.004911 s, 0.004868 s, -0.000043 s, ? 0.9912 mozilla-try x000_revs_x000_added_x000_copies 1346fd0130e4 4c65cbdabc1f : 0.233231 s, 0.222450 s, -0.010781 s, ? 0.9538 mozilla-try x0000_revs_x_added_0_copies 63519bfd42ee a36a2a865d92 : 0.419989 s, 0.370675 s, -0.049314 s, ? 0.8826 mozilla-try x0000_revs_x_added_x_copies 9fe69ff0762d bcabf2a78927 : 0.401521 s, 0.358020 s, -0.043501 s, ? 0.8917 mozilla-try x0000_revs_xx000_added_x_copies 156f6e2674f2 4d0f2c178e66 : 0.179555 s, 0.145235 s, -0.034320 s, ? 0.8089 mozilla-try x0000_revs_xx000_added_0_copies 9eec5917337d 67118cc6dcad : 0.038004 s, 0.037606 s, -0.000398 s, ? 0.9895 mozilla-try x0000_revs_xx000_added_x000_copies 89294cd501d9 7ccb2fc7ccb5 : 52.838482 s, 7.382439 s, -45.456043 s, ? 0.1397 mozilla-try x0000_revs_x0000_added_x0000_copies e928c65095ed e951f4ad123a : 8.705874 s, 7.273506 s, -1.432368 s, ? 0.8355 mozilla-try x00000_revs_x00000_added_0_copies dc8a3ca7010e d16fde900c9c : 1.126708 s, 1.074593 s, -0.052115 s, ? 0.9537 mozilla-try x00000_revs_x0000_added_x0000_copies 8d3fafa80d4b eb884023b810 : 83.854020 s, 27.746195 s, -56.107825 s, ? 0.3309 Below is a table comparing the runtime of the current "filelog centric" algorithm, with the "changeset centric" one, we just modified. The changeset centric algorithm is a significant win in many scenario, but they are still various cases where it is quite slower. When many revision has to be considered the cost of retrieving the copy information, creating new dictionaries, merging dictionaries and checking if revision are ancestors of each other can slow things down. The rest of this series, will introduce a rust version of the copy tracing code to deal with most of theses issues. Repo Case Source-Rev Dest-Rev filelog sidedata Difference Factor --------------------------------------------------------------------------------------------------------------------------------------- mercurial x_revs_x_added_0_copies ad6b123de1c7 39cfcef4f463 : 0.000914 s, 0.000044 s, - 0.000870 s, ? 0.048140 mercurial x_revs_x_added_x_copies 2b1c78674230 0c1d10351869 : 0.001812 s, 0.000138 s, - 0.001674 s, ? 0.076159 mercurial x000_revs_x000_added_x_copies 81f8ff2a9bf2 dd3267698d84 : 0.017954 s, 0.005052 s, - 0.012902 s, ? 0.281386 pypy x_revs_x_added_0_copies aed021ee8ae8 099ed31b181b : 0.001509 s, 0.000219 s, - 0.001290 s, ? 0.145129 pypy x_revs_x000_added_0_copies 4aa4e1f8e19a 359343b9ac0e : 0.206881 s, 0.000055 s, - 0.206826 s, ? 0.000266 pypy x_revs_x_added_x_copies ac52eb7bbbb0 72e022663155 : 0.016951 s, 0.000128 s, - 0.016823 s, ? 0.007551 pypy x_revs_x00_added_x_copies c3b14617fbd7 ace7255d9a26 : 0.019096 s, 0.001089 s, - 0.018007 s, ? 0.057028 pypy x_revs_x000_added_x000_copies df6f7a526b60 a83dc6a2d56f : 0.762506 s, 0.017407 s, - 0.745099 s, ? 0.022829 pypy x000_revs_xx00_added_0_copies 89a76aede314 2f22446ff07e : 1.179211 s, 0.094175 s, - 1.085036 s, ? 0.079863 pypy x000_revs_x000_added_x_copies 8a3b5bfd266e 2c68e87c3efe : 1.249058 s, 0.238009 s, - 1.011049 s, ? 0.190551 pypy x000_revs_x000_added_x000_copies 89a76aede314 7b3dda341c84 : 1.614107 s, 0.125876 s, - 1.488231 s, ? 0.077985 pypy x0000_revs_x_added_0_copies d1defd0dc478 c9cb1334cc78 : 0.001064 s, 3.581556 s, + 3.580492 s, ? 3366.124060 pypy x0000_revs_xx000_added_0_copies bf2c629d0071 4ffed77c095c : 1.061275 s, 0.016721 s, - 1.044554 s, ? 0.015756 pypy x0000_revs_xx000_added_x000_copies 08ea3258278e d9fa043f30c0 : 1.341119 s, 0.242367 s, - 1.098752 s, ? 0.180720 netbeans x_revs_x_added_0_copies fb0955ffcbcd a01e9239f9e7 : 0.027803 s, 0.000165 s, - 0.027638 s, ? 0.005935 netbeans x_revs_x000_added_0_copies 6f360122949f 20eb231cc7d0 : 0.130014 s, 0.000114 s, - 0.129900 s, ? 0.000877 netbeans x_revs_x_added_x_copies 1ada3faf6fb6 5a39d12eecf4 : 0.024990 s, 0.000296 s, - 0.024694 s, ? 0.011845 netbeans x_revs_x00_added_x_copies 35be93ba1e2c 9eec5e90c05f : 0.052201 s, 0.001124 s, - 0.051077 s, ? 0.021532 netbeans x000_revs_xx00_added_0_copies eac3045b4fdd 51d4ae7f1290 : 0.037642 s, 0.013060 s, - 0.024582 s, ? 0.346953 netbeans x000_revs_x000_added_x_copies e2063d266acd 6081d72689dc : 0.197086 s, 0.017112 s, - 0.179974 s, ? 0.086825 netbeans x000_revs_x000_added_x000_copies ff453e9fee32 411350406ec2 : 0.935148 s, 0.660350 s, - 0.274798 s, ? 0.706145 netbeans x0000_revs_xx000_added_x000_copies 588c2d1ced70 1aad62e59ddd : 3.920674 s, 10.032499 s, + 6.111825 s, ? 2.558871 mozilla-central x_revs_x_added_0_copies 3697f962bb7b 7015fcdd43a2 : 0.024232 s, 0.000189 s, - 0.024043 s, ? 0.007800 mozilla-central x_revs_x000_added_0_copies dd390860c6c9 40d0c5bed75d : 0.141483 s, 0.000462 s, - 0.141021 s, ? 0.003265 mozilla-central x_revs_x_added_x_copies 8d198483ae3b 14207ffc2b2f : 0.025775 s, 0.000270 s, - 0.025505 s, ? 0.010475 mozilla-central x_revs_x00_added_x_copies 98cbc58cc6bc 446a150332c3 : 0.084922 s, 0.001474 s, - 0.083448 s, ? 0.017357 mozilla-central x_revs_x000_added_x000_copies 3c684b4b8f68 0a5e72d1b479 : 0.194784 s, 0.004806 s, - 0.189978 s, ? 0.024673 mozilla-central x_revs_x0000_added_x0000_copies effb563bb7e5 c07a39dc4e80 : 2.161103 s, 0.085150 s, - 2.075953 s, ? 0.039401 mozilla-central x000_revs_xx00_added_0_copies 6100d773079a 04a55431795e : 0.089347 s, 0.007064 s, - 0.082283 s, ? 0.079063 mozilla-central x000_revs_x000_added_x_copies 9f17a6fc04f9 2d37b966abed : 0.732171 s, 0.004741 s, - 0.727430 s, ? 0.006475 mozilla-central x000_revs_x000_added_x000_copies 7c97034feb78 4407bd0c6330 : 1.157287 s, 0.190133 s, - 0.967154 s, ? 0.164292 mozilla-central x0000_revs_xx000_added_0_copies 9eec5917337d 67118cc6dcad : 6.726568 s, 0.035651 s, - 6.690917 s, ? 0.005300 mozilla-central x0000_revs_xx000_added_x000_copies f78c615a656c 96a38b690156 : 3.266229 s, 0.440694 s, - 2.825535 s, ? 0.134924 mozilla-central x00000_revs_x0000_added_x0000_copies 6832ae71433c 4c222a1d9a00 : 15.860534 s, 18.454163 s, + 2.593629 s, ? 1.163527 mozilla-central x00000_revs_x00000_added_x000_copies 76caed42cf7c 1daa622bbe42 : 20.450475 s, 31.562719 s, +11.112244 s, ? 1.543373 mozilla-try x_revs_x_added_0_copies aaf6dde0deb8 9790f499805a : 0.080442 s, 0.001189 s, - 0.079253 s, ? 0.014781 mozilla-try x_revs_x000_added_0_copies d8d0222927b4 5bb8ce8c7450 : 0.497672 s, 0.001204 s, - 0.496468 s, ? 0.002419 mozilla-try x_revs_x_added_x_copies 092fcca11bdb 936255a0384a : 0.021183 s, 0.000586 s, - 0.020597 s, ? 0.027664 mozilla-try x_revs_x00_added_x_copies b53d2fadbdb5 017afae788ec : 0.230991 s, 0.001845 s, - 0.229146 s, ? 0.007987 mozilla-try x_revs_x000_added_x000_copies 20408ad61ce5 6f0ee96e21ad : 1.118461 s, 0.063822 s, - 1.054639 s, ? 0.057062 mozilla-try x_revs_x0000_added_x0000_copies effb563bb7e5 c07a39dc4e80 : 2.206083 s, 0.088038 s, - 2.118045 s, ? 0.039907 mozilla-try x000_revs_xx00_added_0_copies 6100d773079a 04a55431795e : 0.089404 s, 0.007389 s, - 0.082015 s, ? 0.082647 mozilla-try x000_revs_x000_added_x_copies 9f17a6fc04f9 2d37b966abed : 0.733043 s, 0.004868 s, - 0.728175 s, ? 0.006641 mozilla-try x000_revs_x000_added_x000_copies 1346fd0130e4 4c65cbdabc1f : 1.163367 s, 0.222450 s, - 0.940917 s, ? 0.191212 mozilla-try x0000_revs_x_added_0_copies 63519bfd42ee a36a2a865d92 : 0.085456 s, 0.370675 s, + 0.285219 s, ? 4.337612 mozilla-try x0000_revs_x_added_x_copies 9fe69ff0762d bcabf2a78927 : 0.083601 s, 0.358020 s, + 0.274419 s, ? 4.282485 mozilla-try x0000_revs_xx000_added_x_copies 156f6e2674f2 4d0f2c178e66 : 7.366614 s, 0.145235 s, - 7.221379 s, ? 0.019715 mozilla-try x0000_revs_xx000_added_0_copies 9eec5917337d 67118cc6dcad : 6.664464 s, 0.037606 s, - 6.626858 s, ? 0.005643 mozilla-try x0000_revs_xx000_added_x000_copies 89294cd501d9 7ccb2fc7ccb5 : 7.467836 s, 7.382439 s, - 0.085397 s, ? 0.988565 mozilla-try x0000_revs_x0000_added_x0000_copies e928c65095ed e951f4ad123a : 9.801294 s, 7.273506 s, - 2.527788 s, ? 0.742097 mozilla-try x00000_revs_x_added_0_copies 6a320851d377 1ebb79acd503 : 0.091886 s, killed mozilla-try x00000_revs_x00000_added_0_copies dc8a3ca7010e d16fde900c9c : 26.491140 s, 1.074593 s, -25.416547 s, ? 0.040564 mozilla-try x00000_revs_x_added_x_copies 5173c4b6f97c 95d83ee7242d : 0.092863 s, killed mozilla-try x00000_revs_x000_added_x_copies 9126823d0e9c ca82787bb23c : 0.226823 s, killed mozilla-try x00000_revs_x0000_added_x0000_copies 8d3fafa80d4b eb884023b810 : 18.914630 s, 27.746195 s, + 8.831565 s, ? 1.466917 mozilla-try x00000_revs_x00000_added_x0000_copies 1b661134e2ca 1ae03d022d6d : 21.198903 s, killed mozilla-try x00000_revs_x00000_added_x000_copies 9b2a99adc05e 8e29777b48e6 : 24.952268 s, killed Differential Revision: https://phab.mercurial-scm.org/D9296
author Pierre-Yves David <pierre-yves.david@octobus.net>
date Mon, 02 Nov 2020 11:03:56 +0100
parents f67741e8264b
children 89a2afe31e82
line wrap: on
line source

# templatekw.py - common changeset template keywords
#
# Copyright 2005-2009 Matt Mackall <mpm@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.

from __future__ import absolute_import

from .i18n import _
from .node import (
    hex,
    nullid,
    wdirid,
    wdirrev,
)

from . import (
    diffutil,
    encoding,
    error,
    hbisect,
    i18n,
    obsutil,
    patch,
    pycompat,
    registrar,
    scmutil,
    templateutil,
    util,
)
from .utils import stringutil

_hybrid = templateutil.hybrid
hybriddict = templateutil.hybriddict
hybridlist = templateutil.hybridlist
compatdict = templateutil.compatdict
compatlist = templateutil.compatlist
_showcompatlist = templateutil._showcompatlist


def getlatesttags(context, mapping, pattern=None):
    '''return date, distance and name for the latest tag of rev'''
    repo = context.resource(mapping, b'repo')
    ctx = context.resource(mapping, b'ctx')
    cache = context.resource(mapping, b'cache')

    cachename = b'latesttags'
    if pattern is not None:
        cachename += b'-' + pattern
        match = stringutil.stringmatcher(pattern)[2]
    else:
        match = util.always

    if cachename not in cache:
        # Cache mapping from rev to a tuple with tag date, tag
        # distance and tag name
        cache[cachename] = {-1: (0, 0, [b'null'])}
    latesttags = cache[cachename]

    rev = ctx.rev()
    todo = [rev]
    while todo:
        rev = todo.pop()
        if rev in latesttags:
            continue
        ctx = repo[rev]
        tags = [
            t
            for t in ctx.tags()
            if (repo.tagtype(t) and repo.tagtype(t) != b'local' and match(t))
        ]
        if tags:
            latesttags[rev] = ctx.date()[0], 0, [t for t in sorted(tags)]
            continue
        try:
            ptags = [latesttags[p.rev()] for p in ctx.parents()]
            if len(ptags) > 1:
                if ptags[0][2] == ptags[1][2]:
                    # The tuples are laid out so the right one can be found by
                    # comparison in this case.
                    pdate, pdist, ptag = max(ptags)
                else:

                    def key(x):
                        tag = x[2][0]
                        if ctx.rev() is None:
                            # only() doesn't support wdir
                            prevs = [c.rev() for c in ctx.parents()]
                            changes = repo.revs(b'only(%ld, %s)', prevs, tag)
                            changessincetag = len(changes) + 1
                        else:
                            changes = repo.revs(b'only(%d, %s)', ctx.rev(), tag)
                            changessincetag = len(changes)
                        # Smallest number of changes since tag wins. Date is
                        # used as tiebreaker.
                        return [-changessincetag, x[0]]

                    pdate, pdist, ptag = max(ptags, key=key)
            else:
                pdate, pdist, ptag = ptags[0]
        except KeyError:
            # Cache miss - recurse
            todo.append(rev)
            todo.extend(p.rev() for p in ctx.parents())
            continue
        latesttags[rev] = pdate, pdist + 1, ptag
    return latesttags[rev]


def getlogcolumns():
    """Return a dict of log column labels"""
    _ = pycompat.identity  # temporarily disable gettext
    # i18n: column positioning for "hg log"
    columns = _(
        b'bookmark:    %s\n'
        b'branch:      %s\n'
        b'changeset:   %s\n'
        b'copies:      %s\n'
        b'date:        %s\n'
        b'extra:       %s=%s\n'
        b'files+:      %s\n'
        b'files-:      %s\n'
        b'files:       %s\n'
        b'instability: %s\n'
        b'manifest:    %s\n'
        b'obsolete:    %s\n'
        b'parent:      %s\n'
        b'phase:       %s\n'
        b'summary:     %s\n'
        b'tag:         %s\n'
        b'user:        %s\n'
    )
    return dict(
        zip(
            [s.split(b':', 1)[0] for s in columns.splitlines()],
            i18n._(columns).splitlines(True),
        )
    )


# basic internal templates
_changeidtmpl = b'{rev}:{node|formatnode}'

# default templates internally used for rendering of lists
defaulttempl = {
    b'parent': _changeidtmpl + b' ',
    b'manifest': _changeidtmpl,
    b'file_copy': b'{name} ({source})',
    b'envvar': b'{key}={value}',
    b'extra': b'{key}={value|stringescape}',
}
# filecopy is preserved for compatibility reasons
defaulttempl[b'filecopy'] = defaulttempl[b'file_copy']

# keywords are callables (see registrar.templatekeyword for details)
keywords = {}
templatekeyword = registrar.templatekeyword(keywords)


@templatekeyword(b'author', requires={b'ctx'})
def showauthor(context, mapping):
    """Alias for ``{user}``"""
    return showuser(context, mapping)


@templatekeyword(b'bisect', requires={b'repo', b'ctx'})
def showbisect(context, mapping):
    """String. The changeset bisection status."""
    repo = context.resource(mapping, b'repo')
    ctx = context.resource(mapping, b'ctx')
    return hbisect.label(repo, ctx.node())


@templatekeyword(b'branch', requires={b'ctx'})
def showbranch(context, mapping):
    """String. The name of the branch on which the changeset was
    committed.
    """
    ctx = context.resource(mapping, b'ctx')
    return ctx.branch()


@templatekeyword(b'branches', requires={b'ctx'})
def showbranches(context, mapping):
    """List of strings. The name of the branch on which the
    changeset was committed. Will be empty if the branch name was
    default. (DEPRECATED)
    """
    ctx = context.resource(mapping, b'ctx')
    branch = ctx.branch()
    if branch != b'default':
        return compatlist(
            context, mapping, b'branch', [branch], plural=b'branches'
        )
    return compatlist(context, mapping, b'branch', [], plural=b'branches')


@templatekeyword(b'bookmarks', requires={b'repo', b'ctx'})
def showbookmarks(context, mapping):
    """List of strings. Any bookmarks associated with the
    changeset. Also sets 'active', the name of the active bookmark.
    """
    repo = context.resource(mapping, b'repo')
    ctx = context.resource(mapping, b'ctx')
    bookmarks = ctx.bookmarks()
    active = repo._activebookmark
    makemap = lambda v: {b'bookmark': v, b'active': active, b'current': active}
    f = _showcompatlist(context, mapping, b'bookmark', bookmarks)
    return _hybrid(f, bookmarks, makemap, pycompat.identity)


@templatekeyword(b'children', requires={b'ctx'})
def showchildren(context, mapping):
    """List of strings. The children of the changeset."""
    ctx = context.resource(mapping, b'ctx')
    childrevs = [b'%d:%s' % (cctx.rev(), cctx) for cctx in ctx.children()]
    return compatlist(
        context, mapping, b'children', childrevs, element=b'child'
    )


# Deprecated, but kept alive for help generation a purpose.
@templatekeyword(b'currentbookmark', requires={b'repo', b'ctx'})
def showcurrentbookmark(context, mapping):
    """String. The active bookmark, if it is associated with the changeset.
    (DEPRECATED)"""
    return showactivebookmark(context, mapping)


@templatekeyword(b'activebookmark', requires={b'repo', b'ctx'})
def showactivebookmark(context, mapping):
    """String. The active bookmark, if it is associated with the changeset."""
    repo = context.resource(mapping, b'repo')
    ctx = context.resource(mapping, b'ctx')
    active = repo._activebookmark
    if active and active in ctx.bookmarks():
        return active
    return b''


@templatekeyword(b'date', requires={b'ctx'})
def showdate(context, mapping):
    """Date information. The date when the changeset was committed."""
    ctx = context.resource(mapping, b'ctx')
    # the default string format is '<float(unixtime)><tzoffset>' because
    # python-hglib splits date at decimal separator.
    return templateutil.date(ctx.date(), showfmt=b'%d.0%d')


@templatekeyword(b'desc', requires={b'ctx'})
def showdescription(context, mapping):
    """String. The text of the changeset description."""
    ctx = context.resource(mapping, b'ctx')
    s = ctx.description()
    if isinstance(s, encoding.localstr):
        # try hard to preserve utf-8 bytes
        return encoding.tolocal(encoding.fromlocal(s).strip())
    elif isinstance(s, encoding.safelocalstr):
        return encoding.safelocalstr(s.strip())
    else:
        return s.strip()


@templatekeyword(b'diffstat', requires={b'ui', b'ctx'})
def showdiffstat(context, mapping):
    """String. Statistics of changes with the following format:
    "modified files: +added/-removed lines"
    """
    ui = context.resource(mapping, b'ui')
    ctx = context.resource(mapping, b'ctx')
    diffopts = diffutil.diffallopts(ui, {b'noprefix': False})
    diff = ctx.diff(opts=diffopts)
    stats = patch.diffstatdata(util.iterlines(diff))
    maxname, maxtotal, adds, removes, binary = patch.diffstatsum(stats)
    return b'%d: +%d/-%d' % (len(stats), adds, removes)


@templatekeyword(b'envvars', requires={b'ui'})
def showenvvars(context, mapping):
    """A dictionary of environment variables. (EXPERIMENTAL)"""
    ui = context.resource(mapping, b'ui')
    env = ui.exportableenviron()
    env = util.sortdict((k, env[k]) for k in sorted(env))
    return compatdict(context, mapping, b'envvar', env, plural=b'envvars')


@templatekeyword(b'extras', requires={b'ctx'})
def showextras(context, mapping):
    """List of dicts with key, value entries of the 'extras'
    field of this changeset."""
    ctx = context.resource(mapping, b'ctx')
    extras = ctx.extra()
    extras = util.sortdict((k, extras[k]) for k in sorted(extras))
    makemap = lambda k: {b'key': k, b'value': extras[k]}
    c = [makemap(k) for k in extras]
    f = _showcompatlist(context, mapping, b'extra', c, plural=b'extras')
    return _hybrid(
        f,
        extras,
        makemap,
        lambda k: b'%s=%s' % (k, stringutil.escapestr(extras[k])),
    )


def _getfilestatus(context, mapping, listall=False):
    ctx = context.resource(mapping, b'ctx')
    revcache = context.resource(mapping, b'revcache')
    if b'filestatus' not in revcache or revcache[b'filestatusall'] < listall:
        stat = ctx.p1().status(
            ctx, listignored=listall, listclean=listall, listunknown=listall
        )
        revcache[b'filestatus'] = stat
        revcache[b'filestatusall'] = listall
    return revcache[b'filestatus']


def _getfilestatusmap(context, mapping, listall=False):
    revcache = context.resource(mapping, b'revcache')
    if b'filestatusmap' not in revcache or revcache[b'filestatusall'] < listall:
        stat = _getfilestatus(context, mapping, listall=listall)
        revcache[b'filestatusmap'] = statmap = {}
        for char, files in zip(pycompat.iterbytestr(b'MAR!?IC'), stat):
            statmap.update((f, char) for f in files)
    return revcache[b'filestatusmap']  # {path: statchar}


@templatekeyword(
    b'file_copies', requires={b'repo', b'ctx', b'cache', b'revcache'}
)
def showfilecopies(context, mapping):
    """List of strings. Files copied in this changeset with
    their sources.
    """
    repo = context.resource(mapping, b'repo')
    ctx = context.resource(mapping, b'ctx')
    cache = context.resource(mapping, b'cache')
    copies = context.resource(mapping, b'revcache').get(b'copies')
    if copies is None:
        if b'getcopies' not in cache:
            cache[b'getcopies'] = scmutil.getcopiesfn(repo)
        getcopies = cache[b'getcopies']
        copies = getcopies(ctx)
    return templateutil.compatfilecopiesdict(
        context, mapping, b'file_copy', copies
    )


# showfilecopiesswitch() displays file copies only if copy records are
# provided before calling the templater, usually with a --copies
# command line switch.
@templatekeyword(b'file_copies_switch', requires={b'revcache'})
def showfilecopiesswitch(context, mapping):
    """List of strings. Like "file_copies" but displayed
    only if the --copied switch is set.
    """
    copies = context.resource(mapping, b'revcache').get(b'copies') or []
    return templateutil.compatfilecopiesdict(
        context, mapping, b'file_copy', copies
    )


@templatekeyword(b'file_adds', requires={b'ctx', b'revcache'})
def showfileadds(context, mapping):
    """List of strings. Files added by this changeset."""
    ctx = context.resource(mapping, b'ctx')
    return templateutil.compatfileslist(
        context, mapping, b'file_add', ctx.filesadded()
    )


@templatekeyword(b'file_dels', requires={b'ctx', b'revcache'})
def showfiledels(context, mapping):
    """List of strings. Files removed by this changeset."""
    ctx = context.resource(mapping, b'ctx')
    return templateutil.compatfileslist(
        context, mapping, b'file_del', ctx.filesremoved()
    )


@templatekeyword(b'file_mods', requires={b'ctx', b'revcache'})
def showfilemods(context, mapping):
    """List of strings. Files modified by this changeset."""
    ctx = context.resource(mapping, b'ctx')
    return templateutil.compatfileslist(
        context, mapping, b'file_mod', ctx.filesmodified()
    )


@templatekeyword(b'files', requires={b'ctx'})
def showfiles(context, mapping):
    """List of strings. All files modified, added, or removed by this
    changeset.
    """
    ctx = context.resource(mapping, b'ctx')
    return templateutil.compatfileslist(context, mapping, b'file', ctx.files())


@templatekeyword(b'graphnode', requires={b'repo', b'ctx', b'cache'})
def showgraphnode(context, mapping):
    """String. The character representing the changeset node in an ASCII
    revision graph."""
    repo = context.resource(mapping, b'repo')
    ctx = context.resource(mapping, b'ctx')
    cache = context.resource(mapping, b'cache')
    return getgraphnode(repo, ctx, cache)


def getgraphnode(repo, ctx, cache):
    return getgraphnodecurrent(repo, ctx, cache) or getgraphnodesymbol(ctx)


def getgraphnodecurrent(repo, ctx, cache):
    wpnodes = repo.dirstate.parents()
    if wpnodes[1] == nullid:
        wpnodes = wpnodes[:1]
    if ctx.node() in wpnodes:
        return b'@'
    else:
        merge_nodes = cache.get(b'merge_nodes')
        if merge_nodes is None:
            from . import mergestate as mergestatemod

            mergestate = mergestatemod.mergestate.read(repo)
            if mergestate.unresolvedcount():
                merge_nodes = (mergestate.local, mergestate.other)
            else:
                merge_nodes = ()
            cache[b'merge_nodes'] = merge_nodes

        if ctx.node() in merge_nodes:
            return b'%'
        return b''


def getgraphnodesymbol(ctx):
    if ctx.obsolete():
        return b'x'
    elif ctx.isunstable():
        return b'*'
    elif ctx.closesbranch():
        return b'_'
    else:
        return b'o'


@templatekeyword(b'graphwidth', requires=())
def showgraphwidth(context, mapping):
    """Integer. The width of the graph drawn by 'log --graph' or zero."""
    # just hosts documentation; should be overridden by template mapping
    return 0


@templatekeyword(b'index', requires=())
def showindex(context, mapping):
    """Integer. The current iteration of the loop. (0 indexed)"""
    # just hosts documentation; should be overridden by template mapping
    raise error.Abort(_(b"can't use index in this context"))


@templatekeyword(b'latesttag', requires={b'repo', b'ctx', b'cache'})
def showlatesttag(context, mapping):
    """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".
    """
    return showlatesttags(context, mapping, None)


def showlatesttags(context, mapping, pattern):
    """helper method for the latesttag keyword and function"""
    latesttags = getlatesttags(context, mapping, pattern)

    # latesttag[0] is an implementation detail for sorting csets on different
    # branches in a stable manner- it is the date the tagged cset was created,
    # not the date the tag was created.  Therefore it isn't made visible here.
    makemap = lambda v: {
        b'changes': _showchangessincetag,
        b'distance': latesttags[1],
        b'latesttag': v,  # BC with {latesttag % '{latesttag}'}
        b'tag': v,
    }

    tags = latesttags[2]
    f = _showcompatlist(context, mapping, b'latesttag', tags, separator=b':')
    return _hybrid(f, tags, makemap, pycompat.identity)


@templatekeyword(b'latesttagdistance', requires={b'repo', b'ctx', b'cache'})
def showlatesttagdistance(context, mapping):
    """Integer. Longest path to the latest tag."""
    return getlatesttags(context, mapping)[1]


@templatekeyword(b'changessincelatesttag', requires={b'repo', b'ctx', b'cache'})
def showchangessincelatesttag(context, mapping):
    """Integer. All ancestors not in the latest tag."""
    tag = getlatesttags(context, mapping)[2][0]
    mapping = context.overlaymap(mapping, {b'tag': tag})
    return _showchangessincetag(context, mapping)


def _showchangessincetag(context, mapping):
    repo = context.resource(mapping, b'repo')
    ctx = context.resource(mapping, b'ctx')
    offset = 0
    revs = [ctx.rev()]
    tag = context.symbol(mapping, b'tag')

    # The only() revset doesn't currently support wdir()
    if ctx.rev() is None:
        offset = 1
        revs = [p.rev() for p in ctx.parents()]

    return len(repo.revs(b'only(%ld, %s)', revs, tag)) + offset


# teach templater latesttags.changes is switched to (context, mapping) API
_showchangessincetag._requires = {b'repo', b'ctx'}


@templatekeyword(b'manifest', requires={b'repo', b'ctx'})
def showmanifest(context, mapping):
    repo = context.resource(mapping, b'repo')
    ctx = context.resource(mapping, b'ctx')
    mnode = ctx.manifestnode()
    if mnode is None:
        mnode = wdirid
        mrev = wdirrev
    else:
        mrev = repo.manifestlog.rev(mnode)
    mhex = hex(mnode)
    mapping = context.overlaymap(mapping, {b'rev': mrev, b'node': mhex})
    f = context.process(b'manifest', mapping)
    return templateutil.hybriditem(
        f, None, f, lambda x: {b'rev': mrev, b'node': mhex}
    )


@templatekeyword(b'obsfate', requires={b'ui', b'repo', b'ctx'})
def showobsfate(context, mapping):
    # this function returns a list containing pre-formatted obsfate strings.
    #
    # This function will be replaced by templates fragments when we will have
    # the verbosity templatekw available.
    succsandmarkers = showsuccsandmarkers(context, mapping)

    ui = context.resource(mapping, b'ui')
    repo = context.resource(mapping, b'repo')
    values = []

    for x in succsandmarkers.tovalue(context, mapping):
        v = obsutil.obsfateprinter(
            ui, repo, x[b'successors'], x[b'markers'], scmutil.formatchangeid
        )
        values.append(v)

    return compatlist(context, mapping, b"fate", values)


def shownames(context, mapping, namespace):
    """helper method to generate a template keyword for a namespace"""
    repo = context.resource(mapping, b'repo')
    ctx = context.resource(mapping, b'ctx')
    ns = repo.names.get(namespace)
    if ns is None:
        # namespaces.addnamespace() registers new template keyword, but
        # the registered namespace might not exist in the current repo.
        return
    names = ns.names(repo, ctx.node())
    return compatlist(
        context, mapping, ns.templatename, names, plural=namespace
    )


@templatekeyword(b'namespaces', requires={b'repo', b'ctx'})
def shownamespaces(context, mapping):
    """Dict of lists. Names attached to this changeset per
    namespace."""
    repo = context.resource(mapping, b'repo')
    ctx = context.resource(mapping, b'ctx')

    namespaces = util.sortdict()

    def makensmapfn(ns):
        # 'name' for iterating over namespaces, templatename for local reference
        return lambda v: {b'name': v, ns.templatename: v}

    for k, ns in pycompat.iteritems(repo.names):
        names = ns.names(repo, ctx.node())
        f = _showcompatlist(context, mapping, b'name', names)
        namespaces[k] = _hybrid(f, names, makensmapfn(ns), pycompat.identity)

    f = _showcompatlist(context, mapping, b'namespace', list(namespaces))

    def makemap(ns):
        return {
            b'namespace': ns,
            b'names': namespaces[ns],
            b'builtin': repo.names[ns].builtin,
            b'colorname': repo.names[ns].colorname,
        }

    return _hybrid(f, namespaces, makemap, pycompat.identity)


@templatekeyword(b'negrev', requires={b'repo', b'ctx'})
def shownegrev(context, mapping):
    """Integer. The repository-local changeset negative revision number,
    which counts in the opposite direction."""
    ctx = context.resource(mapping, b'ctx')
    rev = ctx.rev()
    if rev is None or rev < 0:  # wdir() or nullrev?
        return None
    repo = context.resource(mapping, b'repo')
    return rev - len(repo)


@templatekeyword(b'node', requires={b'ctx'})
def shownode(context, mapping):
    """String. The changeset identification hash, as a 40 hexadecimal
    digit string.
    """
    ctx = context.resource(mapping, b'ctx')
    return ctx.hex()


@templatekeyword(b'obsolete', requires={b'ctx'})
def showobsolete(context, mapping):
    """String. Whether the changeset is obsolete. (EXPERIMENTAL)"""
    ctx = context.resource(mapping, b'ctx')
    if ctx.obsolete():
        return b'obsolete'
    return b''


@templatekeyword(b'onelinesummary', requires={b'ui', b'ctx'})
def showonelinesummary(context, mapping):
    """String. A one-line summary for the ctx (not including trailing newline).
    The default template be overridden in command-templates.oneline-summary."""
    # Avoid cycle:
    # mercurial.cmdutil -> mercurial.templatekw -> mercurial.cmdutil
    from . import cmdutil

    ui = context.resource(mapping, b'ui')
    ctx = context.resource(mapping, b'ctx')
    return cmdutil.format_changeset_summary(ui, ctx)


@templatekeyword(b'path', requires={b'fctx'})
def showpath(context, mapping):
    """String. Repository-absolute path of the current file. (EXPERIMENTAL)"""
    fctx = context.resource(mapping, b'fctx')
    return fctx.path()


@templatekeyword(b'peerurls', requires={b'repo'})
def showpeerurls(context, mapping):
    """A dictionary of repository locations defined in the [paths] section
    of your configuration file."""
    repo = context.resource(mapping, b'repo')
    # see commands.paths() for naming of dictionary keys
    paths = repo.ui.paths
    urls = util.sortdict(
        (k, p.rawloc) for k, p in sorted(pycompat.iteritems(paths))
    )

    def makemap(k):
        p = paths[k]
        d = {b'name': k, b'url': p.rawloc}
        d.update((o, v) for o, v in sorted(pycompat.iteritems(p.suboptions)))
        return d

    return _hybrid(None, urls, makemap, lambda k: b'%s=%s' % (k, urls[k]))


@templatekeyword(b"predecessors", requires={b'repo', b'ctx'})
def showpredecessors(context, mapping):
    """Returns the list of the closest visible predecessors. (EXPERIMENTAL)"""
    repo = context.resource(mapping, b'repo')
    ctx = context.resource(mapping, b'ctx')
    predecessors = sorted(obsutil.closestpredecessors(repo, ctx.node()))
    predecessors = pycompat.maplist(hex, predecessors)

    return _hybrid(
        None,
        predecessors,
        lambda x: {b'ctx': repo[x]},
        lambda x: scmutil.formatchangeid(repo[x]),
    )


@templatekeyword(b'reporoot', requires={b'repo'})
def showreporoot(context, mapping):
    """String. The root directory of the current repository."""
    repo = context.resource(mapping, b'repo')
    return repo.root


@templatekeyword(b'size', requires={b'fctx'})
def showsize(context, mapping):
    """Integer. Size of the current file in bytes. (EXPERIMENTAL)"""
    fctx = context.resource(mapping, b'fctx')
    return fctx.size()


# requires 'fctx' to denote {status} depends on (ctx, path) pair
@templatekeyword(b'status', requires={b'ctx', b'fctx', b'revcache'})
def showstatus(context, mapping):
    """String. Status code of the current file. (EXPERIMENTAL)"""
    path = templateutil.runsymbol(context, mapping, b'path')
    path = templateutil.stringify(context, mapping, path)
    if not path:
        return
    statmap = _getfilestatusmap(context, mapping)
    if path not in statmap:
        statmap = _getfilestatusmap(context, mapping, listall=True)
    return statmap.get(path)


@templatekeyword(b"successorssets", requires={b'repo', b'ctx'})
def showsuccessorssets(context, mapping):
    """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)"""
    repo = context.resource(mapping, b'repo')
    ctx = context.resource(mapping, b'ctx')
    data = []

    if ctx.obsolete():
        ssets = obsutil.successorssets(repo, ctx.node(), closest=True)
        ssets = [[hex(n) for n in ss] for ss in ssets]

        for ss in ssets:
            h = _hybrid(
                None,
                ss,
                lambda x: {b'ctx': repo[x]},
                lambda x: scmutil.formatchangeid(repo[x]),
            )
            data.append(h)

    # Format the successorssets
    def render(d):
        return templateutil.stringify(context, mapping, d)

    def gen(data):
        yield b"; ".join(render(d) for d in data)

    return _hybrid(
        gen(data), data, lambda x: {b'successorset': x}, pycompat.identity
    )


@templatekeyword(b"succsandmarkers", requires={b'repo', b'ctx'})
def showsuccsandmarkers(context, mapping):
    """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)
    """
    repo = context.resource(mapping, b'repo')
    ctx = context.resource(mapping, b'ctx')

    values = obsutil.successorsandmarkers(repo, ctx)

    if values is None:
        values = []

    # Format successors and markers to avoid exposing binary to templates
    data = []
    for i in values:
        # Format successors
        successors = i[b'successors']

        successors = [hex(n) for n in successors]
        successors = _hybrid(
            None,
            successors,
            lambda x: {b'ctx': repo[x]},
            lambda x: scmutil.formatchangeid(repo[x]),
        )

        # Format markers
        finalmarkers = []
        for m in i[b'markers']:
            hexprec = hex(m[0])
            hexsucs = tuple(hex(n) for n in m[1])
            hexparents = None
            if m[5] is not None:
                hexparents = tuple(hex(n) for n in m[5])
            newmarker = (hexprec, hexsucs) + m[2:5] + (hexparents,) + m[6:]
            finalmarkers.append(newmarker)

        data.append({b'successors': successors, b'markers': finalmarkers})

    return templateutil.mappinglist(data)


@templatekeyword(b'p1', requires={b'ctx'})
def showp1(context, mapping):
    """Changeset. The changeset's first parent. ``{p1.rev}`` for the revision
    number, and ``{p1.node}`` for the identification hash."""
    ctx = context.resource(mapping, b'ctx')
    return templateutil.mappingdict({b'ctx': ctx.p1()}, tmpl=_changeidtmpl)


@templatekeyword(b'p2', requires={b'ctx'})
def showp2(context, mapping):
    """Changeset. The changeset's second parent. ``{p2.rev}`` for the revision
    number, and ``{p2.node}`` for the identification hash."""
    ctx = context.resource(mapping, b'ctx')
    return templateutil.mappingdict({b'ctx': ctx.p2()}, tmpl=_changeidtmpl)


@templatekeyword(b'p1rev', requires={b'ctx'})
def showp1rev(context, mapping):
    """Integer. The repository-local revision number of the changeset's
    first parent, or -1 if the changeset has no parents. (DEPRECATED)"""
    ctx = context.resource(mapping, b'ctx')
    return ctx.p1().rev()


@templatekeyword(b'p2rev', requires={b'ctx'})
def showp2rev(context, mapping):
    """Integer. The repository-local revision number of the changeset's
    second parent, or -1 if the changeset has no second parent. (DEPRECATED)"""
    ctx = context.resource(mapping, b'ctx')
    return ctx.p2().rev()


@templatekeyword(b'p1node', requires={b'ctx'})
def showp1node(context, mapping):
    """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)"""
    ctx = context.resource(mapping, b'ctx')
    return ctx.p1().hex()


@templatekeyword(b'p2node', requires={b'ctx'})
def showp2node(context, mapping):
    """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)"""
    ctx = context.resource(mapping, b'ctx')
    return ctx.p2().hex()


@templatekeyword(b'parents', requires={b'repo', b'ctx'})
def showparents(context, mapping):
    """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."""
    repo = context.resource(mapping, b'repo')
    ctx = context.resource(mapping, b'ctx')
    pctxs = scmutil.meaningfulparents(repo, ctx)
    prevs = [p.rev() for p in pctxs]
    parents = [
        [(b'rev', p.rev()), (b'node', p.hex()), (b'phase', p.phasestr())]
        for p in pctxs
    ]
    f = _showcompatlist(context, mapping, b'parent', parents)
    return _hybrid(
        f,
        prevs,
        lambda x: {b'ctx': repo[x]},
        lambda x: scmutil.formatchangeid(repo[x]),
        keytype=int,
    )


@templatekeyword(b'phase', requires={b'ctx'})
def showphase(context, mapping):
    """String. The changeset phase name."""
    ctx = context.resource(mapping, b'ctx')
    return ctx.phasestr()


@templatekeyword(b'phaseidx', requires={b'ctx'})
def showphaseidx(context, mapping):
    """Integer. The changeset phase index. (ADVANCED)"""
    ctx = context.resource(mapping, b'ctx')
    return ctx.phase()


@templatekeyword(b'rev', requires={b'ctx'})
def showrev(context, mapping):
    """Integer. The repository-local changeset revision number."""
    ctx = context.resource(mapping, b'ctx')
    return scmutil.intrev(ctx)


@templatekeyword(b'subrepos', requires={b'ctx'})
def showsubrepos(context, mapping):
    """List of strings. Updated subrepositories in the changeset."""
    ctx = context.resource(mapping, b'ctx')
    substate = ctx.substate
    if not substate:
        return compatlist(context, mapping, b'subrepo', [])
    psubstate = ctx.p1().substate or {}
    subrepos = []
    for sub in substate:
        if sub not in psubstate or substate[sub] != psubstate[sub]:
            subrepos.append(sub)  # modified or newly added in ctx
    for sub in psubstate:
        if sub not in substate:
            subrepos.append(sub)  # removed in ctx
    return compatlist(context, mapping, b'subrepo', sorted(subrepos))


# don't remove "showtags" definition, even though namespaces will put
# a helper function for "tags" keyword into "keywords" map automatically,
# because online help text is built without namespaces initialization
@templatekeyword(b'tags', requires={b'repo', b'ctx'})
def showtags(context, mapping):
    """List of strings. Any tags associated with the changeset."""
    return shownames(context, mapping, b'tags')


@templatekeyword(b'termwidth', requires={b'ui'})
def showtermwidth(context, mapping):
    """Integer. The width of the current terminal."""
    ui = context.resource(mapping, b'ui')
    return ui.termwidth()


@templatekeyword(b'user', requires={b'ctx'})
def showuser(context, mapping):
    """String. The unmodified author of the changeset."""
    ctx = context.resource(mapping, b'ctx')
    return ctx.user()


@templatekeyword(b'instabilities', requires={b'ctx'})
def showinstabilities(context, mapping):
    """List of strings. Evolution instabilities affecting the changeset.
    (EXPERIMENTAL)
    """
    ctx = context.resource(mapping, b'ctx')
    return compatlist(
        context,
        mapping,
        b'instability',
        ctx.instabilities(),
        plural=b'instabilities',
    )


@templatekeyword(b'verbosity', requires={b'ui'})
def showverbosity(context, mapping):
    """String. The current output verbosity in 'debug', 'quiet', 'verbose',
    or ''."""
    ui = context.resource(mapping, b'ui')
    # see logcmdutil.changesettemplater for priority of these flags
    if ui.debugflag:
        return b'debug'
    elif ui.quiet:
        return b'quiet'
    elif ui.verbose:
        return b'verbose'
    return b''


@templatekeyword(b'whyunstable', requires={b'repo', b'ctx'})
def showwhyunstable(context, mapping):
    """List of dicts explaining all instabilities of a changeset.
    (EXPERIMENTAL)
    """
    repo = context.resource(mapping, b'repo')
    ctx = context.resource(mapping, b'ctx')

    def formatnode(ctx):
        return b'%s (%s)' % (scmutil.formatchangeid(ctx), ctx.phasestr())

    entries = obsutil.whyunstable(repo, ctx)

    for entry in entries:
        if entry.get(b'divergentnodes'):
            dnodes = entry[b'divergentnodes']
            dnhybrid = _hybrid(
                None,
                [dnode.hex() for dnode in dnodes],
                lambda x: {b'ctx': repo[x]},
                lambda x: formatnode(repo[x]),
            )
            entry[b'divergentnodes'] = dnhybrid

    tmpl = (
        b'{instability}:{if(divergentnodes, " ")}{divergentnodes} '
        b'{reason} {node|short}'
    )
    return templateutil.mappinglist(entries, tmpl=tmpl, sep=b'\n')


def loadkeyword(ui, extname, registrarobj):
    """Load template keyword from specified registrarobj
    """
    for name, func in pycompat.iteritems(registrarobj._table):
        keywords[name] = func


# tell hggettext to extract docstrings from these functions:
i18nfunctions = keywords.values()