/
fs.go
113 lines (92 loc) · 2.15 KB
/
fs.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
package osutil
import (
"fmt"
"io"
"os"
"path/filepath"
)
// FileExists checks whether the given path exists and belongs to a file.
func FileExists(path string) (bool, error) {
info, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
if info.IsDir() {
return false, fmt.Errorf("%v: is a directory, expected file", path)
}
return true, nil
}
// DirExists checks whether the given path exists and belongs to a directory.
func DirExists(path string) (bool, error) {
info, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
if !info.IsDir() {
return false, fmt.Errorf("%v: is a file, expected directory", path)
}
return true, nil
}
// CreateDirs creates directories from the given directory path arguments.
func CreateDirs(dirPaths ...string) error {
for _, path := range dirPaths {
if err := os.MkdirAll(path, 0755); err != nil {
return err
}
}
return nil
}
// CopyRecursively copies a given directory to the destination.
// Creates the directory if the destination doesn't exist.
func CopyRecursively(srcPath, dstPath string) error {
if err := os.Mkdir(dstPath, 0755); err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("directory %q doesn't exist", filepath.Dir(dstPath))
}
if !os.IsExist(err) {
return err
}
}
return filepath.Walk(srcPath, func(fname string, info os.FileInfo, err error) error {
if err != nil {
return err
}
relPath, err := filepath.Rel(srcPath, fname)
if err != nil {
return err
}
mirrorPath := filepath.Join(dstPath, relPath)
if info.IsDir() {
if err := os.Mkdir(mirrorPath, info.Mode()); err != nil {
if !os.IsExist(err) {
return err
}
}
} else {
fi, err := os.Lstat(fname)
if err != nil {
return err
}
srcf, err := os.Open(fname)
if err != nil {
return err
}
defer srcf.Close()
dstf, err := os.OpenFile(mirrorPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, fi.Mode())
if err != nil {
return err
}
defer dstf.Close()
if _, err := io.Copy(dstf, srcf); err != nil {
return err
}
}
return nil
})
}