-
Notifications
You must be signed in to change notification settings - Fork 0
/
tail.go
74 lines (65 loc) · 1.26 KB
/
tail.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
package csvutil
import (
"io"
"github.com/pkg/errors"
)
// TailOption is option holder for Tail.
type TailOption struct {
// Source file does not have header line. (default false)
NoHeader bool
// Encoding of source file. (default utf8)
Encoding string
// Encoding for output.
OutputEncoding string
// Count is reading line count.
Count int
}
func (o TailOption) validate() error {
if o.Count <= 0 {
return errors.New("negative or zero count")
}
return nil
}
func (o TailOption) outputEncoding() string {
if o.OutputEncoding != "" {
return o.OutputEncoding
}
return o.Encoding
}
// Tail reads lines from tail.
func Tail(r io.Reader, w io.Writer, o TailOption) error {
if err := o.validate(); err != nil {
return errors.Wrap(err, "invalid option")
}
cr, bom := reader(r, o.Encoding)
cw := writer(w, bom, o.outputEncoding())
if !o.NoHeader {
hdr, err := cr.Read()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
cw.Write(hdr)
}
var recs [][]string
for {
rec, err := cr.Read()
if err != nil {
if err == io.EOF {
if len(recs) != 0 {
cw.WriteAll(recs)
}
break
}
return err
}
if len(recs) < o.Count {
recs = append(recs, rec)
continue
}
recs = append(recs[1:], rec)
}
return nil
}