使用模板截断 hg 日志输出中 N 个字符的 "desc"

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

我正在尝试为 hg log 创建自定义模板,其中一部分显示第一行的前 N ​​个(例如 72 个)字符。基于 this answer 到目前为止我得到的另一个问题:

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

现在我试图将该位限制为一定数量的字符。但是,the corresponding template usage docs 不会产生 "substring"、"left" 等的搜索结果。我尝试了一些方法,包括

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

也只是为了测试

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

但他们给出了一个错误:

hg: parse error: unkown function '50'

我敢猜测我想要的是可能的,但我似乎无法找到合适的语法。 我如何构造一个模板来输出提交消息的第一行,最多 N 个字符?

您可以使用正则表达式和 sub() 函数来实现。例如:

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

sub() 函数接受三个参数,模式、替换和要处理的字符串。在这个例子中,我们使用一个组来捕获 0 到 50 个字符(换行符除外),然后是另一个模式来吸收其余部分(以便它被丢弃)。替换字符串仅显示第一组,我们使用 desc 作为输入。只需将上面示例中的 50 更改为您实际需要的宽度即可。

如果您不希望描述被中间词截断,您还可以将 fill()firstline 结合使用。在这里,fill() 会将输入分成几行,然后我们使用输出的第一行。示例:

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

请注意,带有破折号的单词可能仍会被截断,因为 fill() 认为破折号后的位置是换行符的有效选择。