forked from cli/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregexp_writer.go
More file actions
64 lines (53 loc) · 1.05 KB
/
regexp_writer.go
File metadata and controls
64 lines (53 loc) · 1.05 KB
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
package create
import (
"bytes"
"io"
"regexp"
)
func NewRegexpWriter(out io.Writer, re *regexp.Regexp, repl string) *RegexpWriter {
return &RegexpWriter{out: out, re: *re, repl: repl}
}
type RegexpWriter struct {
out io.Writer
re regexp.Regexp
repl string
buf []byte
}
func (s *RegexpWriter) Write(data []byte) (int, error) {
if len(data) == 0 {
return 0, nil
}
filtered := []byte{}
repl := []byte(s.repl)
lines := bytes.SplitAfter(data, []byte("\n"))
if len(s.buf) > 0 {
lines[0] = append(s.buf, lines[0]...)
}
for i, line := range lines {
if i == len(lines) {
s.buf = line
} else {
f := s.re.ReplaceAll(line, repl)
if len(f) > 0 {
filtered = append(filtered, f...)
}
}
}
if len(filtered) != 0 {
_, err := s.out.Write(filtered)
if err != nil {
return 0, err
}
}
return len(data), nil
}
func (s *RegexpWriter) Flush() (int, error) {
if len(s.buf) > 0 {
repl := []byte(s.repl)
filtered := s.re.ReplaceAll(s.buf, repl)
if len(filtered) > 0 {
return s.out.Write(filtered)
}
}
return 0, nil
}