-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileutil.go
127 lines (109 loc) · 2.34 KB
/
fileutil.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
package rpc25519
import (
"fmt"
"io"
"io/fs"
"os"
"os/user"
"syscall"
"time"
)
func fileExists(name string) bool {
fi, err := os.Stat(name)
if err != nil {
return false
}
if fi.IsDir() {
return false
}
return true
}
func dirExists(name string) bool {
fi, err := os.Stat(name)
if err != nil {
return false
}
if fi.IsDir() {
return true
}
return false
}
func fileSize(name string) (int64, error) {
fi, err := os.Stat(name)
if err != nil {
return -1, err
}
return fi.Size(), nil
}
// IsWritable returns true if the file
// does not exist. Otherwise it checks
// the write bits. If any write bits
// (owner, group, others) are set, then
// we return true. Otherwise false.
func isWritable(path string) bool {
if !fileExists(path) {
return true
}
fileInfo, err := os.Stat(path)
panicOn(err)
// Get the file's mode (permission bits)
mode := fileInfo.Mode()
// Check write permission for owner, group, and others
return mode&0222 != 0 // Write permission for any?
}
func copyFileDestSrc(topath, frompath string) (int64, error) {
if !fileExists(frompath) {
return 0, fs.ErrNotExist
}
src, err := os.Open(frompath)
if err != nil {
return 0, err
}
defer src.Close()
dest, err := os.Create(topath)
if err != nil {
return 0, err
}
defer dest.Close()
return io.Copy(dest, src)
}
// returns empty string on error.
func getFileOwnerName(filepath string) string {
// Get file info
fileInfo, err := os.Stat(filepath)
if err != nil {
return "" //, err
}
// Get system-specific file info
stat := fileInfo.Sys()
if stat == nil {
return "" //, fmt.Errorf("no system-specific file info available")
}
// Get owner UID
uid := stat.(*syscall.Stat_t).Uid
// Look up user by UID
owner, err := user.LookupId(fmt.Sprint(uid))
if err != nil {
return "" //, err
}
return owner.Username
}
func truncateFileToZero(path string) error {
var perm os.FileMode
f, err := os.OpenFile(path, os.O_TRUNC, perm)
if err != nil {
return fmt.Errorf("could not open file %q for truncation: %v", path, err)
}
if err = f.Close(); err != nil {
return fmt.Errorf("could not close file handler for %q after truncation: %v", path, err)
}
return nil
}
func FileSizeModTime(name string) (sz int64, modTime time.Time, err error) {
var fi os.FileInfo
fi, err = os.Stat(name)
if err != nil {
return
}
return fi.Size(), fi.ModTime(), nil
}