-
Notifications
You must be signed in to change notification settings - Fork 162
/
file_reporter.go
67 lines (54 loc) · 1.24 KB
/
file_reporter.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
package ui
import (
"io"
"github.com/cheggaaa/pb"
)
type FileReporter struct {
ui UI
}
func NewFileReporter(ui UI) FileReporter {
return FileReporter{ui: ui}
}
type ReadSeekCloser interface {
io.Seeker
io.ReadCloser
}
func (r FileReporter) TrackUpload(size int64, reader io.ReadCloser) ReadSeekCloser {
return &ReadCloserProxy{reader: reader, bar: r.buildBar(size)}
}
func (r FileReporter) TrackDownload(size int64, writer io.Writer) io.Writer {
return io.MultiWriter(writer, r.buildBar(size))
}
func (r FileReporter) buildBar(size int64) *pb.ProgressBar {
bar := pb.New(int(size))
bar.ShowCounters = false
bar.ShowTimeLeft = true
bar.ShowSpeed = true
bar.SetWidth(80)
bar.SetMaxWidth(80)
bar.SetUnits(pb.U_BYTES)
bar.Format("\x00#\x00#\x00 \x00")
bar.Start()
return bar
}
type ReadCloserProxy struct {
reader io.ReadCloser
bar *pb.ProgressBar
}
func (p ReadCloserProxy) Seek(offset int64, whence int) (int64, error) {
seeker, ok := p.reader.(io.Seeker)
if ok {
return seeker.Seek(offset, whence)
}
return 0, nil
}
func (p *ReadCloserProxy) Read(bs []byte) (int, error) {
n, err := p.reader.Read(bs)
p.bar.Add(n)
return n, err
}
func (p *ReadCloserProxy) Close() error {
err := p.reader.Close()
p.bar.Finish()
return err
}