-
Notifications
You must be signed in to change notification settings - Fork 410
Expand file tree
/
Copy pathfilesystem.go
More file actions
113 lines (91 loc) · 2.32 KB
/
filesystem.go
File metadata and controls
113 lines (91 loc) · 2.32 KB
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 fsutil
import (
"bytes"
"io"
"os"
"path/filepath"
"strings"
recursiveCopy "github.com/otiai10/copy"
)
// IsSymlink checks if the provided file info is a symlink
func IsSymlink(mode os.FileMode) bool {
return mode&os.ModeSymlink == os.ModeSymlink
}
// IsRecursiveSymlink checks if the provided non-resolved file info
// is a recursive symlink
func IsRecursiveSymlink(f os.FileInfo, symlinkPath string) bool {
// check if recursive symlink
if IsSymlink(f.Mode()) {
resolvedPath, err := filepath.EvalSymlinks(symlinkPath)
if err != nil || strings.HasPrefix(symlinkPath, filepath.ToSlash(resolvedPath)) {
return true
}
}
return false
}
// WriteToFile writes data to a file
func WriteToFile(data []byte, filePath string) error {
err := os.MkdirAll(filepath.Dir(filePath), 0755)
if err != nil {
return err
}
return os.WriteFile(filePath, data, 0666)
}
// ReadFile reads a file with a given limit
func ReadFile(path string, limit int64) ([]byte, error) {
if limit <= 0 {
return os.ReadFile(path)
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
st, err := f.Stat()
if err != nil {
return nil, err
}
size := st.Size()
if limit > 0 && size > limit {
size = limit
}
buf := bytes.NewBuffer(nil)
buf.Grow(int(size))
_, err = io.Copy(buf, io.LimitReader(f, limit))
return buf.Bytes(), err
}
// Copy copies a file to a destination path
func Copy(sourcePath string, targetPath string, overwrite bool) error {
if overwrite {
return recursiveCopy.Copy(sourcePath, targetPath)
}
var err error
// Convert to absolute path
sourcePath, err = filepath.Abs(sourcePath)
if err != nil {
return err
}
// Convert to absolute path
targetPath, err = filepath.Abs(targetPath)
if err != nil {
return err
}
return filepath.Walk(sourcePath, func(nextSourcePath string, fileInfo os.FileInfo, err error) error {
nextTargetPath := filepath.Join(targetPath, strings.TrimPrefix(nextSourcePath, sourcePath))
if fileInfo == nil {
return nil
}
if !fileInfo.Mode().IsRegular() {
return nil
}
if fileInfo.IsDir() {
_ = os.MkdirAll(nextTargetPath, os.ModePerm)
return Copy(nextSourcePath, nextTargetPath, overwrite)
}
_, statErr := os.Stat(nextTargetPath)
if statErr != nil {
return recursiveCopy.Copy(nextSourcePath, nextTargetPath)
}
return nil
})
}