statusline/statusline.go

109 lines
1.8 KiB
Go

package main
import (
"fmt"
"os"
"runtime"
"strconv"
"time"
"github.com/shirou/gopsutil/v3/load"
"github.com/shirou/gopsutil/v3/mem"
)
const warnFormat = "#[bg=colour208]"
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 usage() {
fmt.Fprintln(os.Stderr, "Usage:", os.Args[0], "<window_width>")
os.Exit(2)
}
func printLoad(precision int) {
l, err := load.Avg()
if err != nil {
panic(err) // fixme
}
if l.Load1 > float64(runtime.NumCPU()) {
fmt.Print(warnFormat)
}
fmt.Printf("[%.[1]*[2]f %.[1]*[3]f %.[1]*[4]f]",
precision, l.Load1, l.Load5, l.Load15)
}
func printMem(absolute, percent bool) {
if !(absolute || percent) {
return
}
v, err := mem.VirtualMemory()
if err != nil {
panic(err) //fixme
}
if v.UsedPercent > 90 {
fmt.Print(warnFormat, "[")
} else {
fmt.Print("#[default][")
}
if absolute {
fmt.Printf("%s/%s", HBin(v.Used, 1), HBin(v.Total, 1))
if percent {
fmt.Print(" ")
}
}
if percent {
fmt.Printf("%.0f%%", v.UsedPercent)
}
fmt.Print("]")
}
func printTime(format string) {
now := time.Now()
fmt.Print(now.Format("#[default]" + format))
}
func main() {
if len(os.Args) != 2 {
usage()
}
cols, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Fprintln(os.Stderr, err)
usage()
}
if cols >= 150 {
printLoad(2)
printMem(true, true)
printTime(" Mon 2006-01-02 15:04")
} else if cols >= 120 {
printLoad(2)
printMem(false, true)
printTime(" 15:04")
} else if cols >= 100 {
printLoad(0)
printMem(false, true)
printTime(" 15:04")
} else if cols >= 80 {
printTime("15:04")
}
}