This repository was archived by the owner on Sep 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathcopy.go
More file actions
96 lines (74 loc) · 1.73 KB
/
copy.go
File metadata and controls
96 lines (74 loc) · 1.73 KB
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
package copy
import (
"bufio"
"fmt"
"io"
"time"
"github.com/docker/docker/pkg/term"
"github.com/fatih/color"
)
// NoTTY turns the progress meters off
var NoTTY bool
// NoOut turns copy output off entirely
var NoOut bool
const megaByte = float64(1024 * 1024)
const readerSize = 65536
// WithProgress implements io.Copy with a buffered reader, then measures
// progress throughout the copy process. The buffer is set at a reasonable size
// for reasonable performance. On error, if io.EOF is not returned then the
// error is returned. Otherwise, it is nil.
func WithProgress(writer io.Writer, reader io.Reader, prefix string) error {
defer color.Unset()
var printed bool
defer func() {
if printed {
fmt.Println()
}
}()
wsz, _ := term.GetWinsize(0)
rd := bufio.NewReaderSize(reader, readerSize)
count := float64(0)
buf := make([]byte, readerSize)
t := time.Now()
for {
rn, err := rd.Read(buf)
count += float64(rn)
if err == io.EOF {
if rn > 0 {
goto write
} else {
return nil
}
}
if err != nil {
return err
}
if NoOut {
goto write
}
if time.Since(t) > 100*time.Millisecond && !NoTTY && wsz.Width != 0 {
printed = true
fmt.Print("\r")
mbs := fmt.Sprintf("%.02fMB", count/megaByte)
color.New(color.FgWhite, color.Bold).Printf("+++ ")
justifiedWidth := int(wsz.Width) - len(mbs) - 9
if justifiedWidth < 0 {
goto write
}
if len(prefix) > int(justifiedWidth) {
prefix = prefix[:int(justifiedWidth)] + "..."
}
color.New(color.FgRed, color.Bold).Printf("%s: ", prefix)
color.New(color.FgWhite).Print(mbs)
t = time.Now()
}
write:
_, werr := writer.Write(buf[:rn])
if werr != nil {
return werr
}
if err == io.EOF {
return nil
}
}
}