-
Notifications
You must be signed in to change notification settings - Fork 51
/
disk_posix.go
59 lines (48 loc) · 1.31 KB
/
disk_posix.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
//go:build linux || darwin
package disk
import (
"context"
"strconv"
"golang.org/x/sys/unix"
)
func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) {
stat := unix.Statfs_t{}
err := unix.Statfs(path, &stat)
if err != nil {
return nil, err
}
bsize := stat.Bsize
ret := &UsageStat{
Path: unescapeFstab(path),
Fstype: getFsType(stat),
Total: stat.Blocks * uint64(bsize),
Free: stat.Bavail * uint64(bsize),
InodesTotal: stat.Files,
InodesFree: stat.Ffree,
}
// if could not get InodesTotal, return empty
if ret.InodesTotal < ret.InodesFree {
return ret, nil
}
ret.InodesUsed = ret.InodesTotal - ret.InodesFree
ret.Used = (stat.Blocks - stat.Bfree) * uint64(bsize)
if ret.InodesTotal == 0 {
ret.InodesUsedPercent = 0
} else {
ret.InodesUsedPercent = (float64(ret.InodesUsed) / float64(ret.InodesTotal)) * 100.0
}
if (ret.Used + ret.Free) == 0 {
ret.UsedPercent = 0
} else {
ret.UsedPercent = (float64(ret.Used) / float64(ret.Used+ret.Free)) * 100.0
}
return ret, nil
}
// Unescape escaped octal chars (like space 040, ampersand 046 and backslash 134) to their real value in fstab fields issue#555
func unescapeFstab(path string) string {
escaped, err := strconv.Unquote(`"` + path + `"`)
if err != nil {
return path
}
return escaped
}