-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilecopier.go
79 lines (64 loc) · 1.64 KB
/
filecopier.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
package main
import (
"fmt"
"io"
"os"
"sync/atomic"
"github.com/bson/imgimporter/workset"
)
/// fileCopier - the part that copies files
type fileCopier struct {
workset.WorkSet
bytesCopied uint64
filesCopied uint32
filesFailed uint32
}
func (f *fileCopier) copy(list []copyItem, nConc int) error {
f.bytesCopied = 0
f.filesCopied = 0
f.filesFailed = 0
workList := make([]interface{}, len(list))
for k, v := range list {
workList[k] = v
}
f.Work(workList, copyConc,
fmt.Sprintf("Copying %d new media files", len(list)),
func(list []interface{}, start int, len int) {
for i := start; i < start+len; i++ {
item := list[i].(copyItem)
fFrom, err := os.Open(item.from)
if err != nil {
f.Errorf("Unable to import %s: %s", item.from, err.Error())
atomic.AddUint32(&f.filesFailed, 1)
continue
}
defer fFrom.Close()
fTo, err := os.Create(item.to)
if err != nil {
f.Errorf("Unable to import to %s: %s", item.to, err.Error())
atomic.AddUint32(&f.filesFailed, 1)
continue
}
defer fTo.Close()
nBytes, err := io.Copy(fTo, fFrom)
if err != nil {
f.Errorf("Failed to import %s: %s", item.from, err.Error())
atomic.AddUint32(&f.filesFailed, 1)
continue
}
atomic.AddUint64(&f.bytesCopied, uint64(nBytes))
atomic.AddUint32(&f.filesCopied, 1)
f.Progress()
}
f.Finalize(func() {})
},
// Progress
func() string {
dur := f.Runtime()
MB := f.bytesCopied / 1024 / 1024
MBps := float64(MB) / dur.Seconds()
return fmt.Sprintf("%d/%d - %vMB in %.1fs (%.1fMB/s)",
f.filesCopied, len(workList), MB, dur.Seconds(), MBps)
})
return nil
}