forked from lilith44/gox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_copy.go
139 lines (112 loc) · 2.28 KB
/
file_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
129
130
131
132
133
134
135
136
137
138
139
package gox
import (
`errors`
`io`
`os`
`path/filepath`
)
func cpFile(src string, dst string) (copyFile string, err error) {
var (
srcFile *os.File
dstFile *os.File
info os.FileInfo
)
if srcFile, err = os.Open(src); nil != err {
return
}
defer func() {
err = srcFile.Close()
}()
ext := filepath.Ext(dst)
if 0 == len(ext) {
_, srcName := filepath.Split(src)
dst = filepath.Join(dst, srcName)
}
if err = DirNotExistCreate(filepath.Dir(dst)); nil != err {
return
}
dst = renameExist(dst)
if dstFile, err = os.Create(dst); nil != err {
return
}
defer func() {
err = dstFile.Close()
}()
if _, err = io.Copy(dstFile, srcFile); nil != err {
return
}
if info, err = os.Stat(src); nil == err {
if err = os.Chmod(dst, info.Mode()); nil != err {
return
}
}
copyFile = src
return
}
func cpDir(src string, dst string) (copyFiles []string, err error) {
var (
srcStat os.FileInfo
srcDir *os.File
obs []os.FileInfo
)
if srcStat, err = os.Stat(src); nil != err {
return
}
if err = os.MkdirAll(dst, srcStat.Mode()); nil != err {
return
}
if srcDir, err = os.Open(src); nil != err {
return
}
defer func() {
srcDir.Close()
}()
if obs, err = srcDir.Readdir(-1); nil != err {
return
}
var errs []error
for _, obj := range obs {
srcPath := src + "/" + obj.Name()
dstPath := renameExist(dst + "/" + obj.Name())
if obj.IsDir() {
var tmpFiles []string
if tmpFiles, err = cpDir(srcPath, dstPath); nil != err {
errs = append(errs, err)
continue
}
copyFiles = append(copyFiles, tmpFiles...)
} else {
var tmpFile string
if tmpFile, err = cpFile(srcPath, dstPath); nil != err {
errs = append(errs, err)
continue
}
copyFiles = append(copyFiles, tmpFile)
}
}
var errString string
for _, err := range errs {
errString += err.Error() + "\n"
}
if errString != "" {
err = errors.New(errString)
}
return
}
func cpAny(src, dst string) (copyFiles []string, err error) {
var si os.FileInfo
if si, err = os.Stat(src); nil != err {
return
}
if si.IsDir() {
tmpDst := renameExist(dst + "/" + si.Name())
copyFiles, err = cpDir(src, tmpDst)
} else {
var tmpFile string
if tmpFile, err = cpFile(src, dst); nil != err {
return
}
copyFiles = append(copyFiles, tmpFile)
}
return
}