statusline/mem/mem.go

57 lines
1,005 B
Go
Raw Permalink Normal View History

2021-07-10 02:19:30 +02:00
package mem
import (
"fmt"
"strings"
"github.com/shirou/gopsutil/v3/mem"
"go.fanir.de/statusline/config"
)
var binarySuffixes = []string{"B", "KiB", "MiB", "GiB", "TiB"}
const binaryFactor = 1024
func HBin(a uint64, precision int) string {
f := float64(a)
var suffix string
for _, suffix = range binarySuffixes {
if f < binaryFactor {
break
}
f /= binaryFactor
}
return fmt.Sprintf("%.*f%s", precision, f, suffix)
}
func Mem(format config.Format, absolute, percent bool) (string, error) {
if !(absolute || percent) {
return "", nil
}
v, err := mem.VirtualMemory()
if err != nil {
return "", err // FIXME
}
s := &strings.Builder{}
if v.UsedPercent > 90 {
fmt.Fprint(s, format.Warning, "[")
} else {
fmt.Fprint(s, format.Default, "[")
}
if absolute {
fmt.Fprintf(s, "%s/%s", HBin(v.Used, 1), HBin(v.Total, 1))
if percent {
fmt.Fprint(s, " ")
}
}
if percent {
fmt.Fprintf(s, "%.0f%%", v.UsedPercent)
}
fmt.Fprint(s, "]")
return s.String(), nil
}