gitgit-loggit-notes

Remove trailing newline from %N format specifier in git-log


Is it possible to easily trim the newline when displaying a note with %N with git log?

I would like to include metadata about a commit by adding it with git-notes and viewing it with something like:

git log --format=format:'%h [%N] %an %s %D'

This seems much cleaner than creating commit messages with meta-data prefixed as is common practice these days, but it seems that there is always a trailing newline on the note.

Any suggestions on how to easily remove it without filtering through external tools?


Solution

  • Use %N%-C().

    %N you know. The - in %-C() means "strip immediately-preceding newlines if this is empty", and the empty color spec C() is empty.

    From comments:

    OP was using %<(20,trunc)%N, and notes by default have an explicitly-encoded trailing newline that the formatter does not strip—so a ten-byte note will have a newline eleventh byte and then the fixed-width will pad that out to 20 bytes with spaces . . . and %-C() will see the immediately-preceding space and do nothing.

    One workaround for this OP found: use %>(20,trunc) instead, short notes will be right-aligned so the trailing newline will always appear there.

    Another was suggested by @Guildenstern in a comment on the question: use a trailer instead, whose value doesn't notionally include the embedded trailing newline.

    git notes will supply any "missing" trailing newline to an added note, even from a file; to create a no-trailing-newline note yourself you have to create the blob manually and create it with the premade object, but even then git log's formatter will add it back. So it looks like rj is pretty much the only option if you want to format the data in a fixed-width field and keep the flexibility advantage notes offer over trailers.