mirror of
https://github.com/moby/moby.git
synced 2022-11-09 12:21:53 -05:00
engine.Tail() to ignore trailing whitespaces.
In its current form, if an error message has two trailing "\n" instead of one, an empty line is resulted (see engine/job.go for an example of such usages). Skipping all trailing whitespaces will give a better error message. Signed-off-by: Nghia Tran <nghia@google.com>
This commit is contained in:
parent
f70567e9a9
commit
b422d8da8f
2 changed files with 16 additions and 9 deletions
|
@ -5,7 +5,9 @@ import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"unicode"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Output struct {
|
type Output struct {
|
||||||
|
@ -16,25 +18,25 @@ type Output struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tail returns the n last lines of a buffer
|
// Tail returns the n last lines of a buffer
|
||||||
// stripped out of the last \n, if any
|
// stripped out of trailing white spaces, if any.
|
||||||
|
//
|
||||||
// if n <= 0, returns an empty string
|
// if n <= 0, returns an empty string
|
||||||
func Tail(buffer *bytes.Buffer, n int) string {
|
func Tail(buffer *bytes.Buffer, n int) string {
|
||||||
if n <= 0 {
|
if n <= 0 {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
bytes := buffer.Bytes()
|
s := strings.TrimRightFunc(buffer.String(), unicode.IsSpace)
|
||||||
if len(bytes) > 0 && bytes[len(bytes)-1] == '\n' {
|
i := len(s) - 1
|
||||||
bytes = bytes[:len(bytes)-1]
|
for ; i >= 0 && n > 0; i-- {
|
||||||
}
|
if s[i] == '\n' {
|
||||||
for i := buffer.Len() - 2; i >= 0; i-- {
|
|
||||||
if bytes[i] == '\n' {
|
|
||||||
n--
|
n--
|
||||||
if n == 0 {
|
if n == 0 {
|
||||||
return string(bytes[i+1:])
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return string(bytes)
|
// when i == -1, return the whole string which is s[0:]
|
||||||
|
return s[i+1:]
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewOutput returns a new Output object with no destinations attached.
|
// NewOutput returns a new Output object with no destinations attached.
|
||||||
|
|
|
@ -111,6 +111,11 @@ func TestTail(t *testing.T) {
|
||||||
"Two\nThree",
|
"Two\nThree",
|
||||||
"One\nTwo\nThree",
|
"One\nTwo\nThree",
|
||||||
}
|
}
|
||||||
|
tests["One\nTwo\n\n\n"] = []string{
|
||||||
|
"",
|
||||||
|
"Two",
|
||||||
|
"One\nTwo",
|
||||||
|
}
|
||||||
for input, outputs := range tests {
|
for input, outputs := range tests {
|
||||||
for n, expectedOutput := range outputs {
|
for n, expectedOutput := range outputs {
|
||||||
output := Tail(bytes.NewBufferString(input), n)
|
output := Tail(bytes.NewBufferString(input), n)
|
||||||
|
|
Loading…
Add table
Reference in a new issue