forked from gokcehan/lf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
copy.go
128 lines (106 loc) · 2.26 KB
/
copy.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
package main
import (
"fmt"
"io"
"os"
"path/filepath"
)
func copySize(srcs []string) (int64, error) {
var total int64
for _, src := range srcs {
_, err := os.Stat(src)
if os.IsNotExist(err) {
return total, fmt.Errorf("src does not exist: %q", src)
}
err = filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("walk: %s", err)
}
total += info.Size()
return nil
})
if err != nil {
return total, err
}
}
return total, nil
}
func copyFile(src, dst string, info os.FileInfo, nums chan int64) error {
buf := make([]byte, 4096)
r, err := os.Open(src)
if err != nil {
return err
}
defer r.Close()
w, err := os.Create(dst)
if err != nil {
return err
}
for {
n, err := r.Read(buf)
if err != nil && err != io.EOF {
w.Close()
os.Remove(dst)
return err
}
if n == 0 {
break
}
if _, err := w.Write(buf[:n]); err != nil {
return err
}
nums <- int64(n)
}
if err := w.Close(); err != nil {
os.Remove(dst)
return err
}
if err := os.Chmod(dst, info.Mode()); err != nil {
os.Remove(dst)
return err
}
return nil
}
func copyAll(srcs []string, dstDir string) (nums chan int64, errs chan error) {
nums = make(chan int64, 1024)
errs = make(chan error, 1024)
go func() {
for _, src := range srcs {
dst := filepath.Join(dstDir, filepath.Base(src))
_, err := os.Stat(dst)
if !os.IsNotExist(err) {
var newPath string
for i := 1; !os.IsNotExist(err); i++ {
newPath = fmt.Sprintf("%s.~%d~", dst, i)
_, err = os.Stat(newPath)
}
dst = newPath
}
filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
errs <- fmt.Errorf("walk: %s", err)
return nil
}
rel, err := filepath.Rel(src, path)
if err != nil {
errs <- fmt.Errorf("relative: %s", err)
return nil
}
newPath := filepath.Join(dst, rel)
if info.IsDir() {
if err := os.MkdirAll(newPath, info.Mode()); err != nil {
errs <- fmt.Errorf("mkdir: %s", err)
}
nums <- info.Size()
} else {
if err := copyFile(path, newPath, info, nums); err != nil {
errs <- fmt.Errorf("copy: %s", err)
}
}
return nil
})
}
close(errs)
}()
return nums, errs
}