-
Notifications
You must be signed in to change notification settings - Fork 0
/
top.go
69 lines (60 loc) · 1.2 KB
/
top.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
package csvutil
import (
"io"
"github.com/pkg/errors"
)
// TopOption is option holder for Top.
type TopOption 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
// Headers is appending header list.
Headers []string
// Count is reading line count.
Count int
}
func (o TopOption) validate() error {
if o.Count <= 0 {
return errors.New("negative or zero count")
}
return nil
}
func (o TopOption) outputEncoding() string {
if o.OutputEncoding != "" {
return o.OutputEncoding
}
return o.Encoding
}
// Top reads lines from top.
func Top(r io.Reader, w io.Writer, o TopOption) 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())
defer cw.Flush()
if !o.NoHeader {
hdr, err := cr.Read()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
cw.Write(hdr)
}
for i := 0; i < o.Count; i++ {
rec, err := cr.Read()
if err != nil {
if err == io.EOF {
break
}
return err
}
cw.Write(rec)
}
return nil
}