当我调用以下命令时:
git log --format=format:"%C(yellow)%h %C(blue)%s %C(green)%ad %C(reset)%an%n%n%-b"
我得到如下所示的输出:
我希望提交主体变暗,所以我尝试在我的格式字符串末尾插入指令 %C(dim)
。但是,似乎没有实现我目标的插入位置:
在换行符之后和 (conditional newline-chomping)
%-b
command 之前插入%C(dim)
正确应用调光效果,但打破条件换行符:git log --format=format:"%C(yellow)%h %C(blue)%s %C(green)%ad %C(reset)%an%n%n%C(dim)%-b"
在换行符和(条件换行符)
%-b
命令之前插入%C(dim)
正确地保留了条件换行符,但是未能应用调光效果(即与原始输出没有变化):git log --format=format:"%C(yellow)%h %C(blue)%s %C(green)%ad %C(reset)%an%C(dim)%n%n%-b"
此外,我无法将 'chomp' 运算符 -
移动到 color 命令,因为它似乎总是“评估”为非空字符串(因此,换行符不会被压缩)。
有没有办法实现我的目标?
最佳答案
The final solution (without any known quirks) is at the bottom of this answer.
解决方法是在格式字符串中为换行符放置一个自定义占位符(不使用 %-b
魔法),然后使用 sed
对输出进行后处理。在下面的示例中,占位符是 CHOMPABLENEWLINES
字符串(当然您可以将其替换为您选择的任何文本,只要确保它不会出现在你的提交消息中):
git log --format=format:"%C(yellow)%h %C(blue)%s %C(green)%ad %C(reset)%an%C(dim)CHOMPABLENEWLINES%b"|sed -e 's/CHOMPABLENEWLINES$//; s/CHOMPABLENEWLINES/\n\n/; $ s/$/\n/'
请注意,此方法还解决了 %C
指令的效果仅延伸到当前行末尾的问题(至少在 git 2.7.4 中)。因此,在多行主体的情况下,颜色仅应用于其第一行。比较:
# Only the first line of a multiline message body is colored
git log --format=format:"%C(yellow)%h %C(blue)%s %C(green)%ad %C(reset)%an%n%n%Cred%b"
# Entire multiline message body is colored (though a byproduct of this
# is that the color setting persists beyond the current
# command - note the red prompt following the output)
git log --format=format:"%C(yellow)%h %C(blue)%s %C(green)%ad %C(reset)%an%CredCHOMPABLENEWLINES%b"|sed -e 's/CHOMPABLENEWLINES$//; s/CHOMPABLENEWLINES/\n\n/; $ s/$/\n/'
可以通过以 %C(reset)
指令结束格式字符串来抵消持久颜色设置的不良副作用。然后我们还需要一个用于 %b
占位符结尾的自定义标记,因为视觉行尾不再是 sed
点的实际行尾看法。在下面的示例中,字符串 ENDOFBODY
用作此类标记(当然,您必须选择它,以便它不会出现在您的预期输出中)。
# This version works with GNU sed. For a portable version (including BSD
# and MacOS X systems) scroll down a little more
git log --format=tformat:"%C(yellow)%h %C(blue)%s %C(green)%ad %C(reset)%an%CredCHOMPABLENEWLINES%bENDOFBODY%C(reset)"|sed -e 's/CHOMPABLENEWLINESENDOFBODY//; s/CHOMPABLENEWLINES/\n\n/; s/ENDOFBODY//'
某些版本或设置的 git 在不直接进入终端时禁用彩色输出。在这种情况下,您还必须向 git log
提供 --color=always
选项。
最终的解决方案,仅使用 sed 的可移植特性,如下所示:
git log --color=always --format=tformat:"%C(yellow)%h %C(blue)%s %C(green)%ad %C(reset)%an%C(red)CHOMPABLENEWLINES%bENDOFBODY%C(reset)"|sed -e 's/CHOMPABLENEWLINESENDOFBODY//; s/CHOMPABLENEWLINES/\'$'\n''\'$'\n/; s/ENDOFBODY//'
关于git - 在 git log 输出中将颜色与条件换行符结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45356760/