line_delimiter.go 1.9 KB

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