diff --git a/entry.go b/entry.go index 2128242..5ed5048 100644 --- a/entry.go +++ b/entry.go @@ -49,7 +49,9 @@ func show() { {"DeviceCache", device.Addr, "BatteryPercentRight"}, } batteries := pp.GetAttrByNames(attrs) - battery = fmt.Sprintf("C:%v%%/L:%v%%/R:%v%%", batteries[0], batteries[1], batteries[2]) + if len(batteries) == len(attrs[0]) { + battery = fmt.Sprintf("C:%v%%/L:%v%%/R:%v%%", batteries[0], batteries[1], batteries[2]) + } } var subInfo, nextOP string diff --git a/plist/plist.go b/plist/plist.go index 63695ed..7ad3338 100644 --- a/plist/plist.go +++ b/plist/plist.go @@ -1,7 +1,9 @@ package plist import ( + "fmt" "howett.net/plist" + "io" "os" ) @@ -27,17 +29,31 @@ func NewPlist(filename string) (*Info, error) { // PlistFileName = "/Library/Preferences/com.apple.Bluetooth.plist" // [["DeviceCache", "e0-eb-40-d4-d2-e9", "BatteryPercent"]] func (i *Info) GetAttrByNames(attrKeys [][]string) []interface{} { - var attr interface{} - var mapattr map[string]interface{} var res []interface{} - for _, condition := range attrKeys { - attr = i.PlistData - for _, c := range condition { - mapattr = attr.(map[string]interface{}) - attr = mapattr[c] + // https://github.com/haoguanguan/bluetooth_flow/issues/2 + attr, err := GetAttr(condition, i.PlistData) + if err != nil { + io.WriteString(os.Stderr, err.Error()+"\n") + continue } res = append(res, attr) } return res } + +func GetAttr(keys []string, attr interface{}) (interface{}, error) { + for _, c := range keys { + if attr == nil { + return nil, fmt.Errorf("no such keys %v", keys) + } + + val, ok := attr.(map[string]interface{}) + if !ok { + return nil, fmt.Errorf("cannot parse keys %v", keys) + } + + attr = val[c] + } + return attr, nil +} \ No newline at end of file