From 981a12a130257cbd1434d2dece483257636c7dbb Mon Sep 17 00:00:00 2001 From: Jesse Chen Date: Fri, 30 Jun 2023 16:19:00 -0700 Subject: [PATCH] go prefixedwriter: fix short write error case In certain cases, formatting as JSON actually reduces the number of bytes. This leads to the bufio.Writer that wraps this returning `short write` error because the number of bytes returned is less than expected. We just want to return the original number of bytes, since we know that we are doing some string manipulation and we are OK with that. See: https://pkg.go.dev/io#Writer ``` Write writes len(p) bytes from p to the underlying data stream. It returns the number of bytes written from p (0 <= n <= len(p)) and any error encountered that caused the write to stop early. Write must return a non-nil error if it returns n < len(p). ``` --- clireporter/prefixedwriter.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/clireporter/prefixedwriter.go b/clireporter/prefixedwriter.go index eb36ce0..243adf4 100644 --- a/clireporter/prefixedwriter.go +++ b/clireporter/prefixedwriter.go @@ -86,6 +86,10 @@ func (w *PrefixedWriter) Write(p []byte) (n int, err error) { h.Write([]byte(w.Prefix)) c := colors[int(h.Sum32())%len(colors)] + // If we format p as a JSON, it's possible that the number of bytes can + // change. + // The writer expects us to return the original length of p. + origLen := len(p) var jsonObj interface{} err = json.Unmarshal([]byte(p), &jsonObj) if err == nil { @@ -106,7 +110,7 @@ func (w *PrefixedWriter) Write(p []byte) (n int, err error) { } _, err = w.Writer.Write([]byte(strings.Join(prefixed, "\n") + "\n")) - return len(p), err + return origLen, err } func leftPad(s string, l int) string {