github.com/timstclair/heapster@v0.20.0-alpha1/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/line_delimiter.go (about) 1 /* 2 Copyright 2015 The Kubernetes Authors All rights reserved. 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 util 18 19 import ( 20 "bytes" 21 "io" 22 "strings" 23 ) 24 25 // A Line Delimiter is a filter that will 26 type LineDelimiter struct { 27 output io.Writer 28 delimiter []byte 29 buf bytes.Buffer 30 } 31 32 // NewLineDelimiter allocates a new io.Writer that will split input on lines 33 // and bracket each line with the delimiter string. This can be useful in 34 // output tests where it is difficult to see and test trailing whitespace. 35 func NewLineDelimiter(output io.Writer, delimiter string) *LineDelimiter { 36 return &LineDelimiter{output: output, delimiter: []byte(delimiter)} 37 } 38 39 // Write writes buf to the LineDelimiter ld. The only errors returned are ones 40 // encountered while writing to the underlying output stream. 41 func (ld *LineDelimiter) Write(buf []byte) (n int, err error) { 42 return ld.buf.Write(buf) 43 } 44 45 // Flush all lines up until now. This will assume insert a linebreak at the current point of the stream. 46 func (ld *LineDelimiter) Flush() (err error) { 47 lines := strings.Split(ld.buf.String(), "\n") 48 for _, line := range lines { 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 }