-
Notifications
You must be signed in to change notification settings - Fork 1
/
progress.go
89 lines (83 loc) · 2.12 KB
/
progress.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
79
80
81
82
83
84
85
86
87
88
89
// Package progress - progress meters through a channel, wrapping an io.Reader
//
// Example:
//
//
// func progress(reader io.Reader) {
// r = NewReader("an_file.tar", reader, 100*time.Millisecond)
// defer r.Close()
//
// var count uint64
// // This goroutine consumes the channel and concatenates the count to display
// // the total as it increases.
// go func(r *Reader) {
// for tick := range r.C {
// count += tick.Value
// fmt.Printf("\r%d", count)
// }
//
// fmt.Println()
// }(r)
//
// // use r like you normally would; progress will be reported to C every 100
// // milliseconds.
// if _, err := io.Copy(ioutil.Discard, r); err != nil {
// panic(err)
// }
// }
//
//
//
package progress
import (
"io"
"time"
)
// Tick is the information supplied to the consumer when progress events arrive
// such as reaching an interval. The time of the event is also recorded.
type Tick struct {
Value uint64
Time time.Time
Artifact string
}
// Reader is a progress-aware reader that communicates its results over channel
// C. Channel C can then be read for information about the progress of the copy.
type Reader struct {
C chan *Tick
interval time.Duration
artifact string
reader io.Reader
value uint64
lastTime time.Time
}
// NewReader creates a new reader for use, wrapping an io.Reader with a
// reporting duration and artifact information.
func NewReader(artifact string, reader io.Reader, interval time.Duration) *Reader {
return &Reader{
C: make(chan *Tick, 1),
interval: interval,
artifact: artifact,
reader: reader,
}
}
// Read bytes from the reader, reporting progress to the channel as data arrives.
func (r *Reader) Read(buf []byte) (int, error) {
n, err := r.reader.Read(buf)
r.value += uint64(n)
if time.Since(r.lastTime) > r.interval {
r.lastTime = time.Now()
r.C <- &Tick{Artifact: r.artifact, Time: r.lastTime, Value: r.value}
r.value = 0
}
return n, err
}
// Close closes the reader and channel.
func (r *Reader) Close() error {
close(r.C)
switch r.reader.(type) {
case io.ReadCloser:
return r.reader.(io.ReadCloser).Close()
default:
return nil
}
}