-
Notifications
You must be signed in to change notification settings - Fork 1
/
progress.go
131 lines (111 loc) · 2.5 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package main
import (
"fmt"
"io"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/dustin/go-humanize"
)
// 782448 63% 110.64kB/s 0:00:04
type Progress struct {
size int64
begin time.Time
lastPrinted time.Time
count int64
onceBegin sync.Once
stop chan struct{}
onceStop sync.Once
}
type ReadProgress struct {
Progress
r io.Reader
}
type WriteProgress struct {
Progress
w io.Writer
}
func newReadProgress(rs io.Reader, size int64) *ReadProgress {
return &ReadProgress{
r: rs,
Progress: Progress{
size: size,
begin: time.Now(),
stop: make(chan struct{}),
},
}
}
func newWriteProgress(w io.Writer, size int64) *WriteProgress {
return &WriteProgress{
w: w,
Progress: Progress{
size: size,
begin: time.Now(),
stop: make(chan struct{}),
},
}
}
func (p *Progress) Close() {
p.onceStop.Do(func() { close(p.stop) })
}
func (p *ReadProgress) Read(buf []byte) (int, error) {
return p.rwFunc(p.r.Read, buf)
}
func (p *WriteProgress) Write(buf []byte) (int, error) {
return p.rwFunc(p.w.Write, buf)
}
func (p *Progress) rwFunc(f func([]byte) (int, error), buf []byte) (int, error) {
// start printing on first call
p.onceBegin.Do(func() { go p.run() })
n, err := f(buf)
atomic.AddInt64(&p.count, int64(n))
return n, err
}
func (p *Progress) run() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
p.maybePrintSpeed()
case <-p.stop:
return
}
}
}
func (p *Progress) maybePrintSpeed() {
now := time.Now()
elapsed := now.Sub(p.lastPrinted)
if elapsed >= time.Second {
p.printSpeed(now)
p.lastPrinted = now
}
}
func (p *Progress) printSpeed(now time.Time) {
count := atomic.LoadInt64(&p.count)
percent := "?"
if p.size > 0 {
percent = strconv.FormatInt(count*100/p.size, 10)
}
speed := "?"
elapsedTime := now.Sub(p.begin)
elapsedSeconds := elapsedTime.Seconds()
if elapsedSeconds > 0 {
bytesPerSecond := float64(count) / elapsedTime.Seconds()
speed = strings.ReplaceAll(humanize.Bytes(uint64(bytesPerSecond)), " ", "")
}
remainingTimeString := "?s"
if p.size > 0 {
totalTime := time.Duration(float64(elapsedTime) * (float64(p.size) / float64(count)))
remainingTime := totalTime - elapsedTime
if remainingTime < 0 {
remainingTime = 0
}
remainingTime = remainingTime.Truncate(time.Second)
remainingTimeString = remainingTime.String()
}
fmt.Fprintf(os.Stderr, "%s %s%% %s/s %s\n", humanize.Comma(count), percent, speed, remainingTimeString)
}