The way I read the git-log manpage:
%C(…): color specification, as described in color.branch.* config option; adding
auto,
at the beginning will emit color only when colors are enabled for log output (bycolor.diff
,color.ui
, or--color
, and respecting the auto settings of the former if we are going to a terminal).auto
alone (i.e.%C(auto)
) will turn on auto coloring on the next placeholders until the color is switched again.
Then one of the following two formats should be the correct way to request colors conditionally (as you'd need to do in a script, alias, or named pretty format) for %d
and %D
:
--pretty='%C(auto)%d'
--pretty='%C(auto,auto)%d'
However, the first format (%C(auto)%d
) doesn't seem to work, testing with these three commands—first, generating color output with no pager; second, attempting to invoke automatic color suppression by piping to cat
; finally, explicitly suppressing color (note, you need to have a branch and/or tag checked out to see the color effect, otherwise %d
outputs nothing):
git --no-pager log -5 --pretty='%C(auto)%d %C(auto,blue)%s'
# correctly shows %d dynamically colored and %s blue
git --no-pager log -5 --pretty='%C(auto)%d %C(auto,blue)%s' | cat
# still colored %d, but %s uncolored
git --no-pager log --color=never -5 --pretty='%C(auto) %d %C(auto,blue)%s'
# same: still colored %d, but %s uncolored
Trying the second format (%C(auto,auto)%d
) doesn't work either:
git --no-pager log -5 --pretty='%C(auto,auto) %d %C(auto,blue)%s'
error: invalid color value: auto
fatal: unable to parse --pretty format
git --no-pager log -5 --pretty='%C(auto,auto) %d %C(auto,blue)%s' | cat
# correct, no colors
git --no-pager log --color=never -5 --pretty='%C(auto,auto) %d %C(auto,blue)%s'
# correct, no colors
I'm not sure what I'm doing wrong. What is the correct format sequence to print colorized %d
and %D
if and only if the output would ordinarily be colored?
Your first format works like expected in respect of colourised/non-colourised output (at least with v2.11.0).
Nevertheless you miss to reset the colour specification, which leads to wrong colours if at the beginning of the next item (if no colour has been set).
Corrected colourspec:
%h %C(auto)%d %C(auto,blue)%s%C(auto,reset)
Tests:
git config pretty.test "%h %C(auto)%d %C(auto,blue)%s%C(auto,reset)"
echo; git --no-pager log -5 --pretty=test
echo; git --no-pager log -5 --pretty=test | cat
echo; git --no-pager log -5 --pretty=test --color=never