-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathdevices.go
78 lines (69 loc) · 1.66 KB
/
devices.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
// Copyright (c) 2015, Daniel Martí <[email protected]>
// See LICENSE for licensing information
package main
import (
"fmt"
"os"
"mvdan.cc/fdroidcl/adb"
)
var cmdDevices = &Command{
UsageLine: "devices",
Short: "List connected devices",
}
func init() {
cmdDevices.Run = runDevices
}
func runDevices(args []string) error {
if err := startAdbIfNeeded(); err != nil {
return err
}
devices, err := adb.Devices()
if err != nil {
return fmt.Errorf("could not get devices: %v", err)
}
for _, device := range devices {
fmt.Printf("%s - %s (%s)\n", device.ID, device.Model, device.Product)
}
return nil
}
func startAdbIfNeeded() error {
if adb.IsServerRunning() {
return nil
}
if err := adb.StartServer(); err != nil {
return fmt.Errorf("could not start ADB server: %v", err)
}
return nil
}
func maybeOneDevice() (*adb.Device, error) {
if err := startAdbIfNeeded(); err != nil {
return nil, err
}
devices, err := adb.Devices()
if err != nil {
return nil, fmt.Errorf("could not get devices: %v", err)
}
if len(devices) < 1 {
return nil, nil
}
envAndroidSerial := os.Getenv("ANDROID_SERIAL")
if len(envAndroidSerial) > 0 {
for _, device := range devices {
if device.ID == envAndroidSerial {
return device, nil
}
}
return nil, fmt.Errorf("ANDROID_SERIAL set, but no device with this serial found")
}
if len(devices) > 1 {
return nil, fmt.Errorf("at most one connected device can be used, if ANDROID_SERIAL was not set")
}
return devices[0], nil
}
func oneDevice() (*adb.Device, error) {
device, err := maybeOneDevice()
if err == nil && device == nil {
err = fmt.Errorf("a connected device is needed")
}
return device, err
}