How can I get `git log` to append ellipsis after the commit subject line if the message body is non-empty?

17 Views Asked by At

E.g. suppose this is what my git history looks like:

$ git log --oneline
f9b86d3 (HEAD -> main) blah the baz
966a640 foobar the frob
ac27e4d Revert "do something special"
338ff0f do something special
...

However suppose 966a640 and ac27e4d have additional lines in their commit message bodies. (f9b86d3 and 338ff0f are just the subject lines / have empty bodies.)

How can I make a git log format specifier that appends an ellipsis to the end of the subject line ONLY IF there is additional text in the body?

E.g. I'd like the output to look like this:

$ $ git log --abbrev-commit --pretty='%h%d %s ???'
f9b86d3 (HEAD -> main) blah the baz
966a640 foobar the frob ...
ac27e4d Revert "do something special" ...
338ff0f do something special
...

I've found %<([n],trunc) and I can almost get there using %<(1,trunc)% b (with %b being the commit message body, and the space in the middle prepending a space if non-empty), but while that does correctly add a two-character ellipses, it unfortunately appears to preserve (only) the newlines from the body:

$ git log --abbrev-commit --pretty='%h%d %s%<(1,trunc)% b'
f9b86d3 (HEAD -> main) blah the baz
966a640 foobar the frob ..




ac27e4d Revert "do something special" ..


338ff0f do something special
1

There are 1 best solutions below

0
vergenzt On

You're very close! To trim the extra newlines from %<(1,trunc)% b you can use %- followed by a placeholder that's guaranteed to be empty.

From https://git-scm.com/docs/git-log:

If you add a - (minus sign) after % of a placeholder, all consecutive line-feeds immediately preceding the expansion are deleted if and only if the placeholder expands to an empty string.

You can do this by requesting a commit "trailer" with a key that doesn't exist, i.e. %-(trailers:key=x-always-empty).

All together:

$ git log --abbrev-commit --pretty='%h%d %s%<(1,trunc)% b%-(trailers:key=x-always-empty)'
f9b86d3 (HEAD -> main) blah the baz
966a640 foobar the frob ..
ac27e4d Revert "do something special" ..
338ff0f do something special