-
Notifications
You must be signed in to change notification settings - Fork 0
/
progress.go
68 lines (55 loc) · 1.8 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
package main
import (
"fmt"
"strings"
)
var (
errDownload = fmt.Errorf("error downloading correct data")
)
// Progress is used to keep track during the download process and to display a progress bar during the operation.
type Progress struct {
total int // total number of bytes to be downloaded
totalString string // size of file to be downloaded, ready for printing
have int // number of bytes we currently have
writeCount int // running count of write operations, for determining if we should print or not
}
// Write prints the number of bytes written to stdout.
func (pr *Progress) Write(p []byte) (int, error) {
n := len(p)
pr.have += n
// We don't need to do expensive print operations that often.
pr.writeCount++
if pr.writeCount%50 > 0 {
return n, nil
}
// Clear the line and print the current status.
fmt.Printf("\r%s", strings.Repeat(" ", 35))
fmt.Printf("%v", pr.String())
return n, nil
}
// String shows the current transfer status.
func (pr *Progress) String() string {
if pr == nil {
return "<nil>"
}
return fmt.Sprintf("\rReceived %v of %v total (%v%%)", Reduce(pr.have), pr.totalString, ((pr.have * 100) / pr.total))
}
// Finish cleans up the terminal line and prints the overall success of the download operation.
func (pr *Progress) Finish() error {
// Print the final status.
fmt.Printf("\r%s", strings.Repeat(" ", 35))
fmt.Printf("%v", pr.String())
// Because we've been mucking around with carriage returns, we need to manually move down a row.
fmt.Println()
if pr.have != pr.total {
Debug("Expected", pr.total, "bytes, Received", pr.have, "bytes")
if pr.have < pr.total {
Log("Failed to download entire episode")
} else {
Log("Downloaded more bytes than expected")
}
return errDownload
}
Log("Episode successfully downloaded")
return nil
}