-
Notifications
You must be signed in to change notification settings - Fork 23
/
output.go
92 lines (79 loc) · 1.76 KB
/
output.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Copyright 2022 Twitter, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"io"
"sync"
)
type synchronizedWriter struct {
io.Writer
sync.Mutex
}
func (s *synchronizedWriter) Write(p []byte) (int, error) {
s.Lock()
defer s.Unlock()
return s.Writer.Write(p)
}
type prefixingWriter struct {
prefix []byte
w io.Writer // has per-Write mutex
buf bytes.Buffer
}
func (s *prefixingWriter) Write(p []byte) (int, error) {
n := len(p)
for {
if s.buf.Len() == 0 {
s.buf.Write(s.prefix)
}
i := bytes.IndexByte(p, '\n')
if i == -1 {
_, err := s.buf.Write(p)
if err != nil {
return 0, err
}
break
}
// found \n
if _, err := s.buf.Write(p[:i+1]); err != nil {
return 0, err
}
_, err := s.w.Write(s.buf.Bytes())
if err != nil {
return 0, err
}
s.buf.Reset()
if i == len(p)-1 {
break
}
p = p[i+1:]
}
return n, nil
}
func (s *prefixingWriter) Close() error {
// TODO track double-closing?
if s.buf.Len() == 0 {
return nil
}
_, err := s.w.Write(s.buf.Bytes())
if err != nil {
return err
}
if (s.buf.Bytes())[s.buf.Len()-1] == '\n' {
return nil
}
// cmd ended without trailing \n, add so that prefixed printing is not malformed
_, err = s.w.Write([]byte{'\n'})
return err
}