-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathos_unix.go
More file actions
36 lines (32 loc) · 1.03 KB
/
os_unix.go
File metadata and controls
36 lines (32 loc) · 1.03 KB
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
//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos
package helper
import (
"fmt"
"math"
"os"
"golang.org/x/sys/unix"
)
// DiskStat returns the total, free, and percentage free of the drive path.
// If no path is provided then the drive of the working directory is used.
//
// The returned string is a humanized percentage, ie "50%".
func DiskStat(path string) (float64, float64, float64, string, error) {
var stat unix.Statfs_t
if path == "" {
wd, err := os.Getwd()
if err != nil {
return 0, 0, 0, "", fmt.Errorf("disk stat getwd: %w", err)
}
path = wd
}
if err := unix.Statfs(path, &stat); err != nil {
return 0, 0, 0, "", fmt.Errorf("unix stat fs: %w", err)
}
// Available blocks * size per block = available space in bytes
const half, hundred = 0.5, 100
totl := float64(stat.Blocks) * float64(stat.Bsize)
free := float64(stat.Bavail) * float64(stat.Bsize)
perc := (free / totl) * hundred
s := fmt.Sprintf("%d%%", int64(math.Floor(perc+half)))
return totl, free, perc, s, nil
}