Fix truncateCommandOutput function

This commit is contained in:
Thomas Miceli 2023-03-18 18:22:27 +01:00
parent 00452d6caf
commit 24f790fb9c
No known key found for this signature in database
GPG key ID: D86C6F6390AF050F

View file

@ -6,34 +6,28 @@ import (
) )
func truncateCommandOutput(out io.Reader, maxBytes int64) (string, bool, error) { func truncateCommandOutput(out io.Reader, maxBytes int64) (string, bool, error) {
var ( var buf []byte
buf []byte var err error
err error
)
if maxBytes < 0 { if maxBytes < 0 {
// read entire output
buf, err = io.ReadAll(out) buf, err = io.ReadAll(out)
if err != nil { } else {
return "", false, err buf, err = io.ReadAll(io.LimitReader(out, maxBytes))
}
return string(buf), false, nil
} }
if err != nil {
// read up to maxBytes bytes
buf = make([]byte, maxBytes)
n, err := io.ReadFull(out, buf)
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
return "", false, err return "", false, err
} }
bytesRead := int64(n) truncated := len(buf) >= int(maxBytes)
// Remove the last line if it's truncated
if truncated {
// Find the index of the last newline character
lastNewline := bytes.LastIndexByte(buf, '\n')
// find index of last newline character if lastNewline > 0 {
lastNewline := bytes.LastIndexByte(buf, '\n') // Trim the data buffer up to the last newline character
if lastNewline >= 0 { buf = buf[:lastNewline]
// truncate buffer to exclude last line }
buf = buf[:lastNewline]
} }
return string(buf), bytesRead == maxBytes, nil return string(buf), truncated, nil
} }