feat: 完善远程构建恢复、工程同步与变体选择

增加持久化构建记录、历史 APK 恢复、断点下载、Gradle 缓存复用、系统代理与按工程选择服务端 JDK。

支持已有工程目录、Git 状态检查、原生忽略规则和文本换行等价比较,修复干净检出与历史同步快照不一致时的误拦截。

优化插件设备可选构建、侧栏滚动、左右日志布局、时间显示和构建变体快速选择,并补充部署与协议文档。

验证:17 项 Go 测试、22 项插件测试及 HTTP/HTTPS 两条端到端测试通过;Linux/macOS 服务端交叉编译通过。
This commit is contained in:
tongtong committed 2026-11-25 02:10:52 +08:00
1 parent 2203afde3c
commit 2cb70beb69
44 files changed
+3310 -236

No files matched your search

+353
View File
@@ -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()
}
}
}
+154
View File
@@ -0,0 +1,154 @@
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestIdempotentBuildCanBeFoundAfterLostResponse(t *testing.T) {
s := testServer(t)
p := project(t, s)
wrapper := "#!/bin/sh\nexit 1\n"
name := "gradlew"
if strings.Contains(os.Getenv("OS"), "Windows") {
name = "gradlew.bat"
wrapper = "@exit /b 1\r\n"
}
call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "rev", Files: map[string]File{name: file(wrapper)}})
body := map[string]string{"revision": "rev", "task": ":app:assembleDebug", "clientRequestId": "persisted-before-submit"}
first := call(t, s, "POST", "/projects/"+p+"/builds", body)
if first.Code != 200 {
t.Fatal(first.Body.String())
}
var b Build
json.Unmarshal(first.Body.Bytes(), &b)
again := call(t, s, "POST", "/projects/"+p+"/builds", body)
var repeated Build
json.Unmarshal(again.Body.Bytes(), &repeated)
if repeated.ID != b.ID {
t.Fatal("duplicate build submitted")
}
found := call(t, s, "GET", "/projects/"+p+"/builds?clientRequestId=persisted-before-submit", nil)
if !strings.Contains(found.Body.String(), b.ID) {
t.Fatal("lost response cannot be recovered")
}
body["revision"] = "different"
if call(t, s, "POST", "/projects/"+p+"/builds", body).Code != 409 {
t.Fatal("idempotency key accepted different source")
}
deadline := time.Now().Add(5 * time.Second)
for {
var state Build
json.Unmarshal(call(t, s, "GET", "/builds/"+b.ID, nil).Body.Bytes(), &state)
if state.Status != "queued" && state.Status != "running" {
break
}
if time.Now().After(deadline) {
t.Fatal("test build stuck")
}
time.Sleep(20 * time.Millisecond)
}
data, e := os.ReadFile(filepath.Join(s.root, "artifacts", b.ID, "build.json"))
if e != nil {
t.Fatal(e)
}
var stored Build
if json.Unmarshal(data, &stored) != nil || stored.RequestID != "persisted-before-submit" {
t.Fatal("submission not durable")
}
}
func TestInterruptedBuildRecoverableButWorkspaceLocked(t *testing.T) {
s := testServer(t)
p := project(t, s)
b := &Build{ID: id(), Project: p, Status: "running", RequestID: "recover-me", Logs: []string{"previous log"}}
s.builds[b.ID] = b
s.persistBuild(b)
os.WriteFile(filepath.Join(s.root, "projects", p, "active-build"), []byte(b.ID), 0600)
s.recoverBuilds()
if b.Status != "interrupted" || !s.projects[p].Busy {
t.Fatal("unsafe recovery state")
}
if w := call(t, s, "GET", "/builds/"+b.ID, nil); w.Code != 200 {
t.Fatal(w.Code)
}
if w := call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "new", Files: map[string]File{}}); w.Code != 409 {
t.Fatal("locked workspace accepted sync")
}
}
func TestExactInstalledGradleReusedAndDifferentVersionRejected(t *testing.T) {
s := testServer(t)
p := project(t, s)
work := s.work(p)
os.MkdirAll(filepath.Join(work, "gradle", "wrapper"), 0700)
os.WriteFile(filepath.Join(work, "gradle", "wrapper", "gradle-wrapper.properties"), []byte("distributionUrl=https\\://services.gradle.org/distributions/gradle-8.13-bin.zip\n"), 0600)
home := filepath.Join(s.root, "Gradle home 中文")
os.MkdirAll(filepath.Join(home, "lib"), 0700)
os.MkdirAll(filepath.Join(home, "bin"), 0700)
os.WriteFile(filepath.Join(home, "lib", "gradle-launcher-8.13.jar"), nil, 0600)
for _, n := range []string{"gradle", "gradle.bat"} {
os.WriteFile(filepath.Join(home, "bin", n), nil, 0700)
}
cfg := BuildEnvironment{GradleHome: home, GradleUserHome: filepath.Join(s.root, "cache")}
_, info, e := s.prepareCommand(work, ":app:assembleDebug", cfg)
if e != nil || info["execution"] != "installed-gradle" {
t.Fatalf("%v %v", e, info)
}
os.Rename(filepath.Join(home, "lib", "gradle-launcher-8.13.jar"), filepath.Join(home, "lib", "gradle-launcher-8.12.jar"))
_, info, e = s.prepareCommand(work, ":app:assembleDebug", cfg)
if e != nil || info["execution"] != "project-wrapper" {
t.Fatal("wrong Gradle version reused")
}
}
func TestProxyAppliedToGradleAndProgressPersists(t *testing.T) {
proxyHit := make(chan bool, 1)
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case proxyHit <- true:
default:
}
http.Error(w, "test proxy denies external network", 403)
}))
defer proxy.Close()
s := testServer(t)
p := project(t, s)
work := s.work(p)
os.MkdirAll(filepath.Join(work, "gradle", "wrapper"), 0700)
os.WriteFile(filepath.Join(work, "gradle", "wrapper", "gradle-wrapper.properties"), []byte("distributionUrl=https\\://services.gradle.org/distributions/gradle-8.13-bin.zip\n"), 0600)
cfg := BuildEnvironment{GradleUserHome: filepath.Join(s.root, "cache"), Proxy: proxy.URL}
raw, target := distributionTarget(work, cfg)
if raw == "" {
t.Fatal("distribution not detected")
}
os.MkdirAll(filepath.Dir(target), 0700)
os.WriteFile(target, make([]byte, 128*1024), 0600)
b := &Build{ID: id(), Project: p, Status: "running", Environment: map[string]string{"execution": "project-wrapper"}}
stop := make(chan struct{})
done := make(chan struct{})
go func() { s.monitorDistribution(b, work, cfg, stop); close(done) }()
select {
case <-proxyHit:
case <-time.After(4 * time.Second):
t.Fatal("system/configured proxy not used")
}
time.Sleep(1500 * time.Millisecond)
close(stop)
<-done
s.mu.Lock()
progress := b.Progress
s.mu.Unlock()
if progress.Current != 128*1024 || progress.Path != target {
t.Fatalf("missing live progress: %+v", progress)
}
if _, e := os.Stat(filepath.Join(s.root, "artifacts", b.ID, "build.json")); e != nil {
t.Fatal("progress not persisted")
}
if !strings.Contains(strings.Join(cfg.environ(), "\n"), "-Dhttps.proxyHost=127.0.0.1") {
t.Fatal("proxy not forwarded to Gradle JVM")
}
}
+147
View File
@@ -0,0 +1,147 @@
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
)
type JDK struct {
Home string `json:"home"`
Version string `json:"version"`
Source string `json:"source"`
}
func javaExecutable(name string) string {
if runtime.GOOS == "windows" {
return name + ".exe"
}
return name
}
func inspectJDK(home, source string) (JDK, bool) {
home, e := filepath.Abs(home)
if e != nil {
return JDK{}, false
}
if resolved, e := filepath.EvalSymlinks(home); e == nil {
home = resolved
}
for _, name := range []string{"java", "javac"} {
if i, e := os.Stat(filepath.Join(home, "bin", javaExecutable(name))); e != nil || !i.Mode().IsRegular() {
return JDK{}, false
}
}
data, e := os.ReadFile(filepath.Join(home, "release"))
if e != nil {
return JDK{}, false
}
version := ""
for _, line := range strings.Split(string(data), "\n") {
if strings.HasPrefix(line, "JAVA_VERSION=") {
version = strings.Trim(strings.TrimSpace(strings.TrimPrefix(line, "JAVA_VERSION=")), `"`)
}
}
if version == "" {
return JDK{}, false
}
return JDK{home, version, source}, true
}
func (s *Server) discoverJDKs() ([]JDK, string) {
result := []JDK{}
seen := map[string]bool{}
add := func(home, source string) {
if home == "" {
return
}
if j, ok := inspectJDK(home, source); ok {
key := j.Home
if runtime.GOOS == "windows" {
key = strings.ToLower(key)
}
if !seen[key] {
seen[key] = true
result = append(result, j)
}
}
}
c, _ := s.buildEnvironment()
add(c.JavaHome, "service-config")
add(os.Getenv("JAVA_HOME"), "JAVA_HOME")
fromBinary := func(path, source string) {
path = strings.TrimSpace(path)
if resolved, e := filepath.EvalSymlinks(path); e == nil {
path = resolved
}
add(filepath.Dir(filepath.Dir(path)), source)
}
for _, name := range []string{"java", "javac"} {
if path, e := exec.LookPath(javaExecutable(name)); e == nil {
fromBinary(path, "PATH")
}
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var out []byte
if runtime.GOOS == "windows" {
out, _ = exec.CommandContext(ctx, "where.exe", "java", "javac").Output()
} else {
out, _ = exec.CommandContext(ctx, "which", "-a", "java", "javac").Output()
}
for _, line := range strings.Split(string(out), "\n") {
if strings.TrimSpace(line) != "" {
fromBinary(line, "where/which")
}
}
roots := []string{filepath.Join(filepath.Dir(s.root), "toolchains")}
if home, e := os.UserHomeDir(); e == nil {
roots = append(roots, filepath.Join(home, ".jdks"))
}
if runtime.GOOS == "windows" {
for _, base := range []string{os.Getenv("ProgramFiles"), os.Getenv("ProgramFiles(x86)")} {
if base != "" {
for _, dir := range []string{"Java", "Eclipse Adoptium", "Microsoft", "Amazon Corretto"} {
roots = append(roots, filepath.Join(base, dir))
}
add(filepath.Join(base, "Android", "Android Studio", "jbr"), "Android Studio")
}
}
} else {
roots = append(roots, "/usr/lib/jvm", "/Library/Java/JavaVirtualMachines")
}
for _, root := range roots {
entries, _ := os.ReadDir(root)
for i, entry := range entries {
if i >= 64 {
break
}
p := filepath.Join(root, entry.Name())
add(p, "installed")
add(filepath.Join(p, "Contents", "Home"), "installed")
}
}
sort.Slice(result, func(i, j int) bool { return result[i].Home < result[j].Home })
return result, c.JavaHome
}
func (s *Server) selectedJDK(home string) (string, error) {
if home == "" {
return "", nil
}
choices, _ := s.discoverJDKs()
for _, j := range choices {
if j.Home == home || (runtime.GOOS == "windows" && strings.EqualFold(j.Home, home)) {
return j.Home, nil
}
}
return "", fmt.Errorf("指定 JDK 不在服务端发现列表中,请刷新服务端 JDK 后重新选择:%s", home)
}
func (s *Server) jdks(w http.ResponseWriter, r *http.Request) {
choices, current := s.discoverJDKs()
jsonOut(w, map[string]any{"jdks": choices, "defaultJavaHome": current})
}
+207 -49
View File
@@ -22,6 +22,7 @@ import (
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
@@ -30,12 +31,14 @@ import (
)
type File struct {
Hash string `json:"hash"`
Data *string `json:"data,omitempty"`
Hash string `json:"hash"`
TextHash string `json:"textHash,omitempty"`
Data *string `json:"data,omitempty"`
}
type SyncRequest struct {
Revision string `json:"revision"`
Files map[string]File `json:"files"`
Git *GitSnapshot `json:"git,omitempty"`
}
type Artifact struct {
Name string `json:"name"`
@@ -43,27 +46,37 @@ type Artifact struct {
Size int64 `json:"size"`
}
type Build struct {
ID string `json:"id"`
Project string `json:"project"`
Revision string `json:"revision"`
Task string `json:"task"`
Status string `json:"status"`
Logs []string `json:"logs"`
Artifacts []Artifact `json:"artifacts"`
cmd *exec.Cmd
cancelled bool
JavaHome string `json:"javaHome,omitempty"`
RequestID string `json:"clientRequestId,omitempty"`
CreatedAt int64 `json:"createdAt"`
Progress Progress `json:"progress"`
Environment map[string]string `json:"environment,omitempty"`
lastPersist time.Time
ID string `json:"id"`
Project string `json:"project"`
Revision string `json:"revision"`
Task string `json:"task"`
Status string `json:"status"`
Logs []string `json:"logs"`
Artifacts []Artifact `json:"artifacts"`
cmd *exec.Cmd
cancelled bool
}
type Project struct {
Revision string `json:"revision"`
Files map[string]File `json:"files"`
Busy bool `json:"-"`
WorkspacePath string `json:"workspacePath,omitempty"`
Git *GitSnapshot `json:"git,omitempty"`
Revision string `json:"revision"`
Files map[string]File `json:"files"`
Busy bool `json:"busy"`
}
type Server struct {
mu sync.Mutex
root, token string
tasks map[string]bool
projects map[string]*Project
builds map[string]*Build
mu sync.Mutex
root, token string
tasks map[string]bool
projects map[string]*Project
builds map[string]*Build
workspaceRoot string
environmentFile string
}
var safeID = regexp.MustCompile(`^[a-f0-9]{32}$`)
@@ -91,7 +104,7 @@ func validPath(p string) bool {
}
}
for _, part := range strings.Split(p, "/") {
if part == ".git" || part == ".gradle" || part == "build" || part == ".idea" || part == "local.properties" {
if reservedSource(part) {
return false
}
}
@@ -102,6 +115,9 @@ func noLinks(root string) error {
if e != nil {
return e
}
if d.IsDir() && p != root && reservedSource(filepath.Base(p)) {
return filepath.SkipDir
}
if d.Type()&os.ModeSymlink != 0 {
return fmt.Errorf("symlink forbidden: %s", p)
}
@@ -118,7 +134,12 @@ func decode(w http.ResponseWriter, r *http.Request, v any) error {
d.DisallowUnknownFields()
return d.Decode(v)
}
func (s *Server) work(p string) string { return filepath.Join(s.root, "projects", p, "work") }
func (s *Server) work(p string) string {
if pr := s.projects[p]; pr != nil && pr.WorkspacePath != "" {
return pr.WorkspacePath
}
return filepath.Join(s.root, "projects", p, "work")
}
func (s *Server) save(p string) error {
b, e := json.Marshal(s.projects[p])
if e != nil {
@@ -144,7 +165,24 @@ 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.1.1", "os": runtime.GOOS, "sync": "http-manifest"})
jsonOut(w, map[string]any{"version": "0.4.1", "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" {
cfg, e := s.buildEnvironment()
if e != nil {
fail(e)
return
}
jsonOut(w, cfg.summary())
return
}
if r.URL.Path == "/api/v1/jdks" && r.Method == "GET" {
s.jdks(w, r)
return
}
if r.URL.Path == "/api/v1/directories" && r.Method == "GET" {
s.browseDirectories(w, r)
return
}
if len(parts) < 3 || parts[0] != "api" || parts[1] != "v1" {
@@ -152,20 +190,15 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
if parts[2] == "projects" {
if len(parts) == 3 && r.Method == "POST" {
p := id()
if e := os.MkdirAll(s.work(p), 0700); e != nil {
fail(e)
return
}
s.projects[p] = &Project{Files: map[string]File{}}
if e := s.save(p); e != nil {
fail(e)
return
}
jsonOut(w, map[string]string{"id": p})
if len(parts) == 4 && parts[3] == "check" && r.Method == "POST" {
s.checkWorkspace(w, r)
return
}
if len(parts) == 3 && r.Method == "POST" {
s.createProject(w, r)
return
}
if len(parts) != 5 || !safeID.MatchString(parts[3]) {
http.NotFound(w, r)
return
@@ -176,8 +209,28 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
return
}
if pr.WorkspacePath != "" {
if _, e := s.validateWorkspace(pr.WorkspacePath); e != nil {
fail(e)
return
}
}
if parts[4] == "manifest" && r.Method == "GET" {
jsonOut(w, pr)
jsonOut(w, s.manifest(p))
return
}
if parts[4] == "builds" && r.Method == "GET" {
items := []*Build{}
for _, b := range s.builds {
if b.Project == p && (r.URL.Query().Get("clientRequestId") == "" || b.RequestID == r.URL.Query().Get("clientRequestId")) {
items = append(items, b)
}
}
sort.Slice(items, func(i, j int) bool { return items[i].CreatedAt > items[j].CreatedAt })
if len(items) > 50 {
items = items[:50]
}
jsonOut(w, map[string]any{"builds": items})
return
}
if parts[4] == "sync" && r.Method == "POST" {
@@ -194,6 +247,10 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fail(errors.New("revision and files required"))
return
}
if e := s.checkGit(p, req.Git); e != nil {
http.Error(w, e.Error(), 409)
return
}
if e := noLinks(s.work(p)); e != nil {
fail(e)
return
@@ -242,6 +299,11 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
}
previousFiles, baseErr := s.syncBase(p)
if baseErr != nil {
fail(baseErr)
return
}
// Validate the entire request before touching the working tree. Invalidate first:
// an interrupted commit must never permit building a mixed source revision.
pr.Revision = ""
@@ -249,8 +311,8 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fail(e)
return
}
for path := range pr.Files {
if _, ok := req.Files[path]; !ok {
for path := range previousFiles {
if _, ok := req.Files[path]; !ok && validPath(path) {
if e := os.Remove(filepath.Join(s.work(p), filepath.FromSlash(path))); e != nil && !os.IsNotExist(e) {
fail(e)
return
@@ -270,9 +332,15 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
pr.Files = map[string]File{}
for path, f := range req.Files {
pr.Files[path] = File{Hash: f.Hash}
actual, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path)))
if e != nil || actual.Hash != f.Hash {
fail(fmt.Errorf("source changed during sync: %s", path))
return
}
pr.Files[path] = actual
}
pr.Revision = req.Revision
pr.Git = req.Git
if e := s.save(p); e != nil {
pr.Revision = ""
fail(e)
@@ -283,8 +351,10 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
if parts[4] == "builds" && r.Method == "POST" {
var req struct {
Revision string `json:"revision"`
Task string `json:"task"`
Revision string `json:"revision"`
Task string `json:"task"`
RequestID string `json:"clientRequestId"`
JavaHome string `json:"javaHome,omitempty"`
}
if e := decode(w, r, &req); e != nil {
fail(e)
@@ -294,11 +364,51 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fail(errors.New("task not allowed"))
return
}
if req.RequestID != "" {
if !regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`).MatchString(req.RequestID) {
fail(errors.New("invalid clientRequestId"))
return
}
for _, old := range s.builds {
if old.Project == p && old.RequestID == req.RequestID {
if old.Task != req.Task || old.Revision != req.Revision || old.JavaHome != req.JavaHome {
http.Error(w, "request ID already used with different parameters", 409)
return
}
jsonOut(w, old)
return
}
}
}
if pr.Busy || req.Revision == "" || pr.Revision != req.Revision {
http.Error(w, "busy or revision mismatch", 409)
return
}
b := &Build{ID: id(), Project: p, Revision: req.Revision, Task: req.Task, Status: "queued", Logs: []string{}, Artifacts: []Artifact{}}
if pr.WorkspacePath != "" {
if e := s.checkGit(p, pr.Git); e != nil {
http.Error(w, e.Error(), 409)
return
}
actual, e := sourceInventory(s.work(p))
if e != nil {
fail(e)
return
}
if !sameSourceHashes(pr.Files, actual) {
http.Error(w, "source changed after sync; sync again", 409)
return
}
}
javaHome, jdkErr := s.selectedJDK(req.JavaHome)
if jdkErr != nil {
fail(jdkErr)
return
}
b := &Build{JavaHome: javaHome, ID: id(), Project: p, Revision: req.Revision, Task: req.Task, RequestID: req.RequestID, CreatedAt: time.Now().UnixMilli(), Status: "queued", Logs: []string{}, Artifacts: []Artifact{}}
if e := s.persistBuild(b); e != nil {
fail(e)
return
}
if e := os.WriteFile(filepath.Join(s.root, "projects", p, "active-build"), []byte(b.ID), 0600); e != nil {
fail(e)
return
@@ -406,6 +516,9 @@ func (w buildWriter) Write(p []byte) (int, error) {
w.s.mu.Lock()
defer w.s.mu.Unlock()
w.b.Logs = append(w.b.Logs, string(p))
if time.Since(w.b.lastPersist) > time.Second {
_ = w.s.persistBuild(w.b)
}
return len(p), nil
}
func (s *Server) run(b *Build) {
@@ -413,11 +526,14 @@ func (s *Server) run(b *Build) {
if b.cancelled {
b.Status = "cancelled"
s.projects[b.Project].Busy = false
_ = s.persistBuild(b)
os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build"))
s.mu.Unlock()
return
}
b.Status = "running"
b.Progress = Progress{Phase: "preparing", Message: "正在检测工具版本、缓存及系统代理", Percent: -1}
_ = s.persistBuild(b)
s.mu.Unlock()
work := s.work(b.Project)
// Remove old APKs only. Retain compilation caches and all other Gradle outputs.
@@ -434,8 +550,31 @@ func (s *Server) run(b *Build) {
})
}
if err == nil {
cmd := gradleCommand(work, b.Task)
cfg, configErr := s.buildEnvironment()
if configErr != nil {
s.finishFailed(b, configErr)
return
}
if b.JavaHome != "" {
cfg.JavaHome = b.JavaHome
}
cmd, info, prepErr := s.prepareCommand(work, b.Task, cfg)
if prepErr != nil {
s.finishFailed(b, prepErr)
return
}
s.mu.Lock()
b.Environment = info
b.Progress = Progress{Phase: "building", Message: "执行项目 Wrapper,准备 Gradle 分发包", Path: info["distributionFile"], Percent: -1}
if info["execution"] == "installed-gradle" {
b.Progress.Message = "已复用 Gradle " + info["requestedGradleVersion"] + ";正在构建"
b.Progress.Path = info["executable"]
}
_ = s.persistBuild(b)
s.mu.Unlock()
buildWriter{s, b}.Write([]byte("构建环境: " + mustJSON(info) + "\n"))
cmd.Dir = work
cmd.Env = cfg.environ()
cmd.Stdout = buildWriter{s, b}
cmd.Stderr = cmd.Stdout
s.mu.Lock()
@@ -447,6 +586,8 @@ func (s *Server) run(b *Build) {
}
s.mu.Unlock()
if err == nil {
stopProgress := make(chan struct{})
go s.monitorDistribution(b, work, cfg, stopProgress)
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
select {
@@ -458,6 +599,7 @@ func (s *Server) run(b *Build) {
err = errors.New("build timeout")
}
}
close(stopProgress)
}
}
artifacts := []Artifact{}
@@ -488,6 +630,7 @@ func (s *Server) run(b *Build) {
s.mu.Lock()
defer s.mu.Unlock()
b.cmd = nil
b.Progress.Phase = "finished"
b.Artifacts = artifacts
b.Status = "success"
if len(artifacts) == 0 && err == nil {
@@ -501,10 +644,7 @@ func (s *Server) run(b *Build) {
b.Status = "cancelled"
}
s.projects[b.Project].Busy = false
dir := filepath.Join(s.root, "artifacts", b.ID)
os.MkdirAll(dir, 0700)
data, _ := json.MarshalIndent(b, "", " ")
os.WriteFile(filepath.Join(dir, "build.json"), data, 0600)
_ = s.persistBuild(b)
os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build"))
}
func main() {
@@ -515,6 +655,8 @@ func main() {
key := flag.String("tls-key", "", "PEM private key path")
initHost := flag.String("init-tls-host", "", "generate a local certificate for this IP/hostname and exit")
tlsDir := flag.String("tls-dir", "./tls", "certificate output directory")
workspaceRoot := flag.String("workspace-root", "", "administrator allowed root for existing project folders; defaults to data/projects")
environmentFile := flag.String("environment-file", "", "trusted build environment JSON; reloaded for each build")
flag.Parse()
if *initHost != "" {
if e := initCertificate(*initHost, *tlsDir); e != nil {
@@ -541,6 +683,14 @@ func main() {
log.Fatal(e)
}
s := &Server{root: abs, token: token, tasks: map[string]bool{}, projects: map[string]*Project{}, builds: map[string]*Build{}}
s.environmentFile = *environmentFile
s.workspaceRoot = *workspaceRoot
if s.workspaceRoot == "" {
s.workspaceRoot = filepath.Join(abs, "projects")
}
if s.workspaceRoot, e = filepath.Abs(s.workspaceRoot); e != nil {
log.Fatal(e)
}
for _, t := range strings.Split(*tasks, ",") {
if !safeTask.MatchString(t) {
log.Fatal("invalid task")
@@ -552,15 +702,17 @@ func main() {
if !safeID.MatchString(entry.Name()) {
continue
}
if _, e := os.Stat(filepath.Join(abs, "projects", entry.Name(), "active-build")); e == nil {
log.Fatalf("unfinished build in project %s: stop its remaining Gradle processes, then remove active-build marker before restarting", entry.Name())
}
data, e := os.ReadFile(filepath.Join(abs, "projects", entry.Name(), "state.json"))
if e != nil {
continue
}
var p Project
if json.Unmarshal(data, &p) == nil {
if p.WorkspacePath != "" {
if _, e := s.validateWorkspace(p.WorkspacePath); e != nil {
log.Fatalf("workspace %s: %v", entry.Name(), e)
}
}
s.projects[entry.Name()] = &p
}
}
@@ -572,9 +724,15 @@ func main() {
}
var b Build
if json.Unmarshal(data, &b) == nil {
if b.CreatedAt == 0 {
if info, e := os.Stat(filepath.Join(abs, "artifacts", entry.Name(), "build.json")); e == nil {
b.CreatedAt = info.ModTime().UnixMilli()
}
}
s.builds[b.ID] = &b
}
}
s.recoverBuilds()
log.Printf("remotecompile listening on %s (%s)", *addr, runtime.GOOS)
srv := &http.Server{Addr: *addr, Handler: s, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 5 * time.Minute, IdleTimeout: 60 * time.Second}
srv.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
+9 -5
View File
@@ -15,7 +15,11 @@ import (
func testServer(t *testing.T) *Server {
t.Helper()
return &Server{root: t.TempDir(), token: "test-token-abcdefghijklmnopqrstuvwxyz", tasks: map[string]bool{":app:assembleDebug": true}, projects: map[string]*Project{}, builds: map[string]*Build{}}
root := t.TempDir()
config := filepath.Join(root, "environment.json")
data, _ := json.Marshal(BuildEnvironment{GradleUserHome: filepath.Join(root, "gradle-cache"), Proxy: "direct"})
os.WriteFile(config, data, 0600)
return &Server{root: root, environmentFile: config, token: "test-token-abcdefghijklmnopqrstuvwxyz", tasks: map[string]bool{":app:assembleDebug": true}, projects: map[string]*Project{}, builds: map[string]*Build{}}
}
func TestRunningCancellation(t *testing.T) {
@@ -114,18 +118,18 @@ func TestSyncAndRevision(t *testing.T) {
s := testServer(t)
p := project(t, s)
path := "/projects/" + p + "/sync"
req := SyncRequest{"one", map[string]File{"a.txt": file("hello"), "b.txt": file("remove me")}}
req := SyncRequest{Revision: "one", Files: map[string]File{"a.txt": file("hello"), "b.txt": file("remove me")}}
if w := call(t, s, "POST", path, req); w.Code != 200 {
t.Fatal(w.Body.String())
}
bad := SyncRequest{"bad", map[string]File{"a.txt": {Hash: "wrong"}}}
bad := SyncRequest{Revision: "bad", Files: map[string]File{"a.txt": {Hash: "wrong"}}}
if w := call(t, s, "POST", path, bad); w.Code != 400 {
t.Fatal(w.Code)
}
if s.projects[p].Revision != "one" {
t.Fatal("invalid sync changed revision")
}
req = SyncRequest{"two", map[string]File{"a.txt": {Hash: digest([]byte("hello"))}}}
req = SyncRequest{Revision: "two", Files: map[string]File{"a.txt": {Hash: digest([]byte("hello"))}}}
if w := call(t, s, "POST", path, req); w.Code != 200 {
t.Fatal(w.Body.String())
}
@@ -153,7 +157,7 @@ func TestBuildArtifactAndFailure(t *testing.T) {
name = "gradlew.bat"
wrapper = "@echo off\r\nmkdir app\\build\\outputs\\apk\\debug 2>nul\r\necho fresh>app\\build\\outputs\\apk\\debug\\app-debug.apk\r\nexit /b 0\r\n"
}
req := SyncRequest{"one", map[string]File{name: file(wrapper)}}
req := SyncRequest{Revision: "one", Files: map[string]File{name: file(wrapper)}}
if w := call(t, s, "POST", "/projects/"+p+"/sync", req); w.Code != 200 {
t.Fatal(w.Body.String())
}
+4 -1
View File
@@ -9,7 +9,10 @@ import (
)
func gradleCommand(work, task string) *exec.Cmd {
c := exec.Command("sh", filepath.Join(work, "gradlew"), task, "--console=plain", "--no-daemon")
return gradleExecutableCommand(filepath.Join(work, "gradlew"), task)
}
func gradleExecutableCommand(binary, task string) *exec.Cmd {
c := exec.Command("sh", binary, task, "--console=plain", "--no-daemon")
c.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
return c
}
+6
View File
@@ -3,11 +3,17 @@ package main
import (
"os/exec"
"strconv"
"syscall"
)
func gradleCommand(work, task string) *exec.Cmd {
return exec.Command("cmd.exe", "/d", "/c", "gradlew.bat", task, "--console=plain", "--no-daemon")
}
func gradleExecutableCommand(binary, task string) *exec.Cmd {
c := exec.Command("cmd.exe")
c.SysProcAttr = &syscall.SysProcAttr{CmdLine: `cmd.exe /d /s /c ""` + binary + `" ` + task + ` --console=plain --no-daemon"`}
return c
}
func killTree(c *exec.Cmd) {
if c.Process != nil {
_ = exec.Command("taskkill.exe", "/PID", strconv.Itoa(c.Process.Pid), "/T", "/F").Run()
+5
View File
@@ -0,0 +1,5 @@
//go:build !windows
package main
func systemProxy() string { return "" }
+18
View File
@@ -0,0 +1,18 @@
package main
import (
"context"
"os/exec"
"strings"
"time"
)
func systemProxy() string {
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
out, e := exec.CommandContext(ctx, "powershell.exe", "-NoProfile", "-NonInteractive", "-Command", `$u=[uri]'https://services.gradle.org';$p=[System.Net.WebRequest]::GetSystemWebProxy();if(-not $p.IsBypassed($u)){$p.GetProxy($u).AbsoluteUri}`).Output()
if e != nil {
return ""
}
return strings.TrimSpace(string(out))
}
+74
View File
@@ -0,0 +1,74 @@
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"time"
)
type Progress struct {
Phase string `json:"phase"`
Message string `json:"message"`
Path string `json:"path"`
Current int64 `json:"current"`
Total int64 `json:"total"`
Percent int `json:"percent"`
}
func (s *Server) persistBuild(b *Build) error {
dir := filepath.Join(s.root, "artifacts", b.ID)
if e := os.MkdirAll(dir, 0700); e != nil {
return e
}
data, e := json.Marshal(b)
if e != nil {
return e
}
target := filepath.Join(dir, "build.json")
if e = os.WriteFile(target+".tmp", data, 0600); e != nil {
return e
}
if e = os.Rename(target+".tmp", target); e == nil {
b.lastPersist = time.Now()
}
return e
}
func (s *Server) finishFailed(b *Build, e error) {
s.mu.Lock()
defer s.mu.Unlock()
b.Status = "failed"
if b.cancelled {
b.Status = "cancelled"
}
b.Logs = append(b.Logs, e.Error())
b.Progress.Phase = "finished"
s.projects[b.Project].Busy = false
_ = s.persistBuild(b)
os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build"))
}
func (s *Server) recoverBuilds() {
for p, pr := range s.projects {
pr.Busy = false
marker, e := os.ReadFile(filepath.Join(s.root, "projects", p, "active-build"))
if e == nil {
pr.Busy = true
bid := strings.TrimSpace(string(marker))
if safeID.MatchString(bid) && s.builds[bid] == nil {
s.builds[bid] = &Build{ID: bid, Project: p, Revision: pr.Revision, Status: "running", Logs: []string{}, Artifacts: []Artifact{}}
}
}
}
for _, b := range s.builds {
if b.Status == "running" || b.Status == "queued" {
b.Status = "interrupted"
b.Progress.Phase = "interrupted"
b.Logs = append(b.Logs, "服务曾重启,构建已中断。若工作区仍锁定,管理员需确认残留 Gradle 进程已停止,再移除 active-build 并重启服务。")
if e := s.persistBuild(b); e != nil {
fmt.Println("build recovery persistence failed:", e)
}
}
}
}
+89
View File
@@ -0,0 +1,89 @@
package main
import (
"encoding/json"
"os"
"os/exec"
"path/filepath"
"testing"
)
func TestCleanSameHeadCanResyncWithoutAcceptingStaleBuild(t *testing.T) {
if _, e := exec.LookPath("git"); e != nil {
t.Skip("Git unavailable")
}
s := testServer(t)
s.workspaceRoot = t.TempDir()
work := filepath.Join(s.workspaceRoot, "checkout")
os.MkdirAll(work, 0700)
git := func(args ...string) {
t.Helper()
if out, e := exec.Command("git", append([]string{"-C", work}, args...)...).CombinedOutput(); e != nil {
t.Fatalf("git: %v %s", e, out)
}
}
git("init", "-q")
git("config", "core.autocrlf", "false")
os.WriteFile(filepath.Join(work, "a.txt"), []byte("original\n"), 0600)
os.WriteFile(filepath.Join(work, "restored.txt"), []byte("tracked\n"), 0600)
git("add", ".")
git("-c", "user.name=Test", "-c", "user.email=test@example.invalid", "commit", "-qm", "base")
g, e := gitSnapshot(work)
if e != nil {
t.Fatal(e)
}
w := call(t, s, "POST", "/projects", WorkspaceRequest{WorkspacePath: work, Git: g})
if w.Code != 200 {
t.Fatal(w.Body.String())
}
var out map[string]string
json.Unmarshal(w.Body.Bytes(), &out)
p := out["id"]
// A successful sync intentionally removed a tracked file; later checkout restores it.
w = call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "old", Files: map[string]File{"a.txt": file("original\n")}, Git: g})
if w.Code != 200 {
t.Fatal(w.Body.String())
}
git("restore", "--worktree", "--", "restored.txt")
// CRLF checkout is Git-clean, even though raw bytes no longer match the old snapshot.
git("config", "core.autocrlf", "true")
os.WriteFile(filepath.Join(work, "a.txt"), []byte("original\r\n"), 0600)
git("add", "--renormalize", ".")
g, e = gitSnapshot(work)
if e != nil || g.Dirty {
out, _ := gitCommand(work, nil, "status", "--porcelain")
diff, _ := gitCommand(work, nil, "diff", "--numstat")
t.Fatalf("fixture not Git-clean: %v %v status=%s diff=%s", g, e, out, diff)
}
originalRevision := s.projects[p].Revision
if e = s.checkGit(p, g); e != nil {
t.Fatal("clean same-HEAD checkout blocked", e)
}
manifest := s.manifest(p)
if manifest.Files["a.txt"].Hash != digest([]byte("original\r\n")) || manifest.Files["restored.txt"].Hash == "" || manifest.Revision != "" {
t.Fatal("manifest did not expose current checkout", manifest)
}
if s.projects[p].Revision != originalRevision || len(s.projects[p].Files) != 1 {
t.Fatal("read-only check rebased persistent snapshot")
}
w = call(t, s, "POST", "/projects/"+p+"/builds", map[string]string{"revision": "old", "task": ":app:assembleDebug"})
if w.Code != 409 {
t.Fatal("stale revision built", w.Body.String())
}
// Reuse the remote raw hash, preserving CRLF, while applying local deletion again.
w = call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "new", Files: map[string]File{"a.txt": {Hash: manifest.Files["a.txt"].Hash}}, Git: g})
if w.Code != 200 {
t.Fatal(w.Body.String())
}
if _, e = os.Stat(filepath.Join(work, "restored.txt")); !os.IsNotExist(e) {
t.Fatal("restored tracked deletion not synchronized")
}
if s.projects[p].Files["a.txt"].TextHash == "" {
t.Fatal("normalized baseline not persisted")
}
// A later real remote edit must remain protected.
os.WriteFile(filepath.Join(work, "a.txt"), []byte("remote real edit\n"), 0600)
if e = s.checkGit(p, g); e == nil {
t.Fatal("real remote edit was accepted")
}
}
+43
View File
@@ -0,0 +1,43 @@
package main
import (
"bytes"
"os"
"path/filepath"
"strings"
"unicode/utf8"
)
// Restrict EOL equivalence to source/config text. Executable scripts remain byte-exact.
func comparableText(path string) bool {
switch strings.ToLower(filepath.Ext(path)) {
case ".kt", ".kts", ".java", ".xml", ".gradle", ".properties", ".json", ".toml", ".yaml", ".yml", ".txt", ".md", ".proto", ".c", ".cc", ".cpp", ".h", ".hpp", ".cmake", ".aidl", ".pro", ".cfg", ".ini", ".csv", ".html", ".css", ".js", ".ts", ".svg":
return true
}
switch strings.ToLower(filepath.Base(path)) {
case ".gitignore", ".gitattributes", ".editorconfig", "cmakelists.txt":
return true
}
return false
}
func comparisonFile(path string) (File, error) {
if comparableText(path) {
info, e := os.Stat(path)
if e != nil {
return File{}, e
}
if info.Size() <= 64<<20 {
b, e := os.ReadFile(path)
if e != nil {
return File{}, e
}
f := File{Hash: digest(b)}
if utf8.Valid(b) && !bytes.ContainsRune(b, 0) {
f.TextHash = digest(bytes.ReplaceAll(b, []byte("\r\n"), []byte("\n")))
}
return f, nil
}
}
h, e := fileDigest(path)
return File{Hash: h}, e
}
+68
View File
@@ -0,0 +1,68 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestTextComparisonPreservesRemoteBytes(t *testing.T) {
s := testServer(t)
p := project(t, s)
path := filepath.Join(s.work(p), "Source.kt")
original := []byte("val x = 1\r\nval y = 2\r\n")
os.WriteFile(path, original, 0600)
s.projects[p].Files["Source.kt"] = File{Hash: digest(original)}
f := s.manifest(p).Files["Source.kt"]
if f.TextHash != digest([]byte("val x = 1\nval y = 2\n")) || f.Hash != digest(original) {
t.Fatal("EOL or raw digest incorrect", f)
}
w := call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "equivalent", Files: map[string]File{"Source.kt": {Hash: f.Hash}}})
if w.Code != 200 {
t.Fatal(w.Body.String())
}
b, _ := os.ReadFile(path)
if string(b) != string(original) {
t.Fatal("remote EOL rewritten")
}
for _, name := range []string{"image.bin", "script.sh", "gradlew"} {
q := filepath.Join(s.work(p), name)
os.WriteFile(q, original, 0600)
actual, _ := comparisonFile(q)
if actual.TextHash != "" {
t.Fatalf("binary/script normalized: %s", name)
}
}
for _, b := range [][]byte{{0xff, 0xfe, 13, 10}, []byte("a\x00\r\n")} {
os.WriteFile(path, b, 0600)
actual, _ := comparisonFile(path)
if actual.TextHash != "" {
t.Fatal("non-UTF8/NUL data normalized")
}
}
}
func TestDiscoveredJDKRequiredAndReleaseParsed(t *testing.T) {
s := testServer(t)
if _, e := s.selectedJDK(filepath.Join(t.TempDir(), "arbitrary")); e == nil {
t.Fatal("undiscovered executable accepted")
}
home := t.TempDir()
os.MkdirAll(filepath.Join(home, "bin"), 0700)
for _, n := range []string{"java", "javac"} {
os.WriteFile(filepath.Join(home, "bin", javaExecutable(n)), []byte("placeholder"), 0600)
}
os.WriteFile(filepath.Join(home, "release"), []byte("JAVA_VERSION=\"21.0.8\"\n"), 0600)
j, ok := inspectJDK(home, "test")
if !ok || j.Version != "21.0.8" {
t.Fatal("installed JDK release not recognized")
}
os.Remove(filepath.Join(home, "bin", javaExecutable("javac")))
if _, ok := inspectJDK(home, "test"); ok {
t.Fatal("JRE without javac offered as JDK")
}
w := call(t, s, "GET", "/jdks", nil)
if w.Code != 200 || !strings.Contains(w.Body.String(), `"defaultJavaHome"`) {
t.Fatal(w.Body.String())
}
}
+539
View File
@@ -0,0 +1,539 @@
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
type GitSnapshot struct {
Head string `json:"head"`
Branch string `json:"branch"`
Dirty bool `json:"dirty"`
Upstream string `json:"upstream"`
AheadBehind string `json:"aheadBehind"`
}
type WorkspaceRequest struct {
WorkspacePath string `json:"workspacePath"`
ProjectID string `json:"projectId,omitempty"`
Git *GitSnapshot `json:"git,omitempty"`
}
func reservedSource(path string) bool {
for _, part := range strings.Split(filepath.ToSlash(path), "/") {
switch strings.ToLower(part) {
case ".git", ".gradle", ".idea", "build", ".remotecompile", ".kotlin", ".cxx", ".externalnativebuild", "node_modules", "local.properties", "key.properties", "keystore.properties":
return true
}
lower := strings.ToLower(part)
if strings.HasPrefix(lower, ".env") || strings.HasSuffix(lower, ".jks") || strings.HasSuffix(lower, ".keystore") {
return true
}
}
return false
}
func fileDigest(path string) (string, error) {
f, e := os.Open(path)
if e != nil {
return "", e
}
defer f.Close()
h := sha256.New()
if _, e = io.Copy(h, f); e != nil {
return "", e
}
return hex.EncodeToString(h.Sum(nil)), nil
}
func (s *Server) strictManifest(p string) *Project {
pr := *s.projects[p]
pr.Files = map[string]File{}
// Never advertise a stale hash: Gradle or a human may have changed/removed a file.
for path, f := range s.projects[p].Files {
if !validPath(path) {
continue
}
if actual, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path))); e == nil && actual.Hash == f.Hash {
pr.Files[path] = actual
}
}
pr.WorkspacePath = s.work(p)
return &pr
}
// A clean checkout is a valid new sync base, even if HEAD did not move.
// Keep this read-only: a build must still match the last committed sync snapshot.
func (s *Server) manifest(p string) *Project {
result := s.strictManifest(p)
if s.projects[p].WorkspacePath == "" {
return result
}
remote, e := gitSnapshot(s.work(p))
if e != nil || remote == nil {
return result
}
if remote.Dirty {
for path, f := range s.projects[p].Files {
if !validPath(path) || f.TextHash == "" {
continue
}
if _, ok := result.Files[path]; ok {
continue
}
current, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path)))
if e == nil && current.TextHash == f.TextHash {
result.Files[path] = current
result.Revision = ""
}
}
return result
}
actual, e := sourceInventory(s.work(p))
if e != nil {
return result
}
result.Files = map[string]File{}
for path := range actual {
f, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path)))
if e != nil {
return s.strictManifest(p)
}
result.Files[path] = f
}
if !sameSourceHashes(s.projects[p].Files, result.Files) {
result.Revision = ""
}
result.Git = remote
return result
}
func sameSourceHashes(a, b map[string]File) bool {
count := 0
for path, f := range a {
if !validPath(path) {
continue
}
count++
if b[path].Hash != f.Hash {
return false
}
}
return count == len(b)
}
// Include restored/deleted tracked files when syncing after a clean reset/checkout.
func (s *Server) syncBase(p string) (map[string]File, error) {
old := s.projects[p].Files
if s.projects[p].WorkspacePath == "" {
return old, nil
}
remote, e := gitSnapshot(s.work(p))
if e != nil {
return nil, e
}
if remote == nil || remote.Dirty {
return old, nil
}
actual, e := sourceInventory(s.work(p))
if e != nil {
return nil, e
}
base := map[string]File{}
for path, f := range old {
base[path] = f
}
for path, f := range actual {
base[path] = f
}
return base, nil
}
func (s *Server) validateWorkspace(path string) (string, error) {
if !filepath.IsAbs(path) {
return "", fmt.Errorf("请填写服务端已有文件夹的绝对路径")
}
root := s.workspaceRoot
if root == "" {
root = filepath.Join(s.root, "projects")
}
root, e := filepath.Abs(root)
if e != nil {
return "", e
}
path = filepath.Clean(path)
dataRel, dataErr := filepath.Rel(s.root, path)
if dataErr == nil && dataRel != ".." && !strings.HasPrefix(dataRel, ".."+string(filepath.Separator)) {
parts := strings.Split(filepath.ToSlash(dataRel), "/")
if len(parts) != 3 || parts[0] != "projects" || !safeID.MatchString(parts[1]) || parts[2] != "work" {
return "", fmt.Errorf("不能选择服务数据或元数据目录;旧工作区请精确选择 projects/<id>/work")
}
}
rel, e := filepath.Rel(root, path)
if e != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return "", fmt.Errorf("远程文件夹必须位于管理员允许的根目录内:%s", root)
}
// Reject both final and ancestor symlink/junction redirection.
for current := path; ; current = filepath.Dir(current) {
i, e := os.Lstat(current)
if e != nil {
return "", fmt.Errorf("服务端文件夹不存在或不可访问:%s", current)
}
if !i.IsDir() || i.Mode()&os.ModeSymlink != 0 {
return "", fmt.Errorf("远程文件夹不允许符号链接或重解析路径")
}
if current == filepath.Dir(current) {
break
}
}
resolved, e := filepath.EvalSymlinks(path)
if e != nil {
return "", e
}
if !strings.EqualFold(filepath.Clean(resolved), path) {
return "", fmt.Errorf("远程文件夹经过链接重定向")
}
return path, nil
}
// Directory browsing is confined to the administrator's root. Files are never listed.
func (s *Server) browseDirectories(w http.ResponseWriter, r *http.Request) {
root := s.workspaceRoot
if root == "" {
root = filepath.Join(s.root, "projects")
}
root, _ = filepath.Abs(root)
path := r.URL.Query().Get("path")
if path == "" {
path = root
}
path = filepath.Clean(path)
rel, e := filepath.Rel(root, path)
if e != nil || !filepath.IsAbs(path) || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
http.Error(w, "目录超出管理员允许的根目录", 400)
return
}
resolved, e := filepath.EvalSymlinks(path)
if e != nil || !strings.EqualFold(filepath.Clean(resolved), path) {
http.Error(w, "目录不存在或经过链接重定向", 400)
return
}
entries, e := os.ReadDir(path)
if e != nil {
http.Error(w, "服务账户无法读取该目录", 400)
return
}
dirs := []map[string]string{}
for _, entry := range entries {
if entry.IsDir() && !reservedSource(entry.Name()) {
dirs = append(dirs, map[string]string{"name": entry.Name(), "path": filepath.Join(path, entry.Name())})
}
if len(dirs) >= 1000 {
break
}
}
parent := ""
if rel != "." {
parent = filepath.Dir(path)
}
_, selectErr := s.validateWorkspace(path)
jsonOut(w, map[string]any{"path": path, "root": root, "parent": parent, "selectable": selectErr == nil, "directories": dirs, "limit": 1000})
}
func gitCommand(work string, input []byte, args ...string) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "git", append([]string{"-c", "safe.directory=" + work, "-C", work}, args...)...)
cmd.Stdin = bytes.NewReader(input)
cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0", "GIT_OPTIONAL_LOCKS=0")
return cmd.Output()
}
func gitSnapshot(work string) (*GitSnapshot, error) {
// Only inspect the selected repository, never silently inherit its parent repository.
if _, e := os.Stat(filepath.Join(work, ".git")); os.IsNotExist(e) {
return nil, nil
}
if _, e := gitCommand(work, nil, "rev-parse", "--is-inside-work-tree"); e != nil {
return nil, fmt.Errorf("服务端 Git 仓库无法读取;请检查 Git 安装、仓库所有者及服务账户权限")
}
if _, e := gitCommand(work, nil, "status", "--porcelain", "--untracked-files=normal"); e != nil {
return nil, fmt.Errorf("无法读取服务端 Git 状态")
}
read := func(args ...string) string {
b, _ := gitCommand(work, nil, args...)
return strings.TrimSpace(string(b))
}
return &GitSnapshot{Head: read("rev-parse", "--verify", "HEAD"), Branch: read("symbolic-ref", "--short", "-q", "HEAD"), Dirty: read("status", "--porcelain", "--untracked-files=normal") != "", Upstream: read("rev-parse", "--abbrev-ref", "@{upstream}"), AheadBehind: read("rev-list", "--left-right", "--count", "HEAD...@{upstream}")}, nil
}
func sourceInventory(work string) (map[string]File, error) {
if e := noLinks(work); e != nil {
return nil, e
}
result := map[string]File{}
git, e := gitSnapshot(work)
if e != nil {
return nil, e
}
var paths []string
if git != nil {
b, e := gitCommand(work, nil, "ls-files", "-z", "--cached", "--others", "--exclude-standard")
if e != nil {
return nil, fmt.Errorf("无法读取服务端 Git 文件清单")
}
paths = strings.Split(strings.TrimSuffix(string(b), "\x00"), "\x00")
ignored, e := gitCommand(work, b, "check-ignore", "--no-index", "-z", "--stdin")
if e != nil {
if exit, ok := e.(*exec.ExitError); !ok || exit.ExitCode() != 1 {
return nil, fmt.Errorf("服务端 Git 忽略规则检查失败")
}
}
skip := map[string]bool{}
for _, p := range strings.Split(string(ignored), "\x00") {
skip[p] = true
}
filtered := paths[:0]
for _, p := range paths {
if !skip[p] {
filtered = append(filtered, p)
}
}
paths = filtered
} else {
e = filepath.WalkDir(work, func(path string, d os.DirEntry, e error) error {
if e != nil {
return e
}
rel, _ := filepath.Rel(work, path)
if rel == "." {
return nil
}
if reservedSource(rel) {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
if !d.IsDir() {
paths = append(paths, filepath.ToSlash(rel))
}
return nil
})
if e != nil {
return nil, e
}
}
for _, p := range paths {
if p == "" || reservedSource(p) {
continue
}
if !validPath(p) {
return nil, fmt.Errorf("服务端存在无法同步的路径:%s", p)
}
path := filepath.Join(work, filepath.FromSlash(p))
i, e := os.Lstat(path)
if os.IsNotExist(e) {
continue
}
if e != nil {
return nil, e
}
if !i.Mode().IsRegular() {
return nil, fmt.Errorf("服务端源码包含链接或特殊文件:%s", p)
}
h, e := fileDigest(path)
if e != nil {
return nil, e
}
result[p] = File{Hash: h}
}
return result, nil
}
func compareGit(local, remote *GitSnapshot) error {
if remote != nil && local == nil {
return fmt.Errorf("服务端存在 Git 仓库,但本机无法读取 Git 状态")
}
if local != nil && remote != nil && local.Head != remote.Head {
return fmt.Errorf("两边 Git 提交不同,请先手动同步仓库;本机 HEAD=%s,服务端 HEAD=%s", local.Head, remote.Head)
}
return nil
}
func (s *Server) checkGit(p string, local *GitSnapshot) error {
remote, e := gitSnapshot(s.work(p))
if e != nil {
return e
}
if e = compareGit(local, remote); e != nil {
return e
}
if s.projects[p].WorkspacePath == "" {
return nil
}
// A clean matching Git checkout may have been deliberately updated by its owner.
if remote != nil && !remote.Dirty {
return nil
}
// Detect remote edits even after a previous sync intentionally made the remote Git tree dirty.
actual, e := sourceInventory(s.work(p))
if e != nil {
return e
}
for path, f := range s.projects[p].Files {
if !validPath(path) {
continue
}
if actual[path].Hash != f.Hash {
if f.TextHash != "" {
if current, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path))); e == nil && current.TextHash == f.TextHash {
continue
}
}
return fmt.Errorf("服务端源码已变化:%s;为避免覆盖,请先处理服务端修改", path)
}
}
for path := range actual {
if _, ok := s.projects[p].Files[path]; !ok {
return fmt.Errorf("服务端新增源码:%s;请先处理服务端修改", path)
}
}
return nil
}
func (s *Server) checkWorkspace(w http.ResponseWriter, r *http.Request) {
var req WorkspaceRequest
if e := decode(w, r, &req); e != nil {
http.Error(w, e.Error(), 400)
return
}
path, e := s.validateWorkspace(req.WorkspacePath)
if e != nil {
http.Error(w, e.Error(), 400)
return
}
remote, e := gitSnapshot(path)
if e != nil {
http.Error(w, e.Error(), 400)
return
}
e = compareGit(req.Git, remote)
if pr := s.projects[req.ProjectID]; pr != nil && filepath.Clean(s.work(req.ProjectID)) != path {
e = fmt.Errorf("工程ID与服务端文件夹不匹配,请重新保存配置以分配工作区")
}
if e == nil {
if pr := s.projects[req.ProjectID]; pr != nil && pr.Busy {
e = fmt.Errorf("工作区正在构建,请等待完成")
}
}
if e == nil {
if pr := s.projects[req.ProjectID]; pr != nil && filepath.Clean(s.work(req.ProjectID)) == path {
e = s.checkGit(req.ProjectID, req.Git)
} else if remote != nil && remote.Dirty {
e = fmt.Errorf("服务端仓库有未提交修改;首次绑定前请先处理,避免覆盖")
}
}
message := "检查通过;双方 Git HEAD 相同,未提交的本机源码将增量同步"
if remote == nil {
message = "服务端没有 .git,无法比较 Git 提交;同步时使用本机 Git 忽略规则"
}
if e != nil {
message = e.Error()
}
jsonOut(w, map[string]any{"workspacePath": path, "git": remote, "canSync": e == nil, "message": message})
}
func (s *Server) createProject(w http.ResponseWriter, r *http.Request) {
var req WorkspaceRequest
if e := decode(w, r, &req); e != nil && e != io.EOF {
http.Error(w, e.Error(), 400)
return
}
p := id()
pr := &Project{Files: map[string]File{}}
if req.WorkspacePath != "" {
path, e := s.validateWorkspace(req.WorkspacePath)
if e != nil {
http.Error(w, e.Error(), 400)
return
}
for other := range s.projects {
if strings.EqualFold(s.work(other), path) {
if s.projects[other].WorkspacePath == "" && !s.projects[other].Busy {
remote, e := gitSnapshot(path)
if e == nil {
e = compareGit(req.Git, remote)
}
if e == nil && remote != nil && remote.Dirty {
e = fmt.Errorf("服务端仓库有未提交修改,首次绑定前请先处理")
}
if e != nil {
http.Error(w, e.Error(), 409)
return
}
files, e := sourceInventory(path)
if e != nil {
http.Error(w, e.Error(), 400)
return
}
s.projects[other].WorkspacePath = path
s.projects[other].Files = files
s.projects[other].Git = req.Git
if e = s.save(other); e != nil {
http.Error(w, e.Error(), 400)
return
}
jsonOut(w, map[string]string{"id": other, "workspacePath": path})
return
}
http.Error(w, "该服务端文件夹已绑定另一个工程,请选择独立工作区", 409)
return
}
}
for other := range s.projects {
a := strings.ToLower(filepath.Clean(s.work(other))) + string(filepath.Separator)
b := strings.ToLower(path) + string(filepath.Separator)
if strings.HasPrefix(a, b) || strings.HasPrefix(b, a) {
http.Error(w, "服务端工程目录不能与其他工作区重叠", 409)
return
}
}
remote, e := gitSnapshot(path)
if e == nil {
e = compareGit(req.Git, remote)
}
if e == nil && remote != nil && remote.Dirty {
e = fmt.Errorf("服务端仓库有未提交修改,首次绑定前请先处理")
}
if e != nil {
http.Error(w, e.Error(), 409)
return
}
files, e := sourceInventory(path)
if e != nil {
http.Error(w, e.Error(), 400)
return
}
pr.WorkspacePath = path
pr.Files = files
pr.Git = req.Git
}
s.projects[p] = pr
if e := os.MkdirAll(filepath.Join(s.root, "projects", p), 0700); e != nil {
delete(s.projects, p)
http.Error(w, e.Error(), 400)
return
}
if req.WorkspacePath == "" {
if e := os.MkdirAll(s.work(p), 0700); e != nil {
delete(s.projects, p)
http.Error(w, e.Error(), 400)
return
}
}
if e := s.save(p); e != nil {
delete(s.projects, p)
http.Error(w, e.Error(), 400)
return
}
jsonOut(w, map[string]string{"id": p, "workspacePath": s.work(p)})
}
+136
View File
@@ -0,0 +1,136 @@
package main
import (
"encoding/json"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestManifestRechecksActualContent(t *testing.T) {
s := testServer(t)
p := project(t, s)
call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "r", Files: map[string]File{"a.txt": file("source")}})
os.WriteFile(filepath.Join(s.work(p), "a.txt"), []byte("changed by build"), 0600)
w := call(t, s, "GET", "/projects/"+p+"/manifest", nil)
var actual Project
json.Unmarshal(w.Body.Bytes(), &actual)
if len(actual.Files) != 0 {
t.Fatal("advertised stale hash, causing missing content")
}
if w = call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "r2", Files: map[string]File{"a.txt": file("source")}}); w.Code != 200 {
t.Fatal(w.Body.String())
}
}
func TestExistingWorkspaceBoundaryAndGitProtection(t *testing.T) {
if _, e := exec.LookPath("git"); e != nil {
t.Skip("git unavailable")
}
s := testServer(t)
s.workspaceRoot = t.TempDir()
work := filepath.Join(s.workspaceRoot, "中文 project")
os.MkdirAll(work, 0700)
git := func(args ...string) {
t.Helper()
if out, e := exec.Command("git", append([]string{"-C", work}, args...)...).CombinedOutput(); e != nil {
t.Fatalf("git: %v %s", e, out)
}
}
git("init", "-q")
os.WriteFile(filepath.Join(work, "a.txt"), []byte("base"), 0600)
os.WriteFile(filepath.Join(work, ".gitignore"), []byte("ignored/\n"), 0600)
git("add", ".")
git("-c", "user.name=Test", "-c", "user.email=test@example.invalid", "commit", "-qm", "base")
snapshot, e := gitSnapshot(work)
if e != nil {
t.Fatal(e)
}
req := WorkspaceRequest{WorkspacePath: work, Git: snapshot}
w := call(t, s, "POST", "/projects/check", req)
if w.Code != 200 || !strings.Contains(w.Body.String(), `"canSync":true`) {
t.Fatal(w.Body.String())
}
if len(s.projects) != 0 {
t.Fatal("manual check mutated server projects")
}
mismatch := *snapshot
mismatch.Head = "different"
req.Git = &mismatch
w = call(t, s, "POST", "/projects/check", req)
if !strings.Contains(w.Body.String(), `"canSync":false`) {
t.Fatal("mismatched HEAD accepted")
}
req.Git = snapshot
w = call(t, s, "POST", "/projects", req)
if w.Code != 200 {
t.Fatal(w.Body.String())
}
var allocated map[string]string
json.Unmarshal(w.Body.Bytes(), &allocated)
p := allocated["id"]
if s.work(p) != work {
t.Fatal("selected existing path not used")
}
// Local dirty content is intentional; the server must accept subsequent syncs of its own snapshot.
files := map[string]File{}
for path, f := range s.projects[p].Files {
files[path] = f
}
files["a.txt"] = file("local edit")
w = call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "new", Files: files, Git: snapshot})
if w.Code != 200 {
t.Fatal(w.Body.String())
}
req.ProjectID = p
w = call(t, s, "POST", "/projects/check", req)
if !strings.Contains(w.Body.String(), `"canSync":true`) {
t.Fatal(w.Body.String())
}
os.WriteFile(filepath.Join(work, "a.txt"), []byte("remote edit"), 0600)
w = call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "next", Files: files, Git: snapshot})
if w.Code != 409 {
t.Fatal("remote edit overwritten", w.Body.String())
}
if w = call(t, s, "POST", "/projects/"+p+"/builds", map[string]string{"revision": "new", "task": ":app:assembleDebug"}); w.Code != 409 {
t.Fatal("built changed source under stale revision", w.Body.String())
}
req.WorkspacePath = t.TempDir()
if w = call(t, s, "POST", "/projects/check", req); w.Code != 400 {
t.Fatal("allowed root escaped")
}
req.WorkspacePath = filepath.Join(s.workspaceRoot, "missing")
if w = call(t, s, "POST", "/projects/check", req); w.Code != 400 {
t.Fatal("missing folder accepted")
}
// Directory browsing lists folders within the configured root without binding them.
w = call(t, s, "GET", "/directories", nil)
if w.Code != 200 || !strings.Contains(w.Body.String(), "中文 project") {
t.Fatal(w.Body.String())
}
if w = call(t, s, "GET", "/directories?path="+filepath.ToSlash(t.TempDir()), nil); w.Code != 400 {
t.Fatal("directory browser escaped root")
}
}
func TestNativeBuildCachesCannotBeSyncedOrDeleted(t *testing.T) {
s := testServer(t)
p := project(t, s)
path := "app/.cxx/Debug/arm64-v8a/.ninja_deps"
if validPath(path) {
t.Fatal("native cache accepted")
}
os.MkdirAll(filepath.Dir(filepath.Join(s.work(p), filepath.FromSlash(path))), 0700)
os.WriteFile(filepath.Join(s.work(p), filepath.FromSlash(path)), []byte("server cache"), 0600)
s.projects[p].Files[path] = File{Hash: digest([]byte("old upload"))}
w := call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "clean", Files: map[string]File{}})
if w.Code != 200 {
t.Fatal(w.Body.String())
}
if _, e := os.Stat(filepath.Join(s.work(p), filepath.FromSlash(path))); e != nil {
t.Fatal("server cache deleted", e)
}
if len(s.projects[p].Files) != 0 {
t.Fatal("cache stayed in source manifest")
}
}