forked from zach-klippenstein/goadb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
device_info.go
91 lines (74 loc) · 2.09 KB
/
device_info.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package adb
import (
"bufio"
"strings"
"github.com/yosemite-open/go-adb/internal/errors"
)
type DeviceInfo struct {
// Always set.
Serial string
// Product, device, and model are not set in the short form.
Product string
Model string
DeviceInfo string
// Only set for devices connected via USB.
Usb string
}
// IsUsb returns true if the device is connected via USB.
func (d *DeviceInfo) IsUsb() bool {
return d.Usb != ""
}
func newDevice(serial string, attrs map[string]string) (*DeviceInfo, error) {
if serial == "" {
return nil, errors.AssertionErrorf("device serial cannot be blank")
}
return &DeviceInfo{
Serial: serial,
Product: attrs["product"],
Model: attrs["model"],
DeviceInfo: attrs["device"],
Usb: attrs["usb"],
}, nil
}
func parseDeviceList(list string, lineParseFunc func(string) (*DeviceInfo, error)) ([]*DeviceInfo, error) {
devices := []*DeviceInfo{}
scanner := bufio.NewScanner(strings.NewReader(list))
for scanner.Scan() {
device, err := lineParseFunc(scanner.Text())
if err != nil {
return nil, err
}
devices = append(devices, device)
}
return devices, nil
}
func parseDeviceShort(line string) (*DeviceInfo, error) {
fields := strings.Fields(line)
if len(fields) != 2 {
return nil, errors.Errorf(errors.ParseError,
"malformed device line, expected 2 fields but found %d", len(fields))
}
return newDevice(fields[0], map[string]string{})
}
func parseDeviceLong(line string) (*DeviceInfo, error) {
fields := strings.Fields(line)
if len(fields) < 5 {
return nil, errors.Errorf(errors.ParseError,
"malformed device line, expected at least 5 fields but found %d", len(fields))
}
attrs := parseDeviceAttributes(fields[2:])
return newDevice(fields[0], attrs)
}
func parseDeviceAttributes(fields []string) map[string]string {
attrs := map[string]string{}
for _, field := range fields {
key, val := parseKeyVal(field)
attrs[key] = val
}
return attrs
}
// Parses a key:val pair and returns key, val.
func parseKeyVal(pair string) (string, string) {
split := strings.Split(pair, ":")
return split[0], split[1]
}