1package ui 2 3import ( 4 "io" 5 "strings" 6 "sync" 7) 8 9type ComboWriter struct { 10 ui UI 11 uiLock sync.Mutex 12 onNewLine bool 13} 14 15type prefixedWriter struct { 16 w *ComboWriter 17 prefix string 18} 19 20func NewComboWriter(ui UI) *ComboWriter { 21 return &ComboWriter{ui: ui, onNewLine: true} 22} 23 24func (w *ComboWriter) Writer(prefix string) io.Writer { 25 return prefixedWriter{w: w, prefix: prefix} 26} 27 28func (s prefixedWriter) Write(bytes []byte) (int, error) { 29 if len(bytes) == 0 { 30 return 0, nil 31 } 32 33 s.w.uiLock.Lock() 34 defer s.w.uiLock.Unlock() 35 36 lines := strings.Split(string(bytes), "\n") 37 38 for i, line := range lines { 39 lastLine := i == len(lines)-1 40 41 if !lastLine || len(line) > 0 { 42 if s.w.onNewLine { 43 s.w.ui.PrintBlock([]byte(s.prefix)) 44 } 45 46 s.w.ui.PrintBlock([]byte(line)) 47 s.w.onNewLine = false 48 49 if !lastLine { 50 s.w.ui.PrintBlock([]byte("\n")) 51 s.w.onNewLine = true 52 } 53 } 54 } 55 56 return len(bytes), nil 57} 58