-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
files.go
79 lines (65 loc) · 1.31 KB
/
files.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
package path
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
)
// CopyDir copies the contents of a directory from 'src' to 'dest'
func CopyDir(src string, dest string) error {
mode, err := os.Stat(src)
if err != nil {
return err
}
if mode.IsDir() {
dirContents, err := ioutil.ReadDir(src)
if err != nil {
return err
}
for _, f := range dirContents {
srcFileaPath := filepath.Join(src, f.Name())
destFilePath := filepath.Join(dest, f.Name())
if err := CopyDir(srcFileaPath, destFilePath); err != nil {
return err
}
}
return nil
}
if err := os.MkdirAll(filepath.Dir(dest), os.ModePerm); err != nil {
return err
}
return copySingleFile(src, dest, mode)
}
func copySingleFile(src string, dest string, mode os.FileInfo) error {
if src == dest {
return nil
}
// Ensure the file is not a directory
file, err := os.Stat(src)
if err != nil {
return err
}
if file.IsDir() {
return fmt.Errorf("unable to copy directories: %s", src)
}
srcFile, err := os.Open(src)
if err != nil {
return err
}
defer srcFile.Close()
destFile, err := os.Create(dest)
if err != nil {
return err
}
defer destFile.Close()
err = os.Chmod(destFile.Name(), mode.Mode())
if err != nil {
return err
}
_, err = io.Copy(destFile, srcFile)
if err != nil {
return err
}
return nil
}