arbitrary exec example functional

This commit is contained in:
2022-08-02 20:58:35 -07:00
parent 0dddd8ca09
commit 2ae269d3c9
6 changed files with 52 additions and 4 deletions

2
adb.go
View File

@@ -38,7 +38,7 @@ type ConnOptions struct {
SerialNo Serial
}
// Connect to a device by serial number or IP.
// Connect to a device by IP:port.
//
// This will return a Device struct, which can be used to call other methods.
// If the connection fails or cannot complete on time, Connect will return an error.

View File

@@ -0,0 +1,36 @@
package main
import (
"context"
"errors"
"fmt"
"github.com/taigrr/adb"
)
func main() {
command := "ls"
ctx := context.TODO()
devs, err := adb.Devices(ctx)
if err != nil {
fmt.Printf("Error enumerating devices: %v\n", err)
return
}
for _, dev := range devs {
if !dev.IsAuthorized {
fmt.Printf("Dev `%s` is not authorized, authorize it to continue.\n", dev.SerialNo)
continue
}
stdout, stderr, errcode, err := dev.Shell(ctx, command)
_ = stderr
_ = errcode
switch {
case err == nil:
case errors.Is(err, adb.ErrUnspecified):
default:
fmt.Printf("Error running shell command `%s` on dev `%s`: %v\n", command, dev.SerialNo, err)
continue
}
fmt.Printf("%s:\n\n%s\n", dev.SerialNo, stdout)
}
}

2
go.mod
View File

@@ -1,3 +1,5 @@
module github.com/taigrr/adb
go 1.16
require github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510

2
go.sum
View File

@@ -0,0 +1,2 @@
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4=
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ=

View File

@@ -3,6 +3,8 @@ package adb
import (
"context"
"time"
"github.com/google/shlex"
)
// Shell allows you to run an arbitrary shell command against a device.
@@ -12,8 +14,14 @@ import (
// Instead of using Shell, please consider submitting a PR with the functionality
// you require.
func (d Device) Shell(ctx context.Context, command string) (stdout string, stderr string, ErrCode int, err error) {
return "", "", 1, nil
cmd, err := shlex.Split(command)
if err != nil {
return "", "", 1, err
}
prefix := []string{"-s", string(d.SerialNo), "shell"}
cmd = append(prefix, cmd...)
stdout, stderr, errcode, err := execute(ctx, cmd)
return stdout, stderr, errcode, err
}
// adb shell wm size

View File

@@ -47,7 +47,7 @@ func execute(ctx context.Context, args []string) (string, string, int, error) {
if customErr != nil {
err = customErr
}
if code != 0 && err == nil {
if _, ok := err.(*exec.ExitError); ok && code != 0 {
err = fmt.Errorf("received error code %d for stderr `%s`: %w", code, warnings, ErrUnspecified)
}