Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 917
William Pursell Avatar asked Oct 14 '25 08:10

William Pursell


2 Answers

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.

like image 189
jthill Avatar answered Oct 17 '25 01:10

jthill


It looks like current git does not support this, but the following patch seems to work:

diff --git a/notes.c b/notes.c
index 02f1aa39ae..21001b2261 100644
--- a/notes.c
+++ b/notes.c
@@ -1306,7 +1306,9 @@ static void format_note(struct notes_tree *t, const struct object_id *object_oid
                if (!raw)
                        strbuf_addstr(sb, "    ");
                strbuf_add(sb, msg_p, linelen);
-               strbuf_addch(sb, '\n');
+               if (!raw) {
+                       strbuf_addch(sb, '\n');
+               }
        }
 
        free(msg);
like image 21
William Pursell Avatar answered Oct 17 '25 01:10

William Pursell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!