-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
file.go
73 lines (60 loc) 路 1.52 KB
/
file.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
package helper
import (
"fmt"
"os"
"path"
"path/filepath"
cp "github.com/otiai10/copy"
log "github.com/sirupsen/logrus"
)
// Contains checks whether string exists in string slice.
func Contains(t string, a []string) bool {
for _, v := range a {
if v == t {
return true
}
}
return false
}
// CreateFile creates recursively basedir of file and returns created file object.
func CreateFile(p string) (*os.File, error) {
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return nil, fmt.Errorf("failed to create base directories for %s: %w", p, err)
}
f, err := os.Create(p)
if err != nil {
return nil, fmt.Errorf("failed to create file %s: %w", p, err)
}
return f, nil
}
// IsExists return true if file exists.
func IsExists(s string) bool {
_, err := os.Stat(s)
switch {
case err == nil:
return true
case os.IsNotExist(err):
return false
default:
// Schrodinger: file may or may not exist. See err for details.
// Therefore, do *NOT* use !os.IsNotExist(err) to test for file existence
log.Fatal(err)
return false
}
}
// CopyFile copy file to dest. Destination is either file or dir.
func CopyFile(src, dest string) error {
destStat, err := os.Stat(dest)
if err == nil {
if destStat.Mode().IsDir() {
dest = path.Join(dest, filepath.Base(src))
} else {
return fmt.Errorf("failed to copy file '%s': destination '%s' already exists", src, dest)
}
}
err = cp.Copy(src, dest)
if err != nil {
return fmt.Errorf("failed to copy file '%s' to '%s': %w", src, dest, err)
}
return nil
}