feat: 初始化跨平台远程编译服务与 Android Studio 插件
This commit is contained in:
commit
9eba4556db
44 files changed
+2802
No files matched your search
@@ -0,0 +1,5 @@
|
||||
* text=auto
|
||||
*.sh text eol=lf
|
||||
gradlew text eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.jar binary
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
.gradle-user-home/
|
||||
.deployment/
|
||||
server-data/
|
||||
**/.go-cache/
|
||||
**/.gradle/
|
||||
**/.intellijPlatform/
|
||||
**/.idea/
|
||||
*.iml
|
||||
**/build/
|
||||
**/data/
|
||||
dist/
|
||||
.remotecompile/
|
||||
*.log
|
||||
__pycache__/
|
||||
@@ -0,0 +1,89 @@
|
||||
# AGENTS.md — VibeCodingRemoteCompilation
|
||||
|
||||
## 项目目标
|
||||
|
||||
构建 Android Studio 远程编译工具:本机编辑代码,通过增量同步传给局域网服务器,由常驻服务执行 Gradle,插件下载 APK,再使用本机 adb 安装到选定设备。支持未提交的代码,不依赖 Git 提交或 CI 平台。
|
||||
|
||||
当前已按用户要求实现首版原型:server/、plugin/、client/ 分目录,手动 Remote Run 闭环。后续开发基于此实现迭代;未获部署要求时,不自动部署到用户服务器。
|
||||
|
||||
## 技术选型(初始方案)
|
||||
|
||||
| 层次 | 选择 | 原因 |
|
||||
| --- | --- | --- |
|
||||
| 编译服务 | Go,优先标准库 net/http、os/exec、log/slog | 分平台发布独立可执行文件,减少服务端运行时依赖 |
|
||||
| IDE 插件 | Kotlin + IntelliJ Platform Plugin SDK + Gradle Kotlin DSL | 面向 Android Studio;按用户实际 IDE 版本选择兼容平台 |
|
||||
| 控制协议 | 版本化 REST JSON,前缀 /api/v1 | 项目、同步会话、构建、状态、取消及产物管理 |
|
||||
| 日志协议 | SSE,带递增事件编号和重连补读 | 服务端单向推送日志;首版无需 WebSocket |
|
||||
| 源码同步 | 可替换的 SyncProvider;保留 rsync over SSH 方案 | 满足增量同步需求,同时隔离外部工具和系统差异 |
|
||||
| 原生跨平台同步 | 文件清单 + SHA-256 + HTTP 上传变更文件 + 显式删除清单 | Windows 无 rsync 时仍可使用;属于文件级增量,不声称具备 rsync 块级差分 |
|
||||
| 构建执行 | 项目自带 Gradle Wrapper | 使用项目锁定的 Gradle 版本;服务器配置 JDK 和 Android SDK |
|
||||
| 配置与状态 | JSON 配置、磁盘元数据和日志;首版不引入数据库 | 单机服务足够,减少部署组件;元数据采用原子写入 |
|
||||
| 产物存储 | 本地文件系统 + HTTP 下载 + SHA-256 | 每个构建独立保存,插件验证完整性后安装 |
|
||||
| 设备安装 | 插件调用本机 SDK 中的 adb | 手机连接本机,服务器不负责访问本机 USB |
|
||||
| 部署 | 原生二进制优先,Docker 可选 | Windows、Linux、macOS 可运行,不强制 WSL 或 Docker |
|
||||
|
||||
版本选择使用实施时可用的稳定工具链,并提交锁定配置。不要将本文件视为已验证的系统兼容性声明。
|
||||
|
||||
## 跨平台边界
|
||||
|
||||
- 服务端目标为 Windows、Linux、macOS;分别构建对应 OS/CPU 的二进制。实际可用的 Android SDK、JDK、NDK 和项目依赖必须在目标机器验证,不承诺任意系统架构都能编译 Android。
|
||||
- 插件同样考虑 Windows、Linux、macOS。不得硬编码盘符、路径分隔符、shell 或 SDK 位置。
|
||||
- rsync 模式需要客户端和服务器具有兼容的 rsync、SSH 环境;Windows 可显式配置 WSL 或兼容工具。不得将其描述为零依赖原生能力。
|
||||
- 首版优先打通 HTTP 文件级增量同步,rsync 作为可选适配器;如果用户要求 rsync 优先,按用户要求调整实施顺序。
|
||||
- Unix 与 Windows 分别适配 Gradle Wrapper 启动方式。Windows 的 .bat 调用需要明确 shell 边界与参数转义,禁止将客户端输入拼成任意 shell 命令。
|
||||
- 构建取消需适配 Unix 进程组和 Windows 进程树。普通子进程退出不等于整个构建已取消;Gradle Daemon 的清理不得影响其他项目。
|
||||
- 处理空格、中文路径、文件删除、重命名、大小写冲突、符号链接和可执行权限。无法无损映射的路径在同步前明确报错。
|
||||
|
||||
## 核心工作流程与一致性
|
||||
|
||||
1. 插件保存文件,生成源代码版本编号;同步和构建不得运行在 IDE UI 线程。
|
||||
2. 创建同步会话,传输变更及删除信息,校验后提交;失败会话不得作为可构建版本。
|
||||
3. 同一工作区的同步、提交与构建串行加锁;构建期间不得覆盖其源码。多个客户端使用独立工作区。
|
||||
4. 服务端执行已配置且允许的 Gradle 任务,推送日志,保存构建状态。
|
||||
5. 成功后将 APK 复制到以 buildId 隔离的产物目录,记录源码版本、任务、大小及摘要;不得把旧输出误判为本次成功产物。
|
||||
6. 插件仅自动安装当前最新请求的成功产物,明确指定 adb 设备序列号;失败时保留现有设备应用,不自动卸载。
|
||||
|
||||
同步排除 .git、.gradle、各模块 build、local.properties、IDE 缓存和本机凭据;排除规则允许项目配置。服务器保留自己的编译缓存、SDK 配置和工作区输出,正常构建不默认 clean。
|
||||
|
||||
## 第一阶段范围
|
||||
|
||||
- 服务端:健康与能力检查、认证、项目工作区、增量同步会话、构建队列、实时日志、取消、APK 下载与保留策略。
|
||||
- 插件:连接配置、模块及 Gradle 任务配置、Remote Run 按钮、日志面板、下载校验、设备选择及 adb 安装。
|
||||
- 先完成手动 Remote Run 闭环,再加入可关闭的保存后自动构建、3~5 秒防抖及待执行请求合并。
|
||||
- 首版支持普通单 APK;拆分 APK、应用启动、断点调试和 Apply Changes 后续单独适配。不将构建远程化等同于本机无需 SDK/JDK 或无需 Gradle Sync。
|
||||
|
||||
## 服务与安全约束
|
||||
|
||||
- 默认只处理受信任用户与项目;Gradle 脚本本身可执行代码,服务不是不可信代码沙箱。使用专用普通账户运行。
|
||||
- 非回环地址访问要求认证;远程连接使用 HTTPS 或受保护隧道,rsync 使用 SSH;凭据不进入日志、仓库或源码同步。
|
||||
- 工作区与产物 ID 由服务端分配,校验所有相对路径、符号链接与删除目标,禁止越出服务数据目录。
|
||||
- HTTP 同步写入和 rsync 写入必须遵守同一工作区锁。rsync 访问限制为分配的工作区,不因使用外部同步而绕过提交校验。
|
||||
- JDK、SDK、Gradle 任务及环境变量按项目配置与校验;不提供任意远程命令接口。
|
||||
- 固定调试签名以支持覆盖安装;签名密钥通过明确配置管理,不随普通源码同步默认上传。
|
||||
- 服务重启后将未确认结束的任务标记为中断并处理残留执行器;不假报成功或自动重复安装。
|
||||
|
||||
## 建议目录
|
||||
|
||||
```text
|
||||
server/ Go 服务与平台适配
|
||||
plugin/ Android Studio Kotlin 插件
|
||||
protocol/ API、事件、状态及同步协议定义
|
||||
docs/ 架构、部署、使用说明
|
||||
examples/ 示例配置,不含密钥
|
||||
```
|
||||
|
||||
## 开发与验证
|
||||
|
||||
- 先定义协议和状态机,再实现服务、插件;避免插件直接依赖服务内部代码。
|
||||
- 对同步删除与路径隔离、同步/构建互斥、版本对应、任务取消及失败不安装编写有价值的测试。
|
||||
- 分平台验证编译器启动、中文/空格路径、日志编码、取消和产物下载。未实际运行的平台明确注明未验证,交叉编译通过不等于运行验证通过。
|
||||
- 文档与用户沟通使用中文;代码命名使用清晰英文。不得在本阶段创建与任务无关的功能。
|
||||
|
||||
## 参考资料
|
||||
|
||||
- Go 跨平台安装:https://go.dev/doc/install
|
||||
- Go 子进程执行:https://pkg.go.dev/os/exec
|
||||
- Android Studio 插件:https://plugins.jetbrains.com/docs/intellij/android-studio.html
|
||||
- Android 命令行构建:https://developer.android.com/build/building-cmdline
|
||||
- adb:https://developer.android.com/tools/adb
|
||||
- rsync:https://www.samba.org/ftp/rsync/README.html
|
||||
@@ -0,0 +1,90 @@
|
||||
# VibeCoding Remote Compilation · 0.1
|
||||
|
||||
Android Studio 本机编辑 → 增量上传 → 局域网服务编译 → 下载 APK → 本机 adb 安装。
|
||||
|
||||
## 目录
|
||||
|
||||
| 目录 | 内容 |
|
||||
| --- | --- |
|
||||
| `server/` | Go 常驻编译服务,Windows / Linux / macOS 平台适配 |
|
||||
| `plugin/` | Android Studio / IntelliJ Platform 插件 |
|
||||
| `client/` | Python 标准库参考客户端,可独立使用 |
|
||||
| `protocol/` | HTTP 接口与状态定义 |
|
||||
| `docs/` | 部署、使用和版本限制 |
|
||||
| `examples/` | 服务启动示例 |
|
||||
| `dist/` | 本机编译产物,不提交版本控制 |
|
||||
|
||||
## 快速开始
|
||||
|
||||
服务器准备好项目所需 JDK、Android SDK、SDK licenses;在服务进程环境中配置 `JAVA_HOME`、`ANDROID_HOME`,需要时配置 `ANDROID_SDK_ROOT`。NDK 项目另需安装相应版本。无需打开 Android Studio。
|
||||
|
||||
构建服务(Go 1.24 或更高版本):
|
||||
|
||||
```powershell
|
||||
cd server
|
||||
go test ./...
|
||||
go build -o remotecompile.exe .
|
||||
$env:REMOTE_BUILD_TOKEN = '<自行生成的至少24字符随机值>'
|
||||
.\remotecompile.exe -data .\data -tasks ':app:assembleDebug'
|
||||
```
|
||||
|
||||
Linux/macOS:
|
||||
|
||||
```sh
|
||||
cd server
|
||||
go test ./...
|
||||
go build -o remotecompile .
|
||||
export REMOTE_BUILD_TOKEN='<自行生成的至少24字符随机值>'
|
||||
./remotecompile -data ./data -tasks ':app:assembleDebug'
|
||||
```
|
||||
|
||||
默认监听服务器 `127.0.0.1:8765`。在本机建立 SSH 隧道,保持该终端开启:
|
||||
|
||||
```sh
|
||||
ssh -N -L 8765:127.0.0.1:8765 user@服务器IP
|
||||
```
|
||||
|
||||
然后本机插件/客户端填 `http://127.0.0.1:8765`;也可以使用有可信证书的 HTTPS 反向代理。不要把 Token 放在命令行参数里。
|
||||
|
||||
## 使用插件
|
||||
|
||||
插件构建需要 JDK 21、Gradle 8.13。依赖版本固定在 `plugin/build.gradle.kts`;首次构建需要联网下载 IntelliJ 平台。
|
||||
|
||||
```powershell
|
||||
cd plugin
|
||||
.\gradlew.bat buildPlugin
|
||||
```
|
||||
|
||||
ZIP 输出在 `plugin/build/distributions/`。可用已安装的 Android Studio 作为编译平台:
|
||||
|
||||
```powershell
|
||||
.\gradlew.bat buildPlugin '-PstudioPath=C:\你的AndroidStudio安装目录'
|
||||
```
|
||||
|
||||
在 Android Studio 的 Settings → Plugins → 齿轮 → Install Plugin from Disk 选择 ZIP。0.1.1 起配置和运行分开:
|
||||
|
||||
1. 打开右侧齿轮栏 **Remote Configuration**,填服务地址、Token 和 Gradle 任务,点击保存配置。Token 存入 IDE PasswordSafe,后续留空会保留原值。
|
||||
2. 任务例如 `:app:assembleDebug`,需要与服务器 `-tasks` 白名单一致。需要安装时勾选“构建成功后安装到所选设备”。
|
||||
3. adb 路径可留空,自动从项目 `local.properties` 的 SDK 或本机 SDK 环境定位。只有需要指定其他 SDK 时才填写完整路径。
|
||||
4. 在底部 **Remote Compilation** 的设备下拉框选择 USB 手机、无线设备或模拟器。单台在线设备自动选中;列表每 5 秒刷新,也可手动刷新。未授权/离线设备显示状态,无法用于安装。
|
||||
5. 点击顶部运行图标、底部 **Remote Run** 或 Tools → Remote Run,直接使用已保存配置构建。右侧齿轮只打开配置,不触发构建。
|
||||
6. 插件先保存文件,再同步并构建;APK 保存到项目 `.remotecompile/<buildId>.apk`。安装前再次检查目标设备,避免把包安装到其他设备。
|
||||
|
||||
插件目标基础平台为 243(2024.3),具体 Android Studio 版本仍需运行验证。本版不替换原生 Run/Debug,不接管本机 Gradle Sync。
|
||||
|
||||
## 不通过 IDE 验证服务
|
||||
|
||||
本机 Python 3.10+:
|
||||
|
||||
```powershell
|
||||
$env:REMOTE_BUILD_TOKEN = '<与服务器一致的Token>'
|
||||
python client/remote_run.py 'D:\Android项目' --task ':app:assembleDebug'
|
||||
# 下载后安装到指定设备
|
||||
python client/remote_run.py 'D:\Android项目' --device '设备序列号' --adb 'C:\Android\Sdk\platform-tools\adb.exe'
|
||||
```
|
||||
|
||||
客户端与插件分别分配独立工作区,不共享源码或构建输出。源码无需提交 Git。
|
||||
|
||||
Linux/macOS 在 `plugin/` 执行 `sh ./gradlew buildPlugin`。也可使用已安装的 Gradle 8.13 构建。
|
||||
|
||||
参见 [部署与限制](docs/operations.md)、[协议](protocol/api.md)、[验证记录](docs/verification.md)。
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Dependency-free reference client: Python 3.10+, token via environment only."""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.request
|
||||
import urllib.parse
|
||||
import uuid
|
||||
|
||||
EXCLUDE = {'.git', '.gradle', '.idea', '.remotecompile', '.kotlin', 'build', 'node_modules', '__pycache__'}
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Sync, remote build, download and optionally install an APK')
|
||||
parser.add_argument('source', type=Path)
|
||||
parser.add_argument('--url', default='http://127.0.0.1:8765')
|
||||
parser.add_argument('--task', default=':app:assembleDebug')
|
||||
parser.add_argument('--adb', default='adb')
|
||||
parser.add_argument('--device', help='Explicit adb device serial; omit to download only')
|
||||
args = parser.parse_args()
|
||||
token = os.environ.get('REMOTE_BUILD_TOKEN', '')
|
||||
if len(token) < 24:
|
||||
parser.error('Set REMOTE_BUILD_TOKEN to at least 24 characters')
|
||||
endpoint = args.url.rstrip('/')
|
||||
url = urllib.parse.urlparse(endpoint)
|
||||
if url.scheme not in ('https', 'http') or not url.hostname or url.username or url.query or url.fragment:
|
||||
parser.error('Invalid endpoint')
|
||||
if url.scheme == 'http' and url.hostname not in ('127.0.0.1', 'localhost', '::1'):
|
||||
parser.error('Use HTTPS or an SSH tunnel for remote connections')
|
||||
source = args.source.resolve(strict=True)
|
||||
output = source / '.remotecompile'
|
||||
output.mkdir(exist_ok=True)
|
||||
|
||||
def request(method, path, body=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
req = urllib.request.Request(endpoint + '/api/v1' + path, data=data, method=method,
|
||||
headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'})
|
||||
with urllib.request.urlopen(req, timeout=300) as response:
|
||||
result = response.read()
|
||||
return result if '/artifacts/' in path else json.loads(result)
|
||||
|
||||
request('GET', '/health')
|
||||
state_file = output / 'client.json'
|
||||
state = json.loads(state_file.read_text()) if state_file.exists() else {}
|
||||
if state.get('url') != endpoint:
|
||||
state = {'url': endpoint, 'project': request('POST', '/projects')['id']}
|
||||
state_file.write_text(json.dumps(state), encoding='utf-8')
|
||||
project = state['project']
|
||||
remote = request('GET', f'/projects/{project}/manifest')['files']
|
||||
manifest = {}
|
||||
changed = 0
|
||||
for directory, dirs, names in os.walk(source, followlinks=False):
|
||||
for name in list(dirs):
|
||||
if name in EXCLUDE:
|
||||
dirs.remove(name)
|
||||
elif (Path(directory) / name).is_symlink():
|
||||
raise RuntimeError('Symbolic links are unsupported')
|
||||
for name in names:
|
||||
if name == 'local.properties' or name.startswith('.env') or name.endswith(('.jks', '.keystore')) or name in ('key.properties', 'keystore.properties'):
|
||||
continue
|
||||
path = Path(directory) / name
|
||||
if path.is_symlink():
|
||||
raise RuntimeError(f'Symbolic link: {path}')
|
||||
if path.stat().st_size > 64 * 1024 * 1024:
|
||||
raise RuntimeError(f'File exceeds 64 MiB: {path}')
|
||||
content = path.read_bytes()
|
||||
sha = hashlib.sha256(content).hexdigest()
|
||||
relative = path.relative_to(source).as_posix()
|
||||
entry = {'hash': sha}
|
||||
if remote.get(relative, {}).get('hash') != sha:
|
||||
entry['data'] = base64.b64encode(content).decode()
|
||||
changed += 1
|
||||
manifest[relative] = entry
|
||||
revision = str(uuid.uuid4())
|
||||
print(f'Syncing {changed} changed files ({len(manifest)} total)', flush=True)
|
||||
request('POST', f'/projects/{project}/sync', {'revision': revision, 'files': manifest})
|
||||
build = request('POST', f'/projects/{project}/builds', {'revision': revision, 'task': args.task})
|
||||
build_id = build['id']
|
||||
offset = 0
|
||||
try:
|
||||
while True:
|
||||
build = request('GET', f'/builds/{build_id}')
|
||||
for line in build['logs'][offset:]:
|
||||
print(line, end='', flush=True)
|
||||
offset = len(build['logs'])
|
||||
if build['status'] not in ('queued', 'running'):
|
||||
break
|
||||
time.sleep(0.7)
|
||||
except KeyboardInterrupt:
|
||||
request('DELETE', f'/builds/{build_id}')
|
||||
raise
|
||||
if build['status'] != 'success':
|
||||
raise RuntimeError('Build ' + build['status'])
|
||||
if len(build['artifacts']) != 1:
|
||||
raise RuntimeError('Expected exactly one APK; split APKs unsupported in v0.1')
|
||||
artifact = build['artifacts'][0]
|
||||
content = request('GET', f'/builds/{build_id}/artifacts/' + urllib.parse.quote(artifact['name']))
|
||||
if hashlib.sha256(content).hexdigest() != artifact['hash']:
|
||||
raise RuntimeError('APK checksum mismatch')
|
||||
destination = output / (build_id + '.apk')
|
||||
destination.write_bytes(content)
|
||||
print(f'\nAPK: {destination}')
|
||||
if args.device:
|
||||
subprocess.run([args.adb, '-s', args.device, 'install', '-r', str(destination)], check=True, timeout=120)
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Exercises the real service binary and CLI using a simulated Gradle Wrapper.
|
||||
|
||||
This validates transport/lifecycle; it does not validate an Android toolchain.
|
||||
Run: python -m unittest discover -s client -p test_smoke.py -v
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
class SmokeTest(unittest.TestCase):
|
||||
def test_sync_build_download_and_second_revision(self):
|
||||
binary = ROOT / 'dist' / ('remotecompile-windows-amd64.exe' if os.name == 'nt' else 'remotecompile')
|
||||
if not binary.exists():
|
||||
self.skipTest(f'Build service binary first: {binary}')
|
||||
with tempfile.TemporaryDirectory(dir=ROOT) as temp:
|
||||
root = Path(temp)
|
||||
source = root / '中文 project'
|
||||
source.mkdir()
|
||||
(source / 'input.txt').write_text('first')
|
||||
(source / 'deleted.txt').write_text('remove')
|
||||
if os.name == 'nt':
|
||||
(source / 'gradlew.bat').write_text('@echo off\nmkdir app\\build\\outputs\\apk\\debug 2>nul\ncopy /y input.txt app\\build\\outputs\\apk\\debug\\app-debug.apk >nul\nexit /b 0\n')
|
||||
else:
|
||||
(source / 'gradlew').write_text('#!/bin/sh\nmkdir -p app/build/outputs/apk/debug\ncp input.txt app/build/outputs/apk/debug/app-debug.apk\n')
|
||||
with socket.socket() as sock:
|
||||
sock.bind(('127.0.0.1', 0))
|
||||
port = sock.getsockname()[1]
|
||||
endpoint = f'http://127.0.0.1:{port}'
|
||||
env = dict(os.environ, REMOTE_BUILD_TOKEN='test-only-token-abcdefghijklmnopqrstuvwxyz')
|
||||
process = subprocess.Popen([str(binary), '-listen', f'127.0.0.1:{port}', '-data', str(root / 'data')], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
try:
|
||||
for _ in range(100):
|
||||
try:
|
||||
req = urllib.request.Request(endpoint + '/api/v1/health', headers={'Authorization': 'Bearer ' + env['REMOTE_BUILD_TOKEN']})
|
||||
with urllib.request.urlopen(req, timeout=1):
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(.05)
|
||||
else:
|
||||
self.fail('Service did not start')
|
||||
command = [sys.executable, str(ROOT / 'client' / 'remote_run.py'), str(source), '--url', endpoint]
|
||||
first = subprocess.run(command, env=env, capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(first.returncode, 0, first.stderr)
|
||||
self.assertEqual(next((source / '.remotecompile').glob('*.apk')).read_bytes(), b'first')
|
||||
(source / 'input.txt').write_text('second')
|
||||
(source / 'deleted.txt').unlink()
|
||||
second = subprocess.run(command, env=env, capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(second.returncode, 0, second.stderr)
|
||||
self.assertIn('Syncing 1 changed files', second.stdout)
|
||||
artifacts = [p.read_bytes() for p in (source / '.remotecompile').glob('*.apk')]
|
||||
self.assertCountEqual(artifacts, [b'first', b'second'])
|
||||
state = json.loads((source / '.remotecompile' / 'client.json').read_text())
|
||||
self.assertFalse((root / 'data' / 'projects' / state['project'] / 'work' / 'deleted.txt').exists())
|
||||
finally:
|
||||
process.terminate()
|
||||
process.wait(timeout=15)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,25 @@
|
||||
# Ubuntu 22.04 部署
|
||||
|
||||
`install.sh` 将 Linux amd64 服务安装到 `/opt/remotecompile/bin/`,使用 `remotecompile` 系统账户运行,由 systemd 管理并设为开机启动。脚本会重启同名服务;不会安装或修改 Android SDK。
|
||||
|
||||
```sh
|
||||
sudo bash install.sh /tmp/remotecompile-linux-amd64
|
||||
```
|
||||
|
||||
可在首次安装时通过 `sudo env JAVA_HOME=... ANDROID_HOME=... bash ...` 指定服务器已有的 JDK/SDK。已有配置不覆盖;后续修改 `/etc/remotecompile/environment` 后重启。
|
||||
|
||||
- 配置和随机 Token:`/etc/remotecompile/environment`,仅 root 可读。
|
||||
- 数据及缓存:`/var/lib/remotecompile/`,服务账户可写。
|
||||
- 日志:`journalctl -u remotecompile -f`。
|
||||
- 重启:`sudo systemctl restart remotecompile`。
|
||||
- 仅监听 `127.0.0.1:8765`;通过本机 SSH 隧道或 HTTPS 代理访问。
|
||||
- systemd 启用 ProtectHome,SDK 不应放在 `/root` 或 `/home`;建议工具链放在服务可读的 `/opt` 下。按需安装 SDK 组件时需要明确调整工具链目录权限,服务只对自身数据目录拥有写权限。
|
||||
- SDK 自动下载、licenses 和签名材料需要单独准备。服务健康检查通过不代表真实项目已完成构建。
|
||||
|
||||
本机连接示例:
|
||||
|
||||
```sh
|
||||
ssh -N -L 8765:127.0.0.1:8765 root@192.168.5.224
|
||||
```
|
||||
|
||||
插件填 `http://127.0.0.1:8765`;Token 从服务器配置中读取后填入 IDE PasswordSafe。不要把配置提交仓库。
|
||||
Executable
+78
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env bash
|
||||
# Usage: sudo bash install.sh /path/to/remotecompile-linux-amd64
|
||||
# Optional: JAVA_HOME, ANDROID_HOME, ANDROID_SDK_ROOT (existing readable toolchains).
|
||||
set -euo pipefail
|
||||
if [[ $(id -u) != 0 ]]; then echo 'Run as root or through sudo.' >&2; exit 1; fi
|
||||
if [[ $(uname -m) != x86_64 ]]; then echo 'This package requires x86_64 Linux.' >&2; exit 1; fi
|
||||
binary=${1:?Provide the uploaded Linux amd64 executable}
|
||||
[[ -f "$binary" ]] || { echo 'Binary does not exist' >&2; exit 1; }
|
||||
if ! id remotecompile >/dev/null 2>&1; then
|
||||
useradd --system --create-home --home-dir /var/lib/remotecompile --shell /usr/sbin/nologin remotecompile
|
||||
fi
|
||||
install -d -m 0755 /opt/remotecompile/bin
|
||||
install -d -m 0700 /etc/remotecompile
|
||||
install -d -o remotecompile -g remotecompile -m 0700 /var/lib/remotecompile /var/lib/remotecompile/data
|
||||
if [[ ! -f /etc/remotecompile/environment ]]; then
|
||||
umask 077
|
||||
token=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')
|
||||
printf 'REMOTE_BUILD_TOKEN=%s\nHOME=/var/lib/remotecompile\n' "$token" > /etc/remotecompile/environment
|
||||
for key in JAVA_HOME ANDROID_HOME ANDROID_SDK_ROOT; do
|
||||
value=${!key:-}
|
||||
if [[ -n "$value" ]]; then
|
||||
[[ "$value" != *$'\n'* && "$value" != *'"'* && "$value" != *'\\'* ]] || { echo "Unsupported characters in $key" >&2; exit 1; }
|
||||
printf '%s="%s"\n' "$key" "$value" >> /etc/remotecompile/environment
|
||||
fi
|
||||
done
|
||||
fi
|
||||
chmod 0600 /etc/remotecompile/environment
|
||||
# Stop through systemd so existing workers can finish cancellation and persist state.
|
||||
systemctl stop remotecompile.service 2>/dev/null || true
|
||||
install -m 0755 "$binary" /opt/remotecompile/bin/remotecompile
|
||||
cat > /etc/systemd/system/remotecompile.service <<'UNIT'
|
||||
[Unit]
|
||||
Description=VibeCoding Android Remote Compilation
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=remotecompile
|
||||
Group=remotecompile
|
||||
WorkingDirectory=/var/lib/remotecompile
|
||||
EnvironmentFile=/etc/remotecompile/environment
|
||||
ExecStart=/opt/remotecompile/bin/remotecompile -listen 127.0.0.1:8765 -data /var/lib/remotecompile/data -tasks :app:assembleDebug
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
TimeoutStopSec=40
|
||||
KillMode=control-group
|
||||
UMask=0077
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ReadWritePaths=/var/lib/remotecompile
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
UNIT
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now remotecompile.service
|
||||
for _ in {1..20}; do
|
||||
if systemctl is-active --quiet remotecompile.service; then
|
||||
if python3 - <<'PY'
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
config = Path('/etc/remotecompile/environment').read_text()
|
||||
token = next(line.split('=', 1)[1] for line in config.splitlines() if line.startswith('REMOTE_BUILD_TOKEN='))
|
||||
request = urllib.request.Request('http://127.0.0.1:8765/api/v1/health', headers={'Authorization': 'Bearer ' + token})
|
||||
with urllib.request.urlopen(request, timeout=2) as response:
|
||||
print('Health:', response.read().decode())
|
||||
PY
|
||||
then
|
||||
systemctl --no-pager --full status remotecompile.service
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
journalctl -u remotecompile.service --no-pager -n 30
|
||||
exit 1
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Run with sudo on the server; never prints the service token.
|
||||
Uses a simulated wrapper, not a real Android APK build.
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
token = next(line.split('=', 1)[1] for line in Path('/etc/remotecompile/environment').read_text().splitlines() if line.startswith('REMOTE_BUILD_TOKEN='))
|
||||
|
||||
def api(method, route, body=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
request = urllib.request.Request('http://127.0.0.1:8765/api/v1' + route, data=data, method=method,
|
||||
headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'})
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
value = response.read()
|
||||
return value if '/artifacts/' in route else json.loads(value)
|
||||
|
||||
project = api('POST', '/projects')['id']
|
||||
wrapper = b'#!/bin/sh\nset -eu\n"$JAVA_HOME/bin/java" -version\nmkdir -p app/build/outputs/apk/debug\nprintf remote-service-smoke > app/build/outputs/apk/debug/app-debug.apk\n'
|
||||
api('POST', f'/projects/{project}/sync', {'revision': 'deployment-smoke', 'files': {'gradlew': {
|
||||
'hash': hashlib.sha256(wrapper).hexdigest(), 'data': base64.b64encode(wrapper).decode()}}})
|
||||
build_id = api('POST', f'/projects/{project}/builds', {'revision': 'deployment-smoke', 'task': ':app:assembleDebug'})['id']
|
||||
for _ in range(120):
|
||||
build = api('GET', f'/builds/{build_id}')
|
||||
if build['status'] not in ('queued', 'running'):
|
||||
break
|
||||
time.sleep(.25)
|
||||
assert build['status'] == 'success', build
|
||||
artifact = build['artifacts'][0]
|
||||
content = api('GET', f'/builds/{build_id}/artifacts/' + artifact['name'])
|
||||
assert content == b'remote-service-smoke'
|
||||
assert hashlib.sha256(content).hexdigest() == artifact['hash']
|
||||
print(json.dumps({'status': 'passed', 'project': project, 'build': build_id, 'checks': ['sync', 'service-account-java17', 'build', 'download', 'sha256'], 'realAndroidBuild': False}))
|
||||
if len(sys.argv) == 3 and sys.argv[1] == '--export-for':
|
||||
user = pwd.getpwnam(sys.argv[2])
|
||||
folder = Path(user.pw_dir) / '.config' / 'remotecompile'
|
||||
folder.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
os.chown(folder, user.pw_uid, user.pw_gid)
|
||||
target = folder / 'token'
|
||||
with target.open('x', encoding='utf-8') as output:
|
||||
os.fchmod(output.fileno(), 0o600)
|
||||
output.write(token + '\n')
|
||||
os.fchown(output.fileno(), user.pw_uid, user.pw_gid)
|
||||
print('Client credential exported (contents hidden).')
|
||||
@@ -0,0 +1,44 @@
|
||||
# Windows 服务部署
|
||||
|
||||
本目录脚本以管理员权限运行,使用 [WinSW 2.12.0](https://github.com/winsw/winsw/releases/tag/v2.12.0) 官方 x64 包装器将 Go 程序注册为 Windows 服务。配置遵循 [WinSW 2.x 文档](https://winsw.github.io/v2/doc/xmlConfigFile/)。
|
||||
|
||||
将以下文件放入同一目录:
|
||||
|
||||
- `remotecompile-windows-amd64.exe`
|
||||
- `WinSW-x64-v2.12.0.exe`(从官方固定版本下载)
|
||||
- `install.ps1`
|
||||
- `verify.ps1`
|
||||
|
||||
管理员 PowerShell:
|
||||
|
||||
```powershell
|
||||
.\install.ps1 -JavaHome 'C:\工具链\jdk-17' -AndroidHome 'D:\AndroidSdk\Windows'
|
||||
.\verify.ps1
|
||||
```
|
||||
|
||||
默认根目录 `C:\ProgramData\VibeCodingRemoteCompilation`:
|
||||
|
||||
| 位置 | 内容 |
|
||||
| --- | --- |
|
||||
| `bin\remotecompile.exe` | Go 服务 |
|
||||
| `bin\RemoteCompileService.exe` | WinSW(与 Go 程序不同名称,避免 Windows 大小写碰撞) |
|
||||
| `bin\RemoteCompileService.xml` | 配置、工具链路径与随机 Token |
|
||||
| `data\` | 工作区和产物 |
|
||||
| `home\` | 独立 Gradle 缓存和调试签名 |
|
||||
| `logs\` | 包装器与应用日志 |
|
||||
|
||||
服务名 `RemoteCompile`,自动延迟启动,以 `NT AUTHORITY\LocalService` 运行。配置及程序目录只向管理员、SYSTEM 和 LocalService 授权;LocalService 仅可写数据、日志、home 和 temp。LocalService 是系统内置共享低权限账户,不是不可信构建沙箱。
|
||||
|
||||
仅监听 `127.0.0.1:8765`。通过 SSH 隧道访问,不新开防火墙入站规则。Token 副本导出到部署用户的 `.remotecompile-service-token.txt`,并限制 ACL;不会保存 SSH 登录密码。
|
||||
|
||||
`verify.ps1` 验证 JDK 启动、android-35 平台读取、35.0.0 aapt2 执行、同步、模拟构建及产物摘要。它生成的测试文件不是有效 Android APK。
|
||||
|
||||
管理:
|
||||
|
||||
```powershell
|
||||
Get-Service RemoteCompile
|
||||
Restart-Service RemoteCompile
|
||||
Get-Content 'C:\ProgramData\VibeCodingRemoteCompilation\logs\*.log' -Tail 30
|
||||
```
|
||||
|
||||
调整 JDK/SDK 时编辑 XML 对应 env 后重启。服务不修改机器全局 Java 或 Android 环境变量,不自动安装缺失的 SDK 组件。真实构建需要选择与项目 Gradle/AGP 兼容的 JDK。
|
||||
@@ -0,0 +1,64 @@
|
||||
param(
|
||||
[string]$Root = 'C:\ProgramData\VibeCodingRemoteCompilation',
|
||||
[string]$OutputPath = (Join-Path $env:TEMP ('RemoteCompile-diagnostics-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '.txt'))
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$lines = New-Object 'System.Collections.Generic.List[string]'
|
||||
$token = ''
|
||||
$configPath = Join-Path $Root 'bin\RemoteCompileService.xml'
|
||||
if (Test-Path -LiteralPath $configPath) {
|
||||
[xml]$config = Get-Content -LiteralPath $configPath -Raw
|
||||
$token = [string](($config.service.env | Where-Object name -eq 'REMOTE_BUILD_TOKEN').value)
|
||||
}
|
||||
function Add-Section([string]$name, [scriptblock]$collect) {
|
||||
$lines.Add("`r`n## $name")
|
||||
try {
|
||||
$value = (& $collect 2>&1 | Out-String -Width 220)
|
||||
if ($token) { $value = $value.Replace($token, '[REDACTED]') }
|
||||
$value = $value -replace '(?i)Bearer\s+[A-Za-z0-9._~+/-]+', 'Bearer [REDACTED]'
|
||||
$value = $value -replace '(?i)((?:password|passwd|secret|access_token)\s*[=:]\s*)[^\s,;]+', '$1[REDACTED]'
|
||||
$lines.Add($value)
|
||||
} catch { $lines.Add('Collection failed: ' + $_.Exception.Message) }
|
||||
}
|
||||
Add-Section 'System and service' {
|
||||
Get-Date -Format o
|
||||
Get-CimInstance Win32_OperatingSystem | Select-Object Caption,Version,LastBootUpTime
|
||||
Get-CimInstance Win32_Service -Filter "Name='RemoteCompile' OR Name='sshd'" | Select-Object Name,State,StartMode,StartName,ProcessId
|
||||
}
|
||||
Add-Section 'Listening ports' {
|
||||
Get-NetTCPConnection -State Listen | Where-Object LocalPort -in @(22,8765) | Select-Object LocalAddress,LocalPort,OwningProcess
|
||||
}
|
||||
Add-Section 'Toolchain configuration (token omitted)' {
|
||||
if ($config) { $config.service.env | Where-Object name -in @('JAVA_HOME','ANDROID_HOME','ANDROID_SDK_ROOT','GRADLE_USER_HOME','HOME','USERPROFILE') | Select-Object name,value }
|
||||
}
|
||||
Add-Section 'Authenticated local health check' {
|
||||
if (-not $token) { throw 'Service config/token unavailable; run as administrator.' }
|
||||
Invoke-RestMethod -Uri 'http://127.0.0.1:8765/api/v1/health' -Headers @{Authorization="Bearer $token"} -TimeoutSec 5 | ConvertTo-Json -Compress
|
||||
}
|
||||
Add-Section 'Service wrapper and application logs' {
|
||||
Get-ChildItem -LiteralPath (Join-Path $Root 'logs') -File | Where-Object Extension -eq '.log' | ForEach-Object {
|
||||
'FILE: ' + $_.Name
|
||||
Get-Content -LiteralPath $_.FullName -Tail 120
|
||||
}
|
||||
}
|
||||
Add-Section 'Recent build results' {
|
||||
Get-ChildItem -LiteralPath (Join-Path $Root 'data\artifacts') -Filter build.json -Recurse -File -ErrorAction SilentlyContinue |
|
||||
Sort-Object LastWriteTime -Descending | Select-Object -First 5 | ForEach-Object {
|
||||
$build = Get-Content -LiteralPath $_.FullName -Raw | ConvertFrom-Json
|
||||
$build | Select-Object id,project,revision,task,status | ConvertTo-Json -Compress
|
||||
$build.logs | Select-Object -Last 120
|
||||
}
|
||||
}
|
||||
Add-Section 'Active build markers' {
|
||||
Get-ChildItem -LiteralPath (Join-Path $Root 'data\projects') -Filter active-build -Recurse -File -ErrorAction SilentlyContinue | ForEach-Object {
|
||||
$_.FullName
|
||||
Get-Content -LiteralPath $_.FullName
|
||||
}
|
||||
}
|
||||
Add-Section 'Related service control events (48 hours)' {
|
||||
Get-WinEvent -FilterHashtable @{LogName='System';ProviderName='Service Control Manager';StartTime=(Get-Date).AddDays(-2)} -MaxEvents 300 |
|
||||
Where-Object Message -match 'RemoteCompile|VibeCoding|sshd|OpenSSH' | Select-Object TimeCreated,Id,LevelDisplayName,Message | Format-List
|
||||
}
|
||||
[IO.File]::WriteAllText($OutputPath,($lines -join "`r`n"),(New-Object Text.UTF8Encoding($false)))
|
||||
Write-Output "Diagnostics saved: $OutputPath"
|
||||
Write-Output 'The service token is redacted. Review build output for project-specific secrets before sharing.'
|
||||
@@ -0,0 +1,24 @@
|
||||
$ErrorActionPreference='Stop'
|
||||
$candidates=New-Object 'System.Collections.Generic.List[string]'
|
||||
foreach($base in @('C:\Program Files','D:\Program Files','D:\ProgramFiles')) {
|
||||
foreach($folder in @(Get-ChildItem -LiteralPath $base -Directory -ErrorAction SilentlyContinue | Where-Object {$_.Name -match 'Java|JDK|Android|Studio|JetBrains|Microsoft|Eclipse|BellSoft'})) {
|
||||
$candidates.Add($folder.FullName)
|
||||
$candidates.Add((Join-Path $folder.FullName 'jbr'))
|
||||
foreach($child in @(Get-ChildItem -LiteralPath $folder.FullName -Directory -ErrorAction SilentlyContinue)) {
|
||||
$candidates.Add($child.FullName)
|
||||
$candidates.Add((Join-Path $child.FullName 'jbr'))
|
||||
}
|
||||
}
|
||||
}
|
||||
$selected=$null
|
||||
foreach($candidate in $candidates) {
|
||||
$release=Join-Path $candidate 'release'
|
||||
if((Test-Path -LiteralPath "$candidate\bin\java.exe") -and (Test-Path -LiteralPath $release)) {
|
||||
$version=Get-Content -LiteralPath $release | Where-Object {$_ -match '^JAVA_VERSION="(17|21)\.'}
|
||||
if($version){$selected=$candidate;break}
|
||||
}
|
||||
}
|
||||
if(-not $selected){$selected='C:\Program Files\Java\jdk-25.0.3';Write-Output 'Only JDK25 detected; older Gradle projects require configuring a compatible JDK.'}
|
||||
Write-Output "Selected JAVA_HOME=$selected"
|
||||
& "$PSScriptRoot\install.ps1" -JavaHome $selected
|
||||
& "$PSScriptRoot\verify.ps1"
|
||||
@@ -0,0 +1,89 @@
|
||||
param(
|
||||
[string]$Root = 'C:\ProgramData\VibeCodingRemoteCompilation',
|
||||
[Parameter(Mandatory=$true)][string]$JavaHome,
|
||||
[string]$AndroidHome = 'D:\AndroidSdk\Windows'
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Administrator required' }
|
||||
if (-not (Test-Path -LiteralPath "$JavaHome\bin\java.exe")) { throw 'Invalid JavaHome' }
|
||||
if (-not (Test-Path -LiteralPath "$AndroidHome\platforms")) { throw 'Invalid AndroidHome' }
|
||||
foreach ($name in @('remotecompile-windows-amd64.exe','WinSW-x64-v2.12.0.exe')) {
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot $name))) { throw "Missing $name" }
|
||||
}
|
||||
if (Get-Service RemoteCompile -ErrorAction SilentlyContinue) {
|
||||
Stop-Service RemoteCompile
|
||||
(Get-Service RemoteCompile).WaitForStatus('Stopped',[TimeSpan]::FromSeconds(45))
|
||||
}
|
||||
New-Item -ItemType Directory -Force -Path $Root | Out-Null
|
||||
& icacls.exe $Root /inheritance:r /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' '*S-1-5-19:(OI)(CI)RX' | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Root ACL failed' }
|
||||
foreach ($dir in @('bin','logs','data','home','temp')) { New-Item -ItemType Directory -Force -Path (Join-Path $Root $dir) | Out-Null }
|
||||
foreach ($dir in @('logs','data','home','temp')) {
|
||||
& icacls.exe (Join-Path $Root $dir) /grant:r '*S-1-5-19:(OI)(CI)M' | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Data ACL failed' }
|
||||
}
|
||||
$config = Join-Path $Root 'bin\RemoteCompileService.xml'
|
||||
if (Test-Path -LiteralPath $config) {
|
||||
[xml]$old = Get-Content -LiteralPath $config -Raw
|
||||
$token = ($old.service.env | Where-Object name -eq 'REMOTE_BUILD_TOKEN').value
|
||||
} else {
|
||||
$bytes = New-Object byte[] 32
|
||||
$rng = [Security.Cryptography.RandomNumberGenerator]::Create()
|
||||
try { $rng.GetBytes($bytes) } finally { $rng.Dispose() }
|
||||
$token = ([BitConverter]::ToString($bytes)).Replace('-','').ToLowerInvariant()
|
||||
}
|
||||
if ($token.Length -lt 24) { throw 'Invalid token' }
|
||||
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'remotecompile-windows-amd64.exe') -Destination "$Root\bin\remotecompile.exe" -Force
|
||||
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'WinSW-x64-v2.12.0.exe') -Destination "$Root\bin\RemoteCompileService.exe" -Force
|
||||
function XmlEscape([string]$value) { [Security.SecurityElement]::Escape($value) }
|
||||
$safeRoot = XmlEscape $Root
|
||||
$safeJava = XmlEscape $JavaHome
|
||||
$safeSdk = XmlEscape $AndroidHome
|
||||
$xml = @"
|
||||
<service>
|
||||
<id>RemoteCompile</id>
|
||||
<name>VibeCoding Remote Compilation</name>
|
||||
<description>Android remote build service, loopback only.</description>
|
||||
<executable>$safeRoot\bin\remotecompile.exe</executable>
|
||||
<arguments>-listen 127.0.0.1:8765 -data "$safeRoot\data" -tasks :app:assembleDebug</arguments>
|
||||
<workingdirectory>$safeRoot</workingdirectory>
|
||||
<startmode>Automatic</startmode>
|
||||
<delayedAutoStart>true</delayedAutoStart>
|
||||
<stoptimeout>40 sec</stoptimeout>
|
||||
<onfailure action="restart" delay="10 sec"/>
|
||||
<logpath>$safeRoot\logs</logpath>
|
||||
<log mode="roll-by-size"><sizeThreshold>10240</sizeThreshold><keepFiles>4</keepFiles></log>
|
||||
<serviceaccount><domain>NT AUTHORITY</domain><user>LocalService</user></serviceaccount>
|
||||
<env name="REMOTE_BUILD_TOKEN" value="$token"/>
|
||||
<env name="JAVA_HOME" value="$safeJava"/>
|
||||
<env name="ANDROID_HOME" value="$safeSdk"/>
|
||||
<env name="ANDROID_SDK_ROOT" value="$safeSdk"/>
|
||||
<env name="GRADLE_USER_HOME" value="$safeRoot\home\.gradle"/>
|
||||
<env name="HOME" value="$safeRoot\home"/>
|
||||
<env name="USERPROFILE" value="$safeRoot\home"/>
|
||||
<env name="TEMP" value="$safeRoot\temp"/>
|
||||
<env name="TMP" value="$safeRoot\temp"/>
|
||||
</service>
|
||||
"@
|
||||
[IO.File]::WriteAllText($config,$xml,(New-Object Text.UTF8Encoding($false)))
|
||||
if (-not (Get-Service RemoteCompile -ErrorAction SilentlyContinue)) {
|
||||
& "$Root\bin\RemoteCompileService.exe" install
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Service installation failed' }
|
||||
}
|
||||
Start-Service RemoteCompile
|
||||
$headers = @{Authorization="Bearer $token"}
|
||||
$healthy = $false
|
||||
for ($i=0;$i -lt 30;$i++) {
|
||||
try {
|
||||
$result = Invoke-RestMethod -Uri 'http://127.0.0.1:8765/api/v1/health' -Headers $headers -TimeoutSec 2
|
||||
Write-Output ('Health: ' + ($result | ConvertTo-Json -Compress)); $healthy=$true; break
|
||||
} catch { Start-Sleep -Seconds 1 }
|
||||
}
|
||||
if (-not $healthy) { throw "Service health failed. Check $Root\logs" }
|
||||
$tokenPath = Join-Path $env:USERPROFILE '.remotecompile-service-token.txt'
|
||||
[IO.File]::WriteAllText($tokenPath,$token,(New-Object Text.UTF8Encoding($false)))
|
||||
$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
||||
& icacls.exe $tokenPath /inheritance:r /grant:r "*$($sid):R" '*S-1-5-18:F' '*S-1-5-32-544:F' | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Token ACL failed' }
|
||||
Get-CimInstance Win32_Service -Filter "Name='RemoteCompile'" | Select-Object Name,State,StartMode,StartName
|
||||
Write-Output 'Client token exported privately; contents hidden.'
|
||||
@@ -0,0 +1,40 @@
|
||||
param([string]$Root='C:\ProgramData\VibeCodingRemoteCompilation')
|
||||
$ErrorActionPreference='Stop'
|
||||
[xml]$config=Get-Content -LiteralPath "$Root\bin\RemoteCompileService.xml" -Raw
|
||||
$token=($config.service.env | Where-Object name -eq 'REMOTE_BUILD_TOKEN').value
|
||||
$headers=@{Authorization="Bearer $token"}
|
||||
function Api([string]$method,[string]$path,$body=$null) {
|
||||
$args=@{Method=$method;Uri="http://127.0.0.1:8765/api/v1$path";Headers=$headers;TimeoutSec=30}
|
||||
if($null -ne $body){$args.ContentType='application/json';$args.Body=($body | ConvertTo-Json -Depth 12 -Compress)}
|
||||
Invoke-RestMethod @args
|
||||
}
|
||||
$project=(Api POST '/projects').id
|
||||
$wrapper=@'
|
||||
@echo off
|
||||
"%JAVA_HOME%\bin\java.exe" -version
|
||||
if errorlevel 1 exit /b 1
|
||||
if not exist "%ANDROID_HOME%\platforms\android-35\android.jar" exit /b 2
|
||||
"%ANDROID_HOME%\build-tools\35.0.0\aapt2.exe" version
|
||||
if errorlevel 1 exit /b 3
|
||||
mkdir app\build\outputs\apk\debug 2>nul
|
||||
echo windows-service-smoke>app\build\outputs\apk\debug\app-debug.apk
|
||||
exit /b 0
|
||||
'@
|
||||
$content=[Text.Encoding]::ASCII.GetBytes($wrapper.Replace("`n","`r`n"))
|
||||
$sha=[Security.Cryptography.SHA256]::Create()
|
||||
try {$hash=([BitConverter]::ToString($sha.ComputeHash($content))).Replace('-','').ToLowerInvariant()}finally{$sha.Dispose()}
|
||||
$files=@{'gradlew.bat'=@{hash=$hash;data=[Convert]::ToBase64String($content)}}
|
||||
Api POST "/projects/$project/sync" @{revision='windows-deploy-smoke';files=$files} | Out-Null
|
||||
$build=(Api POST "/projects/$project/builds" @{revision='windows-deploy-smoke';task=':app:assembleDebug'}).id
|
||||
for($i=0;$i -lt 120;$i++) {
|
||||
$result=Api GET "/builds/$build"
|
||||
if($result.status -notin @('queued','running')){break}
|
||||
Start-Sleep -Milliseconds 250
|
||||
}
|
||||
if($result.status -ne 'success'){throw ($result | ConvertTo-Json -Depth 6)}
|
||||
$artifact=$result.artifacts[0]
|
||||
$download=Join-Path $env:TEMP 'remotecompile-deploy-smoke.apk'
|
||||
Invoke-WebRequest -UseBasicParsing -Uri "http://127.0.0.1:8765/api/v1/builds/$build/artifacts/$($artifact.name)" -Headers $headers -OutFile $download
|
||||
if((Get-FileHash -LiteralPath $download -Algorithm SHA256).Hash.ToLowerInvariant() -ne $artifact.hash){throw 'Artifact hash mismatch'}
|
||||
Remove-Item -LiteralPath $download
|
||||
Write-Output "PASS: sync, LocalService JDK, SDK android-35 read, aapt2, build, download, SHA256. Build=$build. Simulated APK only."
|
||||
@@ -0,0 +1,57 @@
|
||||
# Windows 192.168.5.222 部署记录
|
||||
|
||||
日期:2026-11-24(Asia/Shanghai)。
|
||||
|
||||
## 运行环境
|
||||
|
||||
- Windows 11 x64,观察到系统版本 10.0.26300.9974。
|
||||
- SSH 用户 tt;具有管理员权限;登录密码未写入文件。
|
||||
- Android SDK:`D:\AndroidSdk\Windows`,已存在完整平台、Build Tools 和 licenses。
|
||||
- JAVA_HOME:`C:\Program Files\Java\jdk-25.0.3`。未修改系统全局环境变量。扫描范围内只找到 JDK25 和用户目录中的旧 JBR11,暂未确认 JDK17/21。
|
||||
|
||||
## 已安装
|
||||
|
||||
- 服务名:`RemoteCompile`,状态 Running,Automatic 延迟启动。
|
||||
- 运行账户:`NT AUTHORITY\LocalService`。
|
||||
- 程序及配置:`C:\ProgramData\VibeCodingRemoteCompilation\bin`。
|
||||
- 服务包装器:官方 WinSW 2.12.0 x64;文件上传前后 SHA-256 已核对。
|
||||
- 数据:`C:\ProgramData\VibeCodingRemoteCompilation\data`。
|
||||
- 缓存与用户目录:`C:\ProgramData\VibeCodingRemoteCompilation\home`。
|
||||
- 日志:`C:\ProgramData\VibeCodingRemoteCompilation\logs`。
|
||||
- 服务端监听:`127.0.0.1:8765`;未增加明文接口防火墙入站规则。
|
||||
- Gradle 任务白名单:`:app:assembleDebug`。
|
||||
|
||||
## 本机插件配置
|
||||
|
||||
| 字段 | 值 |
|
||||
| --- | --- |
|
||||
| 地址 | `http://127.0.0.1:18765` |
|
||||
| Token | 本机 `.deployment/client-token-192.168.5.222.txt`,复制到插件 PasswordSafe |
|
||||
| 任务 | `:app:assembleDebug` |
|
||||
| adb 与设备 | 使用本机 adb,指定设备序列号 |
|
||||
|
||||
已建立 SSH 隧道:本机 18765 → tt@192.168.5.222 → 服务器 127.0.0.1:8765。该隧道不设为开机启动;重新连接可运行 `examples/connect-192.168.5.222.ps1`,终端保持开启。
|
||||
|
||||
Ubuntu 192.168.5.224 的本机 8765 隧道和 Token 文件未被替换。
|
||||
|
||||
服务器 Token 在受 ACL 保护的 `bin\RemoteCompileService.xml`;给 tt 的副本在 `C:\Users\tt\.remotecompile-service-token.txt`。本机凭据在被 Git 忽略的 `.deployment/` 目录,不包含 SSH 密码。
|
||||
|
||||
## 验证结果
|
||||
|
||||
- 认证健康接口通过;本机经 SSH 隧道返回 HTTP 200,os=windows。
|
||||
- 以 LocalService 账户启动 JDK,通过环境变量读取 SDK android-35 的 android.jar,并成功执行 Build Tools 35.0.0 的 aapt2。
|
||||
- 源码同步、模拟构建、独立 APK 产物下载与 SHA-256 校验通过。
|
||||
- 验收 buildId:`1063235cb4c172b6b725995b9cdd00be`。
|
||||
- 验收产物是模拟文件,不是真实 Android APK,不能安装。
|
||||
|
||||
## 实际项目构建前
|
||||
|
||||
JDK25 与旧版 Gradle 不兼容。根据实际项目的 Gradle/AGP 版本配置 JDK17 或 JDK21,然后编辑 `bin\RemoteCompileService.xml` 中的 JAVA_HOME 并重启服务。本次未安装新 JDK,也未执行实际项目构建或手机安装。
|
||||
|
||||
管理命令(管理员 PowerShell):
|
||||
|
||||
```powershell
|
||||
Get-Service RemoteCompile
|
||||
Restart-Service RemoteCompile
|
||||
Get-Content 'C:\ProgramData\VibeCodingRemoteCompilation\logs\*.log' -Tail 30
|
||||
```
|
||||
@@ -0,0 +1,53 @@
|
||||
# 192.168.5.224 部署记录
|
||||
|
||||
部署日期:2026-11-24(Asia/Shanghai)。
|
||||
|
||||
## 实际环境
|
||||
|
||||
- SSH 用户:`tt`,通过 sudo 安装;未启用 root SSH 登录。
|
||||
- 实际系统:Ubuntu 24.04.5 LTS,Linux x86_64(机器名包含 Ubuntu2204,但发行版信息为 24.04)。
|
||||
- 服务账户:`remotecompile`,无交互登录 shell。
|
||||
- JDK:`/usr/lib/jvm/java-17-openjdk-amd64`,仅为本服务配置,未更改系统默认 JDK。
|
||||
|
||||
## 已部署
|
||||
|
||||
- 二进制:`/opt/remotecompile/bin/remotecompile`。
|
||||
- systemd:`remotecompile.service`,已运行,已设为开机启动。
|
||||
- 配置:`/etc/remotecompile/environment`,root 权限 0600,包含服务生成的随机 Token。
|
||||
- 状态及构建缓存:`/var/lib/remotecompile/data`。
|
||||
- 服务地址:`127.0.0.1:8765`,未向局域网直接开放明文接口。
|
||||
- 允许的任务:`:app:assembleDebug`。
|
||||
|
||||
本机已建立 `127.0.0.1:8765 → SSH tt@192.168.5.224 → 127.0.0.1:8765` 隧道。隧道不设为开机启动,重启本机后运行 `examples/connect-192.168.5.224.ps1`。首次部署启动的隧道 PID 记录在 `.deployment/tunnel.pid`,诊断日志在 `.deployment/tunnel.log`。
|
||||
|
||||
插件配置:
|
||||
|
||||
| 字段 | 值 |
|
||||
| --- | --- |
|
||||
| 服务地址 | `http://127.0.0.1:8765` |
|
||||
| Token | 从本机 `.deployment/client-token.txt` 复制,不提交仓库 |
|
||||
| Gradle 任务 | `:app:assembleDebug` |
|
||||
| adb、设备序列号 | 按本机设备配置 |
|
||||
|
||||
服务器侧给 tt 的 Token 副本位于 `/home/tt/.config/remotecompile/token`,权限 0600;本机 `.deployment/` 已被 Git 忽略。SSH 登录密码未写入部署文件。
|
||||
|
||||
## 验收
|
||||
|
||||
- 上传二进制 SHA-256 与本机一致:`c0ac7eef3651a77a91b324ea5ccafc3b83344fa03395b04e8f0a95de6db42c99`。
|
||||
- 服务远端健康检查通过,本机经 SSH 隧道健康检查 HTTP 200。
|
||||
- 认证后的源码同步、服务账户 JDK 17 执行、模拟构建、独立产物下载与 SHA-256 校验通过。
|
||||
- 本次模拟构建不是实际 Android APK,不应安装其产物。
|
||||
|
||||
## 待补齐的 Android SDK
|
||||
|
||||
服务器用户配置中存在 `ANDROID_HOME=/mnt/sdk/AndroidSdk`,但该目录不存在;`/usr/lib/android-sdk` 只有 platform-tools,检查范围内尚未确认完整 SDK 的可用位置。
|
||||
|
||||
本次未安装 SDK 平台或修改现有 SDK,也未执行真实项目构建。需要找到实际 SDK 或按项目 compileSdk/build-tools 要求安装后,将可被服务账户访问的路径写入 `/etc/remotecompile/environment`,然后重启服务。systemd 的 ProtectHome 会限制访问 `/home` 和 `/root`;优先使用 `/opt` 等位置。
|
||||
|
||||
管理命令:
|
||||
|
||||
```sh
|
||||
sudo systemctl status remotecompile
|
||||
sudo journalctl -u remotecompile -f
|
||||
sudo systemctl restart remotecompile
|
||||
```
|
||||
@@ -0,0 +1,49 @@
|
||||
# 运行说明与首版边界
|
||||
|
||||
## 部署
|
||||
|
||||
- 服务是前台常驻进程;可交给 systemd、launchd 或 Windows 服务包装工具托管。暂未提供原生服务安装器。
|
||||
- JDK、SDK、Gradle 下载网络及 debug keystore 均使用服务账户环境。首次运行项目前确认 SDK licenses 已接受。
|
||||
- 原生服务不要求 Python;Python 只用于可选参考客户端。插件运行在 IDE JVM 内。
|
||||
- 数据目录只能给一个服务实例使用;本版未实现跨进程数据锁,禁止同时启动多个实例。
|
||||
- 默认仅监听回环。局域网用 SSH 隧道,或将服务放在 HTTPS 反向代理之后;客户端拒绝非回环明文 HTTP。
|
||||
- 构建任务白名单用逗号分隔,如 `-tasks ':app:assembleDebug,:app:assembleDemoDebug'`。一次请求选择其中一个任务。
|
||||
- Gradle 构建脚本等价于受信任代码执行;本版不提供容器隔离,使用专用低权限账户。Token 相同的客户端属于同一信任域,不提供多租户隔离。
|
||||
|
||||
## 数据及恢复
|
||||
|
||||
```text
|
||||
data/
|
||||
projects/<projectId>/state.json 已提交源码清单
|
||||
projects/<projectId>/work/ 源码及 Gradle 构建缓存
|
||||
projects/<projectId>/active-build 正在执行任务的标记
|
||||
artifacts/<buildId>/build.json 终态、日志与产物清单
|
||||
artifacts/<buildId>/*.apk 独立 APK
|
||||
```
|
||||
|
||||
Ctrl+C 或 SIGTERM 会尝试取消执行中的任务并等待终态落盘。崩溃或强制终止后,如果仍有 `active-build`,服务拒绝启动,避免在残留 Gradle 进程还运行时覆盖源码。管理员须先确认并终止该工作区残留的 Gradle/Java 进程,再删除该工作区 `active-build` 文件后重启;不要随意结束其他项目的 Gradle Daemon。
|
||||
|
||||
任务固定超时 30 分钟。取消按 Unix 进程组 / Windows taskkill 进程树执行;需在真实项目确认其插件启动的外部子进程遵守这一边界。
|
||||
|
||||
本版没有自动产物保留策略;日志和 APK 会累积。仅在服务停止且无残留构建时清理不需要的 `artifacts/<buildId>`。删除项目工作区会使客户端保存的 projectId 失效,需要清理对应客户端映射后重新分配。不要将插件配置复制给不同机器共享同一工作区。
|
||||
|
||||
## 首版已实现
|
||||
|
||||
- 手动 Remote Run;文件级增量 HTTP 同步及删除传播。
|
||||
- revision 校验、同工作区互斥、Token、路径与摘要校验。
|
||||
- Gradle 执行、实时日志查询/SSE、取消及固定超时。
|
||||
- APK 下载、校验与本机指定设备覆盖安装。
|
||||
- 本机配置保存和 IDE PasswordSafe Token 保存。
|
||||
|
||||
## 后续功能
|
||||
|
||||
- rsync/SSH SyncProvider,保存后自动构建、防抖与最新版本合并。
|
||||
- 自定义同步排除、可执行权限清单、符号链接和文件/目录互换迁移支持。
|
||||
- 更细的锁粒度、上传分片、日志分页/字节流解码、全局并发限制、自动保留策略。
|
||||
- 拆分 APK、自动启动、IDE 原生 Run/Debug 集成。设备下拉框已在插件 0.1.1 实现。
|
||||
|
||||
首版同步期间扫描、磁盘提交仍会占用全局互斥锁,适合个人或少量可信开发者。同步失败不会回滚文件,但会使 revision 失效;必须重新同步才能构建。
|
||||
|
||||
普通单 APK 任务才会自动安装;若返回多个 APK,客户端明确失败并保留产物供排查。本机 SDK/JDK、代码索引与 Gradle Sync 仍按 Android Studio 自身要求配置。
|
||||
|
||||
不要依赖默认同步规则识别所有密钥:首次使用前检查项目内容,服务端签名材料应单独配置,避免上传自定义命名的密钥文件。本版默认排除 .jks、.keystore、.env*、key.properties 和 keystore.properties。
|
||||
@@ -0,0 +1,30 @@
|
||||
# 插件 0.1.1
|
||||
|
||||
## 报错修复
|
||||
|
||||
用户堆栈指向 `RemoteRunAction → ToolWindow.show 回调 → saveAllDocuments()`:新版 IDE 的工具窗口回调运行在 UI(RELAX) 上,处于 EDT 并不代表已持有写意图锁。
|
||||
|
||||
保存流程现在先通过 Application.invokeLater 调度,再在显式 WriteIntentReadAction 中保存;网络同步、设备读取和构建继续在后台执行。依据 [IntelliJ 线程模型](https://plugins.jetbrains.com/docs/intellij/threading-model.html)。
|
||||
|
||||
## 配置与运行
|
||||
|
||||
- 右侧 **Remote Configuration** 齿轮栏:服务地址、Token、Gradle 任务、可选 adb 路径和构建后安装开关;点击“保存配置”。该入口只打开配置。
|
||||
- 顶部绿色运行图标:使用已保存配置直接执行 Remote Run。
|
||||
- 底部 **Remote Compilation**:设备下拉选择、刷新、运行/取消和日志。
|
||||
- Tools 菜单提供运行和设置两个独立入口。
|
||||
|
||||
## 设备
|
||||
|
||||
从本机项目 local.properties 的 SDK、SDK 环境变量及常用 SDK 目录定位 adb,也可在右侧覆盖路径。通过 `adb devices -l` 获取 USB、无线设备及模拟器,显示型号、连接状态和序列号,无需手工输入序列号。
|
||||
|
||||
每 5 秒自动刷新,支持手动刷新;记住用户选择。只有一台在线设备时自动选中,多台设备首次使用时需选择;离线和未授权设备不用于安装。安装前重新检查本次任务开始时选定的设备,断开时保留 APK 并显示原因。
|
||||
|
||||
## 升级
|
||||
|
||||
在 Android Studio 的 Settings → Plugins → 齿轮 → Install Plugin from Disk 选择 `remote-compilation-plugin-0.1.1.zip`,然后重启 IDE。原插件 ID、连接配置字段及 PasswordSafe 凭据名称保留,可继续读取已有配置。设备选择改为下拉框。
|
||||
|
||||
源码中的设备解析测试覆盖 USB、模拟器、无线离线、未授权、adb 启动提示和重复序列号;SDK 定位测试覆盖空格与中文路径。配置测试覆盖运行中分配工作区与用户修改设置之间的数据保留。
|
||||
|
||||
2026-11-24 验证:`gradle -p plugin test buildPlugin --offline --no-daemon --console=plain` 成功,6 项单元测试通过。已生成并复制 `dist/remote-compilation-plugin-0.1.1.zip`。本机 adb 能读取当前连接的在线手机。
|
||||
|
||||
具体 Android Studio 新版本上的窗口行为和真实手机安装仍需要安装新版 ZIP 后验证;当前 SDK 编译目标为 IntelliJ 243。
|
||||
@@ -0,0 +1,11 @@
|
||||
# 插件 0.1.2:保存文件 API 兼容修复
|
||||
|
||||
0.1.1 在 Application.invokeLater 内显式调用 WriteIntentReadAction.run(ThrowableRunnable),其二进制签名在用户 IDE 中已经改变,导致 NoSuchMethodError。该调用是上一版修复引入的兼容问题。
|
||||
|
||||
0.1.2 删除对此静态方法的依赖,保留 Application.invokeLater 调度,在其提供的写意图上下文中保存文件;没有退回 ToolWindow.show 回调直接保存的旧实现。用户堆栈也显示 ApplicationImpl.runIntendedWriteActionOnCurrentThread 已包装此回调。依据 [官方线程模型](https://plugins.jetbrains.com/docs/intellij/threading-model.html)。
|
||||
|
||||
升级包:`dist/remote-compilation-plugin-0.1.2.zip`。通过 Install Plugin from Disk 安装后重启 Android Studio。设备下拉选择和独立配置侧栏保持可用。
|
||||
|
||||
编译目标仍为 IntelliJ 243,用户实际 IDE 上的运行验证需安装新版 ZIP 后进行。打包时检查 RemotePanel.class 不再引用 WriteIntentReadAction,避免再次交付带有已移除签名的字节码。
|
||||
|
||||
2026-11-24:离线执行 `test buildPlugin` 成功,7 项测试通过(包含此次字节码兼容回归测试);已检查发布 ZIP 中的版本为 0.1.2,RemotePanel.class 不含不兼容 API 引用。
|
||||
@@ -0,0 +1,24 @@
|
||||
# 首版验证记录
|
||||
|
||||
日期:2026-11-24。宿主:Windows amd64;Go 1.26.2、Gradle 8.13、JDK 21。插件构建平台:IntelliJ IDEA Community 2024.3.5(243)。
|
||||
|
||||
## 已通过
|
||||
|
||||
- `go test -v ./...`:6 项测试,覆盖认证、跨平台路径校验、增量同步/删除、同步失败不更新 revision、繁忙工作区拒绝同步、陈旧版本拒绝构建、任务白名单、产物下载摘要、构建失败无产物、排队及运行中取消、SSE 重连偏移。
|
||||
- `go vet ./...`:通过。
|
||||
- Windows amd64 服务二进制编译。
|
||||
- Linux amd64 / macOS arm64 交叉编译。
|
||||
- `python -m unittest discover -s client -p test_smoke.py -v`:真实服务二进制 + Python 客户端 + 模拟 Gradle Wrapper,验证中文/空格路径、首次构建下载、第二次只上传一个变更文件、删除传播,以及不同 buildId 的产物隔离。
|
||||
- 插件 `buildPlugin`:成功生成 ZIP,Kotlin 编译及 IntelliJ 字节码处理通过。
|
||||
- Gradle Wrapper:已生成,锁定 Gradle 8.13。
|
||||
|
||||
运行中取消测试在受限沙箱中无法结束进程树,获得执行权限后重跑通过;完整测试集也在该环境重跑通过。插件初次依赖下载失败,允许下载后构建成功;后一次离线打包发生 Kotlin Daemon 缓存访问限制,编译器自动回退进程内编译,最终成功。
|
||||
|
||||
## 未验证
|
||||
|
||||
- 真实 Android 项目的 JDK/SDK/NDK 组合与 Gradle 任务。
|
||||
- 在 Android Studio 中安装插件、操作界面和实际设备 adb 覆盖安装。
|
||||
- Linux/macOS 上的运行行为(目前只完成交叉编译)。
|
||||
- 多用户高并发、断电恢复、HTTPS 代理和用户服务器部署。
|
||||
|
||||
模拟 Wrapper 仅用于验证工具链路,不代表已经编译过真实 Android APK。服务和插件均未部署/安装到用户现有环境。
|
||||
@@ -0,0 +1,3 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
# This local port is separate from the Ubuntu server's 8765 tunnel.
|
||||
ssh -N -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -L 127.0.0.1:18765:127.0.0.1:8765 tt@192.168.5.222
|
||||
@@ -0,0 +1,3 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
# Keep this terminal open while the IDE plugin is connected.
|
||||
ssh -N -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -L 8765:127.0.0.1:8765 tt@192.168.5.224
|
||||
@@ -0,0 +1,6 @@
|
||||
param([string]$Data = "$PSScriptRoot\..\server-data")
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not $env:REMOTE_BUILD_TOKEN -or $env:REMOTE_BUILD_TOKEN.Length -lt 24) {
|
||||
throw '请先通过环境变量配置至少 24 字符的 REMOTE_BUILD_TOKEN'
|
||||
}
|
||||
& "$PSScriptRoot\..\dist\remotecompile-windows-amd64.exe" -data $Data -tasks ':app:assembleDebug'
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${REMOTE_BUILD_TOKEN:?请先配置 REMOTE_BUILD_TOKEN}"
|
||||
exec ./remotecompile -data ./server-data -tasks ':app:assembleDebug'
|
||||
@@ -0,0 +1,27 @@
|
||||
plugins {
|
||||
kotlin("jvm") version "2.1.20"
|
||||
id("org.jetbrains.intellij.platform") version "2.5.0"
|
||||
}
|
||||
group = "studio.tongtong"
|
||||
version = "0.1.2"
|
||||
repositories {
|
||||
mavenCentral()
|
||||
intellijPlatform { defaultRepositories() }
|
||||
}
|
||||
dependencies {
|
||||
intellijPlatform {
|
||||
// Override with -PstudioPath="..." to use an installed Android Studio.
|
||||
val studioPath = providers.gradleProperty("studioPath").orNull
|
||||
if (studioPath != null) local(studioPath) else intellijIdeaCommunity("2024.3.5")
|
||||
}
|
||||
implementation("com.google.code.gson:gson:2.12.1")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
}
|
||||
kotlin { jvmToolchain(21) }
|
||||
// Settings live in a tool window; no IDE Settings configurable needs indexing.
|
||||
tasks.named("buildSearchableOptions") { enabled = false }
|
||||
intellijPlatform {
|
||||
pluginConfiguration {
|
||||
ideaVersion { sinceBuild = "243" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
kotlin.compiler.execution.strategy=in-process
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=false
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
+94
@@ -0,0 +1,94 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -0,0 +1,7 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
rootProject.name = "remote-compilation-plugin"
|
||||
@@ -0,0 +1,53 @@
|
||||
package studio.tongtong.remotecompile
|
||||
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import java.util.Properties
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
data class AdbDevice(val serial: String, val state: String, val model: String) {
|
||||
val online get() = state == "device"
|
||||
override fun toString(): String {
|
||||
val label = when (state) { "device" -> if (serial.startsWith("emulator-")) "模拟器" else "已连接"; "unauthorized" -> "未授权,请在手机上确认"; "offline" -> "离线"; else -> state }
|
||||
return "${model.ifBlank { serial }} · $label ($serial)"
|
||||
}
|
||||
}
|
||||
|
||||
object AdbDevices {
|
||||
fun choose(devices: List<AdbDevice>, preferred: String, explicit: Boolean = false): AdbDevice? {
|
||||
val online = devices.filter { it.online }
|
||||
return online.firstOrNull { it.serial == preferred } ?: if (explicit) null else online.singleOrNull()
|
||||
}
|
||||
fun parse(output: String): List<AdbDevice> = output.lineSequence().map(String::trim)
|
||||
.filter { it.isNotEmpty() && !it.startsWith("List of devices") && !it.startsWith("*") && !it.startsWith("adb:") }
|
||||
.mapNotNull { line ->
|
||||
val fields = line.split(Regex("\\s+"))
|
||||
if (fields.size < 2 || fields[1] !in setOf("device", "offline", "unauthorized", "recovery", "sideload", "bootloader", "no")) null
|
||||
else AdbDevice(fields[0], fields[1], fields.drop(2).firstOrNull { it.startsWith("model:") }?.removePrefix("model:")?.replace('_', ' ') ?: "")
|
||||
}.distinctBy { it.serial }.toList()
|
||||
|
||||
fun resolve(source: Path, configured: String): String {
|
||||
if (configured.isNotBlank() && configured != "adb") return configured
|
||||
val properties = Properties()
|
||||
val local = source.resolve("local.properties")
|
||||
if (Files.isRegularFile(local)) Files.newInputStream(local).use(properties::load)
|
||||
val roots = listOfNotNull(properties.getProperty("sdk.dir"), System.getenv("ANDROID_HOME"), System.getenv("ANDROID_SDK_ROOT"),
|
||||
System.getenv("LOCALAPPDATA")?.let { "$it/Android/Sdk" },
|
||||
System.getProperty("user.home")?.let { "$it/Library/Android/sdk" },
|
||||
System.getProperty("user.home")?.let { "$it/Android/Sdk" })
|
||||
val executable = if (System.getProperty("os.name").startsWith("Windows")) "adb.exe" else "adb"
|
||||
return roots.map { Path.of(it).resolve("platform-tools").resolve(executable) }.firstOrNull { Files.isRegularFile(it) }?.toString() ?: "adb"
|
||||
}
|
||||
|
||||
fun list(adb: String): List<AdbDevice> {
|
||||
val log = Files.createTempFile("remotecompile-devices-", ".log")
|
||||
try {
|
||||
val process = ProcessBuilder(adb, "devices", "-l").redirectErrorStream(true).redirectOutput(log.toFile()).start()
|
||||
try {
|
||||
check(process.waitFor(15, TimeUnit.SECONDS)) { "读取设备超时" }
|
||||
check(process.exitValue() == 0) { "adb 读取设备失败,请检查右侧配置中的 adb 路径" }
|
||||
return parse(Files.readString(log))
|
||||
} finally { if (process.isAlive) { process.destroyForcibly(); process.waitFor(3, TimeUnit.SECONDS) } }
|
||||
} finally { Files.deleteIfExists(log) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package studio.tongtong.remotecompile
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonObject
|
||||
import com.intellij.ide.passwordSafe.PasswordSafe
|
||||
import com.intellij.openapi.actionSystem.AnAction
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.Disposable
|
||||
import com.intellij.util.concurrency.AppExecutorUtil
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.fileEditor.FileDocumentManager
|
||||
import com.intellij.openapi.progress.ProgressIndicator
|
||||
import com.intellij.openapi.progress.Task
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.wm.ToolWindow
|
||||
import com.intellij.openapi.wm.ToolWindowFactory
|
||||
import com.intellij.openapi.wm.ToolWindowManager
|
||||
import com.intellij.ui.content.ContentFactory
|
||||
import java.awt.BorderLayout
|
||||
import java.net.URI
|
||||
import java.net.URLEncoder
|
||||
import java.net.http.HttpClient
|
||||
import java.net.http.HttpRequest
|
||||
import java.net.http.HttpResponse
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import java.security.MessageDigest
|
||||
import java.time.Duration
|
||||
import java.util.Base64
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import javax.swing.*
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class PanelService(val project: Project) {
|
||||
var panel: RemotePanel? = null
|
||||
}
|
||||
|
||||
class RemoteToolWindow : ToolWindowFactory {
|
||||
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
|
||||
val panel = RemotePanel(project)
|
||||
project.getService(PanelService::class.java).panel = panel
|
||||
val content = ContentFactory.getInstance().createContent(panel, "构建日志", false)
|
||||
content.setDisposer(panel)
|
||||
toolWindow.contentManager.addContent(content)
|
||||
}
|
||||
}
|
||||
class RemoteRunAction : AnAction() {
|
||||
override fun actionPerformed(e: AnActionEvent) {
|
||||
val project = e.project ?: return
|
||||
ToolWindowManager.getInstance(project).getToolWindow("Remote Compilation")?.show {
|
||||
project.getService(PanelService::class.java).panel?.runBuild()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class RemoteSettingsAction : AnAction() {
|
||||
override fun actionPerformed(e: AnActionEvent) {
|
||||
e.project?.let { ToolWindowManager.getInstance(it).getToolWindow("Remote Configuration")?.show() }
|
||||
}
|
||||
}
|
||||
|
||||
class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Disposable {
|
||||
private val settings = project.getService(Settings::class.java)
|
||||
private val devices = JComboBox<AdbDevice>()
|
||||
private val refresh = JButton("刷新设备")
|
||||
private val deviceStatus = JLabel("正在读取本机设备…")
|
||||
private val refreshing = AtomicBoolean(false)
|
||||
private var updatingDevices = false
|
||||
@Volatile private var disposed = false
|
||||
private val run = JButton("Remote Run")
|
||||
private val cancel = JButton("取消远程构建")
|
||||
private val log = JTextArea().apply { isEditable = false }
|
||||
@Volatile private var activeBuild = ""
|
||||
@Volatile private var cancelRequested = false
|
||||
@Volatile private var busy = false
|
||||
private val gson = Gson()
|
||||
private val http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(15)).build()
|
||||
private val polling = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay({ refreshDevices() }, 1, 5, TimeUnit.SECONDS)
|
||||
init {
|
||||
val configure = JButton("连接设置")
|
||||
val buttons = JPanel().apply { add(JLabel("目标设备")); add(devices); add(refresh); add(run); add(cancel); add(configure) }
|
||||
val top = JPanel(BorderLayout()).apply { add(buttons, BorderLayout.CENTER); add(deviceStatus, BorderLayout.SOUTH) }
|
||||
devices.prototypeDisplayValue = AdbDevice("serial", "device", "选择本机设备或模拟器")
|
||||
devices.renderer = object : DefaultListCellRenderer() {
|
||||
override fun getListCellRendererComponent(list: JList<*>?, value: Any?, index: Int, selected: Boolean, focus: Boolean): java.awt.Component {
|
||||
val component = super.getListCellRendererComponent(list, value ?: "请选择设备", index, selected, focus)
|
||||
isEnabled = value !is AdbDevice || value.online
|
||||
return component
|
||||
}
|
||||
}
|
||||
devices.addActionListener { if (!updatingDevices) (devices.selectedItem as? AdbDevice)?.takeIf { it.online }?.let { settings.selectDevice(it.serial) } }
|
||||
refresh.addActionListener { refreshDevices() }
|
||||
configure.addActionListener { ToolWindowManager.getInstance(project).getToolWindow("Remote Configuration")?.show() }
|
||||
add(top, BorderLayout.NORTH); add(JScrollPane(log), BorderLayout.CENTER)
|
||||
run.addActionListener { runBuild() }
|
||||
cancel.addActionListener { cancelRequested = true; append("已请求取消,等待当前网络操作结束…") }
|
||||
}
|
||||
override fun dispose() {
|
||||
disposed = true; polling.cancel(false)
|
||||
if (!project.isDisposed && project.getService(PanelService::class.java).panel === this) project.getService(PanelService::class.java).panel = null
|
||||
}
|
||||
fun refreshDevices() {
|
||||
if (disposed || project.isDisposed || !refreshing.compareAndSet(false, true)) return
|
||||
ApplicationManager.getApplication().executeOnPooledThread {
|
||||
val cfg = settings.snapshot()
|
||||
val result = runCatching { AdbDevices.list(AdbDevices.resolve(Path.of(project.basePath ?: error("项目路径不存在")), cfg.adb)) }
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
try {
|
||||
if (!disposed && !project.isDisposed) {
|
||||
val found = result.getOrDefault(emptyList())
|
||||
val previous = (devices.selectedItem as? AdbDevice)?.serial ?: settings.snapshot().device
|
||||
if ((0 until devices.itemCount).map { devices.getItemAt(it) } != found) {
|
||||
updatingDevices = true
|
||||
try {
|
||||
devices.model = DefaultComboBoxModel(found.toTypedArray())
|
||||
devices.selectedItem = AdbDevices.choose(found, previous)
|
||||
} finally { updatingDevices = false }
|
||||
}
|
||||
deviceStatus.text = result.exceptionOrNull()?.message ?: if (found.isEmpty()) "没有检测到设备;请连接手机或启动模拟器" else "${found.count { it.online }} 台可用设备;可自动识别插拔"
|
||||
}
|
||||
} finally { refreshing.set(false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
private fun append(text: String) = ApplicationManager.getApplication().invokeLater {
|
||||
if (!disposed && !project.isDisposed) { log.append(text + "\n"); log.caretPosition = log.document.length }
|
||||
}
|
||||
private fun hash(data: ByteArray) = MessageDigest.getInstance("SHA-256").digest(data).joinToString("") { "%02x".format(it) }
|
||||
private fun request(base: String, secret: String, method: String, route: String, body: Any? = null): ByteArray {
|
||||
val publisher = if (body == null) HttpRequest.BodyPublishers.noBody() else HttpRequest.BodyPublishers.ofString(gson.toJson(body))
|
||||
val req = HttpRequest.newBuilder(URI.create(base + "/api/v1" + route)).timeout(Duration.ofMinutes(5))
|
||||
.header("Authorization", "Bearer $secret").header("Content-Type", "application/json").method(method, publisher).build()
|
||||
val response = http.send(req, HttpResponse.BodyHandlers.ofByteArray())
|
||||
check(response.statusCode() in 200..299) { "HTTP ${response.statusCode()}: ${String(response.body()).take(500)}" }
|
||||
return response.body()
|
||||
}
|
||||
private fun json(base: String, secret: String, method: String, route: String, body: Any? = null) =
|
||||
gson.fromJson(String(request(base, secret, method, route, body)), JsonObject::class.java)
|
||||
fun runBuild() {
|
||||
if (busy) return
|
||||
busy = true; run.isEnabled = false
|
||||
// ToolWindow.show callbacks in newer IDEs can run on Dispatchers.UI(RELAX).
|
||||
// Application.invokeLater supplies write intent across supported IDE versions.
|
||||
// Do not link WriteIntentReadAction.run: its binary signature changed in newer IDEs.
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
if (disposed || project.isDisposed) { busy = false; return@invokeLater }
|
||||
try {
|
||||
FileDocumentManager.getInstance().saveAllDocuments()
|
||||
beginBuild()
|
||||
} catch (e: Exception) {
|
||||
busy = false; run.isEnabled = true; append("无法启动:${e.message ?: e.javaClass.simpleName}")
|
||||
}
|
||||
}
|
||||
}
|
||||
private fun beginBuild() {
|
||||
val cfg = settings.snapshot()
|
||||
val base = cfg.url.trim().trimEnd('/')
|
||||
validateEndpoint(base)
|
||||
val selected = devices.selectedItem as? AdbDevice
|
||||
if (cfg.install) {
|
||||
require(selected == null || selected.online) { "请选择已连接且已授权的设备" }
|
||||
if (selected != null) cfg.device = selected.serial
|
||||
}
|
||||
val source = project.basePath?.let { Path.of(it) } ?: error("项目路径不存在")
|
||||
cancelRequested = false; activeBuild = ""; log.text = ""
|
||||
object : Task.Backgroundable(project, "Remote Compilation", false) {
|
||||
override fun run(indicator: ProgressIndicator) {
|
||||
var secret = ""
|
||||
try {
|
||||
secret = PasswordSafe.instance.getPassword(credentials(base)) ?: ""
|
||||
check(secret.length >= 24) { "请在右侧 Remote Configuration 中保存服务 Token" }
|
||||
if (cfg.install) {
|
||||
val connected = AdbDevices.list(AdbDevices.resolve(source, cfg.adb)).filter { it.online }
|
||||
val target = AdbDevices.choose(connected, selected?.serial ?: cfg.device, explicit = selected != null)
|
||||
check(target != null) { "请从设备列表选择已连接且已授权的设备" }
|
||||
cfg.device = target.serial
|
||||
settings.selectDevice(target.serial)
|
||||
refreshDevices()
|
||||
append("目标设备:$target")
|
||||
}
|
||||
json(base, secret, "GET", "/health")
|
||||
if (cfg.projectId.isBlank()) {
|
||||
cfg.projectId = json(base, secret, "POST", "/projects").get("id").asString
|
||||
settings.projectAllocated(base, cfg.projectId)
|
||||
}
|
||||
val manifest = json(base, secret, "GET", "/projects/${cfg.projectId}/manifest").getAsJsonObject("files")
|
||||
val files = linkedMapOf<String, Map<String, String>>()
|
||||
val excludes = setOf(".git", ".gradle", ".idea", "build", ".remotecompile", "node_modules", ".kotlin")
|
||||
var changed = 0
|
||||
Files.walk(source).use { paths -> paths.filter { path ->
|
||||
val rel = source.relativize(path)
|
||||
rel.none { it.toString() in excludes } && !Files.isDirectory(path)
|
||||
}.forEach { path ->
|
||||
check(!Files.isSymbolicLink(path)) { "暂不支持符号链接:$path" }
|
||||
val name = source.relativize(path).joinToString("/")
|
||||
val leaf = path.fileName.toString()
|
||||
if (leaf == "local.properties" || leaf.endsWith(".jks") || leaf.endsWith(".keystore") || leaf.startsWith(".env") || leaf in setOf("key.properties", "keystore.properties")) return@forEach
|
||||
check(Files.size(path) <= 64L * 1024 * 1024) { "文件超过首版 64MiB 上限:$name" }
|
||||
val bytes = Files.readAllBytes(path); val hash = hash(bytes)
|
||||
files[name] = if (manifest?.getAsJsonObject(name)?.get("hash")?.asString == hash) mapOf("hash" to hash)
|
||||
else { changed++; mapOf("hash" to hash, "data" to Base64.getEncoder().encodeToString(bytes)) }
|
||||
} }
|
||||
check(!cancelRequested) { "已取消" }
|
||||
val revision = UUID.randomUUID().toString()
|
||||
append("同步 ${files.size} 个文件,上传 $changed 个变更文件…")
|
||||
json(base, secret, "POST", "/projects/${cfg.projectId}/sync", mapOf("revision" to revision, "files" to files))
|
||||
check(!cancelRequested) { "已取消" }
|
||||
activeBuild = json(base, secret, "POST", "/projects/${cfg.projectId}/builds", mapOf("revision" to revision, "task" to cfg.task)).get("id").asString
|
||||
var offset = 0
|
||||
var result: JsonObject
|
||||
while (true) {
|
||||
if (cancelRequested) { json(base, secret, "DELETE", "/builds/$activeBuild"); error("已请求取消远程构建") }
|
||||
result = json(base, secret, "GET", "/builds/$activeBuild")
|
||||
val lines = result.getAsJsonArray("logs")
|
||||
while (offset < lines.size()) append(lines[offset++].asString)
|
||||
if (result.get("status").asString !in listOf("queued", "running")) break
|
||||
Thread.sleep(700)
|
||||
}
|
||||
check(result.get("status").asString == "success") { "构建状态:${result.get("status").asString}" }
|
||||
val artifacts = result.getAsJsonArray("artifacts")
|
||||
check(artifacts.size() == 1) { "首版要求恰好一个 APK,实际 ${artifacts.size()} 个;请调整构建任务" }
|
||||
val artifact = artifacts[0].asJsonObject
|
||||
val name = artifact.get("name").asString
|
||||
val encodedName = URLEncoder.encode(name, Charsets.UTF_8).replace("+", "%20")
|
||||
val bytes = request(base, secret, "GET", "/builds/$activeBuild/artifacts/$encodedName")
|
||||
check(hash(bytes) == artifact.get("hash").asString) { "APK 校验失败" }
|
||||
val output = source.resolve(".remotecompile").resolve("$activeBuild.apk")
|
||||
Files.createDirectories(output.parent); Files.write(output, bytes)
|
||||
append("APK 已保存:$output")
|
||||
check(!cancelRequested) { "已取消安装" }
|
||||
if (cfg.install) {
|
||||
val adb = AdbDevices.resolve(source, cfg.adb)
|
||||
check(AdbDevices.list(adb).any { it.serial == cfg.device && it.online }) { "目标设备已断开或未授权,已保留 APK" }
|
||||
val pb = ProcessBuilder(adb, "-s", cfg.device, "install", "-r", output.toString()).redirectErrorStream(true)
|
||||
val outputLog = Files.createTempFile("remotecompile-adb-", ".log")
|
||||
try {
|
||||
val process = pb.redirectOutput(outputLog.toFile()).start()
|
||||
if (!process.waitFor(120, TimeUnit.SECONDS)) { process.destroyForcibly(); error("adb 安装超时") }
|
||||
append(Files.readString(outputLog)); check(process.exitValue() == 0) { "adb 安装失败" }
|
||||
} finally { Files.deleteIfExists(outputLog) }
|
||||
}
|
||||
append("Remote Run 完成")
|
||||
} catch (e: Exception) {
|
||||
// Never print request headers or the token.
|
||||
append("失败:" + (e.message ?: e.javaClass.simpleName).let { if (secret.isNotEmpty()) it.replace(secret, "***") else it })
|
||||
} finally {
|
||||
activeBuild = ""; busy = false
|
||||
ApplicationManager.getApplication().invokeLater { if (!disposed && !project.isDisposed) run.isEnabled = true }
|
||||
}
|
||||
}
|
||||
}.queue()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package studio.tongtong.remotecompile
|
||||
|
||||
import com.intellij.credentialStore.CredentialAttributes
|
||||
import com.intellij.ide.passwordSafe.PasswordSafe
|
||||
import com.intellij.openapi.components.*
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.wm.ToolWindow
|
||||
import com.intellij.openapi.wm.ToolWindowFactory
|
||||
import com.intellij.ui.content.ContentFactory
|
||||
import java.awt.BorderLayout
|
||||
import java.awt.GridLayout
|
||||
import java.net.URI
|
||||
import javax.swing.*
|
||||
|
||||
@State(name = "RemoteCompilation", storages = [Storage("remote-compilation.xml")])
|
||||
@Service(Service.Level.PROJECT)
|
||||
class Settings : PersistentStateComponent<Settings.Data> {
|
||||
data class Data(
|
||||
var url: String = "http://127.0.0.1:8765",
|
||||
var projectId: String = "",
|
||||
var task: String = ":app:assembleDebug",
|
||||
var adb: String = "",
|
||||
var device: String = "",
|
||||
var install: Boolean = false
|
||||
)
|
||||
@Volatile private var data = Data()
|
||||
@Synchronized fun snapshot(): Data = data.copy()
|
||||
override fun getState(): Data = snapshot()
|
||||
@Synchronized override fun loadState(state: Data) { data = state.copy() }
|
||||
@Synchronized fun saveConfiguration(next: Data) {
|
||||
data = next.copy(projectId = if (data.url == next.url) data.projectId else "", device = data.device)
|
||||
}
|
||||
@Synchronized fun selectDevice(serial: String) { data = data.copy(device = serial) }
|
||||
@Synchronized fun projectAllocated(url: String, id: String) {
|
||||
if (data.url == url) data = data.copy(projectId = id)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun credentials(endpoint: String) = CredentialAttributes("RemoteCompilation:$endpoint")
|
||||
internal fun validateEndpoint(base: String) {
|
||||
val uri = runCatching { URI.create(base) }.getOrNull()
|
||||
require(uri != null && uri.host != null && uri.scheme in listOf("http", "https") &&
|
||||
uri.rawUserInfo == null && uri.rawQuery == null && uri.rawFragment == null) { "服务地址无效" }
|
||||
require(uri.scheme != "http" || uri.host in listOf("localhost", "127.0.0.1", "[::1]")) {
|
||||
"远程连接请使用 HTTPS 或 SSH 隧道到本机端口"
|
||||
}
|
||||
}
|
||||
|
||||
class RemoteSettingsToolWindow : ToolWindowFactory {
|
||||
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
|
||||
toolWindow.contentManager.addContent(ContentFactory.getInstance().createContent(RemoteSettingsPanel(project), "连接设置", false))
|
||||
}
|
||||
}
|
||||
|
||||
private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderLayout()) {
|
||||
private val settings = project.getService(Settings::class.java)
|
||||
private val original = settings.snapshot()
|
||||
private val url = JTextField(original.url)
|
||||
private val token = JPasswordField()
|
||||
private val task = JTextField(original.task)
|
||||
private val adb = JTextField(original.adb)
|
||||
private val install = JCheckBox("构建成功后安装到所选设备", original.install)
|
||||
private val save = JButton("保存配置")
|
||||
private val status = JLabel("Token 留空保留已保存值")
|
||||
init {
|
||||
val fields = JPanel(GridLayout(0, 1, 0, 5))
|
||||
listOf("服务地址" to url, "Token(留空保留)" to token, "Gradle 任务" to task,
|
||||
"adb 路径(留空自动使用项目 SDK)" to adb).forEach { (label, field) -> fields.add(JLabel(label)); fields.add(field) }
|
||||
fields.add(install); fields.add(save); fields.add(status)
|
||||
border = BorderFactory.createEmptyBorder(12, 12, 12, 12)
|
||||
add(fields, BorderLayout.NORTH)
|
||||
save.addActionListener {
|
||||
val base = url.text.trim().trimEnd('/')
|
||||
try { validateEndpoint(base); require(task.text.isNotBlank()) { "请填写 Gradle 任务" } }
|
||||
catch (e: IllegalArgumentException) { status.text = e.message; return@addActionListener }
|
||||
val entered = String(token.password); token.text = ""
|
||||
val previous = settings.snapshot()
|
||||
val next = previous.copy(url = base, task = task.text.trim(), adb = adb.text.trim(), install = install.isSelected,
|
||||
projectId = if (previous.url == base) previous.projectId else "")
|
||||
save.isEnabled = false; status.text = "正在保存…"
|
||||
ApplicationManager.getApplication().executeOnPooledThread {
|
||||
val failure = runCatching {
|
||||
if (entered.isNotEmpty()) {
|
||||
require(entered.length >= 24) { "Token 至少需要 24 个字符" }
|
||||
PasswordSafe.instance.setPassword(credentials(base), entered)
|
||||
}
|
||||
settings.saveConfiguration(next)
|
||||
}.exceptionOrNull()
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
if (!project.isDisposed) {
|
||||
save.isEnabled = true
|
||||
status.text = if (failure == null) "已保存;点击工具栏 Remote Run 执行" else "保存失败,请检查 Token 或密码库"
|
||||
project.getService(PanelService::class.java).panel?.refreshDevices()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<idea-plugin>
|
||||
<id>studio.tongtong.remotecompile</id>
|
||||
<name>Remote Compilation</name>
|
||||
<vendor>TongTong Studio</vendor>
|
||||
<description>Sync local Android source to a trusted build service, download APK and install with local adb.</description>
|
||||
<depends>com.intellij.modules.platform</depends>
|
||||
<extensions defaultExtensionNs="com.intellij">
|
||||
<toolWindow id="Remote Compilation" anchor="bottom" factoryClass="studio.tongtong.remotecompile.RemoteToolWindow"/>
|
||||
<toolWindow id="Remote Configuration" anchor="right" icon="AllIcons.General.Settings" factoryClass="studio.tongtong.remotecompile.RemoteSettingsToolWindow"/>
|
||||
</extensions>
|
||||
<actions>
|
||||
<action id="RemoteCompilation.Run" class="studio.tongtong.remotecompile.RemoteRunAction" text="Remote Run" description="Build remotely and install on the selected local device" icon="AllIcons.Actions.Execute">
|
||||
<add-to-group group-id="ToolsMenu" anchor="last"/>
|
||||
<add-to-group group-id="MainToolbarRight" anchor="last"/>
|
||||
<add-to-group group-id="MainToolBar" anchor="last"/>
|
||||
</action>
|
||||
<action id="RemoteCompilation.Settings" class="studio.tongtong.remotecompile.RemoteSettingsAction" text="Remote Compilation Settings" icon="AllIcons.General.Settings">
|
||||
<add-to-group group-id="ToolsMenu" anchor="last"/>
|
||||
</action>
|
||||
</actions>
|
||||
</idea-plugin>
|
||||
@@ -0,0 +1,53 @@
|
||||
package studio.tongtong.remotecompile
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.nio.file.Files
|
||||
import java.util.Properties
|
||||
|
||||
class AdbDevicesTest {
|
||||
@Test fun selectsOnlyOneOnlineDeviceAndNeverReplacesExplicitDisconnectedTarget() {
|
||||
val a = AdbDevice("A", "device", "Phone A")
|
||||
val b = AdbDevice("B", "device", "Phone B")
|
||||
val locked = AdbDevice("C", "unauthorized", "")
|
||||
assertEquals(a, AdbDevices.choose(listOf(a, locked), ""))
|
||||
assertNull(AdbDevices.choose(listOf(a, b), ""))
|
||||
assertEquals(b, AdbDevices.choose(listOf(a, b), "B"))
|
||||
assertNull(AdbDevices.choose(listOf(b), "A", explicit = true))
|
||||
assertNull(AdbDevices.choose(listOf(locked), "C"))
|
||||
}
|
||||
@Test fun parsesUsbWifiAndEmulatorWithoutSelectingUnauthorizedDevice() {
|
||||
val result = AdbDevices.parse("""
|
||||
* daemon not running; starting now at tcp:5037
|
||||
* daemon started successfully
|
||||
List of devices attached
|
||||
USB123 device product:panther model:Pixel_7 device:panther transport_id:1
|
||||
emulator-5554 device product:sdk model:sdk_gphone64_x86_64 transport_id:2
|
||||
192.168.1.2:5555 offline transport_id:3
|
||||
LOCKED unauthorized usb:1-1 transport_id:4
|
||||
""".trimIndent())
|
||||
assertEquals(4, result.size)
|
||||
assertEquals(listOf("USB123", "emulator-5554"), result.filter { it.online }.map { it.serial })
|
||||
assertEquals("Pixel 7", result[0].model)
|
||||
assertTrue(result[1].toString().contains("模拟器"))
|
||||
assertTrue(result[3].toString().contains("未授权"))
|
||||
}
|
||||
@Test fun ignoresDaemonNoiseAndDeduplicatesSerials() {
|
||||
assertEquals(emptyList<AdbDevice>(), AdbDevices.parse("List of devices attached\nadb: server unavailable\n"))
|
||||
assertEquals(1, AdbDevices.parse("A\tdevice\nA\tdevice\n").size)
|
||||
}
|
||||
@Test fun resolvesAdbFromProjectSdkIncludingSpacesAndUnicode() {
|
||||
val root = Files.createTempDirectory("remote-adb-test")
|
||||
try {
|
||||
val sdk = root.resolve("Android SDK 中文")
|
||||
val filename = if (System.getProperty("os.name").startsWith("Windows")) "adb.exe" else "adb"
|
||||
val adb = sdk.resolve("platform-tools").resolve(filename)
|
||||
Files.createDirectories(adb.parent); Files.write(adb, byteArrayOf())
|
||||
val properties = Properties().apply { setProperty("sdk.dir", sdk.toString()) }
|
||||
Files.newOutputStream(root.resolve("local.properties")).use { properties.store(it, null) }
|
||||
assertEquals(adb.toString(), AdbDevices.resolve(root, ""))
|
||||
assertEquals(adb.toString(), AdbDevices.resolve(root, "adb"))
|
||||
assertEquals("custom-adb", AdbDevices.resolve(root, "custom-adb"))
|
||||
} finally { root.toFile().deleteRecursively() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package studio.tongtong.remotecompile
|
||||
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Test
|
||||
|
||||
class BinaryCompatibilityTest {
|
||||
@Test fun saveCallbackDoesNotLinkRemovedWriteIntentReadActionMethod() {
|
||||
// A compile against 243 succeeded in 0.1.1 while the user's newer IDE
|
||||
// failed at linkage. Inspect bytecode, not source/imports, for regression.
|
||||
val bytes = requireNotNull(javaClass.getResourceAsStream("/studio/tongtong/remotecompile/RemotePanel.class")).use { it.readBytes() }
|
||||
assertFalse("RemotePanel must not depend on the changed WriteIntentReadAction binary API",
|
||||
String(bytes, Charsets.ISO_8859_1).contains("com/intellij/openapi/application/WriteIntentReadAction"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package studio.tongtong.remotecompile
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class SettingsTest {
|
||||
@Test fun savingConfigurationDoesNotLoseWorkspaceAllocatedByRunningBuild() {
|
||||
val settings = Settings()
|
||||
val editing = settings.snapshot().copy(task = ":app:assembleDemoDebug")
|
||||
settings.projectAllocated(editing.url, "allocated-during-edit")
|
||||
settings.selectDevice("USB123")
|
||||
settings.saveConfiguration(editing)
|
||||
assertEquals("allocated-during-edit", settings.snapshot().projectId)
|
||||
assertEquals("USB123", settings.snapshot().device)
|
||||
}
|
||||
@Test fun changingEndpointResetsWorkspaceAndOldBuildCannotOverwriteIt() {
|
||||
val settings = Settings()
|
||||
val oldUrl = settings.snapshot().url
|
||||
settings.projectAllocated(oldUrl, "old-workspace")
|
||||
settings.saveConfiguration(settings.snapshot().copy(url = "http://127.0.0.1:18765"))
|
||||
settings.projectAllocated(oldUrl, "late-old-allocation")
|
||||
assertEquals("", settings.snapshot().projectId)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
# HTTP 协议 v1
|
||||
|
||||
所有接口要求 `Authorization: Bearer <token>`。JSON 使用 UTF-8;除下载、SSE 外返回 JSON。HTTP 400 表示请求无效,401 未认证,404 不存在,409 工作区繁忙或版本冲突。
|
||||
|
||||
| 方法 | 路径(前缀 `/api/v1`) | 说明 |
|
||||
| --- | --- | --- |
|
||||
| GET | `/health` | 版本、OS 和同步能力 |
|
||||
| POST | `/projects` | 分配独立工作区,返回 `{ "id": "..." }` |
|
||||
| GET | `/projects/{id}/manifest` | 当前 revision 与 files 清单 |
|
||||
| POST | `/projects/{id}/sync` | 同步完整清单、变更内容并提交新版本 |
|
||||
| POST | `/projects/{id}/builds` | 请求构建,返回 build |
|
||||
| GET | `/builds/{id}` | 状态、日志块与产物 |
|
||||
| DELETE | `/builds/{id}` | 请求取消;继续查询直到终态 |
|
||||
| GET | `/builds/{id}/logs` | SSE 日志,支持 Last-Event-ID 从上次块之后继续 |
|
||||
| GET | `/builds/{id}/artifacts/{name}` | 下载独立保存的产物 |
|
||||
|
||||
## 同步
|
||||
|
||||
```json
|
||||
{
|
||||
"revision": "客户端生成的唯一版本号",
|
||||
"files": {
|
||||
"settings.gradle.kts": { "hash": "SHA-256小写十六进制", "data": "文件Base64" },
|
||||
"app/src/main/AndroidManifest.xml": { "hash": "未变化文件的SHA-256" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`files` 是完整源码清单;上一版本存在、本次未出现的文件会删除。内容变化时提供 data,未变化时省略。所有内容先校验,再使旧 revision 失效并落盘,成功才提交新 revision。写入失败会保留不可构建状态,下次完整同步可恢复;不是文件系统事务回滚。首版一次请求最多 256MiB(包含 Base64 和 JSON),客户端单文件限制 64MiB。
|
||||
|
||||
路径使用 `/`,拒绝路径穿越、绝对路径、Windows 保留名、大小写重复、符号链接和保留目录。服务器不信任客户端提供的 hash,必须校验实际内容。插件和参考客户端使用相同排除约定;`.gitignore` 不会自动套用,确实需要构建的未跟踪文件仍可上传。
|
||||
|
||||
构建请求:
|
||||
|
||||
```json
|
||||
{ "revision": "刚提交的版本号", "task": ":app:assembleDebug" }
|
||||
```
|
||||
|
||||
状态:`queued → running → success | failed | cancelled`。同一工作区只能有一个任务,忙时返回 409;首版没有跨工作区全局限流或持久队列。任务必须命中服务端白名单。源码、工作区与 buildId 绑定,构建中不接受该工作区同步。
|
||||
|
||||
产物记录:`{ "name": "0-app-debug.apk", "hash": "SHA-256", "size": 12345 }`。客户端必须验证摘要后安装。构建前仅删除各模块 `build/outputs/` 下的旧 APK,保留其他编译缓存。服务端成功收集本次 APK 后才报告 success。
|
||||
|
||||
SSE data 是 JSON 编码的日志文本块,不保证以行或 UTF-8 字符边界分块;首版插件通过 GET build 每 700ms 轮询日志,而非消费 SSE。日志 ID 为从 1 开始的块编号。终态发送完所有日志后连接关闭。
|
||||
@@ -0,0 +1,3 @@
|
||||
module remotecompile
|
||||
|
||||
go 1.24.0
|
||||
+595
@@ -0,0 +1,595 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
type File struct {
|
||||
Hash string `json:"hash"`
|
||||
Data *string `json:"data,omitempty"`
|
||||
}
|
||||
type SyncRequest struct {
|
||||
Revision string `json:"revision"`
|
||||
Files map[string]File `json:"files"`
|
||||
}
|
||||
type Artifact struct {
|
||||
Name string `json:"name"`
|
||||
Hash string `json:"hash"`
|
||||
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
|
||||
}
|
||||
type Project struct {
|
||||
Revision string `json:"revision"`
|
||||
Files map[string]File `json:"files"`
|
||||
Busy bool `json:"-"`
|
||||
}
|
||||
type Server struct {
|
||||
mu sync.Mutex
|
||||
root, token string
|
||||
tasks map[string]bool
|
||||
projects map[string]*Project
|
||||
builds map[string]*Build
|
||||
}
|
||||
|
||||
var safeID = regexp.MustCompile(`^[a-f0-9]{32}$`)
|
||||
var safeTask = regexp.MustCompile(`^:?[A-Za-z0-9_]+(:[A-Za-z0-9_]+)*$`)
|
||||
|
||||
func id() string {
|
||||
b := make([]byte, 16)
|
||||
if _, e := rand.Read(b); e != nil {
|
||||
panic(e)
|
||||
}
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
func digest(b []byte) string { h := sha256.Sum256(b); return hex.EncodeToString(h[:]) }
|
||||
func validPath(p string) bool {
|
||||
if p == "" || strings.ContainsAny(p, "\\:\x00<>\"|?*") || strings.HasPrefix(p, "/") {
|
||||
return false
|
||||
}
|
||||
for _, part := range strings.Split(p, "/") {
|
||||
if part == "" || part == "." || part == ".." || strings.TrimRight(part, ". ") != part {
|
||||
return false
|
||||
}
|
||||
base := strings.ToUpper(strings.Split(part, ".")[0])
|
||||
if regexp.MustCompile(`^(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])$`).MatchString(base) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for _, part := range strings.Split(p, "/") {
|
||||
if part == ".git" || part == ".gradle" || part == "build" || part == ".idea" || part == "local.properties" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func noLinks(root string) error {
|
||||
return filepath.WalkDir(root, func(p string, d os.DirEntry, e error) error {
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if d.Type()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("symlink forbidden: %s", p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
func jsonOut(w http.ResponseWriter, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
func decode(w http.ResponseWriter, r *http.Request, v any) error {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 256<<20)
|
||||
d := json.NewDecoder(r.Body)
|
||||
d.DisallowUnknownFields()
|
||||
return d.Decode(v)
|
||||
}
|
||||
func (s *Server) work(p string) string { 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 {
|
||||
return e
|
||||
}
|
||||
path := filepath.Join(s.root, "projects", p, "state.json")
|
||||
if e = os.WriteFile(path+".tmp", b, 0600); e != nil {
|
||||
return e
|
||||
}
|
||||
return os.Rename(path+".tmp", path)
|
||||
}
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+s.token)) != 1 {
|
||||
http.Error(w, "unauthorized", 401)
|
||||
return
|
||||
}
|
||||
if r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/logs") {
|
||||
s.streamLogs(w, r)
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
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.0", "os": runtime.GOOS, "sync": "http-manifest"})
|
||||
return
|
||||
}
|
||||
if len(parts) < 3 || parts[0] != "api" || parts[1] != "v1" {
|
||||
http.NotFound(w, r)
|
||||
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})
|
||||
return
|
||||
}
|
||||
if len(parts) != 5 || !safeID.MatchString(parts[3]) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
p := parts[3]
|
||||
pr := s.projects[p]
|
||||
if pr == nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if parts[4] == "manifest" && r.Method == "GET" {
|
||||
jsonOut(w, pr)
|
||||
return
|
||||
}
|
||||
if parts[4] == "sync" && r.Method == "POST" {
|
||||
if pr.Busy {
|
||||
http.Error(w, "workspace busy", 409)
|
||||
return
|
||||
}
|
||||
var req SyncRequest
|
||||
if e := decode(w, r, &req); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
if req.Revision == "" || req.Files == nil {
|
||||
fail(errors.New("revision and files required"))
|
||||
return
|
||||
}
|
||||
if e := noLinks(s.work(p)); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
staged := map[string][]byte{}
|
||||
seen := map[string]bool{}
|
||||
components := map[string]string{}
|
||||
for path, f := range req.Files {
|
||||
key := strings.ToLower(path)
|
||||
if !validPath(path) || seen[key] {
|
||||
fail(fmt.Errorf("invalid or colliding path: %s", path))
|
||||
return
|
||||
}
|
||||
seen[key] = true
|
||||
segments := strings.Split(path, "/")
|
||||
for i := range segments {
|
||||
prefix := strings.Join(segments[:i+1], "/")
|
||||
lower := strings.ToLower(prefix)
|
||||
if previous, ok := components[lower]; ok && previous != prefix {
|
||||
fail(fmt.Errorf("inconsistent path casing: %s", path))
|
||||
return
|
||||
}
|
||||
components[lower] = prefix
|
||||
}
|
||||
if f.Data != nil {
|
||||
b, e := base64.StdEncoding.DecodeString(*f.Data)
|
||||
if e != nil || digest(b) != f.Hash {
|
||||
fail(fmt.Errorf("hash mismatch: %s", path))
|
||||
return
|
||||
}
|
||||
staged[path] = b
|
||||
} else {
|
||||
b, e := os.ReadFile(filepath.Join(s.work(p), filepath.FromSlash(path)))
|
||||
if e != nil || digest(b) != f.Hash {
|
||||
fail(fmt.Errorf("missing content: %s", path))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
for path := range req.Files {
|
||||
segments := strings.Split(path, "/")
|
||||
for i := 1; i < len(segments); i++ {
|
||||
if seen[strings.ToLower(strings.Join(segments[:i], "/"))] {
|
||||
fail(fmt.Errorf("file/directory collision: %s", path))
|
||||
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 = ""
|
||||
if e := s.save(p); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
for path := range pr.Files {
|
||||
if _, ok := req.Files[path]; !ok {
|
||||
if e := os.Remove(filepath.Join(s.work(p), filepath.FromSlash(path))); e != nil && !os.IsNotExist(e) {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
for path, b := range staged {
|
||||
dest := filepath.Join(s.work(p), filepath.FromSlash(path))
|
||||
if e := os.MkdirAll(filepath.Dir(dest), 0700); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
if e := os.WriteFile(dest, b, 0600); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
}
|
||||
pr.Files = map[string]File{}
|
||||
for path, f := range req.Files {
|
||||
pr.Files[path] = File{Hash: f.Hash}
|
||||
}
|
||||
pr.Revision = req.Revision
|
||||
if e := s.save(p); e != nil {
|
||||
pr.Revision = ""
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
jsonOut(w, pr)
|
||||
return
|
||||
}
|
||||
if parts[4] == "builds" && r.Method == "POST" {
|
||||
var req struct {
|
||||
Revision string `json:"revision"`
|
||||
Task string `json:"task"`
|
||||
}
|
||||
if e := decode(w, r, &req); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
if !s.tasks[req.Task] || !safeTask.MatchString(req.Task) {
|
||||
fail(errors.New("task not allowed"))
|
||||
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 e := os.WriteFile(filepath.Join(s.root, "projects", p, "active-build"), []byte(b.ID), 0600); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
s.builds[b.ID] = b
|
||||
pr.Busy = true
|
||||
go s.run(b)
|
||||
jsonOut(w, b)
|
||||
return
|
||||
}
|
||||
}
|
||||
if parts[2] == "builds" && len(parts) >= 4 {
|
||||
b := s.builds[parts[3]]
|
||||
if b == nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if len(parts) == 4 && r.Method == "GET" {
|
||||
jsonOut(w, b)
|
||||
return
|
||||
}
|
||||
if len(parts) == 4 && r.Method == "DELETE" {
|
||||
if b.Status == "queued" || b.Status == "running" {
|
||||
b.cancelled = true
|
||||
if b.cmd != nil && b.cmd.Process != nil {
|
||||
killTree(b.cmd)
|
||||
}
|
||||
}
|
||||
jsonOut(w, b)
|
||||
return
|
||||
}
|
||||
if len(parts) == 6 && parts[4] == "artifacts" && r.Method == "GET" {
|
||||
for _, a := range b.Artifacts {
|
||||
if a.Name == parts[5] {
|
||||
s.mu.Unlock()
|
||||
http.ServeFile(w, r, filepath.Join(s.root, "artifacts", b.ID, a.Name))
|
||||
s.mu.Lock()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
func (s *Server) streamLogs(w http.ResponseWriter, r *http.Request) {
|
||||
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||
if len(parts) != 5 || parts[0] != "api" || parts[1] != "v1" || parts[2] != "builds" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
offset, _ := strconv.Atoi(r.Header.Get("Last-Event-ID"))
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
s.mu.Lock()
|
||||
b := s.builds[parts[3]]
|
||||
s.mu.Unlock()
|
||||
if b == nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
ticker := time.NewTicker(400 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
s.mu.Lock()
|
||||
lines := append([]string{}, b.Logs...)
|
||||
terminal := b.Status != "queued" && b.Status != "running"
|
||||
s.mu.Unlock()
|
||||
for offset < len(lines) {
|
||||
if _, e := fmt.Fprintf(w, "id: %d\ndata: %s\n\n", offset+1, mustJSON(lines[offset])); e != nil {
|
||||
return
|
||||
}
|
||||
offset++
|
||||
}
|
||||
if f, ok := w.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
if terminal {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
func isOutputAPK(work, p string) bool {
|
||||
rel, e := filepath.Rel(work, p)
|
||||
if e != nil {
|
||||
return false
|
||||
}
|
||||
return strings.Contains("/"+filepath.ToSlash(rel), "/build/outputs/") && strings.HasSuffix(strings.ToLower(p), ".apk")
|
||||
}
|
||||
func mustJSON(v any) string { b, _ := json.Marshal(v); return string(b) }
|
||||
|
||||
type buildWriter struct {
|
||||
s *Server
|
||||
b *Build
|
||||
}
|
||||
|
||||
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))
|
||||
return len(p), nil
|
||||
}
|
||||
func (s *Server) run(b *Build) {
|
||||
s.mu.Lock()
|
||||
if b.cancelled {
|
||||
b.Status = "cancelled"
|
||||
s.projects[b.Project].Busy = false
|
||||
os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build"))
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
b.Status = "running"
|
||||
s.mu.Unlock()
|
||||
work := s.work(b.Project)
|
||||
// Remove old APKs only. Retain compilation caches and all other Gradle outputs.
|
||||
err := noLinks(work)
|
||||
if err == nil {
|
||||
err = filepath.WalkDir(work, func(p string, d os.DirEntry, e error) error {
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if !d.IsDir() && isOutputAPK(work, p) {
|
||||
return os.Remove(p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
if err == nil {
|
||||
cmd := gradleCommand(work, b.Task)
|
||||
cmd.Dir = work
|
||||
cmd.Stdout = buildWriter{s, b}
|
||||
cmd.Stderr = cmd.Stdout
|
||||
s.mu.Lock()
|
||||
b.cmd = cmd
|
||||
if b.cancelled {
|
||||
err = errors.New("cancelled")
|
||||
} else {
|
||||
err = cmd.Start()
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if err == nil {
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- cmd.Wait() }()
|
||||
select {
|
||||
case err = <-done:
|
||||
case <-time.After(30 * time.Minute):
|
||||
killTree(cmd)
|
||||
err = <-done
|
||||
if err == nil {
|
||||
err = errors.New("build timeout")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
artifacts := []Artifact{}
|
||||
if err == nil {
|
||||
err = filepath.WalkDir(work, func(p string, d os.DirEntry, e error) error {
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if d.IsDir() || !isOutputAPK(work, p) {
|
||||
return nil
|
||||
}
|
||||
data, e := os.ReadFile(p)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
name := fmt.Sprintf("%d-%s", len(artifacts), filepath.Base(p))
|
||||
dest := filepath.Join(s.root, "artifacts", b.ID)
|
||||
if e = os.MkdirAll(dest, 0700); e != nil {
|
||||
return e
|
||||
}
|
||||
if e = os.WriteFile(filepath.Join(dest, name), data, 0600); e != nil {
|
||||
return e
|
||||
}
|
||||
artifacts = append(artifacts, Artifact{name, digest(data), int64(len(data))})
|
||||
return nil
|
||||
})
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
b.cmd = nil
|
||||
b.Artifacts = artifacts
|
||||
b.Status = "success"
|
||||
if len(artifacts) == 0 && err == nil {
|
||||
err = errors.New("no APK produced")
|
||||
}
|
||||
if err != nil {
|
||||
b.Status = "failed"
|
||||
b.Logs = append(b.Logs, err.Error())
|
||||
}
|
||||
if b.cancelled {
|
||||
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)
|
||||
os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build"))
|
||||
}
|
||||
func main() {
|
||||
addr := flag.String("listen", "127.0.0.1:8765", "HTTP bind address; use HTTPS proxy or SSH tunnel remotely")
|
||||
root := flag.String("data", "./data", "service data directory")
|
||||
tasks := flag.String("tasks", ":app:assembleDebug", "comma separated allowed Gradle tasks")
|
||||
flag.Parse()
|
||||
token := os.Getenv("REMOTE_BUILD_TOKEN")
|
||||
if len(token) < 24 {
|
||||
log.Fatal("REMOTE_BUILD_TOKEN must contain at least 24 characters")
|
||||
}
|
||||
abs, e := filepath.Abs(*root)
|
||||
if e != nil {
|
||||
log.Fatal(e)
|
||||
}
|
||||
s := &Server{root: abs, token: token, tasks: map[string]bool{}, projects: map[string]*Project{}, builds: map[string]*Build{}}
|
||||
for _, t := range strings.Split(*tasks, ",") {
|
||||
if !safeTask.MatchString(t) {
|
||||
log.Fatal("invalid task")
|
||||
}
|
||||
s.tasks[t] = true
|
||||
}
|
||||
entries, _ := os.ReadDir(filepath.Join(abs, "projects"))
|
||||
for _, entry := range entries {
|
||||
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 {
|
||||
s.projects[entry.Name()] = &p
|
||||
}
|
||||
}
|
||||
entries, _ = os.ReadDir(filepath.Join(abs, "artifacts"))
|
||||
for _, entry := range entries {
|
||||
data, e := os.ReadFile(filepath.Join(abs, "artifacts", entry.Name(), "build.json"))
|
||||
if e != nil {
|
||||
continue
|
||||
}
|
||||
var b Build
|
||||
if json.Unmarshal(data, &b) == nil {
|
||||
s.builds[b.ID] = &b
|
||||
}
|
||||
}
|
||||
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}
|
||||
stop := make(chan os.Signal, 1)
|
||||
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
|
||||
go func() {
|
||||
<-stop
|
||||
s.mu.Lock()
|
||||
for _, b := range s.builds {
|
||||
if b.Status == "running" || b.Status == "queued" {
|
||||
b.cancelled = true
|
||||
if b.cmd != nil {
|
||||
killTree(b.cmd)
|
||||
}
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
srv.Shutdown(ctx)
|
||||
}()
|
||||
if e := srv.ListenAndServe(); e != nil && e != http.ErrServerClosed {
|
||||
log.Fatal(e)
|
||||
}
|
||||
// Let workers persist terminal state and clear their active markers.
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
s.mu.Lock()
|
||||
busy := false
|
||||
for _, p := range s.projects {
|
||||
busy = busy || p.Busy
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if !busy {
|
||||
return
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
var _ io.Writer = buildWriter{}
|
||||
@@ -0,0 +1,188 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
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{}}
|
||||
}
|
||||
|
||||
func TestRunningCancellation(t *testing.T) {
|
||||
s := testServer(t)
|
||||
p := project(t, s)
|
||||
name, wrapper := "gradlew", "#!/bin/sh\nsleep 20\n"
|
||||
if runtime.GOOS == "windows" {
|
||||
name = "gradlew.bat"
|
||||
wrapper = "@echo off\r\nping 127.0.0.1 -n 20 >nul\r\n"
|
||||
}
|
||||
os.WriteFile(filepath.Join(s.work(p), name), []byte(wrapper), 0600)
|
||||
b := &Build{ID: id(), Project: p, Revision: "r", Task: ":app:assembleDebug", Status: "queued", Logs: []string{}}
|
||||
s.builds[b.ID] = b
|
||||
s.projects[p].Busy = true
|
||||
done := make(chan struct{})
|
||||
go func() { s.run(b); close(done) }()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
s.mu.Lock()
|
||||
started := b.cmd != nil && b.cmd.Process != nil
|
||||
s.mu.Unlock()
|
||||
if started {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("executor failed to start")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if w := call(t, s, "DELETE", "/builds/"+b.ID, nil); w.Code != 200 {
|
||||
t.Fatal(w.Body.String())
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("cancel did not stop process tree")
|
||||
}
|
||||
if b.Status != "cancelled" || s.projects[p].Busy {
|
||||
t.Fatal("incorrect cancellation state")
|
||||
}
|
||||
}
|
||||
func TestSSEReplay(t *testing.T) {
|
||||
s := testServer(t)
|
||||
b := &Build{ID: id(), Status: "success", Logs: []string{"first", "second"}}
|
||||
s.builds[b.ID] = b
|
||||
r := httptest.NewRequest("GET", "/api/v1/builds/"+b.ID+"/logs", nil)
|
||||
r.Header.Set("Authorization", "Bearer "+s.token)
|
||||
r.Header.Set("Last-Event-ID", "1")
|
||||
w := httptest.NewRecorder()
|
||||
s.ServeHTTP(w, r)
|
||||
if strings.Contains(w.Body.String(), "first") || !strings.Contains(w.Body.String(), "second") {
|
||||
t.Fatal("SSE replay offset ignored")
|
||||
}
|
||||
}
|
||||
func call(t *testing.T, s *Server, method, path string, body any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
b, _ := json.Marshal(body)
|
||||
r := httptest.NewRequest(method, "/api/v1"+path, bytes.NewReader(b))
|
||||
r.Header.Set("Authorization", "Bearer "+s.token)
|
||||
w := httptest.NewRecorder()
|
||||
s.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
func project(t *testing.T, s *Server) string {
|
||||
w := call(t, s, "POST", "/projects", nil)
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Body.String())
|
||||
}
|
||||
var v map[string]string
|
||||
json.Unmarshal(w.Body.Bytes(), &v)
|
||||
return v["id"]
|
||||
}
|
||||
func file(data string) File {
|
||||
encoded := base64.StdEncoding.EncodeToString([]byte(data))
|
||||
return File{Hash: digest([]byte(data)), Data: &encoded}
|
||||
}
|
||||
func TestPaths(t *testing.T) {
|
||||
for _, p := range []string{"../x", "/x", "C:/x", "a\\b", "a/../x", "a//b", "CON.txt", "a./x", ".git/config", "app/build/x"} {
|
||||
if validPath(p) {
|
||||
t.Errorf("accepted %q", p)
|
||||
}
|
||||
}
|
||||
if !validPath("app/src/中文 a.kt") {
|
||||
t.Fatal("valid unicode path rejected")
|
||||
}
|
||||
}
|
||||
func TestAuthentication(t *testing.T) {
|
||||
s := testServer(t)
|
||||
w := httptest.NewRecorder()
|
||||
s.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/health", nil))
|
||||
if w.Code != 401 {
|
||||
t.Fatal(w.Code)
|
||||
}
|
||||
}
|
||||
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")}}
|
||||
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"}}}
|
||||
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"))}}}
|
||||
if w := call(t, s, "POST", path, req); w.Code != 200 {
|
||||
t.Fatal(w.Body.String())
|
||||
}
|
||||
if _, e := os.Stat(filepath.Join(s.work(p), "b.txt")); !os.IsNotExist(e) {
|
||||
t.Fatal("deleted source retained")
|
||||
}
|
||||
s.projects[p].Busy = true
|
||||
if w := call(t, s, "POST", path, req); w.Code != 409 {
|
||||
t.Fatal("sync allowed while building")
|
||||
}
|
||||
s.projects[p].Busy = false
|
||||
if w := call(t, s, "POST", "/projects/"+p+"/builds", map[string]string{"revision": "one", "task": ":app:assembleDebug"}); w.Code != 409 {
|
||||
t.Fatal("stale revision accepted")
|
||||
}
|
||||
if w := call(t, s, "POST", "/projects/"+p+"/builds", map[string]string{"revision": "two", "task": "evil & command"}); w.Code != 400 {
|
||||
t.Fatal("unapproved command accepted")
|
||||
}
|
||||
}
|
||||
func TestBuildArtifactAndFailure(t *testing.T) {
|
||||
s := testServer(t)
|
||||
p := project(t, s)
|
||||
wrapper := "#!/bin/sh\nmkdir -p app/build/outputs/apk/debug\nprintf fresh > app/build/outputs/apk/debug/app-debug.apk\n"
|
||||
name := "gradlew"
|
||||
if runtime.GOOS == "windows" {
|
||||
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)}}
|
||||
if w := call(t, s, "POST", "/projects/"+p+"/sync", req); w.Code != 200 {
|
||||
t.Fatal(w.Body.String())
|
||||
}
|
||||
b := &Build{ID: id(), Project: p, Revision: "one", Task: ":app:assembleDebug", Status: "queued"}
|
||||
s.builds[b.ID] = b
|
||||
s.projects[p].Busy = true
|
||||
s.run(b)
|
||||
if b.Status != "success" || len(b.Artifacts) != 1 {
|
||||
t.Fatalf("%s %v", b.Status, b.Logs)
|
||||
}
|
||||
a := b.Artifacts[0]
|
||||
w := call(t, s, "GET", "/builds/"+b.ID+"/artifacts/"+a.Name, nil)
|
||||
if w.Code != 200 || digest(w.Body.Bytes()) != a.Hash {
|
||||
t.Fatal("artifact mismatch")
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
wrapper = "@exit /b 1\r\n"
|
||||
} else {
|
||||
wrapper = "#!/bin/sh\nexit 1\n"
|
||||
}
|
||||
os.WriteFile(filepath.Join(s.work(p), name), []byte(wrapper), 0600)
|
||||
failed := &Build{ID: id(), Project: p, Revision: "one", Task: ":app:assembleDebug", Status: "queued"}
|
||||
s.run(failed)
|
||||
if failed.Status != "failed" || len(failed.Artifacts) != 0 {
|
||||
t.Fatal("failed build returned artifacts")
|
||||
}
|
||||
cancelled := &Build{ID: id(), Project: p, Status: "queued", cancelled: true}
|
||||
s.run(cancelled)
|
||||
if cancelled.Status != "cancelled" || s.projects[p].Busy {
|
||||
t.Fatal("queued cancellation failed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//go:build !windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func gradleCommand(work, task string) *exec.Cmd {
|
||||
c := exec.Command("sh", filepath.Join(work, "gradlew"), task, "--console=plain", "--no-daemon")
|
||||
c.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
return c
|
||||
}
|
||||
func killTree(c *exec.Cmd) {
|
||||
if c.Process != nil {
|
||||
_ = syscall.Kill(-c.Process.Pid, syscall.SIGKILL)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func gradleCommand(work, task string) *exec.Cmd {
|
||||
return exec.Command("cmd.exe", "/d", "/c", "gradlew.bat", task, "--console=plain", "--no-daemon")
|
||||
}
|
||||
func killTree(c *exec.Cmd) {
|
||||
if c.Process != nil {
|
||||
_ = exec.Command("taskkill.exe", "/PID", strconv.Itoa(c.Process.Pid), "/T", "/F").Run()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user