| 1 |
/* |
| 2 |
Copyright 2015 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package strings |
| 18 |
|
| 19 |
import ( |
| 20 |
"bytes" |
| 21 |
"io" |
| 22 |
"strings" |
| 23 |
) |
| 24 |
|
| 25 |
// LineDelimiter is a filter that will split input on lines |
| 26 |
// and bracket each line with the delimiter string. |
| 27 |
type LineDelimiter struct { |
| 28 |
output io.Writer |
| 29 |
delimiter []byte |
| 30 |
buf bytes.Buffer |
| 31 |
} |
| 32 |
|
| 33 |
// NewLineDelimiter allocates a new io.Writer that will split input on lines |
| 34 |
// and bracket each line with the delimiter string. This can be useful in |
| 35 |
// output tests where it is difficult to see and test trailing whitespace. |
| 36 |
func NewLineDelimiter(output io.Writer, delimiter string) *LineDelimiter { |
| 37 |
return &LineDelimiter{output: output, delimiter: []byte(delimiter)} |
| 38 |
} |
| 39 |
|
| 40 |
// Write writes buf to the LineDelimiter ld. The only errors returned are ones |
| 41 |
// encountered while writing to the underlying output stream. |
| 42 |
func (ld *LineDelimiter) Write(buf []byte) (n int, err error) { |
| 43 |
return ld.buf.Write(buf) |
| 44 |
} |
| 45 |
|
| 46 |
// Flush all lines up until now. This will assume insert a linebreak at the current point of the stream. |
| 47 |
func (ld *LineDelimiter) Flush() (err error) { |
| 48 |
for line := range strings.SplitSeq(ld.buf.String(), "\n") { |
| 49 |
if _, err = ld.output.Write(ld.delimiter); err != nil { |
| 50 |
return |
| 51 |
} |
| 52 |
if _, err = ld.output.Write([]byte(line)); err != nil { |
| 53 |
return |
| 54 |
} |
| 55 |
if _, err = ld.output.Write(ld.delimiter); err != nil { |
| 56 |
return |
| 57 |
} |
| 58 |
if _, err = ld.output.Write([]byte("\n")); err != nil { |
| 59 |
return |
| 60 |
} |
| 61 |
} |
| 62 |
return |
| 63 |
} |