github.com/wtfutil/wtf@v0.43.0/modules/power/battery.go (about) 1 //go:build !linux && !freebsd 2 3 package power 4 5 import ( 6 "fmt" 7 "os/exec" 8 "regexp" 9 "strconv" 10 "strings" 11 12 "github.com/wtfutil/wtf/utils" 13 ) 14 15 const ( 16 timeRegExp = "^(?:\\d|[01]\\d|2[0-3]):[0-5]\\d" 17 ) 18 19 type Battery struct { 20 args []string 21 cmd string 22 result string 23 24 Charge string 25 Remaining string 26 } 27 28 func NewBattery() *Battery { 29 battery := &Battery{ 30 args: []string{"-g", "batt"}, 31 cmd: "pmset", 32 } 33 34 return battery 35 } 36 37 /* -------------------- Exported Functions -------------------- */ 38 39 func (battery *Battery) Refresh() { 40 data := battery.execute() 41 battery.result = battery.parse(data) 42 } 43 44 func (battery *Battery) String() string { 45 return battery.result 46 } 47 48 /* -------------------- Unexported Functions -------------------- */ 49 50 func (battery *Battery) execute() string { 51 cmd := exec.Command(battery.cmd, battery.args...) 52 return utils.ExecuteCommand(cmd) 53 } 54 55 func (battery *Battery) parse(data string) string { 56 lines := strings.Split(data, "\n") 57 if len(lines) < 2 { 58 return msgNoBattery 59 } 60 61 stats := strings.Split(lines[1], "\t") 62 if len(stats) < 2 { 63 return msgNoBattery 64 } 65 66 details := strings.Split(stats[1], "; ") 67 if len(details) < 3 { 68 return msgNoBattery 69 } 70 71 str := "" 72 str = str + fmt.Sprintf(" %14s: %s\n", "Charge", battery.formatCharge(details[0])) 73 str = str + fmt.Sprintf(" %14s: %s\n", "Remaining", battery.formatRemaining(details[2])) 74 str = str + fmt.Sprintf(" %14s: %s\n", "State", battery.formatState(details[1])) 75 76 return str 77 } 78 79 func (battery *Battery) formatCharge(data string) string { 80 percent, _ := strconv.ParseFloat(strings.Replace(data, "%", "", -1), 32) 81 return utils.ColorizePercent(percent) 82 } 83 84 func (battery *Battery) formatRemaining(data string) string { 85 r, _ := regexp.Compile(timeRegExp) 86 87 result := r.FindString(data) 88 if result == "" || result == "0:00" { 89 result = "-" 90 } 91 92 return result 93 } 94 95 func (battery *Battery) formatState(data string) string { 96 color := "" 97 98 switch data { 99 case "charging": 100 color = "[green]" 101 case "discharging": 102 color = "[yellow]" 103 default: 104 color = "[white]" 105 } 106 107 return color + data + "[white]" 108 }