forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
progress_reader.go
78 lines (64 loc) · 1.87 KB
/
progress_reader.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
75
76
77
78
package net
import (
"io"
"os"
"time"
"github.com/cloudfoundry/cli/cf/formatters"
"github.com/cloudfoundry/cli/cf/terminal"
)
type ProgressReader struct {
ioReadSeeker io.ReadSeeker
bytesRead int64
total int64
quit chan bool
ui terminal.UI
outputInterval time.Duration
}
func NewProgressReader(readSeeker io.ReadSeeker, ui terminal.UI, outputInterval time.Duration) *ProgressReader {
return &ProgressReader{
ioReadSeeker: readSeeker,
ui: ui,
outputInterval: outputInterval,
}
}
func (progressReader *ProgressReader) Read(p []byte) (int, error) {
if progressReader.ioReadSeeker == nil {
return 0, os.ErrInvalid
}
n, err := progressReader.ioReadSeeker.Read(p)
if progressReader.total > int64(0) {
if n > 0 {
if progressReader.quit == nil {
progressReader.quit = make(chan bool)
go progressReader.printProgress(progressReader.quit)
}
progressReader.bytesRead += int64(n)
if progressReader.total == progressReader.bytesRead {
progressReader.quit <- true
return n, err
}
}
}
return n, err
}
func (progressReader *ProgressReader) Seek(offset int64, whence int) (int64, error) {
return progressReader.ioReadSeeker.Seek(offset, whence)
}
func (progressReader *ProgressReader) printProgress(quit chan bool) {
timer := time.NewTicker(progressReader.outputInterval)
for {
select {
case <-quit:
//The spaces are there to ensure we overwrite the entire line
//before using the terminal printer to output Done Uploading
progressReader.ui.PrintCapturingNoOutput("\r ")
progressReader.ui.Say("\rDone uploading")
return
case <-timer.C:
progressReader.ui.PrintCapturingNoOutput("\r%s uploaded...", formatters.ByteSize(progressReader.bytesRead))
}
}
}
func (progressReader *ProgressReader) SetTotalSize(size int64) {
progressReader.total = size
}