Skip to content

Commit

Permalink
Merge pull request #3 from haoguanguan/bugfix/bluetooth_plist_panic
Browse files Browse the repository at this point in the history
[bugfix] panic when bluetooth.plist parse error
  • Loading branch information
o98k-ok authored Jan 28, 2022
2 parents a9b9578 + 539c4f8 commit 780eab9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
4 changes: 3 additions & 1 deletion entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
30 changes: 23 additions & 7 deletions plist/plist.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package plist

import (
"fmt"
"howett.net/plist"
"io"
"os"
)

Expand All @@ -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
}

0 comments on commit 780eab9

Please sign in to comment.