feat: 支持安装前后ADB命令与安装后启动应用
按工程保存前后置命令和自动启动选项,全程绑定选中设备,区分安装与后续动作失败。通过实际APK及目标设备解析Launcher入口,兼容activity-alias;增加模拟进程回归测试及0.8.0三套服务部署记录。
This commit is contained in:
1 parent
6f9cc7e7ea
commit
b46ebd1070
18 files changed
+472
-35
No files matched your search
+36
-7
@@ -109,14 +109,27 @@ func (s *Server) serveADB(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
BuildID string `json:"buildId"`
|
||||
Artifact string `json:"artifact"`
|
||||
Serial string `json:"serial"`
|
||||
BuildID string `json:"buildId"`
|
||||
Artifact string `json:"artifact"`
|
||||
Serial string `json:"serial"`
|
||||
BeforeCommands string `json:"beforeCommands"`
|
||||
AfterCommands string `json:"afterCommands"`
|
||||
LaunchAfter bool `json:"launchAfter"`
|
||||
}
|
||||
if e := decode(w, r, &req); e != nil {
|
||||
http.Error(w, e.Error(), 400)
|
||||
return
|
||||
}
|
||||
before, err := parseInstallCommands(req.BeforeCommands)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 400)
|
||||
return
|
||||
}
|
||||
after, err := parseInstallCommands(req.AfterCommands)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), 400)
|
||||
return
|
||||
}
|
||||
if req.Serial == "" || strings.HasPrefix(req.Serial, "-") || strings.ContainsAny(req.Serial, " \t\r\n\x00") {
|
||||
http.Error(w, "请选择服务端在线且已授权的设备", 400)
|
||||
return
|
||||
@@ -143,7 +156,7 @@ func (s *Server) serveADB(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
defer adbInstallLock.Unlock()
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute)
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 12*time.Minute)
|
||||
defer cancel()
|
||||
out, e := s.adbCommand(ctx, "devices", "-l")
|
||||
if e != nil {
|
||||
@@ -166,14 +179,30 @@ func (s *Server) serveADB(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "服务端APK缺失或摘要校验失败,请重新构建", 409)
|
||||
return
|
||||
}
|
||||
out, e = s.adbCommand(ctx, "-s", req.Serial, "install", "-r", path)
|
||||
var log strings.Builder
|
||||
if e = s.runInstallCommands(ctx, req.Serial, "安装前", before, &log); e != nil {
|
||||
http.Error(w, log.String()+"\n"+e.Error(), 400)
|
||||
return
|
||||
}
|
||||
log.WriteString("[安装APK] adb -s " + req.Serial + " install -r\n")
|
||||
installCtx, installCancel := context.WithTimeout(ctx, 2*time.Minute)
|
||||
out, e = s.adbCommand(installCtx, "-s", req.Serial, "install", "-r", path)
|
||||
installCancel()
|
||||
log.WriteString(out)
|
||||
if e != nil {
|
||||
http.Error(w, e.Error(), 400)
|
||||
http.Error(w, log.String()+"\n"+e.Error(), 400)
|
||||
return
|
||||
}
|
||||
if !strings.Contains(out, "Success") {
|
||||
http.Error(w, "ADB未确认安装成功:"+out, 400)
|
||||
return
|
||||
}
|
||||
jsonOut(w, map[string]any{"success": true, "serial": req.Serial, "output": out})
|
||||
postError := s.runInstallCommands(ctx, req.Serial, "安装后", after, &log)
|
||||
if postError == nil && req.LaunchAfter {
|
||||
postError = s.launchInstalledAPK(ctx, req.Serial, path, &log)
|
||||
}
|
||||
if postError != nil {
|
||||
log.WriteString("\n安装已成功,后续操作未完成:" + postError.Error())
|
||||
}
|
||||
jsonOut(w, map[string]any{"success": true, "serial": req.Serial, "output": log.String(), "postActionsSuccess": postError == nil})
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var shellWord = regexp.MustCompile(`^[A-Za-z0-9_./:@%+=,-]+$`)
|
||||
var apkPackage = regexp.MustCompile(`(?m)^package: name='([A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)+)'`)
|
||||
var launcherComponent = regexp.MustCompile(`^[A-Za-z0-9_.]+/[A-Za-z0-9_.$]+$`)
|
||||
|
||||
func parseInstallCommands(text string) ([][]string, error) {
|
||||
if len(text) > 16<<10 {
|
||||
return nil, fmt.Errorf("安装命令最多16KiB")
|
||||
}
|
||||
result := [][]string{}
|
||||
for i, line := range strings.Split(text, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
words := strings.Fields(line)
|
||||
if strings.EqualFold(words[0], "adb") || strings.EqualFold(words[0], "adb.exe") {
|
||||
words = words[1:]
|
||||
}
|
||||
if len(words) < 2 || words[0] != "shell" {
|
||||
return nil, fmt.Errorf("第%d行仅支持adb shell命令;设备由插件指定,请勿填写-s/-d/-e", i+1)
|
||||
}
|
||||
for _, word := range words {
|
||||
if !shellWord.MatchString(word) {
|
||||
return nil, fmt.Errorf("第%d行参数包含不支持的字符;请勿使用引号、管道、重定向或命令拼接", i+1)
|
||||
}
|
||||
}
|
||||
result = append(result, words)
|
||||
if len(result) > 10 {
|
||||
return nil, fmt.Errorf("每个安装阶段最多10条命令")
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Server) runInstallCommands(ctx context.Context, serial, stage string, commands [][]string, log *strings.Builder) error {
|
||||
for i, args := range commands {
|
||||
fmt.Fprintf(log, "[%s %d/%d] adb -s %s %s\n", stage, i+1, len(commands), serial, strings.Join(args, " "))
|
||||
child, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
out, e := s.adbCommand(child, append([]string{"-s", serial}, args...)...)
|
||||
cancel()
|
||||
log.WriteString(out)
|
||||
if e != nil {
|
||||
return fmt.Errorf("%s命令失败,已停止该阶段:%w", stage, e)
|
||||
}
|
||||
log.WriteString("\n退出码:0\n")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) apkApplicationID(ctx context.Context, path string) (string, error) {
|
||||
cfg, e := s.buildEnvironment()
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
exe := "aapt"
|
||||
if runtime.GOOS == "windows" {
|
||||
exe += ".exe"
|
||||
}
|
||||
candidates, _ := filepath.Glob(filepath.Join(cfg.AndroidHome, "build-tools", "*", exe))
|
||||
sort.Sort(sort.Reverse(sort.StringSlice(candidates)))
|
||||
if binary, e := exec.LookPath(exe); e == nil {
|
||||
candidates = append(candidates, binary)
|
||||
}
|
||||
for _, binary := range candidates {
|
||||
if st, e := os.Stat(binary); e != nil || st.IsDir() {
|
||||
continue
|
||||
}
|
||||
child, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
cmd := exec.CommandContext(child, binary, "dump", "badging", path)
|
||||
var out adbOutput
|
||||
cmd.Stdout = &out
|
||||
cmd.Stderr = &out
|
||||
e := cmd.Run()
|
||||
cancel()
|
||||
if e == nil {
|
||||
if match := apkPackage.FindStringSubmatch(out.String()); match != nil {
|
||||
return match[1], nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("无法从APK读取包名,请检查服务端Android SDK build-tools中的aapt;应用已安装")
|
||||
}
|
||||
|
||||
func (s *Server) launchInstalledAPK(ctx context.Context, serial, path string, log *strings.Builder) error {
|
||||
pkg, e := s.apkApplicationID(ctx, path)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
child, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
out, e := s.adbCommand(child, "-s", serial, "shell", "cmd", "package", "resolve-activity", "--brief", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER", pkg)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
component := ""
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if launcherComponent.MatchString(line) && strings.HasPrefix(line, pkg+"/") {
|
||||
component = line
|
||||
}
|
||||
}
|
||||
if component == "" {
|
||||
return fmt.Errorf("%s没有可解析的默认Launcher入口;保持安装成功", pkg)
|
||||
}
|
||||
fmt.Fprintf(log, "[打开应用] adb -s %s:%s\n", serial, component)
|
||||
out, e = s.adbCommand(child, "-s", serial, "shell", "am", "start", "-W", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER", "-n", "'"+component+"'")
|
||||
log.WriteString(out)
|
||||
if e == nil && (strings.Contains(out, "Error:") || strings.Contains(out, "Exception")) {
|
||||
e = fmt.Errorf("启动失败:%s", out)
|
||||
}
|
||||
return e
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInstallCommandValidation(t *testing.T) {
|
||||
commands, e := parseInstallCommands("# comment\n adb shell settings delete system app_source_white_list\r\nshell am force-stop com.example.app\n")
|
||||
if e != nil || len(commands) != 2 || commands[0][0] != "shell" {
|
||||
t.Fatal(commands, e)
|
||||
}
|
||||
for _, command := range []string{"adb -s other shell settings delete x y", "adb -H host shell id", "adb install app.apk", "adb shell id;reboot", "adb shell echo $HOME", "adb shell id | cat", "adb shell sh -c 'id'", strings.Repeat("shell id\n", 11)} {
|
||||
if _, e := parseInstallCommands(command); e == nil {
|
||||
t.Fatalf("accepted %q", command)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallActionsOrderingFailureAndLauncher(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
exe := filepath.Join(root, "fake-adb")
|
||||
name := "aapt"
|
||||
if runtime.GOOS == "windows" {
|
||||
exe += ".exe"
|
||||
name += ".exe"
|
||||
}
|
||||
helper := filepath.Join(root, "helper.go")
|
||||
writeFixture(t, helper, `package main
|
||||
import("encoding/json";"os";"strings";"fmt")
|
||||
func main(){a:=os.Args[1:];f,_:=os.OpenFile(os.Getenv("HOOK_LOG"),os.O_CREATE|os.O_APPEND|os.O_WRONLY,0600);json.NewEncoder(f).Encode(a);f.Close();text:=strings.Join(a," ");if strings.Contains(text,"fail"){fmt.Println("hook failed");os.Exit(7)};if a[0]=="devices"{fmt.Println("List of devices attached\nselected device model:Tablet");return};if a[0]=="dump"{fmt.Println("package: name='com.example.variant' versionCode='1'");return};if strings.Contains(text,"resolve-activity"){if os.Getenv("NO_LAUNCHER")=="1"{fmt.Println("No activity found")}else{fmt.Println("com.example.variant/.LauncherAlias")};return};fmt.Println("Success")}
|
||||
`)
|
||||
cmd := exec.Command("go", "build", "-o", exe, helper)
|
||||
if out, e := cmd.CombinedOutput(); e != nil {
|
||||
t.Fatalf("%v %s", e, out)
|
||||
}
|
||||
sdk := filepath.Join(root, "sdk")
|
||||
aapt := filepath.Join(sdk, "build-tools", "35.0.0", name)
|
||||
os.MkdirAll(filepath.Dir(aapt), 0700)
|
||||
binary, e := os.ReadFile(exe)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = os.WriteFile(aapt, binary, 0700); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
cfg, _ := json.Marshal(BuildEnvironment{Adb: exe, AndroidHome: sdk})
|
||||
config := filepath.Join(root, "env.json")
|
||||
writeFixture(t, config, string(cfg))
|
||||
bid := strings.Repeat("c", 32)
|
||||
apk := []byte("fake-apk")
|
||||
artifact := Artifact{Name: "0.apk", Hash: digest(apk), Size: int64(len(apk))}
|
||||
s := &Server{root: root, token: "test", environmentFile: config, builds: map[string]*Build{bid: {ID: bid, Status: "success", Artifacts: []Artifact{artifact}}}}
|
||||
writeFixture(t, filepath.Join(root, "artifacts", bid, artifact.Name), string(apk))
|
||||
log := filepath.Join(root, "calls.jsonl")
|
||||
t.Setenv("HOOK_LOG", log)
|
||||
run := func(before, after string, launch bool) *httptest.ResponseRecorder {
|
||||
os.WriteFile(log, nil, 0600)
|
||||
data, _ := json.Marshal(map[string]any{"buildId": bid, "artifact": artifact.Name, "serial": "selected", "beforeCommands": before, "afterCommands": after, "launchAfter": launch})
|
||||
req := httptest.NewRequest("POST", "/api/v1/adb/install", bytes.NewReader(data))
|
||||
req.Header.Set("Authorization", "Bearer test")
|
||||
w := httptest.NewRecorder()
|
||||
s.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
w := run("adb shell settings delete system app_source_white_list", "adb shell settings put system ready 1", true)
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body.String())
|
||||
}
|
||||
raw, _ := os.ReadFile(log)
|
||||
calls := string(raw)
|
||||
last := -1
|
||||
for _, part := range []string{`"delete"`, `"install"`, `"put"`, `"dump"`, `"resolve-activity"`, `"am","start"`} {
|
||||
pos := strings.Index(calls, part)
|
||||
if pos <= last {
|
||||
t.Fatalf("order %s: %s", part, calls)
|
||||
}
|
||||
last = pos
|
||||
}
|
||||
for _, line := range strings.Split(strings.TrimSpace(calls), "\n") {
|
||||
var args []string
|
||||
json.Unmarshal([]byte(line), &args)
|
||||
if args[0] != "dump" && args[0] != "devices" && (len(args) < 2 || args[0] != "-s" || args[1] != "selected") {
|
||||
t.Fatal("wrong target", args)
|
||||
}
|
||||
}
|
||||
w = run("shell fail", "shell id", true)
|
||||
raw, _ = os.ReadFile(log)
|
||||
if w.Code == 200 || strings.Contains(string(raw), `"install"`) {
|
||||
t.Fatal("pre failure did not stop install", w.Code, string(raw))
|
||||
}
|
||||
w = run("", "shell fail", true)
|
||||
raw, _ = os.ReadFile(log)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"postActionsSuccess":false`) || strings.Contains(string(raw), "resolve-activity") {
|
||||
t.Fatal("post failure result", w.Code, w.Body.String())
|
||||
}
|
||||
t.Setenv("NO_LAUNCHER", "1")
|
||||
w = run("", "", true)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"postActionsSuccess":false`) {
|
||||
t.Fatal("missing launcher must keep installed", w.Body.String())
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -182,7 +182,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||
fail := func(e error) { http.Error(w, e.Error(), 400) }
|
||||
if r.URL.Path == "/api/v1/health" {
|
||||
jsonOut(w, map[string]any{"version": "0.7.0", "privateFileList": true, "remoteADB": true, "syncPreflight": true, "dedicatedGit": true, "adminCLI": true, "preflight": true, "textComparison": true, "jdkSelection": true, "workspaceSelection": true, "os": runtime.GOOS, "sync": "http-manifest", "recovery": true})
|
||||
jsonOut(w, map[string]any{"version": "0.8.0", "installActions": true, "privateFileList": true, "remoteADB": true, "syncPreflight": true, "dedicatedGit": true, "adminCLI": true, "preflight": true, "textComparison": true, "jdkSelection": true, "workspaceSelection": true, "os": runtime.GOOS, "sync": "http-manifest", "recovery": true})
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/environment" && r.Method == "GET" {
|
||||
|
||||
Reference in new issue
Block a user