memory.go (1394B)
1 package memory 2 3 import ( 4 "context" 5 "fmt" 6 "os/exec" 7 "strconv" 8 "strings" 9 ) 10 11 type Block struct{} 12 13 func New() *Block { 14 return &Block{} 15 } 16 17 func (b *Block) Name() string { 18 return "memory" 19 } 20 21 func (b *Block) Render(ctx context.Context) (string, error) { 22 var output strings.Builder 23 24 out, err := exec.CommandContext(ctx, "free", "-m").Output() 25 if err != nil { 26 return "", fmt.Errorf("failed to exec: %v", err) 27 } 28 29 for _, l := range strings.Split(string(out), "\n") { 30 if len(l) == 0 { 31 continue 32 } 33 34 fields := strings.Fields(l) 35 if len(fields) < 3 { 36 continue 37 } 38 39 switch fields[0] { 40 case "Mem:": 41 total, err := strconv.ParseFloat(fields[1], 64) 42 if err != nil { 43 return "", fmt.Errorf( 44 "failed to parse total memory: %v", err, 45 ) 46 } 47 used, err := strconv.ParseFloat(fields[2], 64) 48 if err != nil { 49 return "", fmt.Errorf( 50 "failed to parse used memory: %v", err, 51 ) 52 } 53 54 fmt.Fprintf(&output, " %.0f%% ", (used/total)*100) 55 case "Swap:": 56 total, err := strconv.ParseFloat(fields[1], 64) 57 if err != nil { 58 return "", fmt.Errorf( 59 "failed to parse total memory: %v", err, 60 ) 61 } 62 used, err := strconv.ParseFloat(fields[2], 64) 63 if err != nil { 64 return "", fmt.Errorf( 65 "failed to parse used memory: %v", err, 66 ) 67 } 68 69 fmt.Fprintf(&output, " %.0f%%", (used/total)*100) 70 } 71 } 72 73 return output.String(), nil 74 }