-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcopy_windows.go
96 lines (82 loc) · 1.72 KB
/
copy_windows.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
package file
import (
"fmt"
"time"
"unsafe"
"golang.org/x/sys/windows"
)
var kernel32 = windows.NewLazySystemDLL("kernel32.dll")
var procCopyFileW = kernel32.NewProc("CopyFileExW")
type progressCopy struct {
last time.Time
n int
run bool
}
func keta(n uint64) int {
if n < 10 {
return 1
}
return keta(n/10) + 1
}
func progressPrint(total, transfer uint64, this *progressCopy) {
now := time.Now()
if now.Sub(this.last) >= time.Second {
this.n, _ = fmt.Printf("%3d%% %*d/%d\r",
transfer*100/total,
keta(total),
transfer,
total)
this.last = now
this.run = true
}
}
// Copy calls Win32's CopyFile API.
func copyFile(src, dst string, isFailIfExists bool) error {
_src, err := windows.UTF16PtrFromString(src)
if err != nil {
return err
}
_dst, err := windows.UTF16PtrFromString(dst)
if err != nil {
return err
}
var flag uintptr
if isFailIfExists {
flag |= 1
}
var progressCopy1 progressCopy
progressCopy1.last = time.Now()
var cancel uintptr
var rc uintptr
rc, _, err = procCopyFileW.Call(
uintptr(unsafe.Pointer(_src)),
uintptr(unsafe.Pointer(_dst)),
windows.NewCallbackCDecl(progressPrintCallBack),
uintptr(unsafe.Pointer(&progressCopy1)),
uintptr(unsafe.Pointer(&cancel)),
flag)
if progressCopy1.run {
fmt.Printf("%*s\r", progressCopy1.n, "")
}
if rc == 0 {
return err
}
return nil
}
// Move calls Win32's MoveFileEx API.
func moveFile(src, dst string) error {
_src, err := windows.UTF16PtrFromString(src)
if err != nil {
return err
}
_dst, err := windows.UTF16PtrFromString(dst)
if err != nil {
return err
}
return windows.MoveFileEx(
_src,
_dst,
windows.MOVEFILE_REPLACE_EXISTING|
windows.MOVEFILE_COPY_ALLOWED|
windows.MOVEFILE_WRITE_THROUGH)
}