-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile-utils.go
88 lines (73 loc) · 1.5 KB
/
file-utils.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
package simpleutils
import (
"errors"
"os"
"github.com/djherbis/atime"
)
//FileExists returns true if path corresponds to a file, and false
//if it corresponds to nothing or to a directory.
func FileExists(path string) (bool, error) {
fileInfo, err := os.Stat(path)
if err != nil {
return false, err
}
return !fileInfo.IsDir(), nil
}
//IsDirectory returns true if path corresponds to a directory, and false
//if it corresponds to nothing or to a file.
func IsDirectory(path string) (bool, error) {
fileInfo, err := os.Stat(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, err
}
return fileInfo.IsDir(), nil
}
//CopyFile reads file content into memory and writes it to a new file
func CopyFile(srcPath, destPath string) (int64, error) {
failed := false
src, err := os.Open(srcPath)
if err != nil {
return 0, err
}
defer src.Close()
dest, err := os.Create(destPath)
if err != nil {
return 0, err
}
defer func() {
dest.Close()
if failed {
os.Remove(destPath)
}
}()
failed = true
len, err := dest.ReadFrom(src)
if err != nil {
return 0, err
}
err = dest.Sync()
if err != nil {
return 0, err
}
fi, err := os.Stat(srcPath)
if err != nil {
return 0, err
}
err = os.Chmod(destPath, fi.Mode())
if err != nil {
return 0, err
}
atime, err := atime.Stat(srcPath)
if err != nil {
return 0, err
}
err = os.Chtimes(destPath, atime, fi.ModTime())
if err != nil {
return 0, err
}
failed = false
return len, nil
}