当我调用以下命令时:
git log --format=format:"%C(yellow)%h %C(blue)%s %C(green)%ad %C(reset)%an%n%n%-b"
Run Code Online (Sandbox Code Playgroud)
我得到的输出看起来像这样:
我希望提交主体变暗,所以我尝试%C(dim)在格式字符串的末尾插入指令.但是,似乎没有一个插入位置可以实现我的目标:
%C(dim)在换行符之后和(条件换行 - chomping)%-b命令之前插入正确应用调光效果,但会打破条件换行符:
git log --format=format:"%C(yellow)%h %C(blue)%s %C(green)%ad %C(reset)%an%n%n%C(dim)%-b"
Run Code Online (Sandbox Code Playgroud)
%C(dim)在换行符和(条件换行符 - chomping)%-b命令之前插入正确保留条件换行符,但无法应用调光效果(即原始输出没有变化):
git log --format=format:"%C(yellow)%h %C(blue)%s %C(green)%ad %C(reset)%an%C(dim)%n%n%-b"
Run Code Online (Sandbox Code Playgroud)
另外,我无法将'chomp'运算符移动-到color命令,因为它总是看起来"评估"为非空字符串(因此,新行不会被限制).
有没有办法实现我的目标?
最终的解决方案(没有任何已知的怪癖)位于此答案的底部。
解决方法是在格式字符串中为换行符放置一个自定义占位符(不使用魔法%-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/'
Run Code Online (Sandbox Code Playgroud)
请注意,这种方法还解决了指令的效果%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"
Run Code Online (Sandbox Code Playgroud)
# 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/'
Run Code Online (Sandbox Code Playgroud)
持久颜色设置的不良副作用可以通过用指令结束格式字符串来抵消%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//'
Run Code Online (Sandbox Code Playgroud)
当 git 不直接进入终端时,某些版本或设置会禁用彩色输出。在这种情况下,您还必须提供--color=always选项git log。
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//'
Run Code Online (Sandbox Code Playgroud)