-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileutil.go
95 lines (82 loc) · 1.91 KB
/
fileutil.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
package goup
import (
"fmt"
"io"
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/karrick/godirwalk"
)
const (
BufSize = 10 * 1024
)
func copyFile(src, dst string) error {
srcFile, err := os.Open(src)
if err != nil {
return errors.Wrap(err, "Cannot open src")
}
defer srcFile.Close()
srcAttr, err := srcFile.Stat()
if err != nil {
return errors.Wrap(err, "Cannot get src attributes")
}
_, err = os.Stat(dst)
if err == nil {
return fmt.Errorf("File %s alread exists", dst)
}
dstFile, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, srcAttr.Mode())
if err != nil {
err = os.MkdirAll(filepath.Dir(dst), 0666)
if err != nil {
return errors.Wrap(err, "Error when creating parent directory in target location")
}
dstFile, err = os.Create(dst)
if err != nil {
return err
}
}
defer dstFile.Close()
buf := make([]byte, BufSize)
for {
n, err := srcFile.Read(buf)
if err != nil && err != io.EOF {
return err
}
if n == 0 {
break
}
if _, err := dstFile.Write(buf[:n]); err != nil {
return err
}
}
return nil
}
func RecursiveCopyDir(src, dst string) error {
buf := make([]byte, BufSize)
baseDirLen := len(src)
err := godirwalk.Walk(src, &godirwalk.Options{
ScratchBuffer: buf,
Callback: func(osPathname string, de *godirwalk.Dirent) error {
if de.IsDir() {
return nil
}
newPath := filepath.Join(dst, osPathname[baseDirLen:])
err := copyFile(osPathname, newPath)
if err != nil {
fmt.Println("Error: ", err)
}
return err
},
PostChildrenCallback: func(osPathname string, de *godirwalk.Dirent) error {
deChildren, err := godirwalk.ReadDirents(osPathname, buf)
if err != nil {
return err
}
if len(deChildren) > 0 {
return nil
}
return os.MkdirAll(filepath.Join(dst, osPathname[baseDirLen:]), 0666)
},
})
return err
}