Files
RemoteCompilation/server/preflight.go
T
tongtong 6f9cc7e7ea feat: 增加独立构建工作区、服务端ADB与私有文件清单
支持Git提交导入及未提交源码叠加,APK原名下载和完成通知。新增服务端设备安装与按工程维护的私有文件清单,修复Wrapper预检查、布局及IDE读锁和保存状态问题。更新协议、测试和部署记录;服务端0.7.0,插件0.7.1。
2026-11-27 11:04:58 +08:00

319 lines
9.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"context"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
)
type CheckItem struct {
Name string `json:"name"`
Status string `json:"status"`
Path string `json:"path,omitempty"`
Message string `json:"message"`
}
type Preflight struct {
Ready bool `json:"ready"`
Phase string `json:"phase,omitempty"`
Items []CheckItem `json:"items"`
}
func (p *Preflight) add(name, status, path, message string) {
p.Items = append(p.Items, CheckItem{name, status, path, message})
if status == "error" {
p.Ready = false
}
}
func (p Preflight) failure() error {
var messages []string
for _, item := range p.Items {
if item.Status == "error" {
messages = append(messages, item.Name+":"+item.Message+" ["+item.Path+"]")
}
}
if len(messages) > 0 {
return fmt.Errorf("构建前检查未通过:%s", strings.Join(messages, ";"))
}
return nil
}
// Probe the actual service identity/mount namespace, never infer access from mode bits.
// Missing directories are tested through their nearest existing parent, without creating caches.
func probeWritable(path string) error {
if path == "" {
return fmt.Errorf("未配置路径")
}
dir := path
for {
st, e := os.Stat(dir)
if e == nil {
if !st.IsDir() {
return fmt.Errorf("不是目录:%s", dir)
}
break
}
if !os.IsNotExist(e) {
return e
}
parent := filepath.Dir(dir)
if parent == dir {
return e
}
dir = parent
}
f, e := os.CreateTemp(dir, ".remotecompile-permission-*")
if e != nil {
return e
}
name := f.Name()
_, writeErr := f.Write([]byte("permission probe\n"))
closeErr := f.Close()
removeErr := os.Remove(name)
if writeErr != nil {
return writeErr
}
if closeErr != nil {
return closeErr
}
return removeErr
}
func permissionDirectories(work string) error {
return filepath.WalkDir(work, func(path string, d fs.DirEntry, e error) error {
if e != nil {
return e
}
if d.Type()&os.ModeSymlink != 0 {
return fmt.Errorf("工程内存在符号链接:%s", path)
}
if !d.IsDir() {
return nil
}
if path != work && (d.Name() == ".git" || d.Name() == "node_modules") {
return filepath.SkipDir
}
if e := probeWritable(path); e != nil {
return fmt.Errorf("%s:%w", path, e)
}
if path != work && reservedSource(d.Name()) {
return filepath.SkipDir
}
return nil
})
}
// Only literal declarations are inspected. Gradle expressions remain Gradle's responsibility.
var sdkLiteral = regexp.MustCompile(`(?m)\b(compileSdkVersion|compileSdk|buildToolsVersion|ndkVersion)\s*(?:=\s*|\(\s*)?["']?([0-9]+(?:\.[0-9]+)*)(?:["'\s\);]|$)`)
var blockComment = regexp.MustCompile(`(?s)/\*.*?\*/`)
var lineComment = regexp.MustCompile(`(?m)//[^\n]*`)
var cmakeLiteral = regexp.MustCompile(`\bcmake\s*\{\s*version\s*(?:=\s*|\(\s*)?["']([0-9]+(?:\.[0-9]+)+)["']`)
func requiredSDKPackages(work string) ([]string, bool, error) {
var packages []string
seen := map[string]bool{}
android := false
err := filepath.WalkDir(work, func(path string, d fs.DirEntry, e error) error {
if e != nil {
return e
}
if d.Type()&os.ModeSymlink != 0 {
return fmt.Errorf("拒绝读取符号链接:%s", path)
}
if d.IsDir() {
if path != work && reservedSource(d.Name()) {
return filepath.SkipDir
}
return nil
}
if d.Name() != "build.gradle" && d.Name() != "build.gradle.kts" {
return nil
}
st, e := d.Info()
if e != nil {
return e
}
if st.Size() > 4<<20 {
return fmt.Errorf("构建脚本超过检查大小限制:%s", path)
}
data, e := os.ReadFile(path)
if e != nil {
return e
}
text := lineComment.ReplaceAllString(blockComment.ReplaceAllString(string(data), ""), "")
if strings.Contains(text, "com.android.") {
android = true
}
for _, m := range sdkLiteral.FindAllStringSubmatch(text, -1) {
prefix := map[string]string{"compileSdk": "platforms;android-", "compileSdkVersion": "platforms;android-", "ndkVersion": "ndk;", "buildToolsVersion": "build-tools;"}[m[1]]
pkg := prefix + m[2]
if !seen[pkg] {
seen[pkg] = true
packages = append(packages, pkg)
}
android = true
}
for _, m := range cmakeLiteral.FindAllStringSubmatch(text, -1) {
pkg := "cmake;" + m[1]
if !seen[pkg] {
seen[pkg] = true
packages = append(packages, pkg)
}
android = true
}
return nil
})
return packages, android, err
}
func (s *Server) preflight(work string, c BuildEnvironment) Preflight {
p := Preflight{Ready: true, Items: []CheckItem{}}
packages, android, scanErr := requiredSDKPackages(work)
_, jarErr := os.Stat(filepath.Join(work, "gradle", "wrapper", "gradle-wrapper.jar"))
toolStatus := "error"
if !android && jarErr != nil {
toolStatus = "warning"
}
if e := permissionDirectories(work); e != nil {
p.add("工程目录权限", "error", work, e.Error()+"\n"+permissionGuidance(work))
} else {
p.add("工程目录权限", "ok", work, "服务账户可读取并写入工程目录及已有构建目录")
}
for _, dir := range []struct{ name, path string }{{"Gradle 缓存权限", c.GradleUserHome}, {"服务数据权限", s.root}} {
if e := probeWritable(dir.path); e != nil {
p.add(dir.name, "error", dir.path, e.Error()+"\n"+permissionGuidance(dir.path))
} else {
p.add(dir.name, "ok", dir.path, "可创建、写入和删除临时文件")
}
}
javaHome := c.JavaHome
if javaHome == "" {
if bin, e := exec.LookPath(javaExecutable("java")); e == nil {
if real, e := filepath.EvalSymlinks(bin); e == nil {
bin = real
}
javaHome = filepath.Dir(filepath.Dir(bin))
}
}
if j, ok := inspectJDK(javaHome, "preflight"); !ok {
p.add("JDK", toolStatus, javaHome, "未找到完整 JDK(需要 java、javac 和 release);请配置或选择服务端 JDK")
} else {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
cmd := exec.CommandContext(ctx, filepath.Join(j.Home, "bin", javaExecutable("java")), "-version")
cmd.Env = c.environ()
e := cmd.Run()
cancel()
if e != nil {
p.add("JDK", toolStatus, j.Home, "java 无法运行:"+e.Error())
} else {
p.add("JDK", "ok", j.Home, "Java "+j.Version+" 可运行;兼容性由项目 Gradle/AGP 验证")
}
}
version := wrapperVersion(work)
installed := ""
if !c.PreferWrapper {
homes := []string{c.GradleHome}
for _, kind := range []string{"bin", "all"} {
matches, _ := filepath.Glob(filepath.Join(c.GradleUserHome, "wrapper", "dists", "gradle-"+version+"-"+kind, "*", "gradle-"+version))
homes = append(homes, matches...)
}
for _, home := range homes {
if installed = nativeGradle(home, version); installed != "" {
break
}
}
}
if installed != "" {
p.add("Gradle", "ok", installed, "复用版本 "+version)
} else {
wrapper := "gradlew"
if runtime.GOOS == "windows" {
wrapper += ".bat"
}
err := error(nil)
for _, name := range []string{wrapper, "gradle/wrapper/gradle-wrapper.jar", "gradle/wrapper/gradle-wrapper.properties"} {
if f, e := os.Open(filepath.Join(work, filepath.FromSlash(name))); e != nil {
err = e
break
} else {
f.Close()
}
}
if err != nil {
p.add("Gradle", toolStatus, work, "没有可复用的匹配版本,项目 Wrapper 不完整或不可读:"+err.Error())
} else {
p.add("Gradle", "warning", work, "使用项目 Wrapper,分发包可能需要下载;请求版本 "+version)
}
}
if scanErr != nil {
p.add("SDK 需求扫描", "error", work, scanErr.Error())
return p
}
if !android {
p.add("Android SDK", "warning", c.AndroidHome, "未识别静态 Android 配置;动态 SDK/NDK/CMake 版本由 Gradle 检查")
return p
}
sdk := c.AndroidHome
// local.properties wins over environment variables in Android builds.
if data, e := os.ReadFile(filepath.Join(work, "local.properties")); e == nil {
for _, line := range strings.Split(string(data), "\n") {
k, v, ok := strings.Cut(strings.TrimSpace(line), "=")
if ok && strings.TrimSpace(k) == "sdk.dir" {
sdk = strings.ReplaceAll(strings.ReplaceAll(strings.TrimSpace(v), `\:`, ":"), `\\`, `\`)
if !filepath.IsAbs(sdk) {
sdk = filepath.Join(work, sdk)
}
p.add("SDK 路径覆盖", "warning", sdk, "服务端 local.properties 的 sdk.dir 覆盖环境变量")
}
}
}
if st, e := os.Stat(sdk); e != nil || !st.IsDir() {
p.add("Android SDK", "error", sdk, "SDK 目录不存在或不可访问,请配置服务端 Android SDK")
return p
}
writable := probeWritable(sdk)
if writable != nil {
p.add("SDK 写权限", "warning", sdk, "SDK 不可写,缺少组件时无法自动安装:"+writable.Error()+"\n"+permissionGuidance(sdk))
} else {
p.add("SDK 写权限", "ok", sdk, "服务账户可写,允许 Gradle 安装缺少的组件")
}
for _, pkg := range packages {
parts := strings.Split(pkg, ";")
path := filepath.Join(append([]string{sdk}, parts...)...)
marker := "source.properties"
if parts[0] == "platforms" {
marker = "android.jar"
}
if parts[0] == "cmake" {
marker = filepath.Join("bin", javaExecutable("cmake"))
}
if parts[0] == "ndk" {
marker = filepath.Join("build", "cmake", "android.toolchain.cmake")
}
if parts[0] == "build-tools" {
marker = javaExecutable("aapt2")
}
if f, e := os.Open(filepath.Join(path, marker)); e == nil {
f.Close()
p.add(pkg, "ok", path, "已安装且可读")
} else {
status := "warning"
if writable != nil || probeWritable(path) != nil {
status = "error"
}
p.add(pkg, status, path, "组件缺失或不完整;需通过 SDK Manager 安装,或由 Gradle 在许可证和网络可用时自动安装")
}
}
if entries, e := os.ReadDir(filepath.Join(sdk, "licenses")); e != nil || len(entries) == 0 {
p.add("SDK 许可证", "warning", filepath.Join(sdk, "licenses"), "未找到许可证记录,自动安装前需管理员确认许可证")
}
p.add("需求范围", "warning", work, "仅检查静态 compileSdk/buildToolsVersion/ndkVersion 及 cmake 块首部的 version;动态配置与默认工具版本最终由 Gradle 验证")
return p
}