github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/system/disk/disk_posix.go (about) 1 //go:build linux || darwin 2 3 package disk 4 5 import ( 6 "context" 7 "strconv" 8 9 "golang.org/x/sys/unix" 10 ) 11 12 func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) { 13 stat := unix.Statfs_t{} 14 err := unix.Statfs(path, &stat) 15 if err != nil { 16 return nil, err 17 } 18 bsize := stat.Bsize 19 20 ret := &UsageStat{ 21 Path: unescapeFstab(path), 22 Fstype: getFsType(stat), 23 Total: stat.Blocks * uint64(bsize), 24 Free: stat.Bavail * uint64(bsize), 25 InodesTotal: stat.Files, 26 InodesFree: stat.Ffree, 27 } 28 29 // if could not get InodesTotal, return empty 30 if ret.InodesTotal < ret.InodesFree { 31 return ret, nil 32 } 33 34 ret.InodesUsed = ret.InodesTotal - ret.InodesFree 35 ret.Used = (stat.Blocks - stat.Bfree) * uint64(bsize) 36 37 if ret.InodesTotal == 0 { 38 ret.InodesUsedPercent = 0 39 } else { 40 ret.InodesUsedPercent = (float64(ret.InodesUsed) / float64(ret.InodesTotal)) * 100.0 41 } 42 43 if (ret.Used + ret.Free) == 0 { 44 ret.UsedPercent = 0 45 } else { 46 ret.UsedPercent = (float64(ret.Used) / float64(ret.Used+ret.Free)) * 100.0 47 } 48 49 return ret, nil 50 } 51 52 // Unescape escaped octal chars (like space 040, ampersand 046 and backslash 134) to their real value in fstab fields issue#555 53 func unescapeFstab(path string) string { 54 escaped, err := strconv.Unquote(`"` + path + `"`) 55 if err != nil { 56 return path 57 } 58 return escaped 59 }