| 1 | package harness |
| 2 | |
| 3 | import ( |
| 4 | "strings" |
| 5 | "sync" |
| 6 | |
| 7 | "github.com/ipfs/kubo/test/cli/testutils" |
| 8 | ) |
| 9 | |
| 10 | // Buffer is a thread-safe byte buffer. |
| 11 | type Buffer struct { |
| 12 | b strings.Builder |
| 13 | m sync.Mutex |
| 14 | } |
| 15 | |
| 16 | func (b *Buffer) Write(p []byte) (n int, err error) { |
| 17 | b.m.Lock() |
| 18 | defer b.m.Unlock() |
| 19 | return b.b.Write(p) |
| 20 | } |
| 21 | |
| 22 | func (b *Buffer) String() string { |
| 23 | b.m.Lock() |
| 24 | defer b.m.Unlock() |
| 25 | return b.b.String() |
| 26 | } |
| 27 | |
| 28 | // Trimmed returns the bytes as a string, but with the trailing newline removed. |
| 29 | // This only removes a single trailing newline, not all whitespace. |
| 30 | func (b *Buffer) Trimmed() string { |
| 31 | b.m.Lock() |
| 32 | defer b.m.Unlock() |
| 33 | s := b.b.String() |
| 34 | if len(s) == 0 { |
| 35 | return s |
| 36 | } |
| 37 | if s[len(s)-1] == '\n' { |
| 38 | return s[:len(s)-1] |
| 39 | } |
| 40 | return s |
| 41 | } |
| 42 | |
| 43 | func (b *Buffer) Bytes() []byte { |
| 44 | b.m.Lock() |
| 45 | defer b.m.Unlock() |
| 46 | return []byte(b.b.String()) |
| 47 | } |
| 48 | |
| 49 | func (b *Buffer) Lines() []string { |
| 50 | b.m.Lock() |
| 51 | defer b.m.Unlock() |
| 52 | return testutils.SplitLines(b.b.String()) |
| 53 | } |