src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

disk.go (1014B)


      1 package disk
      2 
      3 import (
      4 	"context"
      5 	"fmt"
      6 	"os/exec"
      7 	"strings"
      8 )
      9 
     10 type Block struct {
     11 	mounts []string
     12 }
     13 
     14 func New(mounts ...string) *Block {
     15 	return &Block{mounts: mounts}
     16 }
     17 
     18 func (b *Block) Name() string {
     19 	return "disk"
     20 }
     21 
     22 func (b *Block) Render(ctx context.Context) (string, error) {
     23 	out, err := exec.CommandContext(ctx, "df", "-h").Output()
     24 	if err != nil {
     25 		return "", fmt.Errorf("exec df failed: %v", err)
     26 	}
     27 
     28 	var mounts = map[string]string{}
     29 	for i, l := range strings.Split(string(out), "\n") {
     30 		if i == 0 || len(l) == 0 {
     31 			continue
     32 		}
     33 
     34 		fields := strings.Fields(l)
     35 		if len(fields) < 6 {
     36 			continue
     37 		}
     38 
     39 		var icon rune = ''
     40 		switch fields[5] {
     41 		case "/":
     42 			icon = '/'
     43 		case "/home":
     44 			icon = ''
     45 		}
     46 
     47 		mounts[fields[5]] = fmt.Sprintf("%c %s", icon, fields[4])
     48 	}
     49 
     50 	var output strings.Builder
     51 	for i, m := range b.mounts {
     52 		if s, exists := mounts[m]; exists {
     53 			output.WriteString(s)
     54 			if i < len(b.mounts)-1 {
     55 				output.WriteRune(' ')
     56 			}
     57 		}
     58 	}
     59 
     60 	return output.String(), nil
     61 }