github.com/mponton/terratest@v0.44.0/modules/shell/output.go (about) 1 package shell 2 3 import ( 4 "strings" 5 "sync" 6 ) 7 8 // output contains the output after runnig a command. 9 type output struct { 10 stdout *outputStream 11 stderr *outputStream 12 // merged contains stdout and stderr merged into one stream. 13 merged *merged 14 } 15 16 func newOutput() *output { 17 m := new(merged) 18 return &output{ 19 merged: m, 20 stdout: &outputStream{ 21 merged: m, 22 }, 23 stderr: &outputStream{ 24 merged: m, 25 }, 26 } 27 } 28 29 func (o *output) Stdout() string { 30 if o == nil { 31 return "" 32 } 33 34 return o.stdout.String() 35 } 36 37 func (o *output) Stderr() string { 38 if o == nil { 39 return "" 40 } 41 42 return o.stderr.String() 43 } 44 45 func (o *output) Combined() string { 46 if o == nil { 47 return "" 48 } 49 50 return o.merged.String() 51 } 52 53 type outputStream struct { 54 Lines []string 55 *merged 56 } 57 58 func (st *outputStream) WriteString(s string) (n int, err error) { 59 st.Lines = append(st.Lines, string(s)) 60 return st.merged.WriteString(s) 61 } 62 63 func (st *outputStream) String() string { 64 if st == nil { 65 return "" 66 } 67 68 return strings.Join(st.Lines, "\n") 69 } 70 71 type merged struct { 72 // ensure that there are no parallel writes 73 sync.Mutex 74 Lines []string 75 } 76 77 func (m *merged) String() string { 78 if m == nil { 79 return "" 80 } 81 82 return strings.Join(m.Lines, "\n") 83 } 84 85 func (m *merged) WriteString(s string) (n int, err error) { 86 m.Lock() 87 defer m.Unlock() 88 89 m.Lines = append(m.Lines, string(s)) 90 91 return len(s), nil 92 }