Subject: [PATCH] pkt-line: do not chomp EOL for sideband progress info

From: Jiang Xin <[email-masked]>
Date: Tue, 19 Sep 2023 15:19:56 +0800

From: Jiang Xin <[email-masked]>

In the protocol negotiation stage, we need to turn on the flag
"PACKET_READ_CHOMP_NEWLINE" to chomp EOL for each packet line from
client or server. But when receiving data and progress information
using sideband, we will turn off the flag "PACKET_READ_CHOMP_NEWLINE"
to prevent mangling EOLs from data and progress information.

When both the server and the client support "sideband-all" capability,
we have a dilemma that EOLs in negotiation packets should be trimmed,
but EOLs in progress infomation should be leaved as is.

Move the logic of chomping EOLs from "packet_read_with_status()" to
"packet_reader_read()" can resolve this dilemma.

Signed-off-by: Jiang Xin <[email-masked]>
---
 pkt-line.c | 19 ++++++++++++++++---
 1 file changed, 16 insertions(+), 3 deletions(-)

diff --git a/pkt-line.c b/pkt-line.c
index af83a19f4d..d6d08b6aa6 100644
--- a/pkt-line.c
+++ b/pkt-line.c
@@ -597,12 +597,18 @@ void packet_reader_init(struct packet_reader *reader, int fd,
 enum packet_read_status packet_reader_read(struct packet_reader *reader)
 {
 	struct strbuf scratch = STRBUF_INIT;
+	int options = reader->options;
 
 	if (reader->line_peeked) {
 		reader->line_peeked = 0;
 		return reader->status;
 	}
 
+	/* Do not chomp newlines for sideband progress and error messages */
+	if (reader->use_sideband && options & PACKET_READ_CHOMP_NEWLINE) {
+		options &= ~PACKET_READ_CHOMP_NEWLINE;
+	}
+
 	/*
 	 * Consume all progress packets until a primary payload packet is
 	 * received
@@ -615,7 +621,7 @@ enum packet_read_status packet_reader_read(struct packet_reader *reader)
 							 reader->buffer,
 							 reader->buffer_size,
 							 &reader->pktlen,
-							 reader->options);
+							 options);
 		if (!reader->use_sideband)
 			break;
 		if (demultiplex_sideband(reader->me, reader->status,
@@ -624,12 +630,19 @@ enum packet_read_status packet_reader_read(struct packet_reader *reader)
 			break;
 	}
 
-	if (reader->status == PACKET_READ_NORMAL)
+	if (reader->status == PACKET_READ_NORMAL) {
 		/* Skip the sideband designator if sideband is used */
 		reader->line = reader->use_sideband ?
 			reader->buffer + 1 : reader->buffer;
-	else
+
+		if ((reader->options & PACKET_READ_CHOMP_NEWLINE) &&
+		    reader->buffer[reader->pktlen - 1] == '\n') {
+			reader->buffer[reader->pktlen - 1] = 0;
+			reader->pktlen--;
+		}
+	} else {
 		reader->line = NULL;
+	}
 
 	return reader->status;
 }
-- 
2.40.1.49.g40e13c3520.dirty