pkt-line: do not report packet write errors twice

On write() errors, packet_write() dies with the same error message that is already printed by its callee, packet_write_gently(). This produces an unnecessarily verbose and repetitive output: error: packet write failed fatal: packet write failed: <strerror() message> In addition to that, packet_write_gently() does not always fulfill its caller expectation that errno will be properly set before a non-zero return. In particular, that is not the case for a "data exceeds max packet size" error. So, in this case, packet_write() will call die_errno() and print an strerror(errno) message that might be totally unrelated to the actual error. Fix both those issues by turning packet_write() and packet_write_gently() into wrappers to a common lower level function that doesn't print the error message, but instead returns it on a buffer for the caller to die() or error() as appropriate. Signed-off-by: Matheus Tavares <matheus.bernardino@usp.br> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Matheus Tavares committed Apr 15, 2021 at 18:57 UTC 332ec963bc6fedc0ca9c0b5a66ea842d7fbd6baa
1 file changed +24 -7
pkt-line.c
+24 -7
@@ -194,13 +194,16 @@ int packet_write_fmt_gently(int fd, const char *fmt, ...)
194 return status;
195 }
196
197 -static int packet_write_gently(const int fd_out, const char *buf, size_t size)
197 +static int do_packet_write(const int fd_out, const char *buf, size_t size,
198 + struct strbuf *err)
199 {
200 char header[4];
201 size_t packet_size;
202
202 - if (size > LARGE_PACKET_DATA_MAX)
203 - return error(_("packet write failed - data exceeds max packet size"));
203 + if (size > LARGE_PACKET_DATA_MAX) {
204 + strbuf_addstr(err, _("packet write failed - data exceeds max packet size"));
205 + return -1;
206 + }
207
208 packet_trace(buf, size, 1);
209 packet_size = size + 4;
@@ -215,15 +218,29 @@ static int packet_write_gently(const int fd_out, const char *buf, size_t size)
218 */
219
220 if (write_in_full(fd_out, header, 4) < 0 ||
218 - write_in_full(fd_out, buf, size) < 0)
219 - return error(_("packet write failed"));
221 + write_in_full(fd_out, buf, size) < 0) {
222 + strbuf_addf(err, _("packet write failed: %s"), strerror(errno));
223 + return -1;
224 + }
225 + return 0;
226 +}
227 +
228 +static int packet_write_gently(const int fd_out, const char *buf, size_t size)
229 +{
230 + struct strbuf err = STRBUF_INIT;
231 + if (do_packet_write(fd_out, buf, size, &err)) {
232 + error("%s", err.buf);
233 + strbuf_release(&err);
234 + return -1;
235 + }
236 return 0;
237 }
238
239 void packet_write(int fd_out, const char *buf, size_t size)
240 {
225 - if (packet_write_gently(fd_out, buf, size))
226 - die_errno(_("packet write failed"));
241 + struct strbuf err = STRBUF_INIT;
242 + if (do_packet_write(fd_out, buf, size, &err))
243 + die("%s", err.buf);
244 }
245
246 void packet_buf_write(struct strbuf *buf, const char *fmt, ...)