-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy patheditor.go
56 lines (49 loc) · 1.15 KB
/
editor.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
package editor
import (
"bytes"
"io"
)
// Editor is the line-processor interface
type Editor interface {
Edit(line string) (string, error)
}
// Stream build io.WriteCloser that process lines with editor and write to base io.Writer
func Stream(base io.Writer, editor ...Editor) io.WriteCloser {
return &stream{editors: editor, base: base}
}
type stream struct {
editors []Editor
base io.Writer
buffer []byte
}
func (s *stream) writeLines(lines [][]byte) error {
for _, line := range lines {
line := bytes.TrimSuffix(line, []byte{'\r'})
text := string(append(line, '\n'))
for _, e := range s.editors {
t, err := e.Edit(text)
if err != nil {
return err
}
text = t
}
if _, err := s.base.Write([]byte(text)); err != nil {
return err
}
}
return nil
}
func (s *stream) Write(b []byte) (int, error) {
lines := bytes.Split(append(s.buffer, b...), []byte("\n"))
s.buffer = lines[len(lines)-1]
lines = lines[:len(lines)-1]
if err := s.writeLines(lines); err != nil {
return 0, err
}
return len(b), nil
}
func (s *stream) Close() error {
lines := bytes.Split(s.buffer, []byte(`\n`))
s.buffer = nil
return s.writeLines(lines)
}