From 6f9cc7e7eabde0547a9acf309f9df18c22bbcbee Mon Sep 17 00:00:00 2001 From: tongtongstudio Date: Fri, 27 Nov 2026 11:04:58 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E7=8B=AC=E7=AB=8B?= =?UTF-8?q?=E6=9E=84=E5=BB=BA=E5=B7=A5=E4=BD=9C=E5=8C=BA=E3=80=81=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E7=AB=AFADB=E4=B8=8E=E7=A7=81=E6=9C=89=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E6=B8=85=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 支持Git提交导入及未提交源码叠加,APK原名下载和完成通知。新增服务端设备安装与按工程维护的私有文件清单,修复Wrapper预检查、布局及IDE读锁和保存状态问题。更新协议、测试和部署记录;服务端0.7.0,插件0.7.1。 --- README.md | 7 +- client/remote_run.py | 57 ++- client/test_smoke.py | 23 +- docs/dedicated-workspaces.md | 56 +++ docs/deployment-192.168.5.222.md | 33 ++ docs/deployment-192.168.5.224.md | 24 ++ docs/deployment-local-windows.md | 24 ++ docs/private-files.md | 37 ++ docs/remote-adb.md | 12 + docs/verification.md | 87 +++++ plugin/build.gradle.kts | 2 +- .../tongtong/remotecompile/ApkArtifacts.kt | 5 +- .../studio/tongtong/remotecompile/ApkFiles.kt | 29 ++ .../remotecompile/ApkNotifications.kt | 37 ++ .../tongtong/remotecompile/GitBundles.kt | 21 ++ .../tongtong/remotecompile/LastBuild.kt | 2 +- .../remotecompile/PrivateFilesEditor.kt | 149 ++++++++ .../tongtong/remotecompile/PrivateListText.kt | 7 + .../remotecompile/RemoteToolWindow.kt | 157 ++++++-- .../tongtong/remotecompile/ServerAdb.kt | 33 ++ .../tongtong/remotecompile/ServerErrors.kt | 1 + .../studio/tongtong/remotecompile/Settings.kt | 36 +- plugin/src/main/resources/META-INF/plugin.xml | 1 + .../tongtong/remotecompile/ApkFilesTest.kt | 25 ++ .../remotecompile/ApkNotificationsTest.kt | 22 ++ .../tongtong/remotecompile/GitBundlesTest.kt | 40 ++ .../remotecompile/PrivateListTextTest.kt | 18 + protocol/api.md | 23 ++ server/adb.go | 179 +++++++++ server/adb_test.go | 87 +++++ server/dedicated.go | 263 +++++++++++++ server/dedicated_test.go | 187 +++++++++ server/environment.go | 16 +- server/git_checkout.go | 86 +++++ server/git_checkout_test.go | 114 ++++++ server/main.go | 72 +++- server/preflight.go | 1 + server/private_files.go | 355 ++++++++++++++++++ server/private_files_test.go | 146 +++++++ server/sync_preflight.go | 56 +++ server/sync_preflight_test.go | 44 +++ server/workspace.go | 126 ++++++- server/workspace_files.go | 93 +++++ server/workspace_files_test.go | 36 ++ 44 files changed, 2742 insertions(+), 87 deletions(-) create mode 100644 docs/dedicated-workspaces.md create mode 100644 docs/private-files.md create mode 100644 docs/remote-adb.md create mode 100644 plugin/src/main/kotlin/studio/tongtong/remotecompile/ApkFiles.kt create mode 100644 plugin/src/main/kotlin/studio/tongtong/remotecompile/ApkNotifications.kt create mode 100644 plugin/src/main/kotlin/studio/tongtong/remotecompile/GitBundles.kt create mode 100644 plugin/src/main/kotlin/studio/tongtong/remotecompile/PrivateFilesEditor.kt create mode 100644 plugin/src/main/kotlin/studio/tongtong/remotecompile/PrivateListText.kt create mode 100644 plugin/src/main/kotlin/studio/tongtong/remotecompile/ServerAdb.kt create mode 100644 plugin/src/test/kotlin/studio/tongtong/remotecompile/ApkFilesTest.kt create mode 100644 plugin/src/test/kotlin/studio/tongtong/remotecompile/ApkNotificationsTest.kt create mode 100644 plugin/src/test/kotlin/studio/tongtong/remotecompile/GitBundlesTest.kt create mode 100644 plugin/src/test/kotlin/studio/tongtong/remotecompile/PrivateListTextTest.kt create mode 100644 server/adb.go create mode 100644 server/adb_test.go create mode 100644 server/dedicated.go create mode 100644 server/dedicated_test.go create mode 100644 server/git_checkout.go create mode 100644 server/git_checkout_test.go create mode 100644 server/private_files.go create mode 100644 server/private_files_test.go create mode 100644 server/sync_preflight.go create mode 100644 server/sync_preflight_test.go create mode 100644 server/workspace_files.go create mode 100644 server/workspace_files_test.go diff --git a/README.md b/README.md index fb13fc4..d01bfec 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ ZIP 输出在 `plugin/build/distributions/`。可用已安装的 Android Studio 3. adb 路径可留空,自动从项目 `local.properties` 的 SDK 或本机 SDK 环境定位。只有需要指定其他 SDK 时才填写完整路径。 4. 在底部 **Remote Compilation** 的设备下拉框选择 USB 手机、无线设备或模拟器。单台在线设备自动选中;列表每 5 秒刷新,也可手动刷新。未授权/离线设备显示状态,无法用于安装。 5. 点击顶部运行图标、底部 **Remote Run** 或 Tools → Remote Run,直接使用已保存配置构建。右侧齿轮只打开配置,不触发构建。 -6. 插件先保存文件,再同步并构建;APK 保存到项目 `.remotecompile/-.apk`。安装前再次检查目标设备,避免把包安装到其他设备。 +6. 插件先保存文件,再同步并构建;APK 保存到项目 `.remotecompile/<服务端原始文件名>.apk`(重名追加精确到秒的时间戳)。安装前再次检查目标设备,避免把包安装到其他设备。 插件目标基础平台为 243(2024.3),具体 Android Studio 版本仍需运行验证。本版不替换原生 Run/Debug,不接管本机 Gradle Sync。 @@ -108,3 +108,8 @@ Linux/macOS 在 `plugin/` 执行 `sh ./gradlew buildPlugin`。也可使用已安 服务端/插件0.4.8增加[目录与任务管理 CLI](docs/admin-cli.md):首次自动迁移已有授权到data/access.json,此后通过admin子命令添加或移除目录、精确任务和限定模块的assemble*规则,运行中自动读取,无需重新编译或重启。目录权限与systemd隔离仍需系统管理员配置。目录/任务未授权错误直接给出远程操作命令;404按接口、工程、构建和产物分别说明处理方式。 0.4.9 CLI自动定位本机安装的访问配置,常规命令可直接使用 `remotecompile admin root add <已有工程父目录>`、`remotecompile admin task add ":app:assemble*"`;不再默认当前目录data。多配置时要求显式选择,仍支持 --data/--access-file。新CLI兼容0.4.8服务,插件无需更新。 + +0.5.0新增[专用Git编译工作区](docs/dedicated-workspaces.md):本机提交通过不含文件blob的bundle导入,未提交修改仍按清单增量同步。原远端仓库只读初始化,后续无需pull配合构建。新插件与服务端需一起升级;签名辅助文件可由管理员显式配置,旧客户端保持旧流程。下载APK保留原名,重名追加到秒的时间戳,同一秒继续加序号。 + + +0.7.0支持在侧边栏维护[服务端私有文件清单](docs/private-files.md):IDE编辑路径清单、显式保存、检查并在构建前复制未跟踪的签名脚本和密钥文件。 diff --git a/client/remote_run.py b/client/remote_run.py index a8e7dc2..759efc9 100644 --- a/client/remote_run.py +++ b/client/remote_run.py @@ -4,10 +4,13 @@ import base64 import hashlib import json import os +import re from pathlib import Path import subprocess import ssl import time +import tempfile +from datetime import datetime import urllib.request import urllib.parse import uuid @@ -41,12 +44,16 @@ def main(): 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'}) + upload = body.open('rb') if isinstance(body, Path) else None + data = upload if upload else (json.dumps(body).encode() if body is not None else None) + headers = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/octet-stream' if upload else 'application/json'} + if upload: headers['Content-Length'] = str(body.stat().st_size) + req = urllib.request.Request(endpoint + '/api/v1' + path, data=data, method=method, headers=headers) context = ssl.create_default_context(cafile=args.server_cert) if args.server_cert else None - with urllib.request.urlopen(req, timeout=300, context=context) as response: - result = response.read() + try: + with urllib.request.urlopen(req, timeout=600, context=context) as response: result = response.read() + finally: + if upload: upload.close() return result if '/artifacts/' in path else json.loads(result) health = request('GET', '/health') @@ -59,16 +66,34 @@ def main(): state = json.loads(state_file.read_text()) if state_file.exists() else {} if state.get('url') != endpoint or state.get('remoteFolder') != args.remote_folder: state = {'url': endpoint, 'remoteFolder': args.remote_folder} - inspection = request('POST', '/projects/check', {'workspacePath': args.remote_folder, 'projectId': state.get('project', ''), 'git': local_git}) + dedicated = bool(local_git) + if dedicated and not health.get('dedicatedGit'): raise RuntimeError('Upgrade service to 0.5.0 for dedicated Git workspaces') + binding = {'workspacePath': args.remote_folder, 'projectId': state.get('project', ''), 'git': local_git, 'dedicated': dedicated} + inspection = request('POST', '/projects/check', binding) print('Git check: '+inspection['message'], flush=True) if not inspection['canSync']: raise RuntimeError(inspection['message']) paths = collect(source, local_git) - if not state.get('project'): - state['project'] = request('POST', '/projects', {'workspacePath': args.remote_folder, 'git': local_git})['id'] + if not state.get('project') or dedicated: + state['project'] = request('POST', '/projects', binding)['id'] state_file.write_text(json.dumps(state), encoding='utf-8') project = state['project'] - remote = request('GET', f'/projects/{project}/manifest')['files'] + remote_state = request('GET', f'/projects/{project}/manifest') + previous = (remote_state.get('git') or {}).get('head') + if dedicated and previous != local_git['head']: + def send_bundle(base): + with tempfile.TemporaryDirectory(prefix='remotecompile-bundle-') as directory: + bundle = Path(directory) / 'source.bundle' + command = ['git', '-C', str(source), 'bundle', 'create', '--version=3', str(bundle), 'HEAD', '--filter=blob:none'] + if base and subprocess.run(['git', '-C', str(source), 'merge-base', '--is-ancestor', base, local_git['head']], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0: command.append('^' + base) + subprocess.run(command, check=True, timeout=300, stdout=subprocess.DEVNULL) + if git_snapshot(source)['head'] != local_git['head']: raise RuntimeError('HEAD changed while creating bundle; retry') + request('POST', f'/projects/{project}/git?head=' + local_git['head'], bundle) + try: send_bundle(previous) + except urllib.error.HTTPError as error: + if previous and error.code == 400: send_bundle(None) + else: raise + remote = remote_state['files'] manifest = {} changed = 0 eol_only = 0 @@ -121,8 +146,18 @@ def main(): 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 + '-' + artifact['hash'] + '.apk') - destination.write_bytes(content) + filename = artifact.get('fileName') or (artifact.get('sourcePath') or artifact['name']).replace('\\', '/').split('/')[-1] + if not artifact.get('fileName') and not artifact.get('sourcePath'): + filename = re.sub(r'^\d+-', '', filename) + if re.match(r'(?i)^(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])(?:\.|$)', filename) or not filename.lower().endswith('.apk') or any(c in filename for c in '/\\:*?"<>|') or any(ord(c)<32 for c in filename): raise RuntimeError('Invalid APK filename') + stamp = datetime.now().strftime('%Y%m%d_%H%M%S'); attempt = 0 + while True: + name = filename if attempt == 0 else filename[:-4] + '_' + stamp + ('' if attempt == 1 else '_' + str(attempt)) + '.apk' + destination = output / name + try: + with destination.open('xb') as f: f.write(content) + break + except FileExistsError: attempt += 1 print(f'\nAPK: {destination}') if args.device: subprocess.run([args.adb, '-s', args.device, 'install', '-r', str(destination)], check=True, timeout=120) diff --git a/client/test_smoke.py b/client/test_smoke.py index 5af43d4..53a2955 100644 --- a/client/test_smoke.py +++ b/client/test_smoke.py @@ -54,7 +54,7 @@ class SmokeTest(unittest.TestCase): subprocess.run(['git', '-C', str(source), '-c', 'core.autocrlf=false', 'add', '.'], check=True, capture_output=True) subprocess.run(['git', '-C', str(source), '-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qm', 'base'], check=True, capture_output=True) subprocess.run(['git', 'clone', '--no-hardlinks', str(source), str(workspace)], check=True, capture_output=True) - command = [str(binary), '-workspace-root', str(workspaces), '-listen', f'127.0.0.1:{port}', '-data', str(root / 'data')] + command = [str(binary), '-workspace-root', str(workspaces), '-listen', f'127.0.0.1:{port}', '-data', str(root / '服务 数据')] context = None if secure: import ssl @@ -87,7 +87,10 @@ class SmokeTest(unittest.TestCase): self.assertEqual(first.returncode, 0, first.stderr) self.assertEqual(next((source / '.remotecompile').glob('*.apk')).read_bytes(), b'first\r\n') self.assertEqual((workspace / 'input.txt').read_bytes(), b'first\r\n') - self.assertRegex(first.stdout, r'skipped [1-9][0-9]* EOL-only files') + self.assertIn('专用编译工作区', first.stdout) + (source / 'input.txt').write_bytes(b'new committed content\n') + subprocess.run(['git','-C',str(source),'add','input.txt'],check=True,capture_output=True) + subprocess.run(['git','-C',str(source),'-c','user.name=Test','-c','user.email=test@example.invalid','commit','-qm','next local commit'],check=True,capture_output=True) (source / 'input.txt').write_bytes(b'second\n') (source / 'deleted.txt').unlink() second = subprocess.run(command, env=env, capture_output=True, text=True, timeout=120) @@ -95,11 +98,19 @@ class SmokeTest(unittest.TestCase): self.assertIn('Syncing 1 changed files', second.stdout) artifacts = [p.read_bytes() for p in (source / '.remotecompile').glob('*.apk')] self.assertCountEqual(artifacts, [b'first\r\n', b'second\n']) + names = sorted(p.name for p in (source / '.remotecompile').glob('*.apk')) + self.assertIn('app-debug.apk', names) + self.assertTrue(any(__import__('re').match(r'app-debug_\d{8}_\d{6}(?:_\d+)?\.apk$', name) for name in names)) state = json.loads((source / '.remotecompile' / 'client.json').read_text()) - self.assertFalse((workspace / 'deleted.txt').exists()) - self.assertFalse((workspace / 'ignored/private.txt').exists()) - self.assertFalse((workspace / 'app/.cxx/Debug/.ninja_deps').exists()) - self.assertTrue((workspace / '.git').exists()) + req = urllib.request.Request(endpoint + '/api/v1/projects/' + state['project'] + '/manifest', headers={'Authorization': 'Bearer ' + env['REMOTE_BUILD_TOKEN']}) + with urllib.request.urlopen(req, context=context, timeout=20) as response: + private = Path(json.load(response)['workspacePath']) + self.assertNotEqual(private, workspace) + self.assertFalse((private / 'deleted.txt').exists()) + self.assertTrue((workspace / 'deleted.txt').exists()) + self.assertFalse((private / 'ignored/private.txt').exists()) + self.assertFalse((private / 'app/.cxx/Debug/.ninja_deps').exists()) + self.assertTrue((private / '.git').exists()) if chosen_jdk: req = urllib.request.Request(endpoint + '/api/v1/projects/' + state['project'] + '/builds', headers={'Authorization': 'Bearer ' + env['REMOTE_BUILD_TOKEN']}) with urllib.request.urlopen(req, context=context, timeout=20) as response: diff --git a/docs/dedicated-workspaces.md b/docs/dedicated-workspaces.md new file mode 100644 index 0000000..edc9652 --- /dev/null +++ b/docs/dedicated-workspaces.md @@ -0,0 +1,56 @@ +# 专用 Git 编译工作区与 APK 命名(0.5.0) + +升级服务端和插件至0.5.0。已有连接地址、Token、JDK及工程来源目录继续使用;首次Remote Run会分配新工作区,并关联原工程的构建历史。旧工作区和APK记录保留,不自动清理原仓库中历史同步留下的修改。旧客户端仍走旧流程,应一起升级。 + +## 目录与提交 + +原配置目录(例如 E:\FLY\FLYSN)作为来源绑定和首次只读初始化目录。正常源码按原Git忽略及固定排除规则复制到 `/projects/<新projectId>/work`,不复制原Git目录、构建输出、IDE缓存或默认排除的密钥配置;没有Git的来源目录不做初始化拷贝,直接等待本机文件清单。之后不向原目录写源码或修改原Git索引。 + +本机提交不必push。插件传送Git bundle,再按完整文件清单增量覆盖本机未提交修改及删除。后续提交更新独立工作区的Git基线,无需在原目录pull。服务使用read-tree/update-ref管理元数据,不执行会清理工作区的reset/clean,保留私有.gradle、build及原有全局Gradle依赖缓存。首次迁移的项目编译缓存从新目录开始,依赖缓存、JDK、SDK配置不变。 + +bundle采用Git v3和blob:none过滤,只传提交/目录树元数据;源码内容始终经过原有忽略与凭据排除规则,不允许历史中的密钥blob绕过排除上传。增量bundle缺少前置提交时客户端回退完整元数据bundle。需要Git支持该bundle格式及过滤参数;浅克隆可能需要先补齐历史。说明参考[Git bundle文档](https://git-scm.com/docs/git-bundle)。 + +该私有.git是服务的版本元数据仓库,不含完整历史文件内容,不用于人工checkout/pull/diff开发。人工Git操作仍在原仓库进行。不同客户端分配独立工作区;同一客户端后续复用其projectId。 + +服务持续校验上次同步文件摘要及Git基线/索引。额外人工修改会被拦截。同步前记录仅含文件摘要的Pending日志并使旧revision失效,未完整提交的源码不能构建;重试只接受已知旧/目标内容,不覆盖额外改动。提交或bundle失败不会被当成成功构建。 + +## 服务端签名和辅助文件 + +绝对路径签名配置仍使用服务账户可访问的原路径。相对签名密钥、local.properties、HONOR证书等,不会通过普通源码同步默认复制;管理员可在原 `build-environment.json` 中显式增加 `workspaceFiles`: + +```json +{ + "workspaceFiles": { + "E:\\ZuoyePad\\MagicOSZuoyePadSN": { + "cer/HONOR.CER": "E:\\ZuoyePad\\cer\\HONOR.CER", + "work/app/signing.jks": "E:\\ServerKeys\\signing.jks" + } + } +} +``` + +将该字段合并到原配置,保留JDK、SDK、Gradle和代理字段。外层键为服务端原工程来源目录,目标相对于 `/projects/`。`cer/HONOR.CER` 对应工作区的 `../cer/HONOR.CER`;密钥目标按实际Gradle相对路径调整。来源必须为该服务器的绝对路径,服务账户需有读取权限。 + +只允许受限的密钥、证书、本机属性支持文件,禁止越界或写入.git/build等目录。证书应放work兄弟目录,密钥和本机属性位于work时继续由源码清单排除。首次初始化和每次构建前读取配置并复制,临时文件原子替换,不复制到客户端或Git历史。辅助文件上限16MiB;bundle上传上限1GiB,原HTTP源码请求上限保持不变。 + +## API与恢复兼容 + +- health返回dedicatedGit=true。 +- POST /projects/check 与 /projects 增加dedicated=true,workspacePath仍是原工程来源目录。旧projectId迁移成独立ID,旧构建历史通过legacyProject关联。 +- POST /projects/{id}/git?head= 接收application/octet-stream过滤bundle。导入不会切换HEAD或改工作文件,实际同步时才推进基线。 +- manifest返回专用work目录与上一已完成同步Git基线;后续源码同步、构建、SSE、恢复与下载接口保持原有流程。手动检查尚未初始化的工作区会提示首次运行后检查工具链,实际构建前仍强制预检查。 + +## APK下载 + +新产物字段fileName保存构建输出原始文件名,name继续作为内部下载标识。旧记录优先从sourcePath取得原名,没有路径时去掉服务端旧内部序号前缀。 + +APK仍保存于本机工程的.remotecompile目录:首次为 `app_debug.apk`,同名时为 `app_debug_20261126_123456.apk`,同一秒再次重名则为 `app_debug_20261126_123456_2.apk`。时间采用本机时区,精确到秒。通过排他创建保留已有文件,分片继续按buildId+hash隔离,校验通过后才发布。 + +last-build.json记录实际下载文件名,安装使用最后成功校验的文件;旧版buildId.apk与buildId-hash.apk仍可恢复安装。历史恢复和多APK选择也遵循同名处理规则,不覆盖旧包。 + + +## 0.5.1:同步前检查与下载通知 + +同步前检查返回phase=before-sync,缺少Wrapper只提示并允许源码同步补齐,权限/JDK等其他错误仍阻止同步。同步后的实际构建按原标准严格检查,报告phase=before-build;缺少Wrapper时说明必需文件、忽略规则来源及修复操作。必须保留gradlew、gradlew.bat、gradle/wrapper/gradle-wrapper.jar和gradle-wrapper.properties,不能用gradle/或gradlew*将其排除;.gradle/缓存继续排除。服务不会绕过.gitignore自动同步文件。 + +插件在成功构建的所选APK下载且摘要校验通过后发出Remote build completed通知,包括模块及构建变体;locate在资源管理器定位最终APK(包含重名时间戳),analyze通过IDE的文件打开机制打开同一个APK。普通Remote Run、恢复及单独下载均适用,下载失败不发成功通知。不要求连接设备;构建及下载成功与后续设备安装状态分开呈现。 diff --git a/docs/deployment-192.168.5.222.md b/docs/deployment-192.168.5.222.md index b5163f5..fc919bf 100644 --- a/docs/deployment-192.168.5.222.md +++ b/docs/deployment-192.168.5.222.md @@ -116,3 +116,36 @@ Get-Content 'C:\ProgramData\VibeCodingRemoteCompilation\logs\*.log' -Tail 30 ## 替换0.4.9(2026-11-25) Windows远端已替换0.4.9,备份原程序、XML和access.json。实际运行不带--data的admin task add :app:assembleDebug(幂等)成功自动定位原策略;LocalService继续可读,Automatic/Running。两个工程根目录、原任务和历史双APK构建保留;HTTPS、未知任务操作提示与401验证通过,没有触发业务构建。程序SHA-256:1bf8ef2990b1a37108718f3aa4f1903c24c2538362a05a54942604c1423cd57c。 + +## 全量部署0.4.10(2026-11-25) + +- Windows远端已升级0.4.10,程序、XML和access.json均已备份;保留TongTongStudio、ZuoyePad及用户新增FLY根目录、原任务和历史APK。服务Automatic/Running,CLI自动定位和HTTPS认证验证通过。 +- FLYSN原始同HEAD=53873943b2500cded6e5e0c6ce3901a8956361a0场景检查通过,UsageFragment.java的新摘要出现在manifest,旧revision失效,工具链/权限预检查通过;未同步或构建。 +- 验证期间本机FLYSN HEAD已变为51cf8340e8e0e8f56d0c14e5679fb1aa47aada14,远端仍为53873943b2500cded6e5e0c6ce3901a8956361a0,真实HEAD差异正确拦截。未自动pull/reset或改动源码和Git状态。 + + +## 升级0.5.0(2026-11-26) + +确认无活动构建后,校验新程序SHA-256,备份原程序和配置,替换并重启服务。HTTPS health已返回version=0.5.0、dedicatedGit=true;原目录授权、任务策略、历史成功构建及APK保留,认证401与非法任务拦截验证通过。未同步业务源码或触发构建。需配合0.5.0插件启用专用Git构建工作区;原工程目录及旧记录不会自动清理。相对签名/证书文件迁移参见dedicated-workspaces.md。 + + +## 2026-11-26 ZuoyePadOSHDOS专用工作区签名配置 + +原失败构建a4919bb8fcb8725b9fd085eb038ef1f8在validateSigningUiuiDebug阶段缺少app/keystore/tuixin.jks。服务端原工程已有该密钥,普通源码同步按设计排除密钥。已在build-environment.json中追加workspaceFiles映射:来源工程E:\ZuoyePad\ZuoyePadOSHDOS,目标work/app/keystore/tuixin.jks,来源E:\ZuoyePad\ZuoyePadOSHDOS\app\keystore\tuixin.jks。配置已备份且保留原ACL,按构建热加载,无需重启。密钥内容未读取到日志、未上传至本机,原工程及Gradle签名配置未修改。 + +同一已同步源码复测构建bfa423705656058e67c0c28390c7c5d0成功:BUILD SUCCESSFUL in 17s,131任务(6执行、125复用),产物app_debug.apk、53935696字节。服务账户已实际读取映射签名密钥并完成打包,未安装到设备。 + + +## 2026-11-26 升级0.5.1 + +已检查无活动构建、备份程序及配置并完成升级。保留服务账户、启动方式、目录授权、签名辅助文件映射、环境配置、历史成功构建及APK。HTTPS版本0.5.1、syncPreflight/dedicatedGit能力、401认证和任务白名单拦截验证通过。同步前缺Wrapper改为warning并允许同步补齐,实际构建检查保持严格;缺失提示增加必需文件与Git排除规则说明。没有同步或构建业务源码。 + + +## 2026-11-27 全量部署0.6.0 + +确认空闲后完成程序摘要校验、旧程序和配置备份及升级。服务正常运行,原账户、目录/任务授权、工具链、签名映射、Token/TLS和历史APK保持;HTTPS版本0.6.0、remoteADB能力、历史成功产物、认证及任务拦截验证通过。ADB设备接口和其401保护均已实测;仅列设备,未执行真实设备安装或业务构建。Windows远端和本机各发现2台在线设备;Ubuntu接口正常但当前0台设备。 + + +## 2026-11-27 全量部署0.7.0 + +确认空闲、校验SHA-256并备份旧程序和配置后完成升级。服务账户、启动方式、授权目录与任务、工具链、签名映射、TLS/Token及历史APK保留。HTTPS版本0.7.0及privateFileList能力、私有文件清单GET与401认证、ADB设备接口验证通过;未创建业务清单、同步源码、触发构建或向设备安装应用。插件侧边栏需安装0.7.0后使用。 diff --git a/docs/deployment-192.168.5.224.md b/docs/deployment-192.168.5.224.md index 1ef3724..edb3e3f 100644 --- a/docs/deployment-192.168.5.224.md +++ b/docs/deployment-192.168.5.224.md @@ -125,3 +125,27 @@ sudo systemctl restart remotecompile ## 替换0.4.9(2026-11-25) Ubuntu已替换0.4.9,备份位于 /opt/remotecompile/upgrade-0.4.9-20261125-160753。不带--data的sudo admin task add :app:assembleDebug成功自动定位原策略,文件所有者和权限保持,服务账户可读。两个工程根目录、原任务和成功APK保留;HTTPS和认证验证通过,没有触发业务构建。程序SHA-256:ba18296ae251fe9f918298245913506020fac5a98d98529ef322102d6a70ebf3。 + +## 全量部署0.4.10(2026-11-25) + +Ubuntu已升级0.4.10并验证active;CLI自动定位、原两个工程根目录、任务、历史成功APK和HTTPS认证均正常。原程序、配置和策略备份于 /opt/remotecompile/upgrade-0.4.10-20261125-180305;没有触发业务构建。 + + +## 升级0.5.0(2026-11-26) + +确认无活动构建后,校验新程序SHA-256,备份原程序和配置,替换并重启服务。HTTPS health已返回version=0.5.0、dedicatedGit=true;原目录授权、任务策略、历史成功构建及APK保留,认证401与非法任务拦截验证通过。未同步业务源码或触发构建。需配合0.5.0插件启用专用Git构建工作区;原工程目录及旧记录不会自动清理。相对签名/证书文件迁移参见dedicated-workspaces.md。 + + +## 2026-11-26 升级0.5.1 + +已检查无活动构建、备份程序及配置并完成升级。保留服务账户、启动方式、目录授权、签名辅助文件映射、环境配置、历史成功构建及APK。HTTPS版本0.5.1、syncPreflight/dedicatedGit能力、401认证和任务白名单拦截验证通过。同步前缺Wrapper改为warning并允许同步补齐,实际构建检查保持严格;缺失提示增加必需文件与Git排除规则说明。没有同步或构建业务源码。 + + +## 2026-11-27 全量部署0.6.0 + +确认空闲后完成程序摘要校验、旧程序和配置备份及升级。服务正常运行,原账户、目录/任务授权、工具链、签名映射、Token/TLS和历史APK保持;HTTPS版本0.6.0、remoteADB能力、历史成功产物、认证及任务拦截验证通过。ADB设备接口和其401保护均已实测;仅列设备,未执行真实设备安装或业务构建。Windows远端和本机各发现2台在线设备;Ubuntu接口正常但当前0台设备。 + + +## 2026-11-27 全量部署0.7.0 + +确认空闲、校验SHA-256并备份旧程序和配置后完成升级。服务账户、启动方式、授权目录与任务、工具链、签名映射、TLS/Token及历史APK保留。HTTPS版本0.7.0及privateFileList能力、私有文件清单GET与401认证、ADB设备接口验证通过;未创建业务清单、同步源码、触发构建或向设备安装应用。插件侧边栏需安装0.7.0后使用。 diff --git a/docs/deployment-local-windows.md b/docs/deployment-local-windows.md index a4fa288..f1da367 100644 --- a/docs/deployment-local-windows.md +++ b/docs/deployment-local-windows.md @@ -56,3 +56,27 @@ Get-Content 'C:\ProgramData\VibeCodingRemoteCompilation\logs\*.log' -Tail 50 ## 替换0.4.9(2026-11-25) 本机测试服务已替换0.4.9,旧程序/XML/access.json已备份;不带--data的CLI幂等写入成功,自动定位标准ProgramData策略。服务保持LocalService、Automatic/Running,localhost HTTPS、认证与历史成功APK验证通过,原授权不变。 + +## 全量部署0.4.10(2026-11-25) + +本机服务已升级0.4.10,保留LocalService、Automatic/Running、原策略和历史成功APK;CLI自动定位、localhost HTTPS和认证验证通过。未触发业务构建。 + + +## 2026-11-26 本机服务升级0.5.0 + +管理员升级已完成,程序SHA-256为6781d860591d7d67c9ab17d535e4846dd81fe75945540c7423bccaea5f1cc940。RemoteCompile保持Automatic/Running、LocalService;localhost HTTPS返回version=0.5.0、dedicatedGit=true。原目录授权、历史成功构建7ee80c8f3c78c6a3d0ccf4971ff342c9及APK均保留,401认证、任务白名单与CLI操作提示验证通过。旧程序及配置已备份,未触发业务构建或设备安装。三套服务至此均为0.5.0。 + + +## 2026-11-26 升级0.5.1 + +已检查无活动构建、备份程序及配置并完成升级。保留服务账户、启动方式、目录授权、签名辅助文件映射、环境配置、历史成功构建及APK。HTTPS版本0.5.1、syncPreflight/dedicatedGit能力、401认证和任务白名单拦截验证通过。同步前缺Wrapper改为warning并允许同步补齐,实际构建检查保持严格;缺失提示增加必需文件与Git排除规则说明。没有同步或构建业务源码。 + + +## 2026-11-27 全量部署0.6.0 + +确认空闲后完成程序摘要校验、旧程序和配置备份及升级。服务正常运行,原账户、目录/任务授权、工具链、签名映射、Token/TLS和历史APK保持;HTTPS版本0.6.0、remoteADB能力、历史成功产物、认证及任务拦截验证通过。ADB设备接口和其401保护均已实测;仅列设备,未执行真实设备安装或业务构建。Windows远端和本机各发现2台在线设备;Ubuntu接口正常但当前0台设备。 + + +## 2026-11-27 全量部署0.7.0 + +确认空闲、校验SHA-256并备份旧程序和配置后完成升级。服务账户、启动方式、授权目录与任务、工具链、签名映射、TLS/Token及历史APK保留。HTTPS版本0.7.0及privateFileList能力、私有文件清单GET与401认证、ADB设备接口验证通过;未创建业务清单、同步源码、触发构建或向设备安装应用。插件侧边栏需安装0.7.0后使用。 diff --git a/docs/private-files.md b/docs/private-files.md new file mode 100644 index 0000000..177af57 --- /dev/null +++ b/docs/private-files.md @@ -0,0 +1,37 @@ +# 私有文件清单(0.7.0) + +服务端与插件需升级0.7.0。右侧Remote Configuration增加私有文件清单的检查、IDE编辑、保存到服务端和重新读取入口。清单根据保存的服务地址及服务端工程来源目录定位,不必每个构建重复填写。 + +## 编辑与保存 + +1. 保存连接设置,选定服务端已有工程来源目录。 +2. 点击“编辑私有文件清单(IDE)”,在IDE文本编辑器中直接编辑。 +3. 每行一个工程内相对文件路径,路径分隔符使用/;空行和以#开头的注释行被忽略。 +4. 点击侧边栏“保存清单到服务端”。Ctrl+S仅保存IDE本地编辑副本,不上传;编辑后尚未上传时Remote Run会提醒先上传。 +5. 点击检查,确认每项存在且服务账户可读。缺失文件可以先保存清单,但检查/构建会明确失败,须先在服务器原工程目录补齐。 + +```text +# 来源为服务器原工程目录;不是本机目录 +config.gradle +app/keystore/tuixin.jks +signing.properties +``` + +不存在清单时允许普通构建,检查会提示可以创建。服务器保存于/private-files/<来源目录摘要>.txt,按工程来源目录绑定,Windows忽略来源路径大小写。IDE系统缓存仅保存文本清单,不包含私有文件内容或Token,不进入工程源码同步。 + +服务端同一来源目录的所有客户端共用该清单。保存使用上次读取的摘要比较,其他客户端已修改则返回冲突,防止覆盖。需要放弃本地修改时点击重新读取,会先询问是否替换。IDE重启后再次编辑会先备份不同的旧本地草稿。 + +## 构建行为 + +Git专用构建工作区每次构建前从服务端原工程目录复制清单中的文件到work中的相同相对位置,不要求Git跟踪或取消.gitignore排除。现有服务端workspaceFiles外部文件映射保持兼容。源文件内容不会经插件下载或上传,不写入Git历史,不改动原工程。 + +若某个路径已被普通源码同步管理,清单保存/构建会拒绝冲突;客户端同步请求也不能覆盖清单文件。请先在本机忽略相应文件,并重新同步移除其普通源码记录,再添加清单。工程外的共享密钥继续使用管理员显式workspaceFiles映射。 + +只允许普通文件,拒绝绝对路径、../、反斜杠、.git/缓存/构建目录、符号链接和路径重定向;单个文件上限16MiB,清单上限64KiB/256项。复制使用临时文件原子替换。移出清单后,只删除服务工作区中内容仍匹配上次摘要的私有副本;若已被人工修改则报错保留,来源目录始终不动。清单修改在关联工作区构建期间被拒绝,后续构建也会重新校验所有来源。 + +签名脚本中引用的密钥路径仍须在服务器有效。清单按相同相对路径复制,不会重写config.gradle里硬编码的本机盘符或绝对路径。建议脚本引用工程内的相对密钥路径。缺少签名配置时项目应明确报错,不应静默生成unsigned.apk。 + +本轮未自动部署,也未修改业务项目的签名配置;真实IDE编辑与业务签名构建待升级后验收。 + + +2026-11-27部署更新:三套服务已升级0.7.0并通过私有清单读取/认证与历史记录验收;没有自动创建业务清单,插件仍需安装0.7.0。 diff --git a/docs/remote-adb.md b/docs/remote-adb.md new file mode 100644 index 0000000..8c91284 --- /dev/null +++ b/docs/remote-adb.md @@ -0,0 +1,12 @@ +# 服务端ADB安装(0.6.0) + +需要同时升级服务端和插件至0.6.0。构建ID列新增“使用服务端 ADB 安装”选项,按工程保存;切换后左侧目标设备列表自动读取服务端设备,本机和远端选择分别记忆。连接设置中的构建后安装选项继续控制本机安装;勾选服务端模式即启用服务端安装。 + +Remote Run成功后选择APK,服务端直接安装自己保存的产物,不依赖APK先下载到本机;随后照常下载、校验、发通知。服务端无可用设备时仍编译下载,安装失败单独记录并继续下载,不自动卸载已有应用。右列“服务端安装 APK”可将填写的成功构建ID(留空使用上次记录)安装到选中设备,支持多产物选择,不必再次下载或重编译。“安装已下载 APK”按钮在服务端模式下同样转到服务端安装,避免混用本机设备。 + +服务端需要SDK platform-tools,可在build-environment.json设置adb绝对路径,或复用已有androidHome/platform-tools/adb(.exe)。设备必须在服务运行账户下完成USB授权;无线设备先在服务器完成adb pair/connect,插件列出已连接设备,不执行任意adb命令。Windows LocalService、Ubuntu专用服务账户的授权密钥与桌面登录用户不同,登录用户adb能看见设备不代表服务账户也能看见。 + +本轮只实现并打包,未部署服务或对真实设备安装;HTTP接口使用模拟ADB验证认证、明确序列号、失败构建/错误产物/离线/未授权拦截及APK防篡改。实际设备连接与IDE操作需要部署后验收。 + + +2026-11-27部署更新:三套服务均已升级0.6.0,设备读取API与认证已通过实际服务验证;Windows远端及本机各有2台在线设备,Ubuntu当前0台。未执行真实设备安装,IDE插件需用户安装0.6.0。 diff --git a/docs/verification.md b/docs/verification.md index d0bfb25..5a55917 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -70,3 +70,90 @@ Python CLI 使用新0.4.7服务二进制完成HTTP/HTTPS两项端到端回归, ## 2026-11-25 三套服务替换0.4.9 Windows192.168.5.222、Ubuntu192.168.5.224及localhost均已替换0.4.9。不带--data的CLI实际操作原策略成功,服务账户持续可读;根目录、任务、历史成功APK、HTTPS认证保护和简化管理员命令验证通过。没有新建业务构建或安装设备。此前未部署记录由本轮更新。 + +## 2026-11-25 Git提交更新后含未跟踪文档的误报修复(0.4.10) + +- 真实FLYSN场景:双方HEAD已经更新到53873943b2500cded6e5e0c6ce3901a8956361a0,服务保存的同步Git基线仍是d0d8ed583a4fb43dbb4aab6eff78335afe71efc2。远端已跟踪文件无修改,两个已在基线内且未改变的未跟踪Word文档使整体dirty=true。UsageFragment.java的当前文件、索引与当前HEAD的Git对象一致,CRLF规范化摘要与本机LF内容相同,但与旧同步基线不同。 +- 检查改为逐个验证发生差异的路径:实际文件Git规范化摘要及索引必须同时与当前匹配HEAD一致,才接受它是正常checkout内容。对旧提交跟踪、新提交已删除且工作区/索引都不存在的文件也允许重新同步;不静默重写保存的基线。 +- manifest对已恢复的当前提交文件暴露实际摘要,HEAD或源码变化使旧revision失效;syncBase包含已恢复的已跟踪文件,以便正常同步本机删除。旧revision仍不能直接构建。 +- 4项相关Windows原生测试通过,覆盖旧基线+未跟踪文档、HEAD前进、CRLF、恢复和删除、暂存修改、真实远端编辑、新增未跟踪文件、assume-unchanged隐藏改动及旧快照保护。Windows/Linux程序打包;修复尚未部署。远端只做只读检查,没有修改源码、Git索引、文档或同步元数据。 + +## 2026-11-25 三套服务部署0.4.10 + +192.168.5.222、192.168.5.224和localhost全部升级完成,授权、CLI自动定位、历史APK及认证验证通过。真实FLYSN原始同HEAD检查已通过,旧基线误报消除,新manifest可读且旧revision失效。本机随后新增提交51cf834,而远端仍5387394;该真实提交差异保持拦截。未同步源码、启动业务构建或修改Git状态。此前“修复尚未部署”记录由本轮更新。 + +## 2026-11-26 专用Git构建工作区与APK原名下载(0.5.0) + +- 服务端Windows原生完整测试通过,1项Unix权限测试因平台跳过;后续专用工作区专项回归通过。覆盖完整及增量metadata-only bundle、本机提交前进与未提交覆盖、原目录和Git索引不变、缓存保留、独立客户端、手动改动拦截、Pending重启恢复、旧构建历史关联及显式签名辅助文件。 +- 插件离线test/buildPlugin通过,共31项测试无失败,包含原名下载、秒级及同秒重名保留、非法文件名和无blob Git bundle。 +- Python参考客户端针对本机真实服务二进制的HTTP/HTTPS两项闭环测试通过,使用模拟Gradle验证提交前进、未提交覆盖、删除、CRLF保留、中文空格路径及APK重名;未执行实际业务Android编译或IDE交互安装。 +- Windows/Linux amd64二进制和插件0.5.0已打包。Linux仅交叉编译,尚未运行验证。本轮未部署、提交或推送;现有三套服务仍为0.4.10,需同时升级服务端与客户端。迁移及服务端签名文件映射见dedicated-workspaces.md。 + + +## 2026-11-26 远程服务器部署0.5.0 + +Windows192.168.5.222与Ubuntu192.168.5.224已升级0.5.0。Windows保持Automatic/Running、LocalService;Ubuntu保持active、remotecompile账户,备份位于/opt/remotecompile/upgrade-0.5.0-20261126-131439。两端HTTPS、dedicatedGit能力、原目录授权、任务白名单拦截、401及历史成功APK均验证通过;未触发业务构建或改动业务源码。本机实例另行记录。 + + +## 2026-11-26 本机服务升级0.5.0 + +管理员升级已完成,程序SHA-256为6781d860591d7d67c9ab17d535e4846dd81fe75945540c7423bccaea5f1cc940。RemoteCompile保持Automatic/Running、LocalService;localhost HTTPS返回version=0.5.0、dedicatedGit=true。原目录授权、历史成功构建7ee80c8f3c78c6a3d0ccf4971ff342c9及APK均保留,401认证、任务白名单与CLI操作提示验证通过。旧程序及配置已备份,未触发业务构建或设备安装。三套服务至此均为0.5.0。 + + +## 2026-11-26 0.5.1检查流程、通知及全量部署 + +同步前缺Wrapper降为可补齐提示,权限错误保留阻断;构建前检查不放宽。新增测试覆盖阶段、权限保留及真实git check-ignore规则说明。插件33项测试无失败,buildPlugin通过;新增通知覆盖根任务/子模块变体与HTML转义。下载校验完成后创建通知,locate调用系统文件定位,analyze调用IDE文件打开,实际Android Studio点击行为尚未人工验收。 + +Windows192.168.5.222、Ubuntu192.168.5.224和本机服务均已升级0.5.1,原配置及记录已备份保留。三端HTTPS、版本/能力、历史成功APK、原目录授权、401认证和非法任务拦截均通过。Windows保留用户新增E:\Aoleyun授权和tuixin密钥映射。真实Launcher项目只读检查返回ready=true、Gradle=warning、phase=before-sync,并准确显示.gitignore第14行gradle/与第16行gradlew*;未修改业务源码或触发构建。用户仍需调整本机忽略规则,插件安装0.5.1后使用下载通知。 + +服务端完整Windows原生回归最终通过(98.174s,Unix chmod测试按平台跳过1项)。沙箱运行的ACL/进程树假失败已在正常权限环境重跑验证;默认缓存异常后改用独立缓存完成。Linux二进制为交叉编译,远端已实际运行并完成HTTPS/API验收。 + + +## 2026-11-27 服务端ADB安装0.6.0 + +构建ID列新增按工程保存的服务端ADB安装模式与手动安装按钮,设备列表按模式切换,分别记住设备。构建后直接从服务器产物安装,再下载本机;无设备仍构建下载。安装失败与构建分开,恢复/手动下载不擅自安装旧包。安装已下载按钮在远端模式也转到服务端路径,避免将服务端设备序号用于本机ADB。 + +新增真实子进程模拟ADB测试通过,验证Bearer认证、具体设备参数、只接受成功构建记录产物、设备离线/未授权、篡改摘要与错误产物拒绝。长耗时ADB操作位于全局服务锁之外;有限输出、超时、串行安装。插件已编译测试通过,Windows/Linux二进制已生成。本轮未部署、未在真实设备安装、未做IDE手动点击验收。 + +完整Windows服务端回归通过(174.683s,Unix chmod项按平台跳过),包含新增ADB子进程测试及原同步、互斥、取消、产物与路径保护测试。Linux仅交叉编译,尚未运行验证。 + +最终插件增量test/buildPlugin成功(2m16s),33项测试无失败;已复制0.6.0 ZIP至dist。 + + +## 2026-11-27 三套服务部署0.6.0 + +Windows192.168.5.222、Ubuntu192.168.5.224与本机测试服务已升级0.6.0。Windows保持Automatic/Running、LocalService,Ubuntu保持active、remotecompile账户,Ubuntu备份/opt/remotecompile/upgrade-0.6.0-20261127-033535。三端HTTPS版本/remoteADB能力、原目录授权、历史成功APK、认证与任务规则验证通过。实际服务账户ADB devices接口:Windows远端2台在线、本机2台在线、Ubuntu0台;三端ADB接口未认证均401。未向真实设备安装应用。此前未部署记录由本轮更新;插件仍需安装0.6.0并重启Android Studio。 + + +## 2026-11-27 android_receiver签名诊断与插件0.6.1布局 + +失败构建5fd62a1136e904d7e85683f3c5745c41生成app-aosp-debug-unsigned.apk,ADB报INSTALL_PARSE_FAILED_NO_CERTIFICATES。本机.gitignore排除config.gradle;实际服务器专用工作区8d3cdd36342ca317341eff9b9e3250dd/work经只读确认config.gradle不存在。app/build.gradle.kts仅在文件存在时apply,aosp使用findByName(crosshatch),debug签名设null,使缺失签名配置静默变成unsigned输出。未修改业务项目、签名密钥或服务器配置;应在服务端提供正确的crosshatch签名配置和密钥,并将缺配置改为明确失败。 + +插件0.6.1将设备/构建ID、状态、变体标签/远端ADB选项、变体下拉框/服务端安装按钮改为共享行的等宽两列布局,避免JLabel与JCheckBox高度差及不同间距造成上下错位;其他按钮与进度布局保持。仅插件变化,不需服务重部署。 + +最终0.6.1离线buildPlugin通过(44s),已复制dist安装包;未在实际IDE中做视觉验收,未自动安装插件或重启IDE。 + + +## 2026-11-27 私有文件清单0.7.0 + +右侧连接设置新增按来源目录绑定的清单检查、IDE文本编辑、保存到服务端、重新读取功能。Ctrl+S仅保存本地草稿,侧边栏显式上传;Remote Run会阻止尚未上传的清单修改。列表文件按源路径摘要保存在服务数据private-files目录,PUT使用旧摘要防止覆盖其他编辑,并在同来源构建期间拒绝修改。接口只传路径和检查状态,不传私有文件内容。 + +构建前从原目录复制私有普通文件、限制越界/链接/目录/大小并保护源码清单冲突;独立摘要记录排除私有文件对源码版本的干扰,移除项仅在摘要一致时删除副本。原workspaceFiles映射保留,同目标不同来源明确拒绝。API专项测试覆盖缺失提示、并发编辑、构建中保存拒绝、普通同步不可覆盖、私有副本移除和人工修改保护;服务端完整Windows原生回归通过145.508s(Unix chmod项跳过),最终路径/映射/同步专项回归通过。插件33项测试无失败,最后UTF-8/换行适配后的buildPlugin通过48s。Windows/Linux二进制与插件ZIP已生成;Linux仅交叉编译,尚未运行验证。 + +本轮未部署、未推送或提交,未更改android_receiver等业务工程签名配置,未做实际IDE编辑点击或真实业务签名构建验收。使用方式见docs/private-files.md。 + + +## 2026-11-27 三套服务部署0.7.0 + +Windows192.168.5.222、Ubuntu192.168.5.224和本机服务均升级0.7.0。Windows保持Automatic/Running、LocalService,Ubuntu保持active、remotecompile。Ubuntu备份/opt/remotecompile/upgrade-0.7.0-20261127-042043。三套版本/能力、目录授权、历史成功APK、认证与任务规则保护均通过;私有文件清单读取、尚未创建清单提示和未认证401已实际验证,没有修改业务清单。ADB服务设备读取正常:Windows远端2台、本机2台在线,Ubuntu0台。未执行实际安装或业务构建,插件需用户安装0.7.0。此前未部署记录由本轮更新。 + + +## 2026-11-27 私有清单读锁与保存状态修复(插件0.7.1) + +用户在新版IDE中保存私有清单时FileDocumentManager.getDocument触发read-action断言。保存、重新读取比较及Remote Run前清单检查现已显式runReadAction读取文档和文本;编辑/保存入口通过Application.invokeLater调度到具有写意图的UI回调,不链接跨版本变化的WriteIntentReadAction.run。网络请求继续在后台执行。 + +同时修复上传前截取文本后IDE保存动作可能再去除行尾空格/添加换行的问题:保存文档后再读取上传文本,成功时以服务器回传内容更新基准。构建前按服务端实际消费的文件条目比较,忽略BOM、换行、空行、注释与首尾空白;路径增删改仍提示上传。新增回归测试覆盖格式差异不误报及实际文件变化仍拦截。前面的读锁异常会中断上传,本地Ctrl+S不代表服务端已保存。 + +仅插件变更,服务端0.7.0无需重部署;IDE实际点击保存及在用户当前IDE版本运行待安装后验收。 + +0.7.1离线test/buildPlugin成功(2m3s),共35项测试无失败;最终ZIP已复制到dist,未自动安装或重启IDE。 diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index 05aa335..87ebc18 100644 --- a/plugin/build.gradle.kts +++ b/plugin/build.gradle.kts @@ -3,7 +3,7 @@ plugins { id("org.jetbrains.intellij.platform") version "2.5.0" } group = "studio.tongtong" -version = "0.4.8" +version = "0.7.1" repositories { mavenCentral() intellijPlatform { defaultRepositories() } diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/ApkArtifacts.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/ApkArtifacts.kt index 5eeced8..634cc3b 100644 --- a/plugin/src/main/kotlin/studio/tongtong/remotecompile/ApkArtifacts.kt +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/ApkArtifacts.kt @@ -3,7 +3,7 @@ package studio.tongtong.remotecompile import com.google.gson.JsonObject import java.util.Locale -data class ApkArtifact(val name: String, val hash: String, val size: Long, val sourcePath: String) { +data class ApkArtifact(val name: String, val hash: String, val size: Long, val sourcePath: String, val fileName: String = sourcePath.substringAfterLast('/').replace(Regex("^\\d+-"), "")) { override fun toString() = "$sourcePath — ${String.format(Locale.ROOT, "%.1f", size / 1048576.0)} MiB ($name)" } @@ -11,7 +11,8 @@ object ApkArtifacts { fun read(result: JsonObject): List = result.getAsJsonArray("artifacts").map { value -> val item = value.asJsonObject ApkArtifact(item.get("name").asString, item.get("hash").asString, item.get("size").asLong, - item.get("sourcePath")?.asString ?: item.get("name").asString) + item.get("sourcePath")?.asString ?: item.get("name").asString, + item.get("fileName")?.asString ?: item.get("sourcePath")?.asString?.substringAfterLast('/') ?: item.get("name").asString.replace(Regex("^\\d+-"), "")) }.filter { it.name.endsWith(".apk", ignoreCase = true) }.onEach { require(it.hash.matches(Regex("[a-f0-9]{64}")) && it.size > 0) { "服务端 APK 摘要或大小无效:${it.name}" } } diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/ApkFiles.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/ApkFiles.kt new file mode 100644 index 0000000..a737ae2 --- /dev/null +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/ApkFiles.kt @@ -0,0 +1,29 @@ +package studio.tongtong.remotecompile + +import java.nio.file.* +import java.time.LocalDateTime +import java.time.format.DateTimeFormatter + +object ApkFiles { + fun validName(name: String): Boolean = name.endsWith(".apk", true) && + name.none { it < ' ' || it in "\\/:*?\"<>|" } && + !Regex("(?i)^(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])(?:\\.|$)").containsMatchIn(name) + + fun publish(part: Path, directory: Path, originalName: String, now: LocalDateTime = LocalDateTime.now()): Path { + require(validName(originalName)) { "无效的服务端 APK 文件名:$originalName" } + val stem = originalName.dropLast(4) + val stamp = now.format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + var attempt = 0 + while (true) { + val name = when (attempt) { 0 -> originalName; 1 -> "${stem}_$stamp.apk"; else -> "${stem}_${stamp}_${attempt}.apk" } + val target = directory.resolve(name) + val output = try { Files.newOutputStream(target, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE) } + catch (_: FileAlreadyExistsException) { attempt++; continue } + try { + output.use { out -> Files.newInputStream(part).use { it.transferTo(out) } } + } catch (e: Exception) { Files.deleteIfExists(target); throw e } + Files.delete(part) + return target + } + } +} diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/ApkNotifications.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/ApkNotifications.kt new file mode 100644 index 0000000..3dfd2e1 --- /dev/null +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/ApkNotifications.kt @@ -0,0 +1,37 @@ +package studio.tongtong.remotecompile + +import com.intellij.ide.actions.RevealFileAction +import com.intellij.notification.NotificationAction +import com.intellij.notification.NotificationGroupManager +import com.intellij.notification.NotificationType +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.fileEditor.FileEditorManager +import com.intellij.openapi.project.Project +import com.intellij.openapi.vfs.LocalFileSystem +import com.intellij.openapi.util.text.StringUtil +import java.nio.file.Path + +object ApkNotifications { + fun description(projectName: String, task: String): String { + val segments = task.split(':').filter { it.isNotBlank() } + val module = segments.dropLast(1).joinToString(".").ifBlank { "main" } + val variant = segments.lastOrNull().orEmpty().removePrefix("assemble").replaceFirstChar { it.lowercaseChar() } + return "Build completed successfully for module '${StringUtil.escapeXmlEntities(projectName)}.${StringUtil.escapeXmlEntities(module)}' with 1 build variant:
" + + "Build variant '${StringUtil.escapeXmlEntities(variant)}': locate or analyze the APK." + } + + fun show(project: Project, apk: Path, task: String) { + ApplicationManager.getApplication().invokeLater { + if (project.isDisposed) return@invokeLater + val notice = NotificationGroupManager.getInstance().getNotificationGroup("Remote Compilation Builds") + .createNotification("Remote build completed", description(project.name, task), NotificationType.INFORMATION) + notice.addAction(NotificationAction.createSimple("locate") { RevealFileAction.openFile(apk.toFile()) }) + notice.addAction(NotificationAction.createSimple("analyze") { + LocalFileSystem.getInstance().refreshAndFindFileByIoFile(apk.toFile())?.let { + FileEditorManager.getInstance(project).openFile(it, true) + } + }) + notice.notify(project) + } + } +} diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/GitBundles.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/GitBundles.kt new file mode 100644 index 0000000..b63a483 --- /dev/null +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/GitBundles.kt @@ -0,0 +1,21 @@ +package studio.tongtong.remotecompile + +import java.nio.file.Files +import java.nio.file.Path + +object GitBundles { + fun create(root: Path, head: String, base: String?): Path { + require(head.matches(Regex("[a-fA-F0-9]{40}|[a-fA-F0-9]{64}"))) { "本机 Git 提交无效" } + val directory = Files.createTempDirectory("remotecompile-bundle-") + val bundle = directory.resolve("source.bundle") + try { + val args = mutableListOf("bundle", "create", "--version=3", bundle.toString(), "HEAD", "--filter=blob:none") + if (!base.isNullOrBlank() && base != head && base.matches(Regex("[a-fA-F0-9]{40}|[a-fA-F0-9]{64}")) && + SourceFiles.git(root, listOf("merge-base", "--is-ancestor", base, head)).first == 0) args.add("^$base") + check(SourceFiles.git(root, args).first == 0) { "生成 Git bundle 失败;请确认提交和完整 Git 历史可用" } + check(SourceFiles.snapshot(root)?.head == head) { "生成 bundle 期间本机提交改变,请重试" } + return bundle + } catch (e: Exception) { Files.deleteIfExists(bundle); Files.deleteIfExists(directory); throw e } + } + fun delete(bundle: Path) { Files.deleteIfExists(bundle); Files.deleteIfExists(bundle.parent) } +} diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/LastBuild.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/LastBuild.kt index 0e333c4..22b5168 100644 --- a/plugin/src/main/kotlin/studio/tongtong/remotecompile/LastBuild.kt +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/LastBuild.kt @@ -4,7 +4,7 @@ import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption -data class LastBuild(var server: String = "", var projectId: String = "", var revision: String = "", var task: String = "", var clientRequestId: String = "", var buildId: String = "", var certificate: String = "", var artifactHash: String = "", var javaHome: String = "", var artifactName: String = "") +data class LastBuild(var server: String = "", var projectId: String = "", var revision: String = "", var task: String = "", var clientRequestId: String = "", var buildId: String = "", var certificate: String = "", var artifactHash: String = "", var javaHome: String = "", var artifactName: String = "", var artifactFile: String? = null) object LastBuildStore { private val gson = Gson() fun load(root: Path): LastBuild? { diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/PrivateFilesEditor.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/PrivateFilesEditor.kt new file mode 100644 index 0000000..ede58a8 --- /dev/null +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/PrivateFilesEditor.kt @@ -0,0 +1,149 @@ +package studio.tongtong.remotecompile + +import com.google.gson.Gson +import com.google.gson.JsonObject +import com.intellij.ide.passwordSafe.PasswordSafe +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.application.PathManager +import com.intellij.openapi.components.Service +import com.intellij.openapi.fileEditor.FileDocumentManager +import com.intellij.openapi.fileEditor.FileEditorManager +import com.intellij.openapi.project.Project +import com.intellij.openapi.vfs.LocalFileSystem +import com.intellij.openapi.vfs.VirtualFile +import com.intellij.openapi.util.Computable +import java.net.URI +import java.net.URLEncoder +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 javax.swing.JOptionPane + +@Service(Service.Level.PROJECT) +class PrivateFilesEditor(private val project: Project) { + private data class Session(val file: VirtualFile, var hash: String, var content: String) + private val sessions = mutableMapOf() + private val active = mutableSetOf() + private fun key(cfg: Settings.Data) = cfg.url.trim().trimEnd('/') + "\n" + cfg.remoteFolder.trim() + private fun call(cfg: Settings.Data, content: String? = null, hash: String = ""): JsonObject { + val base = cfg.url.trim().trimEnd('/') + validateEndpoint(base) + require(cfg.remoteFolder.isNotBlank()) { "请先填写并保存服务端工程来源目录" } + val secret = PasswordSafe.instance.getPassword(credentials(base)).orEmpty() + check(secret.isNotBlank()) { "请先保存服务器Token" } + val route = "/private-files" + if (content == null) "?workspacePath=" + URLEncoder.encode(cfg.remoteFolder.trim(), Charsets.UTF_8) else "" + val builder = HttpRequest.newBuilder(URI.create(base + "/api/v1" + route)).timeout(Duration.ofSeconds(60)) + .header("Authorization", "Bearer $secret").header("Content-Type", "application/json") + val req = if (content == null) builder.GET().build() else builder.PUT(HttpRequest.BodyPublishers.ofString(Gson().toJson( + mapOf("workspacePath" to cfg.remoteFolder.trim(), "content" to content, "baseHash" to hash)))).build() + val response = ServerTls.client(cfg.serverCertificate).send(req, HttpResponse.BodyHandlers.ofString()) + check(response.statusCode() in 200..299) { + if (response.statusCode() == 404) "服务端需升级至0.7.0以支持私有文件清单" else response.body().replace(secret, "***") + } + return Gson().fromJson(response.body(), JsonObject::class.java) + } + private fun describe(data: JsonObject): String = buildString { + append(data.get("message").asString) + append("\n清单位置:").append(data.get("manifestPath").asString) + data.getAsJsonArray("entries").forEach { + val entry = it.asJsonObject + append("\n[").append(entry.get("status").asString).append("] ") + .append(entry.get("path").asString).append(":").append(entry.get("message").asString) + } + } + fun check(cfg: Settings.Data, status: (String) -> Unit) = execute(cfg, status, { call(cfg) }) { status(describe(it)) } + + // Network requests run on a worker; model reads hold a read action. + private fun documentText(file: VirtualFile): String? = ApplicationManager.getApplication().runReadAction(Computable { + FileDocumentManager.getInstance().getDocument(file)?.text + }) + private fun onEditorThread(status: (String) -> Unit, action: () -> Unit) { + // invokeLater supplies write intent on modern IDEs; avoid linking the changing + // WriteIntentReadAction.run binary signature across Android Studio versions. + ApplicationManager.getApplication().invokeLater { + if (project.isDisposed) return@invokeLater + try { action() } catch (e: Exception) { status("清单编辑失败:${e.message}") } + } + } + fun edit(cfg: Settings.Data, status: (String) -> Unit, reload: Boolean = false) = + onEditorThread(status) { editOnEditorThread(cfg, status, reload) } + private fun editOnEditorThread(cfg: Settings.Data, status: (String) -> Unit, reload: Boolean) { + val key = key(cfg) + val existing = sessions[key] + if (existing != null && !reload) { + FileEditorManager.getInstance(project).openFile(existing.file, true) + status("已打开本地清单。修改后点击侧边栏“保存清单到服务端”;Ctrl+S只保存本地编辑副本。") + return + } + if (existing != null && reload) { + val current = documentText(existing.file) + if (current != existing.content && JOptionPane.showConfirmDialog(null, "重新读取会替换本地清单修改,是否继续?", "重新读取私有文件清单", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return + } + execute(cfg, status, { call(cfg) }) { data -> + val text = data.get("content").asString.replace("\r\n", "\n").replace('\r', '\n') + val id = MessageDigest.getInstance("SHA-256").digest(key.toByteArray()).joinToString("") { "%02x".format(it) } + val directory = Path.of(PathManager.getSystemPath(), "remotecompile-private-lists") + Files.createDirectories(directory) + val folder = directory.resolve(id) + Files.createDirectories(folder) + val path = folder.resolve("私有文件清单.txt") + // Keep a recoverable local draft when reopening after IDE restart. + if (existing == null && Files.exists(path) && Files.readString(path) != text) { + Files.copy(path, folder.resolve("私有文件清单.draft-${System.currentTimeMillis()}.txt")) + } + val initial = text.ifBlank { "# 每行一个相对于服务端工程来源目录的文件路径,使用 /\n# config.gradle\n# app/keystore/example.jks\n" } + ApplicationManager.getApplication().runWriteAction { + if (existing == null) Files.writeString(path, initial) + val file = existing?.file ?: LocalFileSystem.getInstance().refreshAndFindFileByIoFile(path.toFile()) ?: error("无法创建清单编辑副本") + file.charset = Charsets.UTF_8 + val document = FileDocumentManager.getInstance().getDocument(file) ?: error("无法打开清单文档") + document.setText(initial) + FileDocumentManager.getInstance().saveDocument(document) + sessions[key] = Session(file, data.get("hash").asString, initial) + FileEditorManager.getInstance(project).openFile(file, true) + } + status(describe(data) + "\n已在IDE打开;编辑后请点击“保存清单到服务端”。本地副本只包含路径,不包含签名文件内容。") + } + } + fun save(cfg: Settings.Data, status: (String) -> Unit) = + onEditorThread(status) { saveOnEditorThread(cfg, status) } + private fun saveOnEditorThread(cfg: Settings.Data, status: (String) -> Unit) { + val session = sessions[key(cfg)] ?: run { status("请先点击编辑私有文件清单"); return } + val document = ApplicationManager.getApplication().runReadAction(Computable { + FileDocumentManager.getInstance().getDocument(session.file) + }) ?: run { status("清单文档不可用,请重新编辑"); return } + FileDocumentManager.getInstance().saveDocument(document) + // IDE save actions may strip trailing spaces or add a final newline. + // Publish the document after those changes, never a pre-save snapshot. + val content = documentText(session.file) ?: run { status("清单文档不可用,请重新编辑"); return } + execute(cfg, status, { call(cfg, content, session.hash) }) { data -> + session.hash = data.get("hash").asString; session.content = data.get("content").asString + status("已保存到服务端;构建前会按清单复制文件。\n" + describe(data)) + } + } + fun requirePublished(cfg: Settings.Data) { + val key = key(cfg) + check(key !in active) { "私有文件清单操作仍在进行,请完成后再构建" } + sessions[key]?.let { session -> + val text = documentText(session.file) + check(text == null || PrivateListText.entries(text) == PrivateListText.entries(session.content)) { "私有文件清单已在IDE修改,请先点击侧边栏“保存清单到服务端”" } + } + } + private fun execute(cfg: Settings.Data, status: (String) -> Unit, work: () -> JsonObject, done: (JsonObject) -> Unit) { + val key = key(cfg) + if (!active.add(key)) { status("清单操作正在进行,请稍后"); return } + status("正在处理服务端私有文件清单…") + ApplicationManager.getApplication().executeOnPooledThread { + val result = runCatching(work) + ApplicationManager.getApplication().invokeLater { + active.remove(key) + if (project.isDisposed) return@invokeLater + try { result.fold(done) { status("私有文件清单操作失败:${it.message}") } } + catch (e: Exception) { status("清单编辑失败:${e.message}") } + } + } + } +} diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/PrivateListText.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/PrivateListText.kt new file mode 100644 index 0000000..5db3cee --- /dev/null +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/PrivateListText.kt @@ -0,0 +1,7 @@ +package studio.tongtong.remotecompile + +/** Compare the same effective paths that the server consumes, ignoring editor formatting. */ +object PrivateListText { + fun entries(text: String): List = text.removePrefix("\uFEFF").lineSequence() + .map(String::trim).filter { it.isNotEmpty() && !it.startsWith('#') }.toList() +} diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/RemoteToolWindow.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/RemoteToolWindow.kt index e99c4ef..9b7f0f5 100644 --- a/plugin/src/main/kotlin/studio/tongtong/remotecompile/RemoteToolWindow.kt +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/RemoteToolWindow.kt @@ -70,6 +70,7 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos private var discoveredTasks = emptyList() private val devices = JComboBox() private val refresh = JButton("刷新设备") + private val remoteAdb = JCheckBox("使用服务端 ADB 安装", settings.snapshot().remoteAdb).apply { toolTipText = "读取服务器设备;构建成功后由服务端直接安装 APK,同时保留本机下载" } private val deviceStatus = JLabel("正在读取本机设备…") private val refreshing = AtomicBoolean(false) private var updatingDevices = false @@ -102,10 +103,6 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos init { val configure = JButton("连接设置") val refreshTasks = JButton("刷新变体") - val variants = JPanel(BorderLayout(0, JBUI.scale(6))).apply { - add(JLabel("构建变体 / Gradle 任务"), BorderLayout.NORTH) - add(taskSelector, BorderLayout.CENTER) - } taskSelector.toolTipText = "选择任务或直接输入;自动记住最近 20 个任务" updateTaskChoices(settings.snapshot().task) taskSelector.addActionListener { @@ -116,7 +113,6 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos } refreshTasks.addActionListener { refreshTaskChoices(refreshTasks) } refreshTaskChoices(refreshTasks) - val top = JPanel(BorderLayout(0, JBUI.scale(6))).apply { add(JLabel("目标设备"), BorderLayout.NORTH); add(devices, 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 { @@ -127,6 +123,13 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos } devices.addActionListener { if (!updatingDevices) (devices.selectedItem as? AdbDevice)?.takeIf { it.online }?.let { settings.selectDevice(it.serial) } } refresh.addActionListener { refreshDevices() } + remoteAdb.addActionListener { + if (busy) { remoteAdb.isSelected = settings.snapshot().remoteAdb; return@addActionListener } + settings.selectRemoteAdb(remoteAdb.isSelected) + updatingDevices = true; devices.removeAllItems(); updatingDevices = false + deviceStatus.text = if (remoteAdb.isSelected) "正在读取服务端设备…" else "正在读取本机设备…" + refreshDevices() + } configure.addActionListener { ToolWindowManager.getInstance(project).getToolWindow("Remote Configuration")?.show() } val history = JButton("构建历史").apply { addActionListener { showHistory() } } val installLast = JButton("安装已下载 APK").apply { addActionListener { installDownloaded() } } @@ -143,7 +146,6 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER }, BorderLayout.CENTER) } - top.minimumSize = JBUI.size(0, 0) devices.minimumSize = JBUI.size(0, 24) taskSelector.minimumSize = JBUI.size(0, 24) fun column(vararg parts: JComponent) = JPanel().apply { @@ -156,14 +158,27 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos add(part) } } - val buildIdentity = JPanel(BorderLayout(0, JBUI.scale(6))).apply { - add(JLabel("构建 ID"), BorderLayout.NORTH) - add(buildIdField, BorderLayout.CENTER) - add(JLabel("留空找回上次构建"), BorderLayout.SOUTH) - } - val headings = JPanel(java.awt.GridLayout(1, 2, JBUI.scale(8), 0)).apply { - add(JPanel(BorderLayout()).apply { add(column(top, variants), BorderLayout.NORTH) }) - add(JPanel(BorderLayout()).apply { add(buildIdentity, BorderLayout.NORTH) }) + // Both columns share the same rows, including the differently sized label/checkbox. + val headings = JPanel(java.awt.GridBagLayout()).apply { + fun cell(component: JComponent, x: Int, y: Int, gap: Int) { + component.minimumSize = JBUI.size(0, component.minimumSize.height) + component.preferredSize = java.awt.Dimension(0, component.preferredSize.height) + add(component, java.awt.GridBagConstraints().apply { + gridx = x; gridy = y; weightx = 1.0 + fill = java.awt.GridBagConstraints.BOTH + insets = JBUI.insets(gap, if (x == 0) 0 else 4, 0, if (x == 0) 4 else 0) + }) + } + cell(JLabel("目标设备"), 0, 0, 0) + cell(JLabel("构建 ID"), 1, 0, 0) + cell(devices, 0, 1, 6) + cell(buildIdField, 1, 1, 6) + cell(deviceStatus, 0, 2, 6) + cell(JLabel("留空找回上次构建"), 1, 2, 6) + cell(JLabel("构建变体 / Gradle 任务"), 0, 3, 10) + cell(remoteAdb, 1, 3, 10) + cell(taskSelector, 0, 4, 6) + cell(JButton("服务端安装 APK").apply { addActionListener { installServerBuild() } }, 1, 4, 6) } val actions = JPanel(java.awt.GridLayout(0, 2, JBUI.scale(8), JBUI.scale(6))).apply { add(refreshTasks); add(resume) @@ -227,12 +242,12 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos 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)) } + val result = runCatching { if (cfg.remoteAdb) ServerAdb.devices(cfg) else AdbDevices.list(AdbDevices.resolve(Path.of(project.basePath ?: error("项目路径不存在")), cfg.adb)) } ApplicationManager.getApplication().invokeLater { try { - if (!disposed && !project.isDisposed) { + if (!disposed && !project.isDisposed && settings.snapshot().let { it.remoteAdb == cfg.remoteAdb && it.url == cfg.url }) { val found = result.getOrDefault(emptyList()) - val previous = (devices.selectedItem as? AdbDevice)?.serial ?: settings.snapshot().device + val previous = (devices.selectedItem as? AdbDevice)?.serial ?: (if (cfg.remoteAdb) cfg.remoteDevice else cfg.device) if ((0 until devices.itemCount).map { devices.getItemAt(it) } != found) { updatingDevices = true try { @@ -240,7 +255,7 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos devices.selectedItem = AdbDevices.choose(found, previous) } finally { updatingDevices = false } } - deviceStatus.text = result.exceptionOrNull()?.message ?: if (found.isEmpty()) "没有检测到设备;请连接手机或启动模拟器" else "${found.count { it.online }} 台可用设备;可自动识别插拔" + deviceStatus.text = result.exceptionOrNull()?.message ?: if (found.isEmpty()) "没有检测到设备;请连接手机或启动模拟器" else "${if (cfg.remoteAdb) "服务端" else "本机"} ${found.count { it.online }} 台可用设备;可自动识别插拔" } } finally { refreshing.set(false) } } @@ -292,6 +307,7 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos settings.selectTask(selectedTask) updateTaskChoices(selectedTask) val cfg = settings.snapshot() + project.getService(PrivateFilesEditor::class.java).requirePublished(cfg) val base = cfg.url.trim().trimEnd('/') validateEndpoint(base) require(cfg.remoteFolder.isNotBlank()) { "请在 Remote Configuration 中填写服务端已有工程文件夹,并点击检查远程工程" } @@ -307,27 +323,36 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos secret = PasswordSafe.instance.getPassword(credentials(base)) ?: "" check(secret.length >= 24) { "请在右侧 Remote Configuration 中保存服务 Token" } append("构建任务:${cfg.task}") + append("安装位置:${if (cfg.remoteAdb) "服务端 ADB" else "本机 ADB"}") append(if (selected?.online == true) "目标设备:$selected" else "当前没有选中的在线设备;继续远程编译并下载 APK") val health = json(base, secret, "GET", "/health") check(health.get("recovery")?.asBoolean == true) { "编译服务需升级到 0.2.0 才支持任务找回与环境复用" } check(health.get("textComparison")?.asBoolean == true && health.get("jdkSelection")?.asBoolean == true) { "编译服务需升级到 0.4.0 才支持换行比较及 JDK 选择" } check(health.get("workspaceSelection")?.asBoolean == true) { "编译服务需升级到 0.3.0 才支持工程目录与 Git 检查" } val localGit = SourceFiles.snapshot(source) - val checkBody = mapOf("workspacePath" to cfg.remoteFolder, "projectId" to cfg.projectId, "git" to localGit, "javaHome" to cfg.remoteJavaHome) + val dedicated = localGit != null + if (dedicated) check(health.get("dedicatedGit")?.asBoolean == true) { "服务端需升级至0.5.0以支持专用Git工作区" } + val checkBody = mapOf("workspacePath" to cfg.remoteFolder, "projectId" to cfg.projectId, "git" to localGit, "javaHome" to cfg.remoteJavaHome, "dedicated" to dedicated) val inspection = json(base, secret, "POST", "/projects/check", checkBody) append("远程位置:${inspection.get("workspacePath").asString}") - append("Git 检查:${inspection.get("message").asString};本机=$localGit;服务端=${inspection.get("git")}") + append("Git 检查:${inspection.get("message").asString};本机=$localGit;编译工作区基线=${inspection.get("git")}") check(inspection.get("canSync").asBoolean) { inspection.get("message").asString } inspection.getAsJsonObject("preflight")?.let { report -> append(PreflightChecks.describe(report)) check(report.get("ready").asBoolean) { "远程环境检查未通过,请处理上方错误后重试" } } val candidates = SourceFiles.collect(source, localGit) - if (cfg.projectId.isBlank()) { + if (cfg.projectId.isBlank() || dedicated) { cfg.projectId = json(base, secret, "POST", "/projects", checkBody).get("id").asString settings.projectAllocated(base, cfg.projectId, cfg.remoteFolder) } - val manifest = json(base, secret, "GET", "/projects/${cfg.projectId}/manifest").getAsJsonObject("files") + val remoteState = json(base, secret, "GET", "/projects/${cfg.projectId}/manifest") + if (dedicated) { + val previousHead = remoteState.getAsJsonObject("git")?.get("head")?.asString + if (previousHead != localGit!!.head) uploadGitBundle(base, secret, cfg.projectId, source, localGit.head, previousHead) + append("专用编译工作区:${remoteState.get("workspacePath").asString}") + } + val manifest = remoteState.getAsJsonObject("files") val files = linkedMapOf>() var changed = 0; var lineEndingsOnly = 0 for (path in candidates) { @@ -361,9 +386,14 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos val result = watchBuild(base, secret, activeBuild) buildSucceeded = true append("构建已成功,正在选择和下载 APK") - val output = downloadApk(base, secret, activeBuild, source, result) + val chosen = selectArtifact(source, activeBuild, result) + if (cfg.remoteAdb) { + try { installServer(cfg, activeBuild, chosen, selected) } + catch (e: Exception) { append("构建成功,服务端安装未完成:${e.message};产物保留,可稍后点击服务端安装 APK") } + } + val output = downloadApk(base, secret, activeBuild, source, result, chosen) check(!cancelRequested) { "已取消安装" } - if (cfg.install) { + if (cfg.install && !cfg.remoteAdb) { try { installApkWhenAvailable(source, cfg, selected, output) } catch (e: Exception) { append("编译和下载已成功,安装未完成:${e.message ?: e.javaClass.simpleName};APK 已保留,可稍后点击安装已下载 APK") @@ -380,6 +410,23 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos } }.queue() } + private fun uploadGitBundle(base: String, secret: String, projectId: String, source: Path, head: String, previous: String?) { + fun send(baseHead: String?) { + append("正在生成提交元数据 bundle(不包含文件内容)…") + val bundle = GitBundles.create(source, head, baseHead) + try { + append("上传 Git 提交 $head,bundle ${Files.size(bundle)} 字节") + val req = HttpRequest.newBuilder(URI.create("$base/api/v1/projects/$projectId/git?head=$head")) + .header("Authorization", "Bearer $secret").header("Content-Type", "application/octet-stream") + .timeout(Duration.ofMinutes(10)).POST(HttpRequest.BodyPublishers.ofFile(bundle)).build() + val response = http.send(req, HttpResponse.BodyHandlers.ofString()) + check(response.statusCode() == 200) { ServerErrors.describe(response.statusCode(), "/projects/$projectId/git", response.body()) } + } finally { GitBundles.delete(bundle) } + } + try { send(previous) } catch (e: Exception) { + if (!previous.isNullOrBlank() && e.message.orEmpty().startsWith("HTTP 400:")) { append("增量bundle不可用,重试完整提交历史"); send(null) } else throw e + } + } private fun installApkWhenAvailable(source: Path, cfg: Settings.Data, selected: AdbDevice?, output: Path) { val adb = AdbDevices.resolve(source, cfg.adb) val connected = AdbDevices.list(adb) @@ -437,18 +484,18 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos Thread.sleep(1000) } } - private fun downloadApk(base: String, secret: String, id: String, source: Path, result: JsonObject): Path { + private fun selectArtifact(source: Path, id: String, result: JsonObject): ApkArtifact { require(id.matches(Regex("[a-f0-9]{32}"))) { "无效构建 ID" } val artifacts = ApkArtifacts.read(result) check(artifacts.isNotEmpty()) { "成功构建没有可下载的 APK" } val previous = LastBuildStore.load(source)?.takeIf { it.buildId == id }?.artifactName val artifact = if (artifacts.size == 1) artifacts.single() else { - append("构建生成 ${artifacts.size} 个 APK,请选择要下载的完整安装包;其他产物保留在服务端") + append("构建生成 ${artifacts.size} 个 APK,请选择要使用的完整安装包;其他产物保留在服务端") var chosen: ApkArtifact? = null ApplicationManager.getApplication().invokeAndWait { if (!disposed && !project.isDisposed) { chosen = JOptionPane.showInputDialog(this, - "选择要下载的 APK;不同渠道或签名包请按实际用途选择。\n拆分 APK 需成套安装,当前不支持自动安装拆分包。", + "选择要使用的 APK;不同渠道或签名包请按实际用途选择。\n拆分 APK 需成套安装,当前不支持自动安装拆分包。", "选择构建产物", JOptionPane.QUESTION_MESSAGE, null, artifacts.toTypedArray(), artifacts.firstOrNull { it.name == previous } ?: artifacts.first()) as? ApkArtifact } @@ -456,11 +503,14 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos chosen ?: error("已取消选择 APK;构建已成功,产物仍保留,可点击下载 APK 重新选择") } append("选择 APK:$artifact") + return artifact + } + private fun downloadApk(base: String, secret: String, id: String, source: Path, result: JsonObject, selectedArtifact: ApkArtifact? = null): Path { + val artifact = selectedArtifact ?: selectArtifact(source, id, result) val expected = artifact.hash val size = artifact.size - val output = source.resolve(".remotecompile/$id-$expected.apk"); Files.createDirectories(output.parent) - if (Files.exists(output) && fileHash(output) == expected) { rememberArtifact(source, id, expected, artifact.name); append("复用已下载 APK:$output"); return output } - val part = output.resolveSibling("$id-$expected.apk.part") + val directory = source.resolve(".remotecompile"); Files.createDirectories(directory) + val part = directory.resolve("$id-$expected.apk.part") var received = if (Files.exists(part)) Files.size(part) else 0L if (received > size) { Files.delete(part); received = 0 } if (received < size) { @@ -487,15 +537,49 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos } } check(Files.size(part) == size && fileHash(part) == expected) { Files.deleteIfExists(part); "APK 校验失败,已清理损坏分片" } - Files.move(part, output, java.nio.file.StandardCopyOption.REPLACE_EXISTING) - rememberArtifact(source, id, expected, artifact.name) - showProgress("APK 下载完成", 100); append("APK 已保存:$output"); return output + val output = ApkFiles.publish(part, directory, artifact.fileName) + rememberArtifact(source, id, expected, artifact.name, output.fileName.toString()) + showProgress("APK 下载完成", 100); append("APK 已保存:$output") + ApkNotifications.show(project, output, result.get("task")?.asString.orEmpty()) + return output } - private fun rememberArtifact(source: Path, id: String, expected: String, name: String) { - LastBuildStore.load(source)?.takeIf { it.buildId == id }?.let { it.artifactHash = expected; it.artifactName = name; LastBuildStore.save(source, it) } + private fun rememberArtifact(source: Path, id: String, expected: String, name: String, file: String) { + LastBuildStore.load(source)?.takeIf { it.buildId == id }?.let { it.artifactHash = expected; it.artifactName = name; it.artifactFile = file; LastBuildStore.save(source, it) } + } + private fun installServer(cfg: Settings.Data, id: String, artifact: ApkArtifact, device: AdbDevice?) { + if (device?.online != true) { append("未选择在线服务端设备;跳过安装,继续下载 APK"); return } + append("正在使用服务端 ADB 安装到:$device") + append(ServerAdb.install(cfg, id, artifact.name, device.serial)) + append("服务端安装成功:${artifact.fileName}") + } + private fun installServerBuild() { + if (busy) return + val cfg = settings.snapshot() + if (!cfg.remoteAdb) { append("请先勾选使用服务端 ADB 安装,并选择服务端设备"); return } + val selected = devices.selectedItem as? AdbDevice + if (selected?.online != true) { append("请选择在线且已授权的服务端设备"); return } + val source = project.basePath?.let { Path.of(it) } ?: return + val id = buildIdField.text.trim().ifBlank { LastBuildStore.load(source)?.buildId.orEmpty() } + if (!id.matches(Regex("[a-f0-9]{32}"))) { append("请填写成功构建 ID 或先运行构建"); return } + busy = true; run.isEnabled = false + object : Task.Backgroundable(project, "服务端安装 APK", false) { + override fun run(indicator: ProgressIndicator) { + var secret = "" + try { + val base = cfg.url.trim().trimEnd('/') + http = ServerTls.client(cfg.serverCertificate) + secret = PasswordSafe.instance.getPassword(credentials(base)).orEmpty() + val result = json(base, secret, "GET", "/builds/$id") + check(result.get("status").asString == "success") { "该构建尚未成功" } + installServer(cfg, id, selectArtifact(source, id, result), selected) + } catch (e: Exception) { append("服务端安装失败:${e.message}".let { if (secret.isNotEmpty()) it.replace(secret, "***") else it }) } + finally { busy = false; ApplicationManager.getApplication().invokeLater { if (!disposed && !project.isDisposed) run.isEnabled = true } } + } + }.queue() } private fun installDownloaded() { if (busy) return + if (settings.snapshot().remoteAdb) { installServerBuild(); return } val source = project.basePath?.let { Path.of(it) } ?: return val record = try { LastBuildStore.load(source) ?: error("没有已下载构建记录") } catch (e: Exception) { append(e.message ?: "读取记录失败"); return } @@ -506,7 +590,8 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos override fun run(indicator: ProgressIndicator) { try { val selectedOutput = source.resolve(".remotecompile/${record.buildId}-${record.artifactHash}.apk") - val output = if (Files.isRegularFile(selectedOutput)) selectedOutput else source.resolve(".remotecompile/${record.buildId}.apk") + val recorded = record.artifactFile?.let { require(ApkFiles.validName(it)) { "保存的 APK 文件名无效" }; source.resolve(".remotecompile").resolve(it) } + val output = recorded ?: if (Files.isRegularFile(selectedOutput)) selectedOutput else source.resolve(".remotecompile/${record.buildId}.apk") check(Files.isRegularFile(output) && fileHash(output) == record.artifactHash) { "已下载 APK 缺失或校验失败,请重新下载" } val adb = AdbDevices.resolve(source, cfg.adb) val target = AdbDevices.choose(AdbDevices.list(adb), explicit?.serial ?: cfg.device, explicit != null) diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/ServerAdb.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/ServerAdb.kt new file mode 100644 index 0000000..e5a9ce4 --- /dev/null +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/ServerAdb.kt @@ -0,0 +1,33 @@ +package studio.tongtong.remotecompile + +import com.google.gson.Gson +import com.google.gson.JsonObject +import com.intellij.ide.passwordSafe.PasswordSafe +import java.net.URI +import java.net.http.HttpRequest +import java.net.http.HttpResponse +import java.time.Duration + +object ServerAdb { + private fun call(cfg: Settings.Data, route: String, body: Any? = null): JsonObject { + val base = cfg.url.trim().trimEnd('/') + validateEndpoint(base) + val token = PasswordSafe.instance.getPassword(credentials(base)).orEmpty() + check(token.isNotBlank()) { "请先保存服务器 Token" } + val builder = HttpRequest.newBuilder(URI.create("$base/api/v1/adb/$route")) + .header("Authorization", "Bearer $token").header("Content-Type", "application/json") + .timeout(if (body == null) Duration.ofSeconds(25) else Duration.ofMinutes(4)) + val req = if (body == null) builder.GET().build() else builder.POST(HttpRequest.BodyPublishers.ofString(Gson().toJson(body))).build() + val response = ServerTls.client(cfg.serverCertificate).send(req, HttpResponse.BodyHandlers.ofString()) + check(response.statusCode() in 200..299) { + if (response.statusCode() == 404) "服务端需升级至 0.6.0 才支持远程 ADB" else response.body().replace(token, "***") + } + return Gson().fromJson(response.body(), JsonObject::class.java) + } + fun devices(cfg: Settings.Data): List = call(cfg, "devices").getAsJsonArray("devices").map { + val d = it.asJsonObject + AdbDevice(d.get("serial").asString, d.get("state").asString, d.get("model")?.asString.orEmpty()) + } + fun install(cfg: Settings.Data, buildId: String, artifact: String, serial: String): String = + call(cfg, "install", mapOf("buildId" to buildId, "artifact" to artifact, "serial" to serial)).get("output").asString +} diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/ServerErrors.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/ServerErrors.kt index f81ed3a..5be0566 100644 --- a/plugin/src/main/kotlin/studio/tongtong/remotecompile/ServerErrors.kt +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/ServerErrors.kt @@ -4,6 +4,7 @@ object ServerErrors { fun describe(status: Int, route: String, body: String): String { val detail = body.trim().take(4000) val help = when { + detail.contains("unknown field \"dedicated\"") -> "请将服务端升级至0.5.0,新插件需要专用Git工作区接口。" status == 401 -> "请重新保存该服务器的 Token,再重试。" status == 404 && route == "/health" -> "未找到编译服务的健康接口。请核对服务器地址和端口,连接地址不要重复填写 /api/v1;在远程 Windows 管理员 PowerShell 执行 Get-Service RemoteCompile,Linux 执行 sudo systemctl status remotecompile。" diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/Settings.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/Settings.kt index 492a741..eb17486 100644 --- a/plugin/src/main/kotlin/studio/tongtong/remotecompile/Settings.kt +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/Settings.kt @@ -20,7 +20,7 @@ import javax.swing.event.DocumentListener class ConnectionDefaults : PersistentStateComponent { @Volatile private var data = Settings.Data() @Synchronized override fun getState() = data.copy() - @Synchronized override fun loadState(state: Settings.Data) { data = state.copy(projectId = "", device = "", remoteFolder = "", remoteJavaHome = "", taskHistory = mutableListOf()) } + @Synchronized override fun loadState(state: Settings.Data) { data = state.copy(projectId = "", device = "", remoteAdb = false, remoteDevice = "", remoteFolder = "", remoteJavaHome = "", taskHistory = mutableListOf()) } } @State(name = "RemoteCompilation", storages = [Storage("remote-compilation.xml")]) @@ -36,6 +36,8 @@ class Settings : PersistentStateComponent { var taskHistory: MutableList = mutableListOf(), var adb: String = "", var device: String = "", + var remoteAdb: Boolean = false, + var remoteDevice: String = "", var install: Boolean = false, var serverCertificate: String = "", var configured: Boolean = false @@ -44,7 +46,7 @@ class Settings : PersistentStateComponent { private fun defaults() = ApplicationManager.getApplication()?.getService(ConnectionDefaults::class.java) @Synchronized fun snapshot(): Data { val shared = if (!data.configured) defaults()?.getState() else null - return if (shared?.configured == true) shared.copy(projectId = data.projectId, device = data.device, remoteFolder = data.remoteFolder, remoteJavaHome = data.remoteJavaHome, taskHistory = data.taskHistory.toMutableList()) else data.copy() + return if (shared?.configured == true) shared.copy(remoteAdb = data.remoteAdb, remoteDevice = data.remoteDevice, projectId = data.projectId, device = data.device, remoteFolder = data.remoteFolder, remoteJavaHome = data.remoteJavaHome, taskHistory = data.taskHistory.toMutableList()) else data.copy() } @Synchronized override fun getState(): Data = data.copy() @Synchronized override fun loadState(state: Data) { @@ -54,7 +56,7 @@ class Settings : PersistentStateComponent { } @Synchronized fun saveConfiguration(next: Data, preserveTask: Boolean = false) { val current = snapshot() - data = next.copy(task = if (preserveTask) current.task else next.task, projectId = if (current.url == next.url && current.remoteFolder == next.remoteFolder) current.projectId else "", device = current.device, taskHistory = current.taskHistory.toMutableList(), configured = true) + data = next.copy(task = if (preserveTask) current.task else next.task, projectId = if (current.url == next.url && current.remoteFolder == next.remoteFolder) current.projectId else "", remoteAdb = current.remoteAdb, remoteDevice = if (current.url == next.url) current.remoteDevice else "", device = current.device, taskHistory = current.taskHistory.toMutableList(), configured = true) defaults()?.loadState(data) } @Synchronized fun selectTask(task: String) { @@ -62,7 +64,8 @@ class Settings : PersistentStateComponent { val current = snapshot() data = current.copy(task = task, taskHistory = (listOf(task) + current.taskHistory).distinct().take(20).toMutableList(), configured = true) } - @Synchronized fun selectDevice(serial: String) { data = data.copy(device = serial) } + @Synchronized fun selectDevice(serial: String) { data = if (snapshot().remoteAdb) data.copy(remoteDevice = serial) else data.copy(device = serial) } + @Synchronized fun selectRemoteAdb(enabled: Boolean) { data = snapshot().copy(remoteAdb = enabled, configured = true) } @Synchronized fun projectAllocated(url: String, id: String, remoteFolder: String = snapshot().remoteFolder) { val current = snapshot() if (current.url == url && current.remoteFolder == remoteFolder) data = current.copy(projectId = id, configured = true) @@ -105,11 +108,30 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL private var tokenRequest = 0 init { val fields = JPanel(GridLayout(0, 1, 0, 5)) - listOf("服务地址" to url, "Token(留空保留)" to token, "服务端已有工程文件夹(必填绝对路径)" to remoteFolder, + listOf("服务地址" to url, "Token(留空保留)" to token, "服务端工程来源目录(必填;Git工程只读初始化)" to remoteFolder, "adb 路径(留空自动使用项目 SDK)" to adb).forEach { (label, field) -> fields.add(JLabel(label)); fields.add(field) } val browse = JButton("选择服务端文件夹…") browse.addActionListener { browseRemoteFolder("") } fields.add(browse) + fields.add(JLabel("私有文件清单(按服务端工程来源目录绑定)")) + fun privateAction(action: String) { + val cfg = settings.snapshot() + if (cfg.url.trim().trimEnd('/') != url.text.trim().trimEnd('/') || cfg.remoteFolder != remoteFolder.text.trim() || cfg.serverCertificate != certificate.text.trim()) { + checkResult.text = "请先保存连接设置,再操作该工程的私有文件清单"; return + } + val editor = project.getService(PrivateFilesEditor::class.java) + val report: (String) -> Unit = { if (!project.isDisposed) checkResult.text = it } + when (action) { + "check" -> editor.check(cfg, report) + "edit" -> editor.edit(cfg, report) + "save" -> editor.save(cfg, report) + "reload" -> editor.edit(cfg, report, reload = true) + } + } + listOf("检查私有文件清单" to "check", "编辑私有文件清单(IDE)" to "edit", "保存清单到服务端" to "save", "重新读取服务端清单" to "reload").forEach { (label, action) -> + fields.add(JButton(label).apply { addActionListener { privateAction(action) } }) + } + fields.add(JLabel("构建变体请在构建日志面板左侧选择")) fields.add(JLabel("服务端 JDK(按工程保存)")); fields.add(jdks) val refreshJdks = JButton("检测服务端 JDK(where / 安装目录)") @@ -279,14 +301,14 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL val local = SourceFiles.snapshot(source) val body = mapOf("workspacePath" to folder, "git" to local, "projectId" to (if (saved.url == base && saved.remoteFolder == folder) saved.projectId else ""), - "javaHome" to selectedJavaHome) + "javaHome" to selectedJavaHome, "dedicated" to (local != null)) val req = java.net.http.HttpRequest.newBuilder(java.net.URI.create(base + "/api/v1/projects/check")) .timeout(java.time.Duration.ofSeconds(90)).header("Authorization", "Bearer $secret") .header("Content-Type", "application/json").POST(java.net.http.HttpRequest.BodyPublishers.ofString(com.google.gson.Gson().toJson(body))).build() val response = ServerTls.client(cert).send(req, java.net.http.HttpResponse.BodyHandlers.ofString()) check(response.statusCode() == 200) { ServerErrors.describe(response.statusCode(), "/projects/check", response.body()) } val remote = com.google.gson.Gson().fromJson(response.body(), com.google.gson.JsonObject::class.java) - "${remote.get("message").asString}\n服务端位置:${remote.get("workspacePath").asString}\n本机 Git:$local\n服务端 Git:${remote.get("git")}\n${PreflightChecks.describe(remote.getAsJsonObject("preflight"))}\n(上游差异使用已有本地引用,检查不会 fetch/pull,也不会修改文件)" + "${remote.get("message").asString}\n服务端位置:${remote.get("workspacePath").asString}\n本机 Git:$local\n编译工作区基线:${remote.get("git")}\n${PreflightChecks.describe(remote.getAsJsonObject("preflight"))}\n(上游差异使用已有本地引用,检查不会 fetch/pull,也不会修改文件)" }.getOrElse { (it.message ?: it.javaClass.simpleName).let { message -> if (secret.isEmpty()) message else message.replace(secret, "***") } } ApplicationManager.getApplication().invokeLater { if (!project.isDisposed) { checkRemote.isEnabled = true; checkResult.text = result } } } diff --git a/plugin/src/main/resources/META-INF/plugin.xml b/plugin/src/main/resources/META-INF/plugin.xml index 530da08..0ee00a6 100644 --- a/plugin/src/main/resources/META-INF/plugin.xml +++ b/plugin/src/main/resources/META-INF/plugin.xml @@ -5,6 +5,7 @@ Sync local Android source to a trusted build service, download APK and install with local adb. com.intellij.modules.platform + diff --git a/plugin/src/test/kotlin/studio/tongtong/remotecompile/ApkFilesTest.kt b/plugin/src/test/kotlin/studio/tongtong/remotecompile/ApkFilesTest.kt new file mode 100644 index 0000000..90b228e --- /dev/null +++ b/plugin/src/test/kotlin/studio/tongtong/remotecompile/ApkFilesTest.kt @@ -0,0 +1,25 @@ +package studio.tongtong.remotecompile + +import org.junit.Assert.* +import org.junit.Test +import java.nio.file.Files +import java.time.LocalDateTime + +class ApkFilesTest { + @Test fun preserveNameAndNeverOverwriteSameSecondCollisions() { + val root = Files.createTempDirectory("apk-files-test") + try { + val now = LocalDateTime.of(2026, 11, 26, 12, 34, 56) + val names = (0..2).map { n -> + val part = root.resolve("$n.part"); Files.writeString(part, "apk$n") + ApkFiles.publish(part, root, "应用-debug.apk", now).fileName.toString() + } + assertEquals(listOf("应用-debug.apk", "应用-debug_20261126_123456.apk", "应用-debug_20261126_123456_2.apk"), names) + names.forEachIndexed { index, name -> assertEquals("apk$index", Files.readString(root.resolve(name))) } + } finally { Files.walk(root).use { paths -> paths.sorted(Comparator.reverseOrder()).forEach { Files.delete(it) } } } + } + @Test fun rejectUnsafeFileNames() { + listOf("../x.apk", "C:\\x.apk", "CON.apk", "x.apk/other.apk", "x\n.apk").forEach { assertFalse(ApkFiles.validName(it)) } + assertTrue(ApkFiles.validName("app_debug.apk")) + } +} diff --git a/plugin/src/test/kotlin/studio/tongtong/remotecompile/ApkNotificationsTest.kt b/plugin/src/test/kotlin/studio/tongtong/remotecompile/ApkNotificationsTest.kt new file mode 100644 index 0000000..8f40ea7 --- /dev/null +++ b/plugin/src/test/kotlin/studio/tongtong/remotecompile/ApkNotificationsTest.kt @@ -0,0 +1,22 @@ +package studio.tongtong.remotecompile + +import org.junit.Assert.* +import org.junit.Test + +class ApkNotificationsTest { + @Test fun describesRootAndModuleVariants() { + val root = ApkNotifications.description("酷比桌面", ":assembleAospWithoutQuickstepTDT65Release") + assertTrue(root.contains("酷比桌面.main")) + assertTrue(root.contains("aospWithoutQuickstepTDT65Release")) + val app = ApkNotifications.description("Project", ":app:assembleUiuiDebug") + assertTrue(app.contains("Project.app")) + assertTrue(app.contains("uiuiDebug")) + assertTrue(app.contains("locate or analyze")) + } + + @Test fun escapesNotificationHtml() { + val text = ApkNotifications.description("", ":assembleDebug") + assertFalse(text.contains(" paths.sorted(Comparator.reverseOrder()).forEach { it.toFile().setWritable(true); Files.delete(it) } } } + } +} diff --git a/plugin/src/test/kotlin/studio/tongtong/remotecompile/PrivateListTextTest.kt b/plugin/src/test/kotlin/studio/tongtong/remotecompile/PrivateListTextTest.kt new file mode 100644 index 0000000..6a211b5 --- /dev/null +++ b/plugin/src/test/kotlin/studio/tongtong/remotecompile/PrivateListTextTest.kt @@ -0,0 +1,18 @@ +package studio.tongtong.remotecompile + +import org.junit.Assert.* +import org.junit.Test + +class PrivateListTextTest { + @Test fun saveFormattingDoesNotMakePublishedListDirty() { + val saved = "\uFEFF# private files\r\nconfig.gradle \r\n\r\n app/key.jks\r\n" + val formatted = "# updated comment\nconfig.gradle\napp/key.jks" + assertEquals(PrivateListText.entries(saved), PrivateListText.entries(formatted)) + } + @Test fun actualFileChangesStillRequireUpload() { + val saved = PrivateListText.entries("config.gradle\napp/key.jks\n") + assertNotEquals(saved, PrivateListText.entries("config.gradle\napp/other.jks\n")) + assertNotEquals(saved, PrivateListText.entries("config.gradle\n")) + assertNotEquals(saved, PrivateListText.entries("config.gradle\napp/key.jks\nlocal.properties")) + } +} diff --git a/protocol/api.md b/protocol/api.md index 197eb78..ad2b10d 100644 --- a/protocol/api.md +++ b/protocol/api.md @@ -99,3 +99,26 @@ artifacts 的每一项包含 name(下载接口标识)、hash(SHA-256)、 ## 访问管理(0.4.8) health新增adminCLI=true;不提供远程HTTP管理写入。服务首次启动将原有目录和任务参数保存到data/access.json,此后该文件是授权来源,每次请求加载;CLI写入采用文件锁及原子替换。未授权目录/任务仍返回400文本,包含该服务器实际可执行文件和data路径的admin命令;配置不可读或损坏返回503并拒绝新请求。任务规则支持精确名称及限定assemble系列的尾部星号,实际请求仍只允许一个符合safeTask的任务名。目录边界、同步锁和源码校验不变。详见docs/admin-cli.md。 + +## 专用Git工作区(0.5.0) + +WorkspaceRequest增加dedicated布尔值;新Git客户端使用true,workspacePath只作原目录绑定与只读初始化。Project增加dedicated、legacyProject、pending;实际私有目录为data/projects/id/work。新增POST /projects/{id}/git?head=<提交OID>,以application/octet-stream上传Git v3 blob:none过滤bundle,要求认证及项目锁,最大1GiB。接收后校验前置提交与HEAD,导入提交/树对象,工作树在完整清单同步时才更新。pending仅持久化摘要,失败源码不具有可构建revision。Artifact增加fileName原始名称;内部name和下载URL保持兼容。详见docs/dedicated-workspaces.md。 + + +0.5.1:health增加syncPreflight=true。已初始化工作区的检查返回preflight.phase=before-sync,缺失Wrapper暂作warning允许同步,其他错误仍拦截。实际构建前再次严格检查,phase=before-build;缺失工具提示忽略规则及修复步骤。接口请求格式不变,旧0.5.0插件可使用服务端修复。 + + +## 0.6.0 服务端ADB安装 + +health增加remoteADB=true,现有Bearer认证及HTTPS配置适用。 + +- GET /api/v1/adb/devices:返回devices数组,各项serial/state/model;列出服务账户执行adb可见的设备,不读取客户端设备。 +- POST /api/v1/adb/install:请求{"buildId":"构建ID","artifact":"产物内部name","serial":"设备序列号"}。只接受已成功构建的保存APK并校验大小和SHA-256,重新确认设备在线且已授权,调用adb -s install -r <产物路径>。不提供任意命令或客户端文件路径接口。成功返回success/serial/output;失败400、离线或产物校验失败409。安装串行互斥,执行上限3分钟,不占用构建服务全局锁;超时或连接断开时结果未确认,不自动重试或卸载。 +- build-environment.json可配置adb可执行文件绝对路径;留空优先AndroidHome/platform-tools,其次服务账户PATH。不会自动下载安装SDK,也不会共享交互用户的ADB授权密钥。服务器设备需在服务账户运行的ADB实例中授权;无线设备需先在服务器端完成连接/配对。 + + +## 0.7.0 私有文件清单 + +health增加privateFileList=true。GET /api/v1/private-files?workspacePath=<服务端来源目录>返回workspacePath/manifestPath/exists/content/hash/ready/message/entries(path,status,message)。PUT同一路径,请求workspacePath/content/baseHash;乐观并发冲突或同来源正在构建返回409,非法清单400,仍要求Bearer认证及工程根目录授权。保存允许文件暂时缺失,响应ready=false逐项说明;实际构建则拒绝。此接口只操作路径清单,不返回私有文件内容。 + +Project持久化privateFiles摘要用于区分普通源码与私有文件和安全清理;同步清单与私有路径冲突则拒绝。构建前在源工程内读取并复制,参见docs/private-files.md。 diff --git a/server/adb.go b/server/adb.go new file mode 100644 index 0000000..56216a8 --- /dev/null +++ b/server/adb.go @@ -0,0 +1,179 @@ +package main + +import ( + "bytes" + "context" + "fmt" + "net/http" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "sync" + "time" +) + +type adbDevice struct { + Serial string `json:"serial"` + State string `json:"state"` + Model string `json:"model"` +} + +var adbInstallLock sync.Mutex + +func parseADBDevices(output string) []adbDevice { + devices := []adbDevice{} + for _, line := range strings.Split(output, "\n") { + fields := strings.Fields(line) + if len(fields) < 2 || (fields[1] != "device" && fields[1] != "offline" && fields[1] != "unauthorized") { + continue + } + d := adbDevice{Serial: fields[0], State: fields[1]} + for _, field := range fields[2:] { + if strings.HasPrefix(field, "model:") { + d.Model = strings.ReplaceAll(strings.TrimPrefix(field, "model:"), "_", " ") + } + } + devices = append(devices, d) + } + return devices +} + +type adbOutput struct{ bytes.Buffer } + +func (b *adbOutput) Write(p []byte) (int, error) { + n := len(p) + left := 64*1024 - b.Len() + if left > 0 { + if left > n { + left = n + } + _, _ = b.Buffer.Write(p[:left]) + } + return n, nil +} + +func (s *Server) adbCommand(ctx context.Context, args ...string) (string, error) { + cfg, e := s.buildEnvironment() + if e != nil { + return "", e + } + binary := cfg.Adb + if binary == "" { + name := "adb" + if runtime.GOOS == "windows" { + name += ".exe" + } + if cfg.AndroidHome != "" { + candidate := filepath.Join(cfg.AndroidHome, "platform-tools", name) + if st, e := os.Stat(candidate); e == nil && !st.IsDir() { + binary = candidate + } + } + if binary == "" { + binary, e = exec.LookPath(name) + if e != nil { + return "", fmt.Errorf("服务账户找不到adb:请安装SDK platform-tools,或在build-environment.json的adb字段配置可执行文件绝对路径") + } + } + } + cmd := exec.CommandContext(ctx, binary, args...) + var output adbOutput + cmd.Stdout = &output + cmd.Stderr = &output + e = cmd.Run() + if ctx.Err() != nil { + return output.String(), fmt.Errorf("服务端adb超时或请求取消;安装结果尚未确认,请检查设备") + } + if e != nil { + return output.String(), fmt.Errorf("服务端adb失败:%w;%s", e, output.String()) + } + return output.String(), nil +} + +func (s *Server) serveADB(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/adb/devices" && r.Method == "GET" { + ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) + defer cancel() + out, e := s.adbCommand(ctx, "devices", "-l") + if e != nil { + http.Error(w, e.Error(), 400) + return + } + jsonOut(w, map[string]any{"devices": parseADBDevices(out)}) + return + } + if r.URL.Path != "/api/v1/adb/install" || r.Method != "POST" { + http.NotFound(w, r) + return + } + var req struct { + BuildID string `json:"buildId"` + Artifact string `json:"artifact"` + Serial string `json:"serial"` + } + if e := decode(w, r, &req); e != nil { + http.Error(w, e.Error(), 400) + return + } + if req.Serial == "" || strings.HasPrefix(req.Serial, "-") || strings.ContainsAny(req.Serial, " \t\r\n\x00") { + http.Error(w, "请选择服务端在线且已授权的设备", 400) + return + } + s.mu.Lock() + b := s.builds[req.BuildID] + var chosen *Artifact + if b != nil && b.Status == "success" { + for _, a := range b.Artifacts { + if a.Name == req.Artifact && strings.HasSuffix(strings.ToLower(a.Name), ".apk") { + v := a + chosen = &v + break + } + } + } + s.mu.Unlock() + if chosen == nil { + http.Error(w, "只能安装成功构建中已保存的APK,请选择正确的构建及产物", 400) + return + } + if !adbInstallLock.TryLock() { + http.Error(w, "服务端正在安装,请稍后重试", 409) + return + } + defer adbInstallLock.Unlock() + ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute) + defer cancel() + out, e := s.adbCommand(ctx, "devices", "-l") + if e != nil { + http.Error(w, e.Error(), 400) + return + } + online := false + for _, d := range parseADBDevices(out) { + if d.Serial == req.Serial && d.State == "device" { + online = true + } + } + if !online { + http.Error(w, "所选服务端设备已离线或未授权,请刷新设备列表;不会自动安装到其他设备", 409) + return + } + path := filepath.Join(s.root, "artifacts", req.BuildID, chosen.Name) + data, e := os.ReadFile(path) + if e != nil || int64(len(data)) != chosen.Size || digest(data) != chosen.Hash { + http.Error(w, "服务端APK缺失或摘要校验失败,请重新构建", 409) + return + } + out, e = s.adbCommand(ctx, "-s", req.Serial, "install", "-r", path) + if e != nil { + http.Error(w, e.Error(), 400) + return + } + if !strings.Contains(out, "Success") { + http.Error(w, "ADB未确认安装成功:"+out, 400) + return + } + jsonOut(w, map[string]any{"success": true, "serial": req.Serial, "output": out}) +} diff --git a/server/adb_test.go b/server/adb_test.go new file mode 100644 index 0000000..d3cfff4 --- /dev/null +++ b/server/adb_test.go @@ -0,0 +1,87 @@ +package main + +import ( + "bytes" + "encoding/json" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestServerADBTargetsStoredArtifactAndAuthorizedDevice(t *testing.T) { + root := t.TempDir() + helper := filepath.Join(root, "adb-helper.go") + exe := filepath.Join(root, "adb-helper") + if runtime.GOOS == "windows" { + exe += ".exe" + } + writeFixture(t, helper, `package main +import("os";"fmt";"encoding/json") +func main(){ f,_:=os.OpenFile(os.Getenv("ADB_TEST_LOG"),os.O_CREATE|os.O_APPEND|os.O_WRONLY,0600);json.NewEncoder(f).Encode(os.Args[1:]);f.Close();if os.Args[1]=="devices"{fmt.Println("List of devices attached\nremote-123 device model:Remote_Tablet\nlocked unauthorized")}else{fmt.Println("Success")} } +`) + cmd := exec.Command("go", "build", "-o", exe, helper) + if out, e := cmd.CombinedOutput(); e != nil { + t.Fatalf("helper: %v %s", e, out) + } + log := filepath.Join(root, "calls.jsonl") + t.Setenv("ADB_TEST_LOG", log) + cfg := filepath.Join(root, "env.json") + data, _ := json.Marshal(BuildEnvironment{Adb: exe}) + writeFixture(t, cfg, string(data)) + bid := strings.Repeat("a", 32) + content := []byte("apk-fixture") + a := Artifact{Name: "0-app.apk", Size: int64(len(content)), Hash: digest(content)} + s := &Server{root: root, token: "secret", environmentFile: cfg, builds: map[string]*Build{bid: {ID: bid, Status: "success", Artifacts: []Artifact{a}}}} + apk := filepath.Join(root, "artifacts", bid, a.Name) + writeFixture(t, apk, string(content)) + call := func(route, method, token string, body any) *httptest.ResponseRecorder { + b, _ := json.Marshal(body) + req := httptest.NewRequest(method, "/api/v1/adb/"+route, bytes.NewReader(b)) + req.Header.Set("Authorization", "Bearer "+token) + w := httptest.NewRecorder() + s.ServeHTTP(w, req) + return w + } + if w := call("devices", "GET", "wrong", nil); w.Code != 401 { + t.Fatal(w.Code) + } + if w := call("devices", "GET", "secret", nil); w.Code != 200 || !strings.Contains(w.Body.String(), "Remote Tablet") { + t.Fatal(w.Code, w.Body.String()) + } + request := map[string]string{"buildId": bid, "artifact": a.Name, "serial": "remote-123"} + if w := call("install", "POST", "secret", request); w.Code != 200 { + t.Fatal(w.Code, w.Body.String()) + } + raw, _ := os.ReadFile(log) + if !strings.Contains(string(raw), `["-s","remote-123","install","-r",`) { + t.Fatal(string(raw)) + } + for _, serial := range []string{"locked", "missing", "-d"} { + request["serial"] = serial + if w := call("install", "POST", "secret", request); w.Code == 200 { + t.Fatal("accepted unauthorized/missing serial", serial) + } + } + request["serial"] = "remote-123" + writeFixture(t, apk, "tampered") + if w := call("install", "POST", "secret", request); w.Code != 409 { + t.Fatal(w.Code, w.Body.String()) + } + request["artifact"] = "../foreign.apk" + if w := call("install", "POST", "secret", request); w.Code != 400 { + t.Fatal(w.Code) + } + raw, _ = os.ReadFile(log) + if strings.Count(string(raw), `"install"`) != 1 { + t.Fatal("unexpected additional install", string(raw)) + } + s.builds[bid].Status = "failed" + request["artifact"] = a.Name + if w := call("install", "POST", "secret", request); w.Code != 400 { + t.Fatal(w.Code) + } +} diff --git a/server/dedicated.go b/server/dedicated.go new file mode 100644 index 0000000..467f30d --- /dev/null +++ b/server/dedicated.go @@ -0,0 +1,263 @@ +package main + +import ( + "bufio" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "time" +) + +type PendingSync struct { + Files map[string]File `json:"files"` +} + +func (s *Server) createDedicated(w http.ResponseWriter, req WorkspaceRequest) { + if req.Git == nil || !gitObjectID.MatchString(req.Git.Head) { + http.Error(w, "专用工作区需要有效Git提交", 400) + return + } + path, e := s.validateWorkspace(req.WorkspacePath) + if e != nil { + http.Error(w, e.Error(), 400) + return + } + if pr := s.projects[req.ProjectID]; pr != nil && pr.Dedicated { + if !sameAccessValue(pr.WorkspacePath, path) { + http.Error(w, "工程绑定目录不匹配", 409) + return + } + jsonOut(w, map[string]string{"id": req.ProjectID, "workspacePath": path, "buildWorkspace": s.work(req.ProjectID)}) + return + } + p := id() + pr := &Project{WorkspacePath: path, Dedicated: true, Files: map[string]File{}} + if previous := s.projects[req.ProjectID]; previous != nil && !previous.Dedicated && sameAccessValue(previous.WorkspacePath, path) { + pr.LegacyProject = req.ProjectID + } + s.projects[p] = pr + work := s.work(p) + if e = os.MkdirAll(work, 0700); e == nil { + args := []string{"init", "-q"} + if len(req.Git.Head) == 64 { + args = append(args, "--object-format=sha256") + } + _, e = gitCommand(work, nil, args...) + } + if e == nil { + e = s.seedDedicated(p, path) + } + if e == nil { + var cfg BuildEnvironment + cfg, e = s.buildEnvironment() + if e == nil { + e = s.prepareWorkspaceFiles(p, cfg) + } + } + if e == nil { + e = s.save(p) + } + if e != nil { + delete(s.projects, p) + http.Error(w, e.Error(), 400) + return + } + jsonOut(w, map[string]string{"id": p, "workspacePath": path, "buildWorkspace": work}) +} + +// 只读初始化普通源码,凭据及缓存继续遵循现有排除规则;不改写原仓库索引。 +func (s *Server) seedDedicated(p, source string) error { + if _, e := os.Stat(filepath.Join(source, ".git")); os.IsNotExist(e) { + return nil + } + files, e := sourceInventory(source) + if e != nil { + return e + } + for path := range files { + dest := filepath.Join(s.work(p), filepath.FromSlash(path)) + if e = os.MkdirAll(filepath.Dir(dest), 0700); e != nil { + return e + } + input, err := os.Open(filepath.Join(source, filepath.FromSlash(path))) + if err != nil { + return err + } + info, err := input.Stat() + if err != nil || !info.Mode().IsRegular() { + input.Close() + return fmt.Errorf("初始化来源不是普通文件:%s", path) + } + output, err := os.OpenFile(dest, os.O_CREATE|os.O_EXCL|os.O_WRONLY, info.Mode().Perm()) + if err != nil { + input.Close() + return err + } + _, err = io.Copy(output, input) + input.Close() + closed := output.Close() + if err == nil { + err = closed + } + if err != nil { + return err + } + value, err := comparisonFile(dest) + if err != nil { + return err + } + s.projects[p].Files[path] = value + } + return nil +} + +func (s *Server) checkDedicated(p string, local *GitSnapshot) error { + pr := s.projects[p] + if local == nil || !gitObjectID.MatchString(local.Head) { + return fmt.Errorf("专用工作区需要有效的本机 Git 提交") + } + if pr.Git != nil && pr.Pending == nil { + head, err := gitCommand(s.work(p), nil, "rev-parse", "HEAD") + if err != nil || strings.TrimSpace(string(head)) != pr.Git.Head { + return fmt.Errorf("专用工作区 Git 基线被外部修改,请先检查") + } + if pr.Git.Branch != "" { + branch, err := gitCommand(s.work(p), nil, "symbolic-ref", "--short", "-q", "HEAD") + if err != nil || strings.TrimSpace(string(branch)) != pr.Git.Branch { + return fmt.Errorf("专用工作区Git分支被外部修改") + } + } + if _, err := gitCommand(s.work(p), nil, "diff-index", "--cached", "--quiet", "--no-renames", pr.Git.Head, "--"); err != nil { + return fmt.Errorf("专用工作区 Git 索引被外部修改,请先处理暂存内容") + } + } + actual, e := s.projectInventory(p) + if e != nil { + return e + } + for path, f := range actual { + before, old := pr.Files[path] + if old && (before.Hash == f.Hash || before.TextHash != "" && func() bool { + current, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path))) + return e == nil && current.TextHash == before.TextHash + }()) { + continue + } + if pr.Pending != nil && pr.Pending.Files[path].Hash == f.Hash { + continue + } + return fmt.Errorf("专用编译工作区存在额外修改:%s;请先检查该文件,服务不会覆盖人工修改", path) + } + for path := range pr.Files { + if _, exists := actual[path]; !exists { + if pr.Pending != nil { + continue + } + return fmt.Errorf("专用编译工作区文件被删除:%s", path) + } + } + return nil +} + +func (s *Server) importBundle(w http.ResponseWriter, r *http.Request, p string) { + pr := s.projects[p] + if !pr.Dedicated { + http.Error(w, "请使用专用编译工作区", 400) + return + } + if pr.Busy { + http.Error(w, "workspace busy", 409) + return + } + head := r.URL.Query().Get("head") + if !gitObjectID.MatchString(head) { + http.Error(w, "invalid Git commit", 400) + return + } + if e := s.checkDedicated(p, &GitSnapshot{Head: head}); e != nil { + http.Error(w, e.Error(), 409) + return + } + file, e := os.CreateTemp(filepath.Join(s.root, "projects", p), "bundle-*") + if e != nil { + http.Error(w, e.Error(), 400) + return + } + defer os.Remove(file.Name()) + _, e = io.Copy(file, http.MaxBytesReader(w, r.Body, 1<<30)) + closeErr := file.Close() + if e == nil { + e = closeErr + } + if e == nil { + _, e = gitCommandFor(s.work(p), nil, 5*time.Minute, "bundle", "verify", file.Name()) + } + if e == nil { + header, openErr := os.Open(file.Name()) + if openErr != nil { + e = openErr + } else { + scanner := bufio.NewScanner(io.LimitReader(header, 1<<20)) + scanner.Buffer(make([]byte, 4096), 1<<20) + filtered := false + for scanner.Scan() { + line := scanner.Text() + if line == "" { + break + } + if line == "@filter=blob:none" { + filtered = true + } + } + if !filtered { + e = fmt.Errorf("只接受blob:none过滤bundle,禁止历史文件内容绕过源码排除规则") + } + header.Close() + } + } + if e == nil { + var refs []byte + refs, e = gitCommand(s.work(p), nil, "bundle", "list-heads", file.Name(), "HEAD") + fields := strings.Fields(string(refs)) + if e == nil && (len(fields) != 2 || fields[0] != head || fields[1] != "HEAD") { + e = fmt.Errorf("bundle HEAD 与请求提交不一致") + } + } + if e == nil { + _, e = gitCommandFor(s.work(p), nil, 5*time.Minute, "bundle", "unbundle", file.Name()) + } + if e != nil { + http.Error(w, "Git bundle 导入失败或缺少前置提交,请重试完整 bundle:"+e.Error(), 400) + return + } + jsonOut(w, map[string]string{"head": head}) +} + +func (s *Server) advanceDedicated(p string, g *GitSnapshot) error { + if g == nil || !gitObjectID.MatchString(g.Head) { + return fmt.Errorf("本机提交无效") + } + kind, e := gitCommand(s.work(p), nil, "cat-file", "-t", g.Head) + if e != nil || strings.TrimSpace(string(kind)) != "commit" { + return fmt.Errorf("请先上传本机提交的 Git bundle") + } + if _, e = gitCommand(s.work(p), nil, "read-tree", g.Head); e != nil { + return e + } + if g.Branch != "" { + ref := "refs/heads/" + g.Branch + if _, e = gitCommand(s.work(p), nil, "check-ref-format", ref); e != nil { + return fmt.Errorf("本机Git分支名无效") + } + if _, e = gitCommand(s.work(p), nil, "update-ref", ref, g.Head); e != nil { + return e + } + _, e = gitCommand(s.work(p), nil, "symbolic-ref", "HEAD", ref) + } else { + _, e = gitCommand(s.work(p), nil, "update-ref", "--no-deref", "HEAD", g.Head) + } + return e +} diff --git a/server/dedicated_test.go b/server/dedicated_test.go new file mode 100644 index 0000000..b489da0 --- /dev/null +++ b/server/dedicated_test.go @@ -0,0 +1,187 @@ +package main + +import ( + "bytes" + "encoding/json" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestDedicatedCommitBundleOverlayAndIsolation(t *testing.T) { + if _, e := exec.LookPath("git"); e != nil { + t.Skip("Git unavailable") + } + s := testServer(t) + s.workspaceRoot = t.TempDir() + original := filepath.Join(s.workspaceRoot, "human") + os.MkdirAll(original, 0700) + client := t.TempDir() + git := func(work string, args ...string) string { + t.Helper() + out, e := gitCommandFor(work, nil, 60e9, args...) + if e != nil { + t.Fatalf("git %v: %v", args, e) + } + return string(bytes.TrimSpace(out)) + } + commit := func(work string) string { + t.Helper() + git(work, "add", ".") + git(work, "-c", "user.name=Test", "-c", "user.email=test@example.invalid", "commit", "-qm", "snapshot") + return git(work, "rev-parse", "HEAD") + } + git(original, "init", "-q") + writeFixture(t, filepath.Join(original, "a.txt"), "human committed\n") + humanHead := commit(original) + writeFixture(t, filepath.Join(original, "a.txt"), "human uncommitted change\n") + git(client, "init", "-q") + git(client, "config", "core.autocrlf", "false") + wrapperName, wrapper := "gradlew", "#!/bin/sh\nmkdir -p app/build/outputs/apk/debug\nprintf apk > app/build/outputs/apk/debug/real-name.apk\n" + if runtime.GOOS == "windows" { + wrapperName = "gradlew.bat" + wrapper = "@echo off\r\nmkdir app\\build\\outputs\\apk\\debug 2>nul\r\necho apk>app\\build\\outputs\\apk\\debug\\real-name.apk\r\nexit /b 0\r\n" + } + writeFixture(t, filepath.Join(client, "a.txt"), "commit A\n") + writeFixture(t, filepath.Join(client, wrapperName), wrapper) + writeFixture(t, filepath.Join(client, "fixture.jks"), "must never be uploaded") + a := commit(client) + originalIndex, _ := os.ReadFile(filepath.Join(original, ".git", "index")) + legacy := id() + s.projects[legacy] = &Project{WorkspacePath: original, Files: map[string]File{}, Git: &GitSnapshot{Head: humanHead}} + os.MkdirAll(filepath.Join(s.root, "projects", legacy), 0700) + if e := s.save(legacy); e != nil { + t.Fatal(e) + } + oldBuild := &Build{ID: id(), Project: legacy, Status: "success", Logs: []string{}, Artifacts: []Artifact{}} + s.builds[oldBuild.ID] = oldBuild + if e := s.persistBuild(oldBuild); e != nil { + t.Fatal(e) + } + response := call(t, s, "POST", "/projects", WorkspaceRequest{WorkspacePath: original, Dedicated: true, ProjectID: legacy, Git: &GitSnapshot{Head: a}}) + if response.Code != 200 { + t.Fatal(response.Body.String()) + } + var created map[string]string + json.Unmarshal(response.Body.Bytes(), &created) + p := created["id"] + if s.projects[p].LegacyProject != legacy { + t.Fatal("legacy history link missing") + } + history := call(t, s, "GET", "/projects/"+p+"/builds", nil) + if history.Code != 200 || !strings.Contains(history.Body.String(), oldBuild.ID) { + t.Fatal("old build hidden after migration", history.Body.String()) + } + if s.work(p) == original { + t.Fatal("dedicated workspace uses human folder") + } + sendBundle := func(head, base string) { + t.Helper() + bundle := filepath.Join(t.TempDir(), "source.bundle") + args := []string{"bundle", "create", "--version=3", bundle, "HEAD", "--filter=blob:none"} + if base != "" { + args = append(args, "^"+base) + } + git(client, args...) + data, e := os.ReadFile(bundle) + if e != nil { + t.Fatal(e) + } + request := httptest.NewRequest("POST", "/api/v1/projects/"+p+"/git?head="+head, bytes.NewReader(data)) + request.Header.Set("Authorization", "Bearer "+s.token) + w := httptest.NewRecorder() + s.ServeHTTP(w, request) + if w.Code != 200 { + t.Fatal(w.Code, w.Body.String()) + } + } + sync := func(head, revision, content string) int { + t.Helper() + w := call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Git: &GitSnapshot{Head: head, Branch: "source-branch"}, Revision: revision, Files: map[string]File{"a.txt": file(content), wrapperName: file(wrapper)}}) + if w.Code != 200 && w.Code != 400 && w.Code != 409 { + t.Fatal(w.Code, w.Body.String()) + } + return w.Code + } + sendBundle(a, "") + if objects := git(s.work(p), "cat-file", "--batch-all-objects", "--batch-check=%(objecttype)"); strings.Contains(objects, "blob") { + t.Fatal("bundle uploaded file contents including excluded secrets") + } + if sync(a, "one", "uncommitted overlay A\n") != 200 { + t.Fatal("initial overlay failed") + } + bld := &Build{ID: id(), Project: p, Revision: "one", Task: ":app:assembleDebug", Status: "queued"} + s.builds[bld.ID] = bld + s.projects[p].Busy = true + s.run(bld) + if bld.Status != "success" || len(bld.Artifacts) != 1 || bld.Artifacts[0].FileName != "real-name.apk" { + t.Fatal("dedicated build did not produce original artifact name", bld.Status, bld.Logs, bld.Artifacts) + } + writeFixture(t, filepath.Join(s.work(p), ".gradle", "cache-marker"), "keep") + writeFixture(t, filepath.Join(client, "a.txt"), "commit B\n") + writeFixture(t, filepath.Join(client, "b.txt"), "locally deleted after commit\n") + b := commit(client) + sendBundle(b, a) + if sync(b, "two", "uncommitted overlay B\n") != 200 { + t.Fatal("next local commit blocked") + } + if git(s.work(p), "symbolic-ref", "--short", "HEAD") != "source-branch" { + t.Fatal("local branch identity not preserved") + } + if git(s.work(p), "rev-parse", "HEAD") != b { + t.Fatal("Git baseline not advanced") + } + if data, e := os.ReadFile(filepath.Join(s.work(p), ".gradle", "cache-marker")); e != nil || string(data) != "keep" { + t.Fatal("cache removed") + } + oldBlob := git(client, "rev-parse", a+":a.txt") + git(s.work(p), "update-index", "--cacheinfo", "100644,"+oldBlob+",a.txt") + if sync(b, "staged-blocked", "overwrite") != 409 { + t.Fatal("manual index edit overwritten") + } + git(s.work(p), "read-tree", b) + writeFixture(t, filepath.Join(s.work(p), "a.txt"), "manual remote edit\n") + if sync(b, "blocked", "overwrite") != 409 { + t.Fatal("manual edit overwritten") + } + writeFixture(t, filepath.Join(s.work(p), "a.txt"), "uncommitted overlay B\n") + writeFixture(t, filepath.Join(client, "a.txt"), "commit C\n") + c := commit(client) + if sync(c, "missing-bundle", "overlay C\n") != 400 { + t.Fatal("unimported commit accepted") + } + if s.projects[p].Revision != "" || s.projects[p].Pending == nil || s.projects[p].Pending.Files["a.txt"].Data != nil { + t.Fatal("failed sync not journaled safely") + } + state, e := os.ReadFile(filepath.Join(s.root, "projects", p, "state.json")) + if e != nil { + t.Fatal(e) + } + var restarted Project + json.Unmarshal(state, &restarted) + s.projects[p] = &restarted + sendBundle(c, b) + if sync(c, "three", "overlay C\n") != 200 { + t.Fatal("interrupted sync cannot recover") + } + if data, e := os.ReadFile(filepath.Join(original, "a.txt")); e != nil || string(data) != "human uncommitted change\n" { + t.Fatal("human source modified") + } + afterIndex, _ := os.ReadFile(filepath.Join(original, ".git", "index")) + if !bytes.Equal(originalIndex, afterIndex) { + t.Fatal("human Git index changed") + } + if git(original, "rev-parse", "HEAD") != humanHead { + t.Fatal("human Git changed") + } + // 另一个客户端绑定同一来源,也必须拥有独立的工作区。 + response = call(t, s, "POST", "/projects", WorkspaceRequest{WorkspacePath: original, Dedicated: true, Git: &GitSnapshot{Head: c}}) + json.Unmarshal(response.Body.Bytes(), &created) + if response.Code != 200 || created["id"] == p { + t.Fatal("clients share workspace") + } +} diff --git a/server/environment.go b/server/environment.go index ddaa1da..a43a839 100644 --- a/server/environment.go +++ b/server/environment.go @@ -19,13 +19,15 @@ import ( ) type BuildEnvironment struct { - GradleHome string `json:"gradleHome"` - GradleUserHome string `json:"gradleUserHome"` - JavaHome string `json:"javaHome"` - AndroidHome string `json:"androidHome"` - Proxy string `json:"proxy"` - ProxySource string `json:"proxySource"` - PreferWrapper bool `json:"preferWrapper"` + Adb string `json:"adb,omitempty"` + WorkspaceFiles map[string]map[string]string `json:"workspaceFiles,omitempty"` + GradleHome string `json:"gradleHome"` + GradleUserHome string `json:"gradleUserHome"` + JavaHome string `json:"javaHome"` + AndroidHome string `json:"androidHome"` + Proxy string `json:"proxy"` + ProxySource string `json:"proxySource"` + PreferWrapper bool `json:"preferWrapper"` } func (s *Server) buildEnvironment() (BuildEnvironment, error) { diff --git a/server/git_checkout.go b/server/git_checkout.go new file mode 100644 index 0000000..f0d1561 --- /dev/null +++ b/server/git_checkout.go @@ -0,0 +1,86 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "regexp" + "strings" +) + +type gitEntry struct{ mode, hash string } +type cleanCheckout struct { + work string + head, index, previous map[string]gitEntry +} + +var gitObjectID = regexp.MustCompile(`^[0-9a-fA-F]{40}([0-9a-fA-F]{24})?$`) + +func gitTree(work, head string) (map[string]gitEntry, error) { + if !gitObjectID.MatchString(head) { + return nil, fmt.Errorf("无法验证 Git 提交标识") + } + data, e := gitCommand(work, nil, "ls-tree", "-r", "-z", head) + if e != nil { + return nil, e + } + result := map[string]gitEntry{} + for _, record := range strings.Split(string(data), "\x00") { + meta, path, ok := strings.Cut(record, "\t") + fields := strings.Fields(meta) + if ok && len(fields) == 3 && fields[1] == "blob" { + result[path] = gitEntry{fields[0], fields[2]} + } + } + return result, nil +} +func inspectCheckout(work string, remote, previous *GitSnapshot) (*cleanCheckout, error) { + if remote == nil { + return nil, nil + } + head, e := gitTree(work, remote.Head) + if e != nil { + return nil, e + } + data, e := gitCommand(work, nil, "ls-files", "--stage", "-z") + if e != nil { + return nil, e + } + c := &cleanCheckout{work: work, head: head, index: map[string]gitEntry{}, previous: map[string]gitEntry{}} + for _, record := range strings.Split(string(data), "\x00") { + meta, path, ok := strings.Cut(record, "\t") + fields := strings.Fields(meta) + if ok && len(fields) == 3 { + if fields[2] == "0" { + c.index[path] = gitEntry{fields[0], fields[1]} + } else { + c.index[path] = gitEntry{mode: "conflict"} + } + } + } + if previous != nil && previous.Head != remote.Head && gitObjectID.MatchString(previous.Head) { + // 旧对象不可用时不放行删除,保持保守保护。 + if old, e := gitTree(work, previous.Head); e == nil { + c.previous = old + } + } + return c, nil +} +func (c *cleanCheckout) matches(path string) bool { + if c == nil { + return false + } + head, tracked := c.head[path] + index, indexed := c.index[path] + if !tracked { + _, wasTracked := c.previous[path] + _, e := os.Lstat(filepath.Join(c.work, filepath.FromSlash(path))) + return wasTracked && !indexed && os.IsNotExist(e) + } + if !indexed || index != head || (head.mode != "100644" && head.mode != "100755") { + return false + } + // 实际读取文件并应用 Git 规范化,不能依赖 status 缓存或 assume-unchanged。 + hash, e := gitCommand(c.work, nil, "hash-object", "--path="+path, "--", path) + return e == nil && strings.TrimSpace(string(hash)) == head.hash +} diff --git a/server/git_checkout_test.go b/server/git_checkout_test.go new file mode 100644 index 0000000..9503b79 --- /dev/null +++ b/server/git_checkout_test.go @@ -0,0 +1,114 @@ +package main + +import ( + "encoding/json" + "os" + "os/exec" + "path/filepath" + "testing" +) + +func TestCheckoutAdvancedWithManagedUntrackedFiles(t *testing.T) { + if _, e := exec.LookPath("git"); e != nil { + t.Skip("Git unavailable") + } + s := testServer(t) + s.workspaceRoot = t.TempDir() + work := filepath.Join(s.workspaceRoot, "checkout") + os.MkdirAll(work, 0700) + git := func(args ...string) { + t.Helper() + if out, e := exec.Command("git", append([]string{"-C", work}, args...)...).CombinedOutput(); e != nil { + t.Fatalf("git %v: %v %s", args, e, out) + } + } + put := func(path, text string) { t.Helper(); writeFixture(t, filepath.Join(work, path), text) } + snapshot := func() *GitSnapshot { + t.Helper() + g, e := gitSnapshot(work) + if e != nil { + t.Fatal(e) + } + return g + } + git("init", "-q") + git("config", "core.autocrlf", "false") + put("a.txt", "old\n") + put("gone.txt", "removed in next commit\n") + put("restored.txt", "tracked\n") + git("add", ".") + git("-c", "user.name=Test", "-c", "user.email=test@example.invalid", "commit", "-qm", "old") + old := snapshot() + response := call(t, s, "POST", "/projects", WorkspaceRequest{WorkspacePath: work, Git: old}) + if response.Code != 200 { + t.Fatal(response.Body.String()) + } + var project map[string]string + json.Unmarshal(response.Body.Bytes(), &project) + p := project["id"] + response = call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "old", Git: old, Files: map[string]File{"a.txt": file("old\n"), "gone.txt": file("removed in next commit\n"), "notes.docx": file("managed untracked document")}}) + if response.Code != 200 { + t.Fatal(response.Body.String()) + } + // 两边更新到新提交,未跟踪文档使仓库整体仍为 dirty。 + git("restore", "--worktree", "--", "restored.txt") + put("a.txt", "new committed content\n") + os.Remove(filepath.Join(work, "gone.txt")) + put("added.txt", "new tracked file\n") + git("add", "a.txt", "gone.txt", "restored.txt", "added.txt") + git("-c", "user.name=Test", "-c", "user.email=test@example.invalid", "commit", "-qm", "new") + git("config", "core.autocrlf", "true") + put("a.txt", "new committed content\r\n") + current := snapshot() + if !current.Dirty || current.Head == old.Head { + t.Fatal("fixture must have advanced HEAD and untracked document") + } + if e := s.checkGit(p, current); e != nil { + t.Fatal("pristine tracked files blocked by unrelated untracked file", e) + } + manifest := s.manifest(p) + if manifest.Git == nil || manifest.Git.Head != current.Head || manifest.Revision != "" || manifest.Files["a.txt"].Hash != digest([]byte("new committed content\r\n")) || manifest.Files["added.txt"].Hash == "" || manifest.Files["restored.txt"].Hash == "" { + t.Fatal("manifest omitted current checkout", manifest) + } + if s.projects[p].Revision != "old" || len(s.projects[p].Files) != 3 { + t.Fatal("read-only check modified baseline") + } + response = call(t, s, "POST", "/projects/"+p+"/builds", map[string]string{"task": ":app:assembleDebug", "revision": "old"}) + if response.Code != 409 { + t.Fatal("stale snapshot was accepted", response.Body.String()) + } + // 索引有真实暂存修改时,即使工作文件被恢复为HEAD,也不能放行。 + put("a.txt", "staged change\n") + git("add", "a.txt") + put("a.txt", "new committed content\r\n") + if e := s.checkGit(p, current); e == nil { + t.Fatal("staged change silently accepted") + } + git("reset", "--", "a.txt") + // 新增、修改未跟踪文件仍需保护。 + put("surprise.txt", "remote new file\n") + if e := s.checkGit(p, current); e == nil { + t.Fatal("untracked remote addition accepted") + } + os.Remove(filepath.Join(work, "surprise.txt")) + put("notes.docx", "remote document edit") + if e := s.checkGit(p, current); e == nil { + t.Fatal("untracked remote edit accepted") + } + put("notes.docx", "managed untracked document") + response = call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "new", Git: current, Files: map[string]File{"a.txt": {Hash: manifest.Files["a.txt"].Hash}, "notes.docx": {Hash: manifest.Files["notes.docx"].Hash}}}) + if response.Code != 200 { + t.Fatal("new snapshot sync failed", response.Body.String()) + } + for _, path := range []string{"added.txt", "restored.txt", "gone.txt"} { + if _, e := os.Stat(filepath.Join(work, path)); !os.IsNotExist(e) { + t.Fatal("tracked local deletion was not applied", path) + } + } + // assume-unchanged 不得掩盖实际服务端改动。 + git("update-index", "--assume-unchanged", "a.txt") + put("a.txt", "real remote change\n") + if e := s.checkGit(p, current); e == nil { + t.Fatal("hidden real remote edit accepted") + } +} diff --git a/server/main.go b/server/main.go index e9f910e..ecc79c4 100644 --- a/server/main.go +++ b/server/main.go @@ -45,6 +45,7 @@ type Artifact struct { Hash string `json:"hash"` Size int64 `json:"size"` SourcePath string `json:"sourcePath,omitempty"` + FileName string `json:"fileName,omitempty"` } type Build struct { JavaHome string `json:"javaHome,omitempty"` @@ -64,6 +65,10 @@ type Build struct { cancelled bool } type Project struct { + PrivateFiles map[string]File `json:"privateFiles,omitempty"` + LegacyProject string `json:"legacyProject,omitempty"` + Dedicated bool `json:"dedicated,omitempty"` + Pending *PendingSync `json:"pending,omitempty"` WorkspacePath string `json:"workspacePath,omitempty"` Git *GitSnapshot `json:"git,omitempty"` Revision string `json:"revision"` @@ -139,7 +144,7 @@ func decode(w http.ResponseWriter, r *http.Request, v any) error { return d.Decode(v) } func (s *Server) work(p string) string { - if pr := s.projects[p]; pr != nil && pr.WorkspacePath != "" { + if pr := s.projects[p]; pr != nil && pr.WorkspacePath != "" && !pr.Dedicated { return pr.WorkspacePath } return filepath.Join(s.root, "projects", p, "work") @@ -164,6 +169,10 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.streamLogs(w, r) return } + if strings.HasPrefix(r.URL.Path, "/api/v1/adb/") { + s.serveADB(w, r) + return + } s.mu.Lock() defer s.mu.Unlock() if e := s.reloadAccessPolicy(); e != nil { @@ -173,7 +182,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/") fail := func(e error) { http.Error(w, e.Error(), 400) } if r.URL.Path == "/api/v1/health" { - jsonOut(w, map[string]any{"version": "0.4.9", "adminCLI": true, "preflight": true, "textComparison": true, "jdkSelection": true, "workspaceSelection": true, "os": runtime.GOOS, "sync": "http-manifest", "recovery": true}) + jsonOut(w, map[string]any{"version": "0.7.0", "privateFileList": true, "remoteADB": true, "syncPreflight": true, "dedicatedGit": true, "adminCLI": true, "preflight": true, "textComparison": true, "jdkSelection": true, "workspaceSelection": true, "os": runtime.GOOS, "sync": "http-manifest", "recovery": true}) return } if r.URL.Path == "/api/v1/environment" && r.Method == "GET" { @@ -189,6 +198,10 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.jdks(w, r) return } + if r.URL.Path == "/api/v1/private-files" { + s.servePrivateFiles(w, r) + return + } if r.URL.Path == "/api/v1/directories" && r.Method == "GET" { s.browseDirectories(w, r) return @@ -223,6 +236,10 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } } + if parts[4] == "git" && r.Method == "POST" { + s.importBundle(w, r, p) + return + } if parts[4] == "manifest" && r.Method == "GET" { jsonOut(w, s.manifest(p)) return @@ -230,7 +247,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { if parts[4] == "builds" && r.Method == "GET" { items := []*Build{} for _, b := range s.builds { - if b.Project == p && (r.URL.Query().Get("clientRequestId") == "" || b.RequestID == r.URL.Query().Get("clientRequestId")) { + if (b.Project == p || pr.LegacyProject != "" && b.Project == pr.LegacyProject) && (r.URL.Query().Get("clientRequestId") == "" || b.RequestID == r.URL.Query().Get("clientRequestId")) { items = append(items, b) } } @@ -255,6 +272,25 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { fail(errors.New("revision and files required")) return } + if pr.Dedicated { + names, err := s.privateNames(p) + if err != nil { + fail(err) + return + } + for _, name := range names { + if privateConflict(req.Files, name) { + fail(fmt.Errorf("私有文件与普通源码同步冲突:%s;请在本机忽略该文件", name)) + return + } + } + for name := range pr.PrivateFiles { + if privateConflict(req.Files, name) { + fail(fmt.Errorf("私有文件仍在工作区:%s;请先完成清单移除后的构建清理", name)) + return + } + } + } if e := s.checkGit(p, req.Git); e != nil { http.Error(w, e.Error(), 409) return @@ -315,10 +351,23 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // 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 pr.Dedicated { + journal := map[string]File{} + for path, f := range req.Files { + journal[path] = File{Hash: f.Hash} + } + pr.Pending = &PendingSync{Files: journal} + } if e := s.save(p); e != nil { fail(e) return } + if pr.Dedicated { + if e := s.advanceDedicated(p, req.Git); e != nil { + fail(e) + return + } + } for path := range previousFiles { if _, ok := req.Files[path]; !ok && validPath(path) { if e := os.Remove(filepath.Join(s.work(p), filepath.FromSlash(path))); e != nil && !os.IsNotExist(e) { @@ -349,6 +398,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { } pr.Revision = req.Revision pr.Git = req.Git + pr.Pending = nil if e := s.save(p); e != nil { pr.Revision = "" fail(e) @@ -401,7 +451,13 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { http.Error(w, e.Error(), 409) return } - actual, e := sourceInventory(s.work(p)) + var actual map[string]File + var e error + if pr.Dedicated { + actual, e = s.projectInventory(p) + } else { + actual, e = sourceInventory(s.work(p)) + } if e != nil { fail(e) return @@ -544,6 +600,7 @@ func (s *Server) run(b *Build) { return } b.Status = "running" + source := s.projects[b.Project].WorkspacePath b.Progress = Progress{Phase: "preparing", Message: "正在检测工具版本、缓存及系统代理", Percent: -1} _ = s.persistBuild(b) s.mu.Unlock() @@ -556,7 +613,12 @@ func (s *Server) run(b *Build) { if b.JavaHome != "" { cfg.JavaHome = b.JavaHome } + if e := s.prepareWorkspaceFiles(b.Project, cfg); e != nil { + s.finishFailed(b, e) + return + } report := s.preflight(work, cfg) + s.explainWrapper(&report, work, source, false) for _, item := range report.Items { buildWriter{s, b}.Write([]byte(fmt.Sprintf("环境检查 [%s] %s:%s [%s]\n", item.Status, item.Name, item.Message, item.Path))) } @@ -643,7 +705,7 @@ func (s *Server) run(b *Build) { if e = os.WriteFile(filepath.Join(dest, name), data, 0600); e != nil { return e } - artifacts = append(artifacts, Artifact{Name: name, Hash: digest(data), Size: int64(len(data)), SourcePath: artifactSourcePath(work, p)}) + artifacts = append(artifacts, Artifact{Name: name, Hash: digest(data), Size: int64(len(data)), SourcePath: artifactSourcePath(work, p), FileName: filepath.Base(p)}) return nil }) } diff --git a/server/preflight.go b/server/preflight.go index f23f460..5a01cfb 100644 --- a/server/preflight.go +++ b/server/preflight.go @@ -21,6 +21,7 @@ type CheckItem struct { } type Preflight struct { Ready bool `json:"ready"` + Phase string `json:"phase,omitempty"` Items []CheckItem `json:"items"` } diff --git a/server/private_files.go b/server/private_files.go new file mode 100644 index 0000000..e15488a --- /dev/null +++ b/server/private_files.go @@ -0,0 +1,355 @@ +package main + +import ( + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "runtime" + "strings" +) + +func privatePath(name string) bool { + if strings.ContainsAny(name, "\\:\x00<>\"|?*") || name == "" { + return false + } + for _, r := range name { + if r < 32 || r == 127 { + return false + } + } + parts := strings.Split(name, "/") + leaf := parts[len(parts)-1] + for _, part := range parts { + if strings.TrimRight(part, ". ") != part { + return false + } + } + if strings.EqualFold(leaf, ".gitignore") || strings.EqualFold(leaf, ".gitattributes") || (reservedSource(leaf) && !strings.HasSuffix(strings.ToLower(leaf), ".jks") && !strings.HasSuffix(strings.ToLower(leaf), ".keystore") && leaf != "local.properties" && leaf != "key.properties" && leaf != "keystore.properties" && !strings.HasPrefix(leaf, ".env")) { + return false + } + parts[len(parts)-1] = "private.asset" + return validPath(strings.Join(parts, "/")) && leaf != "." && leaf != ".." && validPath("file/"+strings.TrimSuffix(leaf, filepath.Ext(leaf))+".asset") +} + +func parsePrivateList(content string) ([]string, error) { + if len(content) > 64<<10 { + return nil, fmt.Errorf("私有文件清单不能超过64KiB") + } + names := []string{} + seen := map[string]bool{} + for n, line := range strings.Split(strings.TrimPrefix(content, "\ufeff"), "\n") { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + if !privatePath(line) { + return nil, fmt.Errorf("清单第%d行路径非法:%s;请填写工程内相对文件路径,使用/,禁止绝对路径、../及缓存目录", n+1, line) + } + key := line + if runtime.GOOS == "windows" { + key = strings.ToLower(key) + } + if seen[key] { + return nil, fmt.Errorf("私有文件重复:%s", line) + } + seen[key] = true + names = append(names, line) + if len(names) > 256 { + return nil, fmt.Errorf("私有文件清单最多256项") + } + } + return names, nil +} + +func (s *Server) privateList(source string) (string, string, error) { + key := filepath.Clean(source) + if runtime.GOOS == "windows" { + key = strings.ToLower(key) + } + path := filepath.Join(s.root, "private-files", digest([]byte(key))+".txt") + data, e := os.ReadFile(path) + if os.IsNotExist(e) { + return path, "", nil + } + return path, string(data), e +} + +func privateSource(source, name string) (string, error) { + path := filepath.Join(source, filepath.FromSlash(name)) + for current := path; current != source; current = filepath.Dir(current) { + info, e := os.Lstat(current) + if e != nil { + return "", fmt.Errorf("来源目录缺少文件或无法读取:%s", name) + } + if info.Mode()&os.ModeSymlink != 0 { + return "", fmt.Errorf("私有文件不允许符号链接:%s", name) + } + resolved, e := filepath.EvalSymlinks(current) + if e != nil || !sameAccessValue(resolved, current) { + return "", fmt.Errorf("私有文件路径被重定向:%s", name) + } + } + f, e := os.Open(path) + if e != nil { + return "", fmt.Errorf("服务账户不能读取私有文件:%s", name) + } + defer f.Close() + info, e := f.Stat() + if e != nil || !info.Mode().IsRegular() || info.Size() > 16<<20 { + return "", fmt.Errorf("私有文件须为不超过16MiB的普通文件:%s", name) + } + return path, nil +} + +func (s *Server) privateReport(source, content, path string, exists bool) map[string]any { + names, e := parsePrivateList(content) + entries := []map[string]string{} + ready := e == nil + if e == nil { + for _, name := range names { + status := "ok" + message := "存在且服务账户可读" + if _, err := privateSource(source, name); err != nil { + status = "error" + message = err.Error() + ready = false + } + entries = append(entries, map[string]string{"path": name, "status": status, "message": message}) + } + } + message := "私有文件清单已读取;路径相对于服务端工程来源目录" + if !exists { + message = "尚未创建私有文件清单;点击编辑后保存到服务端" + } + if e != nil { + message = e.Error() + } + return map[string]any{"workspacePath": source, "manifestPath": path, "exists": exists, "content": content, "hash": digest([]byte(content)), "ready": ready, "entries": entries, "message": message} +} + +func (s *Server) servePrivateFiles(w http.ResponseWriter, r *http.Request) { + source := r.URL.Query().Get("workspacePath") + var req struct { + WorkspacePath string `json:"workspacePath"` + Content string `json:"content"` + BaseHash string `json:"baseHash"` + } + if r.Method == "PUT" { + if e := decode(w, r, &req); e != nil { + http.Error(w, e.Error(), 400) + return + } + source = req.WorkspacePath + } else if r.Method != "GET" { + http.Error(w, "method not allowed", 405) + return + } + source, e := s.validateWorkspace(source) + if e != nil { + http.Error(w, e.Error(), 400) + return + } + path, content, e := s.privateList(source) + if e != nil { + http.Error(w, e.Error(), 400) + return + } + if r.Method == "PUT" { + names, e := parsePrivateList(req.Content) + if e != nil { + http.Error(w, e.Error(), 400) + return + } + if req.BaseHash != digest([]byte(content)) { + http.Error(w, "服务端清单已被其他编辑修改,请备份本地内容后重新读取清单", 409) + return + } + for _, pr := range s.projects { + if sameAccessValue(pr.WorkspacePath, source) { + if pr.Busy { + http.Error(w, "该工程正在构建,请结束后保存清单", 409) + return + } + for _, name := range names { + if pr.Pending != nil && privateConflict(pr.Pending.Files, name) { + http.Error(w, "私有文件与未完成的同步任务冲突:"+name, 409) + return + } + if privateConflict(pr.Files, name) { + http.Error(w, "私有文件与普通源码同步冲突:"+name+";请先在本机忽略并重新同步移除后再配置", 409) + return + } + } + } + } + if e = os.MkdirAll(filepath.Dir(path), 0700); e == nil { + var f *os.File + f, e = os.CreateTemp(filepath.Dir(path), ".list-*") + if e == nil { + temp := f.Name() + _, e = io.WriteString(f, req.Content) + closeErr := f.Close() + if e == nil { + e = closeErr + } + if e == nil { + e = os.Rename(temp, path) + } + os.Remove(temp) + } + } + if e != nil { + http.Error(w, e.Error(), 400) + return + } + content = req.Content + } + _, statErr := os.Stat(path) + jsonOut(w, s.privateReport(source, content, path, statErr == nil)) +} + +func (s *Server) privateNames(p string) ([]string, error) { + _, content, e := s.privateList(s.projects[p].WorkspacePath) + if e != nil { + return nil, e + } + return parsePrivateList(content) +} + +func (s *Server) projectInventory(p string) (map[string]File, error) { + files, e := dedicatedInventory(s.work(p)) + if e != nil { + return nil, e + } + for name := range s.projects[p].PrivateFiles { + if _, managed := s.projects[p].Files[name]; !managed { + delete(files, name) + } + } + return files, nil +} + +func (s *Server) preparePrivateFiles(p string) error { + pr := s.projects[p] + if !pr.Dedicated { + return nil + } + names, e := s.privateNames(p) + if e != nil { + return e + } + if len(names) == 0 && len(pr.PrivateFiles) == 0 { + return nil + } + source, e := s.validateWorkspace(pr.WorkspacePath) + if e != nil { + return e + } + wanted := map[string]string{} + for _, name := range names { + if privateConflict(pr.Files, name) { + return fmt.Errorf("私有文件与源码同步冲突:%s", name) + } + path, err := privateSource(source, name) + if err != nil { + return err + } + wanted[name] = path + } + root := s.work(p) + if e = noLinks(root); e != nil { + return e + } + if pr.PrivateFiles == nil { + pr.PrivateFiles = map[string]File{} + } + for name, old := range pr.PrivateFiles { + if _, keep := wanted[name]; !keep { + dest := filepath.Join(root, filepath.FromSlash(name)) + data, err := os.ReadFile(dest) + if err == nil { + if digest(data) != old.Hash { + return fmt.Errorf("已移出清单的私有文件与保存摘要不一致,无法自动删除:%s", name) + } + if err = os.Remove(dest); err != nil { + return err + } + } else if !os.IsNotExist(err) { + return err + } + delete(pr.PrivateFiles, name) + } + } + for name, path := range wanted { + input, err := os.Open(path) + if err != nil { + return fmt.Errorf("读取私有文件失败:%s", name) + } + data, err := io.ReadAll(io.LimitReader(input, (16<<20)+1)) + input.Close() + if err != nil { + return fmt.Errorf("读取私有文件失败:%s", name) + } + if len(data) > 16<<20 { + return fmt.Errorf("私有文件超过16MiB:%s", name) + } + // Journal names before copying so a restart can distinguish private files from extra source edits. + pr.PrivateFiles[name] = File{Hash: digest(data)} + if err = s.save(p); err != nil { + return err + } + dest := filepath.Join(root, filepath.FromSlash(name)) + if err = os.MkdirAll(filepath.Dir(dest), 0700); err != nil { + return err + } + f, err := os.CreateTemp(filepath.Dir(dest), ".private-*") + if err != nil { + return err + } + temp := f.Name() + _, err = f.Write(data) + closeErr := f.Close() + if err == nil { + err = closeErr + } + if err == nil { + err = os.Rename(temp, dest) + } + os.Remove(temp) + if err != nil { + return err + } + } + return s.save(p) +} + +func privateConflict(files map[string]File, name string) bool { + for path := range files { + if path == name || (runtime.GOOS == "windows" && strings.EqualFold(path, name)) { + return true + } + } + return false +} +func (s *Server) privatePreflight(report *Preflight, source string) { + path, content, e := s.privateList(source) + if e != nil { + report.add("私有文件清单", "error", path, e.Error()) + return + } + _, statErr := os.Stat(path) + result := s.privateReport(source, content, path, statErr == nil) + if _, e := parsePrivateList(content); e != nil { + report.add("私有文件清单", "error", path, e.Error()) + return + } + if statErr != nil { + report.add("私有文件清单", "warning", path, "尚未创建;如需未跟踪签名文件,请在侧边栏编辑私有文件清单并保存到服务端") + return + } + for _, entry := range result["entries"].([]map[string]string) { + report.add("私有文件", entry["status"], entry["path"], entry["message"]) + } +} diff --git a/server/private_files_test.go b/server/private_files_test.go new file mode 100644 index 0000000..66e240c --- /dev/null +++ b/server/private_files_test.go @@ -0,0 +1,146 @@ +package main + +import ( + "bytes" + "encoding/json" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestPrivateListPaths(t *testing.T) { + for _, path := range []string{"config.gradle", "app/keystore/test.jks", "key.properties", ".env", "signing.properties", "sign/HONOR.CER"} { + if !privatePath(path) { + t.Errorf("rejected %q", path) + } + } + for _, path := range []string{"../secret", "/tmp/key", "C:/key.jks", "x\\key.jks", "a/../key.jks", ".git/config", "build/key.jks", "app/.gradle/x", ".gitignore", ".gitattributes", "foo.", "foo ", "file?bad.jks", "NUL.jks"} { + if privatePath(path) { + t.Errorf("accepted %q", path) + } + } + names, e := parsePrivateList("\ufeff# comment\r\nconfig.gradle\r\n\napp/key.jks\n") + if e != nil || len(names) != 2 { + t.Fatal(names, e) + } + if _, e = parsePrivateList("config.gradle\nconfig.gradle"); e == nil { + t.Fatal("duplicate accepted") + } +} + +func TestPrivateListAPIAndWorkspaceLifecycle(t *testing.T) { + root := t.TempDir() + sources := t.TempDir() + source := filepath.Join(sources, "source 工程") + if e := os.MkdirAll(source, 0700); e != nil { + t.Fatal(e) + } + p := strings.Repeat("a", 32) + s := &Server{root: root, token: "private-test", workspaceRoot: sources, projects: map[string]*Project{p: {Dedicated: true, WorkspacePath: source, Files: map[string]File{}}}} + work := s.work(p) + if e := os.MkdirAll(work, 0700); e != nil { + t.Fatal(e) + } + if _, e := gitCommand(work, nil, "init", "-q"); e != nil { + t.Fatal(e) + } + call := func(method, token string, body any) *httptest.ResponseRecorder { + b, _ := json.Marshal(body) + req := httptest.NewRequest(method, "/api/v1/private-files?workspacePath="+strings.ReplaceAll(source, " ", "%20"), bytes.NewReader(b)) + req.Header.Set("Authorization", "Bearer "+token) + w := httptest.NewRecorder() + s.ServeHTTP(w, req) + return w + } + if w := call("GET", "bad", nil); w.Code != 401 { + t.Fatal(w.Code) + } + get := func() map[string]any { + w := call("GET", s.token, nil) + if w.Code != 200 { + t.Fatal(w.Code, w.Body.String()) + } + var v map[string]any + if e := json.Unmarshal(w.Body.Bytes(), &v); e != nil { + t.Fatal(e) + } + return v + } + first := get() + if first["exists"].(bool) { + t.Fatal("unexpected existing list") + } + put := func(content, hash string) *httptest.ResponseRecorder { + return call("PUT", s.token, map[string]string{"workspacePath": source, "content": content, "baseHash": hash}) + } + w := put("config.gradle\nkeys/platform.jks\n", first["hash"].(string)) + if w.Code != 200 { + t.Fatal(w.Code, w.Body.String()) + } + if get()["ready"].(bool) { + t.Fatal("missing source files must be reported") + } + if e := s.preparePrivateFiles(p); e == nil { + t.Fatal("missing private file accepted") + } + writeFixture(t, filepath.Join(source, "config.gradle"), "// private script\n") + writeFixture(t, filepath.Join(source, "keys", "platform.jks"), "private-key-fixture") + if !get()["ready"].(bool) { + t.Fatal("existing sources not ready") + } + if e := s.preparePrivateFiles(p); e != nil { + t.Fatal(e) + } + raw, e := os.ReadFile(filepath.Join(work, "config.gradle")) + if e != nil || string(raw) != "// private script\n" { + t.Fatal(string(raw), e) + } + files, e := s.projectInventory(p) + if e != nil || len(files) != 0 { + t.Fatal(files, e) + } + syncBody, _ := json.Marshal(SyncRequest{Revision: "next", Files: map[string]File{"config.gradle": {Hash: digest([]byte("x"))}}}) + syncRequest := httptest.NewRequest("POST", "/api/v1/projects/"+p+"/sync", bytes.NewReader(syncBody)) + syncRequest.Header.Set("Authorization", "Bearer "+s.token) + syncResponse := httptest.NewRecorder() + s.ServeHTTP(syncResponse, syncRequest) + if syncResponse.Code != 400 || !strings.Contains(syncResponse.Body.String(), "私有文件与普通源码同步冲突") { + t.Fatal(syncResponse.Code, syncResponse.Body.String()) + } + if w = put("", first["hash"].(string)); w.Code != 409 { + t.Fatal("stale edit accepted", w.Code) + } + current := get() + if w = put("", current["hash"].(string)); w.Code != 200 { + t.Fatal(w.Code, w.Body.String()) + } + writeFixture(t, filepath.Join(work, "config.gradle"), "manual-change") + if e = s.preparePrivateFiles(p); e == nil { + t.Fatal("modified private file removed") + } + raw, _ = os.ReadFile(filepath.Join(work, "config.gradle")) + if string(raw) != "manual-change" { + t.Fatal("modified copy not preserved") + } + writeFixture(t, filepath.Join(work, "config.gradle"), "// private script\n") + if e = s.preparePrivateFiles(p); e != nil { + t.Fatal(e) + } + if _, e = os.Stat(filepath.Join(work, "config.gradle")); !os.IsNotExist(e) { + t.Fatal("removed private file retained") + } + if _, e = os.Stat(filepath.Join(source, "config.gradle")); e != nil { + t.Fatal("source changed", e) + } + s.projects[p].Files["config.gradle"] = File{Hash: "source"} + if w = put("config.gradle", get()["hash"].(string)); w.Code != 409 { + t.Fatal("source collision accepted", w.Code) + } + delete(s.projects[p].Files, "config.gradle") + s.projects[p].Busy = true + if w = put("config.gradle", get()["hash"].(string)); w.Code != 409 { + t.Fatal("busy write accepted", w.Code) + } +} diff --git a/server/sync_preflight.go b/server/sync_preflight.go new file mode 100644 index 0000000..1a03eb1 --- /dev/null +++ b/server/sync_preflight.go @@ -0,0 +1,56 @@ +package main + +import ( + "path/filepath" + "runtime" + "strings" +) + +// A previous workspace can lack files that the next source sync will supply. +// Permissions and other environment failures remain fatal before sync. +func (s *Server) preflightForSync(work, source string, cfg BuildEnvironment) Preflight { + report := s.preflight(work, cfg) + s.explainWrapper(&report, work, source, true) + return report +} + +func (s *Server) explainWrapper(report *Preflight, work, source string, beforeSync bool) { + report.Phase = "before-build" + if beforeSync { + report.Phase = "before-sync" + } + for i := range report.Items { + item := &report.Items[i] + if item.Name != "Gradle" || !strings.Contains(item.Message, "Wrapper 不完整或不可读") { + continue + } + wrapper := "gradlew" + if runtime.GOOS == "windows" { + wrapper += ".bat" + } + names := []string{wrapper, "gradle/wrapper/gradle-wrapper.jar", "gradle/wrapper/gradle-wrapper.properties"} + item.Message += "。请确保本机包含 " + strings.Join(names, "、") + ",且未被 .gitignore、.git/info/exclude 或全局忽略规则排除;gradle/ 和 gradlew* 会排除构建必需文件,缓存仅需排除 .gradle/。" + if source != "" && filepath.Clean(source) != filepath.Clean(work) { + ignored, _ := gitCommand(source, nil, append([]string{"check-ignore", "-v", "--"}, names...)...) + if detail := strings.TrimSpace(string(ignored)); detail != "" { + if len(detail) > 4096 { + detail = detail[:4096] + } + item.Message += " 服务端原工程的忽略规则(本机也需检查):\n" + detail + } + } + if beforeSync { + item.Status = "warning" + item.Message += " 当前为同步前检查,允许继续同步补齐;同步后构建前会再次严格检查。" + } else { + // Preserve the strict build-time status chosen by the normal preflight. + item.Message += " 源码已同步但仍缺少所需工具链;请修正本机忽略规则后重新 Remote Run,或在服务端配置匹配版本的 Gradle。" + } + } + report.Ready = true + for _, item := range report.Items { + if item.Status == "error" { + report.Ready = false + } + } +} diff --git a/server/sync_preflight_test.go b/server/sync_preflight_test.go new file mode 100644 index 0000000..c3eecf2 --- /dev/null +++ b/server/sync_preflight_test.go @@ -0,0 +1,44 @@ +package main + +import ( + "path/filepath" + "strings" + "testing" +) + +func TestSyncPreflightDefersOnlyWrapperFailure(t *testing.T) { + s := &Server{} + for _, permissionFailure := range []bool{false, true} { + report := Preflight{Items: []CheckItem{{Name: "Gradle", Status: "error", Message: "没有可复用的匹配版本,项目 Wrapper 不完整或不可读:missing"}}} + if permissionFailure { + report.Items = append(report.Items, CheckItem{Name: "工程目录权限", Status: "error", Message: "denied"}) + } + s.explainWrapper(&report, t.TempDir(), "", true) + if report.Ready == permissionFailure || report.Phase != "before-sync" { + t.Fatalf("unexpected sync report: %+v", report) + } + checkStatus(t, report, "Gradle", "warning") + if !strings.Contains(report.Items[0].Message, "同步后构建前会再次严格检查") { + t.Fatal(report.Items[0].Message) + } + } +} + +func TestBuildPreflightExplainsIgnoredWrapperAndRemainsStrict(t *testing.T) { + source := t.TempDir() + if _, e := gitCommand(source, nil, "init", "-q"); e != nil { + t.Fatal(e) + } + writeFixture(t, filepath.Join(source, ".gitignore"), "gradle/\ngradlew*\n") + report := Preflight{Items: []CheckItem{{Name: "Gradle", Status: "error", Message: "项目 Wrapper 不完整或不可读:missing"}}} + (&Server{}).explainWrapper(&report, t.TempDir(), source, false) + if report.Ready || report.Phase != "before-build" { + t.Fatalf("build must remain blocked: %+v", report) + } + checkStatus(t, report, "Gradle", "error") + for _, text := range []string{".gitignore:1:gradle/", "gradlew*", "重新 Remote Run"} { + if !strings.Contains(report.Items[0].Message, text) { + t.Fatalf("missing %q in %s", text, report.Items[0].Message) + } + } +} diff --git a/server/workspace.go b/server/workspace.go index 93585a4..68af4a1 100644 --- a/server/workspace.go +++ b/server/workspace.go @@ -23,6 +23,7 @@ type GitSnapshot struct { AheadBehind string `json:"aheadBehind"` } type WorkspaceRequest struct { + Dedicated bool `json:"dedicated,omitempty"` WorkspacePath string `json:"workspacePath"` ProjectID string `json:"projectId,omitempty"` JavaHome string `json:"javaHome,omitempty"` @@ -74,7 +75,7 @@ func (s *Server) strictManifest(p string) *Project { // Keep this read-only: a build must still match the last committed sync snapshot. func (s *Server) manifest(p string) *Project { result := s.strictManifest(p) - if s.projects[p].WorkspacePath == "" { + if s.projects[p].WorkspacePath == "" || s.projects[p].Dedicated { return result } remote, e := gitSnapshot(s.work(p)) @@ -95,6 +96,23 @@ func (s *Server) manifest(p string) *Project { result.Revision = "" } } + checkout, err := inspectCheckout(s.work(p), remote, s.projects[p].Git) + if err == nil { + actual, inventoryErr := sourceInventory(s.work(p)) + if inventoryErr == nil { + for path := range actual { + if _, exists := result.Files[path]; !exists && checkout.matches(path) { + if current, err := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path))); err == nil { + result.Files[path] = current + } + } + } + } + } + if !sameSourceHashes(s.projects[p].Files, result.Files) || (s.projects[p].Git != nil && s.projects[p].Git.Head != remote.Head) { + result.Revision = "" + } + result.Git = remote return result } actual, e := sourceInventory(s.work(p)) @@ -109,7 +127,7 @@ func (s *Server) manifest(p string) *Project { } result.Files[path] = f } - if !sameSourceHashes(s.projects[p].Files, result.Files) { + if !sameSourceHashes(s.projects[p].Files, result.Files) || (s.projects[p].Git != nil && s.projects[p].Git.Head != remote.Head) { result.Revision = "" } result.Git = remote @@ -132,6 +150,18 @@ func sameSourceHashes(a, b map[string]File) bool { // Include restored/deleted tracked files when syncing after a clean reset/checkout. func (s *Server) syncBase(p string) (map[string]File, error) { old := s.projects[p].Files + if s.projects[p].Dedicated { + base := map[string]File{} + for path, f := range old { + base[path] = f + } + if s.projects[p].Pending != nil { + for path, f := range s.projects[p].Pending.Files { + base[path] = f + } + } + return base, nil + } if s.projects[p].WorkspacePath == "" { return old, nil } @@ -139,7 +169,7 @@ func (s *Server) syncBase(p string) (map[string]File, error) { if e != nil { return nil, e } - if remote == nil || remote.Dirty { + if remote == nil { return old, nil } actual, e := sourceInventory(s.work(p)) @@ -150,8 +180,14 @@ func (s *Server) syncBase(p string) (map[string]File, error) { for path, f := range old { base[path] = f } + var checkout *cleanCheckout + if remote.Dirty { + checkout, _ = inspectCheckout(s.work(p), remote, s.projects[p].Git) + } for path, f := range actual { - base[path] = f + if !remote.Dirty || checkout.matches(path) { + base[path] = f + } } return base, nil } @@ -248,7 +284,10 @@ func (s *Server) browseDirectories(w http.ResponseWriter, r *http.Request) { jsonOut(w, map[string]any{"path": path, "root": root, "roots": roots, "parent": parent, "selectable": selectErr == nil, "directories": dirs, "limit": 1000}) } func gitCommand(work string, input []byte, args ...string) ([]byte, error) { - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + return gitCommandFor(work, input, 30*time.Second, args...) +} +func gitCommandFor(work string, input []byte, timeout time.Duration, args ...string) ([]byte, error) { + ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() cmd := exec.CommandContext(ctx, "git", append([]string{"-c", "safe.directory=" + work, "-C", work}, args...)...) cmd.Stdin = bytes.NewReader(input) @@ -272,12 +311,20 @@ func gitSnapshot(work string) (*GitSnapshot, error) { } return &GitSnapshot{Head: read("rev-parse", "--verify", "HEAD"), Branch: read("symbolic-ref", "--short", "-q", "HEAD"), Dirty: read("status", "--porcelain", "--untracked-files=normal") != "", Upstream: read("rev-parse", "--abbrev-ref", "@{upstream}"), AheadBehind: read("rev-list", "--left-right", "--count", "HEAD...@{upstream}")}, nil } -func sourceInventory(work string) (map[string]File, error) { +func sourceInventory(work string) (map[string]File, error) { return sourceInventoryMode(work, false) } +func dedicatedInventory(work string) (map[string]File, error) { return sourceInventoryMode(work, true) } +func sourceInventoryMode(work string, dedicated bool) (map[string]File, error) { if e := noLinks(work); e != nil { return nil, e } result := map[string]File{} - git, e := gitSnapshot(work) + var git *GitSnapshot + var e error + if dedicated { + git = &GitSnapshot{} + } else { + git, e = gitSnapshot(work) + } if e != nil { return nil, e } @@ -365,6 +412,9 @@ func compareGit(local, remote *GitSnapshot) error { return nil } func (s *Server) checkGit(p string, local *GitSnapshot) error { + if s.projects[p].Dedicated { + return s.checkDedicated(p, local) + } remote, e := gitSnapshot(s.work(p)) if e != nil { return e @@ -384,6 +434,15 @@ func (s *Server) checkGit(p string, local *GitSnapshot) error { if e != nil { return e } + var checkout *cleanCheckout + checked := false + clean := func(path string) bool { + if !checked { + checkout, _ = inspectCheckout(s.work(p), remote, s.projects[p].Git) + checked = true + } + return checkout.matches(path) + } for path, f := range s.projects[p].Files { if !validPath(path) { continue @@ -394,11 +453,14 @@ func (s *Server) checkGit(p string, local *GitSnapshot) error { continue } } - return fmt.Errorf("服务端源码已变化:%s;为避免覆盖,请先处理服务端修改", path) + if clean(path) { + continue + } + return fmt.Errorf("服务端源码已变化:%s;该文件既不匹配上次同步版本,也未能确认与当前 Git 提交一致,请先处理服务端修改", path) } } for path := range actual { - if _, ok := s.projects[p].Files[path]; !ok { + if _, ok := s.projects[p].Files[path]; !ok && !clean(path) { return fmt.Errorf("服务端新增源码:%s;请先处理服务端修改", path) } } @@ -415,6 +477,46 @@ func (s *Server) checkWorkspace(w http.ResponseWriter, r *http.Request) { http.Error(w, e.Error(), 400) return } + if req.Dedicated { + var err error + buildWork := "" + if pr := s.projects[req.ProjectID]; pr != nil && pr.Dedicated { + if !sameAccessValue(pr.WorkspacePath, path) { + err = fmt.Errorf("工程绑定目录不匹配") + } else if pr.Busy { + err = fmt.Errorf("工作区正在构建") + } else { + err = s.checkDedicated(req.ProjectID, req.Git) + buildWork = s.work(req.ProjectID) + } + } + if req.Git == nil || !gitObjectID.MatchString(req.Git.Head) { + err = fmt.Errorf("请选择具有有效 Git 提交的本机工程") + } + message := "专用编译工作区:本机提交通过 bundle 导入,原远端仓库不参与同步或构建" + if err != nil { + message = err.Error() + } + var baseline *GitSnapshot + if pr := s.projects[req.ProjectID]; pr != nil && pr.Dedicated { + baseline = pr.Git + } + report := Preflight{Ready: true, Items: []CheckItem{{Name: "专用工作区", Status: "warning", Message: "首次Remote Run会初始化独立目录;初始化后可在此检查工具链,构建前也会再次检查"}}} + if buildWork != "" && err == nil { + cfg, configErr := s.buildEnvironment() + if configErr == nil && req.JavaHome != "" { + cfg.JavaHome, configErr = s.selectedJDK(req.JavaHome) + } + if configErr != nil { + report = Preflight{Items: []CheckItem{{Name: "环境配置", Status: "error", Message: configErr.Error()}}} + } else { + report = s.preflightForSync(buildWork, path, cfg) + } + } + s.privatePreflight(&report, path) + jsonOut(w, map[string]any{"workspacePath": path, "buildWorkspace": buildWork, "canSync": err == nil, "message": message, "git": baseline, "preflight": report}) + return + } remote, e := gitSnapshot(path) if e != nil { http.Error(w, e.Error(), 400) @@ -454,7 +556,7 @@ func (s *Server) checkWorkspace(w http.ResponseWriter, r *http.Request) { if configErr != nil { report = Preflight{Items: []CheckItem{{Name: "环境配置", Status: "error", Message: configErr.Error()}}} } else { - report = s.preflight(path, cfg) + report = s.preflightForSync(path, path, cfg) } } jsonOut(w, map[string]any{"workspacePath": path, "git": remote, "canSync": e == nil, "message": message, "preflight": report}) @@ -465,6 +567,10 @@ func (s *Server) createProject(w http.ResponseWriter, r *http.Request) { http.Error(w, e.Error(), 400) return } + if req.Dedicated { + s.createDedicated(w, req) + return + } p := id() pr := &Project{Files: map[string]File{}} if req.WorkspacePath != "" { diff --git a/server/workspace_files.go b/server/workspace_files.go new file mode 100644 index 0000000..6206e32 --- /dev/null +++ b/server/workspace_files.go @@ -0,0 +1,93 @@ +package main + +import ( + "fmt" + "io" + "os" + "path/filepath" + "strings" +) + +// 支持文件只接受管理员配置;不从源码同步或Git历史提取密钥。 +func (s *Server) prepareWorkspaceFiles(p string, c BuildEnvironment) error { + pr := s.projects[p] + if !pr.Dedicated { + return nil + } + var configured map[string]string + for source, files := range c.WorkspaceFiles { + if sameAccessValue(filepath.Clean(source), pr.WorkspacePath) { + configured = files + break + } + } + names, err := s.privateNames(p) + if err != nil { + return err + } + root := filepath.Join(s.root, "projects", p) + for relative, source := range configured { + for _, name := range names { + if sameAccessValue(relative, "work/"+name) && !sameAccessValue(source, filepath.Join(pr.WorkspacePath, filepath.FromSlash(name))) { + return fmt.Errorf("私有文件清单与已有workspaceFiles映射来源冲突:%s;请移除一处配置", name) + } + } + ext := strings.ToLower(filepath.Ext(relative)) + base := filepath.Base(relative) + mapped := relative + switch ext { + case ".jks", ".keystore", ".cer": + mapped = strings.TrimSuffix(relative, filepath.Ext(relative)) + ".asset" + default: + if base != "local.properties" && base != "key.properties" && base != "keystore.properties" { + return fmt.Errorf("仅允许配置服务端签名/证书及本机属性支持文件:%s", relative) + } + mapped = filepath.ToSlash(filepath.Join(filepath.Dir(relative), "support.asset")) + } + if !validPath(mapped) || (strings.HasPrefix(relative, "work/") && ext == ".cer") { + return fmt.Errorf("非法支持文件目标:%s;证书应放在work的兄弟目录", relative) + } + if !filepath.IsAbs(source) { + return fmt.Errorf("支持文件来源必须为服务端绝对路径:%s", relative) + } + if e := noLinks(root); e != nil { + return e + } + dest := filepath.Join(root, filepath.FromSlash(relative)) + if e := os.MkdirAll(filepath.Dir(dest), 0700); e != nil { + return e + } + input, e := os.Open(source) + if e != nil { + return fmt.Errorf("不能读取已配置的支持文件 %s:%w", relative, e) + } + info, e := input.Stat() + if e != nil || !info.Mode().IsRegular() || info.Size() > 16<<20 { + input.Close() + return fmt.Errorf("支持文件必须为小于16MiB的普通文件:%s", relative) + } + output, e := os.CreateTemp(filepath.Dir(dest), ".support-*") + if e != nil { + input.Close() + return e + } + name := output.Name() + written, copyErr := io.Copy(output, io.LimitReader(input, (16<<20)+1)) + if copyErr == nil && written > 16<<20 { + copyErr = fmt.Errorf("支持文件过大:%s", relative) + } + input.Close() + closeErr := output.Close() + if copyErr == nil { + copyErr = closeErr + } + if copyErr == nil { + copyErr = os.Rename(name, dest) + } + os.Remove(name) + if copyErr != nil { + return copyErr + } + } + return s.preparePrivateFiles(p) +} diff --git a/server/workspace_files_test.go b/server/workspace_files_test.go new file mode 100644 index 0000000..0ab6cd6 --- /dev/null +++ b/server/workspace_files_test.go @@ -0,0 +1,36 @@ +package main + +import ( + "os" + "path/filepath" + "testing" +) + +func TestExplicitWorkspaceSupportFilesAreConfined(t *testing.T) { + s := testServer(t) + p := project(t, s) + pr := s.projects[p] + pr.Dedicated = true + pr.WorkspacePath = t.TempDir() + cert := filepath.Join(t.TempDir(), "HONOR.CER") + key := filepath.Join(t.TempDir(), "key.jks") + writeFixture(t, cert, "certificate") + writeFixture(t, key, "key material") + c := BuildEnvironment{WorkspaceFiles: map[string]map[string]string{pr.WorkspacePath: {"cer/HONOR.CER": cert, "work/app/key.jks": key}}} + if e := s.prepareWorkspaceFiles(p, c); e != nil { + t.Fatal(e) + } + root := filepath.Join(s.root, "projects", p) + for relative, want := range map[string]string{"cer/HONOR.CER": "certificate", "work/app/key.jks": "key material"} { + data, e := os.ReadFile(filepath.Join(root, filepath.FromSlash(relative))) + if e != nil || string(data) != want { + t.Fatal(relative, e) + } + } + for _, target := range []string{"../escape.cer", "work/.git/hooks/key.jks", "work/public.cer", "work/build/key.jks", "state.json"} { + c.WorkspaceFiles[pr.WorkspacePath] = map[string]string{target: cert} + if e := s.prepareWorkspaceFiles(p, c); e == nil { + t.Fatal("unsafe support target accepted", target) + } + } +}