-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfileutils.go
260 lines (223 loc) · 6.84 KB
/
fileutils.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
// Package fileutils provides useful, high-level file operations
package fileutils
import (
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
)
// IsFile returns true if filename exists
func IsFile(filename string) bool {
return exists(filename, false)
}
// IsDir returns true if directory exists
func IsDir(dirname string) bool {
return exists(dirname, true)
}
func exists(name string, dir bool) bool {
info, err := os.Stat(name)
if os.IsNotExist(err) {
return false
}
if dir {
return info.IsDir()
}
return !info.IsDir()
}
// CopyFile copies a file from source to dest, preserving mode.
// Any existing file will be overwritten.
func CopyFile(src string, dst string) error {
srcInfo, err := os.Stat(src)
if err != nil {
return fmt.Errorf("can't stat %s: %w", src, err)
}
if !srcInfo.Mode().IsRegular() {
return fmt.Errorf("can't copy non-regular source file %s (%s)", src, srcInfo.Mode().String())
}
srcFh, err := os.Open(src) //nolint:gosec
if err != nil {
return fmt.Errorf("can't open source file %s: %w", src, err)
}
defer srcFh.Close()
err = os.MkdirAll(filepath.Dir(dst), 0750)
if err != nil {
return fmt.Errorf("can't make destination directory %s: %w", filepath.Dir(dst), err)
}
dstFh, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, srcInfo.Mode()) //nolint:gosec
if err != nil {
return fmt.Errorf("can't create destination file %s: %w", dst, err)
}
defer dstFh.Close()
size, err := io.Copy(dstFh, srcFh)
if err != nil {
return fmt.Errorf("can't copy data: %w", err)
}
if size != srcInfo.Size() {
return fmt.Errorf("incomplete copy, %d of %d", size, srcInfo.Size())
}
return dstFh.Sync()
}
// CopyDir copies all files from src to dst, recursively
func CopyDir(src string, dst string) error {
list, err := ListFiles(src)
if err != nil {
return fmt.Errorf("can't list source files in %s: %w", src, err)
}
for _, srcFile := range list {
stripSrcDir := strings.TrimPrefix(srcFile, src)
dstFile := filepath.Join(dst, stripSrcDir)
if err = CopyFile(srcFile, dstFile); err != nil {
return fmt.Errorf("can't copy %s to %s: %w", srcFile, dstFile, err)
}
}
return nil
}
// ListFiles gets recursive list of all files in a directory
func ListFiles(directory string) (list []string, err error) {
err = filepath.Walk(directory, func(path string, info os.FileInfo, e error) error {
if e != nil {
return e
}
if info.IsDir() {
return nil
}
list = append(list, path)
return nil
})
sort.Slice(list, func(i, j int) bool {
return list[i] < list[j]
})
return list, err
}
// TempFileName returns a new temporary file name in the directory dir.
// The filename is generated by taking pattern and adding a random
// string to the end. If pattern includes a "*", the random string
// replaces the last "*".
// If dir is the empty string, TempFileName uses the default directory
// for temporary files (see os.TempDir).
// Multiple programs calling TempFileName simultaneously
// will not choose the same file name.
func TempFileName(dir, pattern string) (string, error) {
if dir == "" {
dir = os.TempDir()
}
// prefixAndSuffix splits pattern by the last wildcard "*", if applicable
prefix, suffix := pattern, ""
if pos := strings.LastIndex(pattern, "*"); pos != -1 {
prefix, suffix = pattern[:pos], pattern[pos+1:]
}
// try to generate unique name
const maxTries = 10000
const randomBytes = 16 // 32 hex chars
for i := 0; i < maxTries; i++ {
// generate random bytes
b := make([]byte, randomBytes)
if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("failed to generate random name: %w", err)
}
// create file name and check if it exists
name := filepath.Join(dir, prefix+hex.EncodeToString(b)+suffix)
if _, err := os.Stat(name); os.IsNotExist(err) {
return name, nil
}
}
return "", errors.New("failed to create temporary file name after multiple attempts")
}
var reInvalidPathChars = regexp.MustCompile(`[<>:"|?*]+`) // invalid path characters
const maxPathLength = 1024 // maximum length for path
// SanitizePath returns a sanitized version of the given path.
func SanitizePath(s string) string {
s = strings.TrimSpace(s)
s = reInvalidPathChars.ReplaceAllString(filepath.Clean(s), "_")
// Normalize path separators to '/'
s = strings.ReplaceAll(s, `\`, "/")
if len(s) > maxPathLength {
s = s[:maxPathLength]
}
return s
}
// MoveFile moves a file from src to dst.
// If rename fails (e.g., cross-device move), it will fall back to copy+delete.
// It will create destination directories if they don't exist.
func MoveFile(src, dst string) error {
if src == "" {
return errors.New("empty source path")
}
if dst == "" {
return errors.New("empty destination path")
}
// check if source exists
srcInfo, err := os.Stat(src)
if err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("source file not found: %s", src)
}
return fmt.Errorf("failed to stat source file: %w", err)
}
// ensure source is a regular file
if !srcInfo.Mode().IsRegular() {
return fmt.Errorf("source is not a regular file: %s", src)
}
// try atomic rename first
if err = os.Rename(src, dst); err == nil {
return nil
}
// create destination directory if needed
if err = os.MkdirAll(filepath.Dir(dst), 0o750); err != nil {
return fmt.Errorf("failed to create destination directory: %w", err)
}
// try rename again after creating directory
if err = os.Rename(src, dst); err == nil {
return nil
}
// fallback to copy+delete if rename fails
if err = CopyFile(src, dst); err != nil {
return fmt.Errorf("failed to copy file: %w", err)
}
// verify the copy succeeded and sizes match
dstInfo, err := os.Stat(dst)
if err != nil {
return fmt.Errorf("failed to stat destination file: %w", err)
}
if srcInfo.Size() != dstInfo.Size() {
return fmt.Errorf("size mismatch after copy: source %d, destination %d", srcInfo.Size(), dstInfo.Size())
}
// remove the source file
if err := os.Remove(src); err != nil {
return fmt.Errorf("failed to remove source file: %w", err)
}
return nil
}
// TouchFile creates an empty file if it doesn't exist,
// or updates access and modification times if it does.
func TouchFile(path string) error {
if path == "" {
return errors.New("empty path")
}
// try to get file info
_, err := os.Stat(path)
if err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("failed to stat file: %w", err)
}
// create empty file with default mode
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) //nolint:gosec // intentionally permissive
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
}
return f.Close()
}
// file exists, update timestamps
now := time.Now()
return os.Chtimes(path, now, now)
}