-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
81 lines (66 loc) · 1.71 KB
/
utils.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
package vfs
import (
"io"
"path/filepath"
)
// CopyFile slow copy file across different FS
func CopyFile(srcFs FS, srcFilePath string, destFs FS, destFilePath string) error {
// Some code from https://www.socketloop.com/tutorials/golang-copy-directory-including-sub-directories-files
srcFile, err := srcFs.Open(srcFilePath)
if err != nil {
return err
}
defer srcFile.Close()
srcInfo, err := srcFile.Stat()
if err != nil {
return err
}
destFile, err := destFs.Create(destFilePath)
if err != nil {
return err
}
defer destFile.Close()
_, err = io.Copy(destFile, srcFile)
if err != nil {
return err
}
if err != nil {
err = destFs.Chmod(destFilePath, srcInfo.Mode())
}
return nil
}
// CopyDir slow copy dir across different FS
func CopyDir(srcFs FS, srcDirPath string, destFs FS, destDirPath string) error {
// Some code from https://www.socketloop.com/tutorials/golang-copy-directory-including-sub-directories-files
// get properties of source dir
srcInfo, err := srcFs.Stat(srcDirPath)
if err != nil {
return err
}
// create dest dir
if err = destFs.MkdirAll(destDirPath, srcInfo.Mode()); err != nil {
return err
}
directory, err := srcFs.Open(srcDirPath)
if err != nil {
return err
}
defer directory.Close()
entries, err := directory.Readdir(-1)
for _, e := range entries {
srcFullPath := filepath.Join(srcDirPath, e.Name())
destFullPath := filepath.Join(destDirPath, e.Name())
if e.IsDir() {
// create sub-directories - recursively
if err = CopyDir(srcFs, srcFullPath, destFs, destFullPath); err != nil {
return err
}
} else {
// perform copy
if err = CopyFile(srcFs, srcFullPath, destFs, destFullPath); err != nil {
return err
}
}
}
return nil
}