Search code examples
formattingmercurialhgrcdiffstat

How to add different colors to mercurial template command?


What I want:

A command that prints number of added (+) and removed (-) from change log, where the added portion(+) written in green and deleted portion (-) written in red.


What I have currently:

hg log -T {diffstat} prints what I want (+20/-31:) but in black color.

hg log -T "{label('custom.colorcode', diffstat)} \n" prints the entire diffstat (+20/-31:) in green (my custom.colorcode is set to green in .hgrc)


References:

https://www.mercurial-scm.org/repo/hg/help/templates

Can I add custom colors to mercurial command templates?


Solution

  • I don't believe there is a way for Mercurial to automatically parse the diffstat output and to assign colors to parts of it, but you can use a workaround by doing the parsing yourself. E.g. with the following template:

    hg log -T '{sub("(.*): (.*)/(.*)", "\\1: \033[0;32m\\2\033[0m/\033[0;31m\\3\033[0m", diffstat)}\n'
    

    Note that this hardcodes ANSI color escapes (32 for green, 31 for red). If you want to do it with labels, this is also possible, but much slower (because diffstat has to be calculated multiple times). This approach can still be useful for other keywords, so I'm explaining it anyway. Here is an example template:

    {sub(":.*","",diffstat)}: \
    {label("diff.inserted", sub(".*([+][0-9]+).*", "\\1", diffstat))}/\
    {label("diff.deleted", sub(".*(-[0-9]+).*", "\\1", diffstat))}
    

    The easiest way to use such a long template is to put it in a file (for example ~/.hgtemplates/diffstat) and then use hg log -T ~/.hgtemplates/diffstat. If a template contains a slash or backslash and corresponds to an existing file, Mercurial will look at the contents of the file instead. Long templates can also be put in the templates section of your .hgrc, e.g.:

    [templates]
    diffstat = "{sub(":.*","",diffstat)}: \
      {label("diff.inserted", sub(".*([+][0-9]+).*", "\\1", diffstat))}/\
      {label("diff.deleted", sub(".*(-[0-9]+).*", "\\1", diffstat))}\n"
    

    And can then be used with the corresponding name (e.g. hg log -T diffstat).