feat: 完善远程构建恢复、工程同步与变体选择
增加持久化构建记录、历史 APK 恢复、断点下载、Gradle 缓存复用、系统代理与按工程选择服务端 JDK。 支持已有工程目录、Git 状态检查、原生忽略规则和文本换行等价比较,修复干净检出与历史同步快照不一致时的误拦截。 优化插件设备可选构建、侧栏滚动、左右日志布局、时间显示和构建变体快速选择,并补充部署与协议文档。 验证:17 项 Go 测试、22 项插件测试及 HTTP/HTTPS 两条端到端测试通过;Linux/macOS 服务端交叉编译通过。
This commit is contained in:
1 parent
2203afde3c
commit
2cb70beb69
44 files changed
+3310
-236
No files matched your search
@@ -0,0 +1,353 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type BuildEnvironment struct {
|
||||
GradleHome string `json:"gradleHome"`
|
||||
GradleUserHome string `json:"gradleUserHome"`
|
||||
JavaHome string `json:"javaHome"`
|
||||
AndroidHome string `json:"androidHome"`
|
||||
Proxy string `json:"proxy"`
|
||||
ProxySource string `json:"proxySource"`
|
||||
PreferWrapper bool `json:"preferWrapper"`
|
||||
}
|
||||
|
||||
func (s *Server) buildEnvironment() (BuildEnvironment, error) {
|
||||
c := BuildEnvironment{GradleHome: os.Getenv("GRADLE_HOME"), GradleUserHome: os.Getenv("GRADLE_USER_HOME"), JavaHome: os.Getenv("JAVA_HOME"), AndroidHome: os.Getenv("ANDROID_HOME")}
|
||||
if c.AndroidHome == "" {
|
||||
c.AndroidHome = os.Getenv("ANDROID_SDK_ROOT")
|
||||
}
|
||||
if s.environmentFile != "" {
|
||||
data, e := os.ReadFile(s.environmentFile)
|
||||
if e != nil {
|
||||
return c, fmt.Errorf("read environment config: %w", e)
|
||||
}
|
||||
if e = json.Unmarshal(data, &c); e != nil {
|
||||
return c, e
|
||||
}
|
||||
}
|
||||
if c.GradleUserHome == "" {
|
||||
home, _ := os.UserHomeDir()
|
||||
c.GradleUserHome = filepath.Join(home, ".gradle")
|
||||
}
|
||||
if c.GradleHome == "" {
|
||||
name := "gradle"
|
||||
if runtime.GOOS == "windows" {
|
||||
name = "gradle.bat"
|
||||
}
|
||||
if p, e := exec.LookPath(name); e == nil {
|
||||
c.GradleHome = filepath.Dir(filepath.Dir(p))
|
||||
}
|
||||
}
|
||||
if c.Proxy == "direct" {
|
||||
c.Proxy = ""
|
||||
c.ProxySource = "disabled"
|
||||
}
|
||||
if c.Proxy != "" {
|
||||
if c.ProxySource == "" {
|
||||
c.ProxySource = "configured"
|
||||
}
|
||||
} else if c.ProxySource != "disabled" {
|
||||
for _, key := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"} {
|
||||
if p := os.Getenv(key); p != "" {
|
||||
c.Proxy = p
|
||||
c.ProxySource = key
|
||||
break
|
||||
}
|
||||
}
|
||||
if c.Proxy == "" {
|
||||
c.Proxy = systemProxy()
|
||||
if c.Proxy != "" {
|
||||
c.ProxySource = "system"
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.Proxy != "" {
|
||||
p, e := url.Parse(c.Proxy)
|
||||
if e != nil || p.Hostname() == "" || (p.Scheme != "http" && p.Scheme != "https") {
|
||||
return c, fmt.Errorf("invalid HTTP proxy URL")
|
||||
}
|
||||
if p.User != nil || p.RawQuery != "" || p.Fragment != "" || (p.Path != "" && p.Path != "/") {
|
||||
return c, fmt.Errorf("authenticated proxy URLs are not supported; use system-integrated credentials or a local proxy without URL credentials")
|
||||
}
|
||||
if net.ParseIP(p.Hostname()) == nil && !regexp.MustCompile(`^[A-Za-z0-9.-]+$`).MatchString(p.Hostname()) {
|
||||
return c, fmt.Errorf("unsupported proxy hostname")
|
||||
}
|
||||
}
|
||||
if c.ProxySource == "" {
|
||||
c.ProxySource = "direct"
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
func (c BuildEnvironment) summary() map[string]string {
|
||||
return map[string]string{"gradleHome": c.GradleHome, "gradleUserHome": c.GradleUserHome, "javaHome": c.JavaHome, "androidHome": c.AndroidHome, "proxy": c.Proxy, "proxySource": c.ProxySource, "preferWrapper": fmt.Sprint(c.PreferWrapper)}
|
||||
}
|
||||
func (c BuildEnvironment) environ() []string {
|
||||
env := os.Environ()
|
||||
put := func(k, v string) {
|
||||
if v == "" {
|
||||
return
|
||||
}
|
||||
prefix := strings.ToUpper(k) + "="
|
||||
filtered := env[:0]
|
||||
for _, entry := range env {
|
||||
if !strings.HasPrefix(strings.ToUpper(entry), prefix) {
|
||||
filtered = append(filtered, entry)
|
||||
}
|
||||
}
|
||||
env = append(filtered, k+"="+v)
|
||||
}
|
||||
put("GRADLE_USER_HOME", c.GradleUserHome)
|
||||
put("GRADLE_HOME", c.GradleHome)
|
||||
put("JAVA_HOME", c.JavaHome)
|
||||
put("ANDROID_HOME", c.AndroidHome)
|
||||
put("ANDROID_SDK_ROOT", c.AndroidHome)
|
||||
opts := os.Getenv("GRADLE_OPTS") + " -Djava.net.useSystemProxies=true"
|
||||
if c.ProxySource == "disabled" {
|
||||
opts = os.Getenv("GRADLE_OPTS") + " -Djava.net.useSystemProxies=false -Dhttp.proxyHost= -Dhttps.proxyHost="
|
||||
filtered := env[:0]
|
||||
for _, entry := range env {
|
||||
k, _, _ := strings.Cut(entry, "=")
|
||||
if strings.ToUpper(k) != "HTTP_PROXY" && strings.ToUpper(k) != "HTTPS_PROXY" {
|
||||
filtered = append(filtered, entry)
|
||||
}
|
||||
}
|
||||
env = filtered
|
||||
}
|
||||
if c.Proxy != "" {
|
||||
p, _ := url.Parse(c.Proxy)
|
||||
port := p.Port()
|
||||
if port == "" {
|
||||
port = "80"
|
||||
if p.Scheme == "https" {
|
||||
port = "443"
|
||||
}
|
||||
}
|
||||
opts += " -Dhttp.proxyHost=" + p.Hostname() + " -Dhttp.proxyPort=" + port + " -Dhttps.proxyHost=" + p.Hostname() + " -Dhttps.proxyPort=" + port
|
||||
put("HTTP_PROXY", c.Proxy)
|
||||
put("HTTPS_PROXY", c.Proxy)
|
||||
}
|
||||
put("GRADLE_OPTS", opts)
|
||||
return env
|
||||
}
|
||||
func wrapperProperties(work string) map[string]string {
|
||||
props := map[string]string{}
|
||||
data, _ := os.ReadFile(filepath.Join(work, "gradle", "wrapper", "gradle-wrapper.properties"))
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
k, v, ok := strings.Cut(line, "=")
|
||||
if ok {
|
||||
v = strings.ReplaceAll(v, `\:`, ":")
|
||||
v = strings.ReplaceAll(v, `\=`, "=")
|
||||
v = strings.ReplaceAll(v, `\\`, `\`)
|
||||
props[strings.TrimSpace(k)] = strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
return props
|
||||
}
|
||||
|
||||
var distributionVersion = regexp.MustCompile(`gradle-([0-9][A-Za-z0-9.\-]*)-(?:bin|all)\.zip$`)
|
||||
|
||||
func wrapperVersion(work string) string {
|
||||
u, e := url.Parse(wrapperProperties(work)["distributionUrl"])
|
||||
if e != nil {
|
||||
return ""
|
||||
}
|
||||
matches := distributionVersion.FindStringSubmatch(filepath.Base(u.Path))
|
||||
if len(matches) > 1 {
|
||||
return matches[1]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func nativeGradle(home, version string) string {
|
||||
if home == "" || version == "" {
|
||||
return ""
|
||||
}
|
||||
if _, e := os.Stat(filepath.Join(home, "lib", "gradle-launcher-"+version+".jar")); e != nil {
|
||||
return ""
|
||||
}
|
||||
name := "gradle"
|
||||
if runtime.GOOS == "windows" {
|
||||
name = "gradle.bat"
|
||||
}
|
||||
p := filepath.Join(home, "bin", name)
|
||||
if _, e := os.Stat(p); e != nil {
|
||||
return ""
|
||||
}
|
||||
return p
|
||||
}
|
||||
func (s *Server) prepareCommand(work, task string, c BuildEnvironment) (*exec.Cmd, map[string]string, error) {
|
||||
if e := os.MkdirAll(c.GradleUserHome, 0700); e != nil {
|
||||
return nil, nil, fmt.Errorf("Gradle cache not writable: %s: %w", c.GradleUserHome, e)
|
||||
}
|
||||
f, e := os.CreateTemp(c.GradleUserHome, ".remotecompile-write-check-")
|
||||
if e != nil {
|
||||
return nil, nil, fmt.Errorf("service account cannot write Gradle cache %s: %w", c.GradleUserHome, e)
|
||||
}
|
||||
f.Close()
|
||||
os.Remove(f.Name())
|
||||
info := c.summary()
|
||||
version := wrapperVersion(work)
|
||||
info["requestedGradleVersion"] = version
|
||||
info["execution"] = "project-wrapper"
|
||||
if raw, target := distributionTarget(work, c); raw != "" {
|
||||
u, _ := url.Parse(raw)
|
||||
info["distributionUrl"] = u.Scheme + "://" + u.Host + u.EscapedPath()
|
||||
info["distributionFile"] = strings.TrimSuffix(target, ".part")
|
||||
}
|
||||
homes := []string{c.GradleHome}
|
||||
if version != "" {
|
||||
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 c.PreferWrapper {
|
||||
break
|
||||
}
|
||||
if binary := nativeGradle(home, version); binary != "" {
|
||||
if strings.ContainsAny(binary, "\"\r\n&|<>^%!") {
|
||||
return nil, nil, fmt.Errorf("unsupported shell characters in configured Gradle path")
|
||||
}
|
||||
info["execution"] = "installed-gradle"
|
||||
info["configuredGradleHome"] = c.GradleHome
|
||||
info["gradleHome"] = home
|
||||
delete(info, "distributionFile")
|
||||
info["executable"] = binary
|
||||
return gradleExecutableCommand(binary, task), info, nil
|
||||
}
|
||||
}
|
||||
return gradleCommand(work, task), info, nil
|
||||
}
|
||||
func distributionTarget(work string, c BuildEnvironment) (string, string) {
|
||||
p := wrapperProperties(work)
|
||||
raw := p["distributionUrl"]
|
||||
u, e := url.Parse(raw)
|
||||
if e != nil || u.Host == "" || u.Scheme != "https" {
|
||||
return "", ""
|
||||
}
|
||||
name := filepath.Base(u.Path)
|
||||
if !distributionVersion.MatchString(name) {
|
||||
return "", ""
|
||||
}
|
||||
base := c.GradleUserHome
|
||||
if p["zipStoreBase"] == "PROJECT" {
|
||||
base = work
|
||||
}
|
||||
rel := p["zipStorePath"]
|
||||
if rel == "" {
|
||||
rel = "wrapper/dists"
|
||||
}
|
||||
if filepath.IsAbs(rel) || strings.Contains(rel, "..") {
|
||||
return "", ""
|
||||
}
|
||||
safeURL := *u
|
||||
safeURL.User = nil
|
||||
sum := md5.Sum([]byte(safeURL.String()))
|
||||
hash := new(big.Int).SetBytes(sum[:]).Text(36)
|
||||
return raw, filepath.Join(base, rel, strings.TrimSuffix(name, ".zip"), hash, name+".part")
|
||||
}
|
||||
func (s *Server) monitorDistribution(b *Build, work string, c BuildEnvironment, stop <-chan struct{}) {
|
||||
raw, path := distributionTarget(work, c)
|
||||
if raw == "" {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
native := b.Environment["execution"] == "installed-gradle"
|
||||
s.mu.Unlock()
|
||||
if native {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go func() {
|
||||
select {
|
||||
case <-stop:
|
||||
cancel()
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}()
|
||||
total := int64(0)
|
||||
client := &http.Client{Timeout: 8 * time.Second}
|
||||
if c.Proxy != "" {
|
||||
p, _ := url.Parse(c.Proxy)
|
||||
client.Transport = &http.Transport{Proxy: http.ProxyURL(p)}
|
||||
} else {
|
||||
client.Transport = &http.Transport{}
|
||||
}
|
||||
req, _ := http.NewRequestWithContext(ctx, "HEAD", raw, nil)
|
||||
if response, e := client.Do(req); e == nil {
|
||||
if response.StatusCode >= 200 && response.StatusCode < 300 {
|
||||
total = response.ContentLength
|
||||
}
|
||||
response.Body.Close()
|
||||
}
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
started := time.Now()
|
||||
seen := false
|
||||
baseline := int64(0)
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-ticker.C:
|
||||
st, e := os.Stat(path)
|
||||
if e != nil {
|
||||
if seen {
|
||||
s.mu.Lock()
|
||||
if b.Status == "running" {
|
||||
b.Progress = Progress{Phase: "building", Message: "Gradle 分发包下载已结束,正在解压或构建", Path: strings.TrimSuffix(path, ".part")}
|
||||
_ = s.persistBuild(b)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
continue
|
||||
}
|
||||
current := st.Size()
|
||||
if !seen {
|
||||
baseline = current
|
||||
started = time.Now()
|
||||
seen = true
|
||||
}
|
||||
percent := -1
|
||||
if total > 0 {
|
||||
percent = int(current * 100 / total)
|
||||
if percent > 100 {
|
||||
percent = 100
|
||||
}
|
||||
}
|
||||
msg := fmt.Sprintf("Gradle 下载 %.1f MiB", float64(current)/(1024*1024))
|
||||
if total > 0 {
|
||||
msg += fmt.Sprintf(" / %.1f MiB (%d%%)", float64(total)/(1024*1024), percent)
|
||||
}
|
||||
msg += fmt.Sprintf(",平均 %.1f KiB/s", float64(current-baseline)/1024/(time.Since(started).Seconds()+0.001))
|
||||
s.mu.Lock()
|
||||
if b.Status == "running" {
|
||||
b.Progress = Progress{Phase: "downloading-gradle", Message: msg, Path: path, Current: current, Total: total, Percent: percent}
|
||||
_ = s.persistBuild(b)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user