Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: remove unicode chars before parsing battery XML #15

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions battery.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const (
Full
Charging
Discharging
NotCharging
)

var states = [...]string{
Expand All @@ -59,6 +60,7 @@ var states = [...]string{
Full: "Full",
Charging: "Charging",
Discharging: "Discharging",
NotCharging: "Not Charging",
}

func (s State) String() string {
Expand Down
13 changes: 12 additions & 1 deletion battery_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ package battery
import (
"math"
"os/exec"
"strings"
"unicode"

plist "howett.net/plist"
)
Expand All @@ -50,8 +52,17 @@ func readBatteries() ([]*battery, error) {
return nil, nil
}

// Battery XML data can contain illegal unicode characters
printOnly := func(r rune) rune {
if unicode.IsPrint(r) {
return r
}
return -1
}
batteryXML := []byte(strings.Map(printOnly, string(out)))

var data []*battery
if _, err = plist.Unmarshal(out, &data); err != nil {
if _, err = plist.Unmarshal(batteryXML, &data); err != nil {
return nil, err
}
return data, nil
Expand Down
1 change: 1 addition & 0 deletions battery_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ func TestNewState(t *testing.T) {
}{
{"Charging", Charging, nil},
{"charging", Charging, nil},
{"Not Charging", NotCharging, nil},
{"strange", Unknown, fmt.Errorf("Invalid state `strange`")},
}

Expand Down