line_delimiter.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. // A Line Delimiter is a filter that will
  20. type LineDelimiter struct {
  21. output io.Writer
  22. delimiter []byte
  23. buf bytes.Buffer
  24. }
  25. // NewLineDelimiter allocates a new io.Writer that will split input on lines
  26. // and bracket each line with the delimiter string. This can be useful in
  27. // output tests where it is difficult to see and test trailing whitespace.
  28. func NewLineDelimiter(output io.Writer, delimiter string) *LineDelimiter {
  29. return &LineDelimiter{output: output, delimiter: []byte(delimiter)}
  30. }
  31. // Write writes buf to the LineDelimiter ld. The only errors returned are ones
  32. // encountered while writing to the underlying output stream.
  33. func (ld *LineDelimiter) Write(buf []byte) (n int, err error) {
  34. return ld.buf.Write(buf)
  35. }
  36. // Flush all lines up until now. This will assume insert a linebreak at the current point of the stream.
  37. func (ld *LineDelimiter) Flush() (err error) {
  38. lines := strings.Split(ld.buf.String(), "\n")
  39. for _, line := range lines {
  40. if _, err = ld.output.Write(ld.delimiter); err != nil {
  41. return
  42. }
  43. if _, err = ld.output.Write([]byte(line)); err != nil {
  44. return
  45. }
  46. if _, err = ld.output.Write(ld.delimiter); err != nil {
  47. return
  48. }
  49. if _, err = ld.output.Write([]byte("\n")); err != nil {
  50. return
  51. }
  52. }
  53. return
  54. }