Cut off the "desc" at N characters in hg log output with templates

517 views Asked by At

I'm trying to create a custom template for hg log with a part that shows the first N (e.g. 72) characters of the first line. Based off this answer to a different question I've gotten so far:

hg log --template '{desc|strip|firstline}\n'

Now I'm trying to limit that bit to a certain number of characters. However, the corresponding template usage docs yields no search results for "substring", "left", etc. I've tried a few things, including

hg log --template '{desc|strip|firstline|strip|50}\n'

and just for testing also

hg log --template '{desc|strip|50}\n'

but they give an error:

hg: parse error: unkown function '50'

I'd hazard a guess that what I want is possible, but I just seem unable to find the appropriate syntax. How can I construct a template that outputs the first line of a commit message, up to a maximum of N characters?

1

There are 1 answers

3
Reimer Behrends On BEST ANSWER

You can use regular expressions and the sub() function to accomplish that. For example:

hg log --template '{sub("^(.{0,50})(.|\n)*","\\1",desc)}\n'

The sub() function takes three arguments, the pattern, the replacement, and the string to be processed. In this example, we use a group that captures anywhere from 0 to 50 characters (except newline), followed by another pattern that slurps up the rest (so that it gets discarded). The replacement string simply shows the first group, and we use desc as the input. Simply change the 50 in the example above with the width you actually want.

If you don't want descriptions cut off mid-word, you can also use fill() in conjunction with firstline. Here, fill() will break the input into lines, then we use the first line of the output. Example:

hg log --template '{fill(desc,"50")|firstline}\n'

Note that words with dashes in them may still be cut off, since fill() considers the position after a dash to be a valid choice for a linebreak.