diff --git a/.gitignore b/.gitignore index 2ad0133..21d5a19 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,5 @@ dist/ .remotecompile/ *.log __pycache__/ + +.cache/ diff --git a/README.md b/README.md index 5755833..3ee48fd 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# VibeCoding Remote Compilation · 0.1 +# VibeCoding Remote Compilation · 0.4 Android Studio 本机编辑 → 增量上传 → 局域网服务编译 → 下载 APK → 本机 adb 安装。 @@ -6,6 +6,12 @@ Android Studio 本机编辑 → 增量上传 → 局域网服务编译 → 下 插件 0.1.4 支持 [连接配置与 Token 自动恢复](docs/plugin-0.1.4.md),保存一次后重启恢复,新项目复用最近保存的默认连接。 +0.2.0 增加 [构建恢复、历史 APK、缓存复用、系统代理和下载进度](docs/recovery-and-environment.md)。 + +0.3.0 增加 [必填远程目录、服务端目录选择、手动 Git 检查与 .gitignore 同步](docs/project-workspaces.md)。 + +0.4.0 增加 [CRLF/LF 等价比较与按工程选择服务端 JDK](docs/text-comparison-and-jdks.md)。 + ## 目录 | 目录 | 内容 | @@ -29,7 +35,7 @@ cd server go test ./... go build -o remotecompile.exe . $env:REMOTE_BUILD_TOKEN = '<自行生成的至少24字符随机值>' -.\remotecompile.exe -data .\data -tasks ':app:assembleDebug' +.\remotecompile.exe -data .\data -workspace-root 'D:\RemoteProjects' -tasks ':app:assembleDebug' ``` Linux/macOS: @@ -39,7 +45,7 @@ cd server go test ./... go build -o remotecompile . export REMOTE_BUILD_TOKEN='<自行生成的至少24字符随机值>' -./remotecompile -data ./data -tasks ':app:assembleDebug' +./remotecompile -data ./data -workspace-root /srv/remote-projects -tasks ':app:assembleDebug' ``` 默认监听服务器 `127.0.0.1:8765`。在本机建立 SSH 隧道,保持该终端开启: @@ -67,8 +73,8 @@ ZIP 输出在 `plugin/build/distributions/`。可用已安装的 Android Studio 在 Android Studio 的 Settings → Plugins → 齿轮 → Install Plugin from Disk 选择 ZIP。0.1.1 起配置和运行分开: -1. 打开右侧齿轮栏 **Remote Configuration**,填服务地址、Token 和 Gradle 任务,点击保存配置。Token 存入 IDE PasswordSafe,后续留空会保留原值。 -2. 任务例如 `:app:assembleDebug`,需要与服务器 `-tasks` 白名单一致。需要安装时勾选“构建成功后安装到所选设备”。 +1. 打开右侧齿轮栏 **Remote Configuration**,填服务地址、Token 和服务端已有工程文件夹,点击“检查远程工程”后保存配置。服务端文件夹为每个工程的必填独立配置,可用“选择服务端文件夹”浏览管理员允许的目录。Token 存入 IDE PasswordSafe,后续留空会保留原值。 +2. 在构建日志面板左侧“构建变体 / Gradle 任务”选择任务,例如 `:app:assembleCrosshatchDebug`;选择自动保存,可直接输入完整任务,最近使用的任务会保留。任务需要与服务器 `-tasks` 白名单一致。需要安装时勾选“构建成功后安装到所选设备”。 3. adb 路径可留空,自动从项目 `local.properties` 的 SDK 或本机 SDK 环境定位。只有需要指定其他 SDK 时才填写完整路径。 4. 在底部 **Remote Compilation** 的设备下拉框选择 USB 手机、无线设备或模拟器。单台在线设备自动选中;列表每 5 秒刷新,也可手动刷新。未授权/离线设备显示状态,无法用于安装。 5. 点击顶部运行图标、底部 **Remote Run** 或 Tools → Remote Run,直接使用已保存配置构建。右侧齿轮只打开配置,不触发构建。 @@ -78,16 +84,16 @@ ZIP 输出在 `plugin/build/distributions/`。可用已安装的 Android Studio ## 不通过 IDE 验证服务 -本机 Python 3.10+: +本机 Python 3.10+;使用 Git 忽略规则需要安装 Git: ```powershell $env:REMOTE_BUILD_TOKEN = '<与服务器一致的Token>' -python client/remote_run.py 'D:\Android项目' --task ':app:assembleDebug' +python client/remote_run.py 'D:\Android项目' --remote-folder 'D:\RemoteProjects\MyApp' --task ':app:assembleDebug' # 下载后安装到指定设备 -python client/remote_run.py 'D:\Android项目' --device '设备序列号' --adb 'C:\Android\Sdk\platform-tools\adb.exe' +python client/remote_run.py 'D:\Android项目' --remote-folder 'D:\RemoteProjects\MyApp' --device '设备序列号' --adb 'C:\Android\Sdk\platform-tools\adb.exe' ``` -客户端与插件分别分配独立工作区,不共享源码或构建输出。源码无需提交 Git。 +客户端与插件各自绑定独立的已有服务端工程目录。服务器通过 `-workspace-root` 指定允许的父目录,并给服务账户读取及修改工程的权限。源码无需提交 Git;两边已有 Git 仓库时会核对 HEAD。 Linux/macOS 在 `plugin/` 执行 `sh ./gradlew buildPlugin`。也可使用已安装的 Gradle 8.13 构建。 diff --git a/client/remote_run.py b/client/remote_run.py index b6ad983..731127e 100644 --- a/client/remote_run.py +++ b/client/remote_run.py @@ -11,13 +11,16 @@ import time import urllib.request import urllib.parse import uuid +from source_files import git_snapshot, collect, text_hash -EXCLUDE = {'.git', '.gradle', '.idea', '.remotecompile', '.kotlin', 'build', 'node_modules', '__pycache__'} def main(): parser = argparse.ArgumentParser(description='Sync, remote build, download and optionally install an APK') parser.add_argument('source', type=Path) parser.add_argument('--url', default='http://127.0.0.1:8765') + parser.add_argument('--remote-folder', required=True, help='Existing absolute project folder on the server') + parser.add_argument('--java-home', default='', help='JDK home selected from server /jdks; blank inherits service default') + parser.add_argument('--exact-line-endings', action='store_true', help='Upload CRLF/LF-only changes too') parser.add_argument('--task', default=':app:assembleDebug') parser.add_argument('--adb', default='adb') parser.add_argument('--server-cert', help='Trusted server public PEM certificate for LAN HTTPS') @@ -45,42 +48,53 @@ def main(): result = response.read() return result if '/artifacts/' in path else json.loads(result) - request('GET', '/health') + health = request('GET', '/health') + if not health.get('workspaceSelection'): + raise RuntimeError('Upgrade service to 0.3.0 for workspace selection') + if not health.get('textComparison') or not health.get('jdkSelection'): + raise RuntimeError('Upgrade service to 0.4.0 for EOL comparison and JDK selection') + local_git = git_snapshot(source) state_file = output / 'client.json' state = json.loads(state_file.read_text()) if state_file.exists() else {} - if state.get('url') != endpoint: - state = {'url': endpoint, 'project': request('POST', '/projects')['id']} + 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}) + 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'] state_file.write_text(json.dumps(state), encoding='utf-8') project = state['project'] remote = request('GET', f'/projects/{project}/manifest')['files'] manifest = {} changed = 0 - for directory, dirs, names in os.walk(source, followlinks=False): - for name in list(dirs): - if name in EXCLUDE: - dirs.remove(name) - elif (Path(directory) / name).is_symlink(): - raise RuntimeError('Symbolic links are unsupported') - for name in names: - if name == 'local.properties' or name.startswith('.env') or name.endswith(('.jks', '.keystore')) or name in ('key.properties', 'keystore.properties'): - continue - path = Path(directory) / name - if path.is_symlink(): - raise RuntimeError(f'Symbolic link: {path}') - if path.stat().st_size > 64 * 1024 * 1024: - raise RuntimeError(f'File exceeds 64 MiB: {path}') - content = path.read_bytes() - sha = hashlib.sha256(content).hexdigest() - relative = path.relative_to(source).as_posix() - entry = {'hash': sha} - if remote.get(relative, {}).get('hash') != sha: + eol_only = 0 + for path in paths: + if path.stat().st_size > 64 * 1024 * 1024: + raise RuntimeError(f'File exceeds 64 MiB: {path}') + content = path.read_bytes() + sha = hashlib.sha256(content).hexdigest() + relative = path.relative_to(source).as_posix() + entry = {'hash': sha} + previous = remote.get(relative, {}) + if previous.get('hash') != sha: + normalized = text_hash(relative, content) if not args.exact_line_endings else None + if normalized is not None and normalized == previous.get('textHash'): + entry = {'hash': previous['hash']} + eol_only += 1 + else: entry['data'] = base64.b64encode(content).decode() changed += 1 - manifest[relative] = entry + manifest[relative] = entry + latest_git = git_snapshot(source) + if (latest_git or {}).get('head') != (local_git or {}).get('head') or (latest_git or {}).get('branch') != (local_git or {}).get('branch'): + raise RuntimeError('Git state changed during scan; retry') revision = str(uuid.uuid4()) - print(f'Syncing {changed} changed files ({len(manifest)} total)', flush=True) - request('POST', f'/projects/{project}/sync', {'revision': revision, 'files': manifest}) - build = request('POST', f'/projects/{project}/builds', {'revision': revision, 'task': args.task}) + print(f'Syncing {changed} changed files ({len(manifest)} total), skipped {eol_only} EOL-only files', flush=True) + request('POST', f'/projects/{project}/sync', {'revision': revision, 'files': manifest, 'git': local_git}) + build = request('POST', f'/projects/{project}/builds', {'revision': revision, 'task': args.task, 'javaHome': args.java_home}) build_id = build['id'] offset = 0 try: diff --git a/client/source_files.py b/client/source_files.py new file mode 100644 index 0000000..a7adecb --- /dev/null +++ b/client/source_files.py @@ -0,0 +1,70 @@ +"""Use Git's own ignore implementation, including nested rules and negation.""" +import os +from pathlib import Path +import subprocess + +EXCLUDE = {'.git', '.gradle', '.idea', '.remotecompile', '.kotlin', 'build', 'node_modules', '.cxx', '.externalnativebuild', '__pycache__'} + +def reserved(name): + parts = name.lower().split('/') + leaf = parts[-1] + return any(p in EXCLUDE for p in parts) or leaf == 'local.properties' or leaf.startswith('.env') or leaf.endswith(('.jks', '.keystore')) or leaf in ('key.properties', 'keystore.properties') + +def git(root, *args, data=None): + return subprocess.run(['git', '-C', str(root), *args], input=data, capture_output=True, timeout=60) + +def git_snapshot(root): + try: + repo = git(root, 'rev-parse', '--is-inside-work-tree') + except FileNotFoundError: + return None + if repo.returncode or repo.stdout.strip() != b'true': + return None + def read(*args): + result = git(root, *args) + return result.stdout.decode('utf-8').strip() if result.returncode == 0 else '' + status = git(root, 'status', '--porcelain', '--untracked-files=normal') + if status.returncode: + raise RuntimeError('Cannot read local Git status') + return dict(head=read('rev-parse', '--verify', 'HEAD'), branch=read('symbolic-ref', '--short', '-q', 'HEAD'), dirty=bool(status.stdout), upstream=read('rev-parse', '--abbrev-ref', '@{upstream}'), aheadBehind=read('rev-list', '--left-right', '--count', 'HEAD...@{upstream}')) + +def collect(root: Path, snapshot): + if snapshot is not None: + listing = git(root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard') + if listing.returncode: + raise RuntimeError('Cannot list Git source files') + names = [p for p in dict.fromkeys(listing.stdout.decode('utf-8').split('\0')) if p and not reserved(p)] + ignored = git(root, 'check-ignore', '--no-index', '-z', '--stdin', data=('\0'.join(names)+'\0').encode('utf-8')) if names else None + if ignored is not None and ignored.returncode not in (0, 1): + raise RuntimeError('Git ignore check failed; sync stopped') + skipped = set(ignored.stdout.decode('utf-8').split('\0')) if ignored else set() + paths = [root / p for p in names if p not in skipped and os.path.lexists(root / p)] + else: + paths = [] + for directory, dirs, names in os.walk(root, followlinks=False): + dirs[:] = [d for d in dirs if not reserved((Path(directory)/d).relative_to(root).as_posix())] + for d in dirs: + if (Path(directory)/d).is_symlink(): + raise RuntimeError('Directory symlinks unsupported') + paths.extend(Path(directory)/n for n in names if not reserved((Path(directory)/n).relative_to(root).as_posix())) + if any(p.name == '.gitignore' for p in paths): + raise RuntimeError('.gitignore found without a readable Git working tree; sync stopped') + for path in paths: + if path.is_symlink() or not path.is_file(): + raise RuntimeError(f'Symlinks, submodules and nested repositories unsupported: {path}') + return paths + + +def text_hash(name, content): + import hashlib + leaf = Path(name).name.lower() + extensions = {'.kt', '.kts', '.java', '.xml', '.gradle', '.properties', '.json', '.toml', '.yaml', '.yml', '.txt', '.md', '.proto', '.c', '.cc', '.cpp', '.h', '.hpp', '.cmake', '.aidl', '.pro', '.cfg', '.ini', '.csv', '.html', '.css', '.js', '.ts', '.svg'} + if Path(leaf).suffix not in extensions and leaf not in {'.gitignore', '.gitattributes', '.editorconfig', 'cmakelists.txt'}: + return None + if b'\0' in content: + return None + try: + content.decode('utf-8') + except UnicodeDecodeError: + return None + return hashlib.sha256(content.replace(b'\r\n', b'\n')).hexdigest() diff --git a/client/test_smoke.py b/client/test_smoke.py index ac61d41..5af43d4 100644 --- a/client/test_smoke.py +++ b/client/test_smoke.py @@ -31,7 +31,7 @@ class SmokeTest(unittest.TestCase): root = Path(temp) source = root / '中文 project' source.mkdir() - (source / 'input.txt').write_text('first') + (source / 'input.txt').write_bytes(b'first\n') (source / 'deleted.txt').write_text('remove') if os.name == 'nt': (source / 'gradlew.bat').write_text('@echo off\nmkdir app\\build\\outputs\\apk\\debug 2>nul\ncopy /y input.txt app\\build\\outputs\\apk\\debug\\app-debug.apk >nul\nexit /b 0\n') @@ -42,13 +42,27 @@ class SmokeTest(unittest.TestCase): port = sock.getsockname()[1] endpoint = f'{"https" if secure else "http"}://127.0.0.1:{port}' env = dict(os.environ, REMOTE_BUILD_TOKEN='test-only-token-abcdefghijklmnopqrstuvwxyz') - command = [str(binary), '-listen', f'127.0.0.1:{port}', '-data', str(root / 'data')] + workspaces = root / 'workspaces' + workspace = workspaces / 'existing 工程' + workspace.mkdir(parents=True) + (source / '.gitignore').write_text('ignored/\n**/.cxx/\n**/build/\n.remotecompile/\n') + (source / 'ignored').mkdir() + (source / 'ignored/private.txt').write_text('must not upload') + (source / 'app/.cxx/Debug').mkdir(parents=True) + (source / 'app/.cxx/Debug/.ninja_deps').write_bytes(b'local native cache') + subprocess.run(['git', '-C', str(source), 'init', '-q'], check=True, capture_output=True) + 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')] context = None if secure: import ssl subprocess.run([str(binary), '-init-tls-host', '127.0.0.1', '-tls-dir', str(root/'tls')], check=True, capture_output=True) command += ['-tls-cert', str(root/'tls/server.crt'), '-tls-key', str(root/'tls/server.key')] context = ssl.create_default_context(cafile=str(root/'tls/server.crt')) + subprocess.run(['git', '-C', str(workspace), 'config', 'core.autocrlf', 'true'], check=True, capture_output=True) + (workspace / 'input.txt').write_bytes(b'first\r\n') process = subprocess.Popen(command, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) try: for _ in range(100): @@ -60,21 +74,38 @@ class SmokeTest(unittest.TestCase): time.sleep(.05) else: self.fail('Service did not start') - command = [sys.executable, str(ROOT / 'client' / 'remote_run.py'), str(source), '--url', endpoint] + command = [sys.executable, str(ROOT / 'client' / 'remote_run.py'), str(source), '--url', endpoint, '--remote-folder', str(workspace)] + req = urllib.request.Request(endpoint + '/api/v1/jdks', headers={'Authorization': 'Bearer ' + env['REMOTE_BUILD_TOKEN']}) + with urllib.request.urlopen(req, context=context, timeout=20) as response: + jdks = json.load(response)['jdks'] + chosen_jdk = next((j for j in jdks if j['version'].startswith('21')), jdks[0] if jdks else None) + if chosen_jdk: + command += ['--java-home', chosen_jdk['home']] if secure: command += ['--server-cert', str(root/'tls/server.crt')] - first = subprocess.run(command, env=env, capture_output=True, text=True, timeout=30) + first = subprocess.run(command, env=env, capture_output=True, text=True, timeout=120) self.assertEqual(first.returncode, 0, first.stderr) - self.assertEqual(next((source / '.remotecompile').glob('*.apk')).read_bytes(), b'first') - (source / 'input.txt').write_text('second') + 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') + (source / 'input.txt').write_bytes(b'second\n') (source / 'deleted.txt').unlink() - second = subprocess.run(command, env=env, capture_output=True, text=True, timeout=30) + second = subprocess.run(command, env=env, capture_output=True, text=True, timeout=120) self.assertEqual(second.returncode, 0, second.stderr) self.assertIn('Syncing 1 changed files', second.stdout) artifacts = [p.read_bytes() for p in (source / '.remotecompile').glob('*.apk')] - self.assertCountEqual(artifacts, [b'first', b'second']) + self.assertCountEqual(artifacts, [b'first\r\n', b'second\n']) state = json.loads((source / '.remotecompile' / 'client.json').read_text()) - self.assertFalse((root / 'data' / 'projects' / state['project'] / 'work' / 'deleted.txt').exists()) + 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()) + 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: + build = json.load(response)['builds'][0] + self.assertEqual(build['javaHome'], chosen_jdk['home']) + self.assertEqual(build['environment']['javaHome'], chosen_jdk['home']) finally: process.terminate() process.wait(timeout=15) diff --git a/deploy/windows/capture-environment.ps1 b/deploy/windows/capture-environment.ps1 new file mode 100644 index 0000000..2c3f6ff --- /dev/null +++ b/deploy/windows/capture-environment.ps1 @@ -0,0 +1,23 @@ +param([string]$OutputPath=(Join-Path $PWD 'build-environment.json')) +$ErrorActionPreference='Stop' +$gradle=$env:GRADLE_HOME +if(-not $gradle){$command=Get-Command gradle.bat -ErrorAction SilentlyContinue;if($command){$gradle=Split-Path (Split-Path $command.Source)}} +$cache=$env:GRADLE_USER_HOME +if(-not $cache -and $gradle){$folder=[IO.DirectoryInfo]$gradle;while($folder){if(Test-Path -LiteralPath (Join-Path $folder.FullName 'caches\modules-2')){$cache=$folder.FullName;break};$folder=$folder.Parent}} +if(-not $cache){$cache=Join-Path $env:USERPROFILE '.gradle'} +$sdk=$env:ANDROID_HOME;if(-not $sdk){$sdk=$env:ANDROID_SDK_ROOT} +$proxy='';$source='' +foreach($name in @('HTTPS_PROXY','HTTP_PROXY')){$value=[Environment]::GetEnvironmentVariable($name);if($value){$proxy=$value;$source=$name;break}} +if(-not $proxy){$url=[uri]'https://services.gradle.org';$system=[Net.WebRequest]::GetSystemWebProxy();if(-not $system.IsBypassed($url)){$proxy=$system.GetProxy($url).AbsoluteUri;$source='windows-interactive-user-system'}} +$safeProxy='' +if($proxy){ + $parsed=[uri]$proxy + if($parsed.UserInfo){throw 'Authenticated proxy detected. No credentials or configuration were saved. Use an unauthenticated local proxy.'} + if($parsed.Scheme -notin @('http','https') -or -not $parsed.Host){throw 'Unsupported proxy configuration; nothing saved.'} + # Persist only protocol, host and port; discard any query, fragment or path. + $safeProxy=('{0}://{1}:{2}' -f $parsed.Scheme,$parsed.DnsSafeHost,$parsed.Port) +} +$config=@{gradleHome=$gradle;gradleUserHome=$cache;javaHome=$env:JAVA_HOME;androidHome=$sdk;proxy=$safeProxy;proxySource=$source} +if(-not $config.javaHome){$config.Remove('javaHome')};if(-not $config.androidHome){$config.Remove('androidHome')} +[IO.File]::WriteAllText($OutputPath,($config | ConvertTo-Json),(New-Object Text.UTF8Encoding($false))) +Write-Output "Captured current user tool/cache/proxy settings to $OutputPath (no token)." diff --git a/deploy/windows/upgrade-service.ps1 b/deploy/windows/upgrade-service.ps1 new file mode 100644 index 0000000..5c8e621 --- /dev/null +++ b/deploy/windows/upgrade-service.ps1 @@ -0,0 +1,35 @@ +param([string]$Root='C:\ProgramData\VibeCodingRemoteCompilation',[string]$EnvironmentFile=(Join-Path $PSScriptRoot 'build-environment.json'),[switch]$GrantCacheAccess) +$ErrorActionPreference='Stop' +$markers=@(Get-ChildItem -LiteralPath "$Root\data\projects" -Directory -ErrorAction SilentlyContinue | ForEach-Object {Get-Item -LiteralPath (Join-Path $_.FullName 'active-build') -ErrorAction SilentlyContinue}) +if($markers.Count){Write-Output 'Active build IDs (not stopped):';$markers | ForEach-Object{Get-Content -LiteralPath $_.FullName};throw 'Wait for active builds; this upgrade never cancels them automatically.'} +$configPath="$Root\bin\RemoteCompileService.xml" +[xml]$config=Get-Content -LiteralPath $configPath -Raw +$next=Join-Path $PSScriptRoot 'remotecompile-windows-amd64.exe' +if(-not(Test-Path -LiteralPath $next)){throw 'New binary missing'} +if(-not(Test-Path -LiteralPath $EnvironmentFile)){throw 'Capture build-environment.json from the intended developer account first'} +$environment=Get-Content -LiteralPath $EnvironmentFile -Raw | ConvertFrom-Json +if(-not $environment.gradleUserHome){throw 'Gradle cache path required'} +New-Item -ItemType Directory -Force -Path $environment.gradleUserHome | Out-Null +# Traverse parent directories, grant writes only to the explicitly selected Gradle cache. +if($GrantCacheAccess){ +$parent=Split-Path $environment.gradleUserHome +while($parent -and $parent -ne [IO.Path]::GetPathRoot($parent)){ + & icacls.exe $parent /grant '*S-1-5-19:(X)' | Out-Null + if($LASTEXITCODE -ne 0){throw "Cannot grant cache path traversal: $parent"} + $parent=Split-Path $parent +} +& icacls.exe $environment.gradleUserHome /grant '*S-1-5-19:(OI)(CI)M' | Out-Null +if($LASTEXITCODE -ne 0){throw 'Cannot grant selected Gradle cache permission'} +} +Stop-Service RemoteCompile +(Get-Service RemoteCompile).WaitForStatus('Stopped',[TimeSpan]::FromSeconds(45)) +Copy-Item -LiteralPath "$Root\bin\remotecompile.exe" -Destination "$Root\bin\remotecompile.before-0.2.0.exe" -Force +Copy-Item -LiteralPath $configPath -Destination "$configPath.before-0.2.0.xml" -Force +Copy-Item -LiteralPath $next -Destination "$Root\bin\remotecompile.exe" -Force +$destination="$Root\build-environment.json" +Copy-Item -LiteralPath $EnvironmentFile -Destination $destination -Force +$config.service.arguments=([string]$config.service.arguments -replace '\s+-environment-file\s+"[^"]*"','')+" -environment-file `"$destination`"" +[IO.File]::WriteAllText($configPath,$config.OuterXml,(New-Object Text.UTF8Encoding($false))) +Start-Service RemoteCompile +Get-Service RemoteCompile | Select-Object Name,Status +Write-Output 'Updated service. Verify HTTPS health and /api/v1/environment with the existing token and certificate.' diff --git a/docs/deployment-192.168.5.222.md b/docs/deployment-192.168.5.222.md index 66a9aa8..8ed720b 100644 --- a/docs/deployment-192.168.5.222.md +++ b/docs/deployment-192.168.5.222.md @@ -1,57 +1,88 @@ # Windows 192.168.5.222 部署记录 -日期:2026-11-24(Asia/Shanghai)。 +日期:2026-11-24(Asia/Shanghai)。服务端版本:0.4.1(保留下方历史验收记录)。 -## 运行环境 +## 运行配置 -- Windows 11 x64,观察到系统版本 10.0.26300.9974。 -- SSH 用户 tt;具有管理员权限;登录密码未写入文件。 -- Android SDK:`D:\AndroidSdk\Windows`,已存在完整平台、Build Tools 和 licenses。 -- JAVA_HOME:`C:\Program Files\Java\jdk-25.0.3`。未修改系统全局环境变量。扫描范围内只找到 JDK25 和用户目录中的旧 JBR11,暂未确认 JDK17/21。 +- Windows 11 x64;SSH 用户 tt。密码未写入文件。 +- Windows 服务 `RemoteCompile`,自动启动,以 `NT AUTHORITY\LocalService` 运行。 +- 服务根目录:`C:\ProgramData\VibeCodingRemoteCompilation`;工作区、历史任务和原 Token 保留。 +- 地址:`https://192.168.5.222:8765`,直接局域网连接,无需本机 SSH 转发端口。 +- 防火墙仅允许 `192.168.5.0/24` 访问此程序的 TCP 8765。 +- 白名单任务:`:app:assembleDebug`。 +- 独立 JDK 17:`C:\ProgramData\VibeCodingRemoteCompilation\toolchains\jdk-17`。未改变系统全局 JDK25。 +- Android SDK:`D:\AndroidSdk\Windows`。 +- 复用依赖缓存:`E:\.gradle`。为服务账户授予此缓存写权限。 +- 检测到缓存内 Gradle 8.13,将其 bin/lib 复制到服务 toolchains/gradle-8.13,供低权限服务读取;未重新下载 Gradle 分发包。 +- 构建环境:服务根目录 `build-environment.json`,每次构建重新加载。 +- 捕获 tt 系统代理:`http://127.0.0.1:7890`,来源 `windows-interactive-user-system`。代理进程需持续运行;系统代理改变后重新捕获配置。 -## 已安装 +## 插件配置 -- 服务名:`RemoteCompile`,状态 Running,Automatic 延迟启动。 -- 运行账户:`NT AUTHORITY\LocalService`。 -- 程序及配置:`C:\ProgramData\VibeCodingRemoteCompilation\bin`。 -- 服务包装器:官方 WinSW 2.12.0 x64;文件上传前后 SHA-256 已核对。 -- 数据:`C:\ProgramData\VibeCodingRemoteCompilation\data`。 -- 缓存与用户目录:`C:\ProgramData\VibeCodingRemoteCompilation\home`。 -- 日志:`C:\ProgramData\VibeCodingRemoteCompilation\logs`。 -- 服务端监听:`127.0.0.1:8765`;未增加明文接口防火墙入站规则。 -- Gradle 任务白名单:`:app:assembleDebug`。 - -## 本机插件配置 +安装 `dist/remote-compilation-plugin-0.2.0.zip` 并重启 IDE。在 Remote Configuration 设置: | 字段 | 值 | | --- | --- | -| 地址 | `http://127.0.0.1:18765` | -| Token | 本机 `.deployment/client-token-192.168.5.222.txt`,复制到插件 PasswordSafe | -| 任务 | `:app:assembleDebug` | -| adb 与设备 | 使用本机 adb,指定设备序列号 | +| 服务地址 | `https://192.168.5.222:8765` | +| Token | 原 Token;本机私有文件 `.deployment/client-token-192.168.5.222.txt` | +| 服务器证书 | 本机 `.deployment/server-192.168.5.222.crt` 的绝对路径 | +| Gradle 任务 | `:app:assembleDebug` | +| 安装设备 | 在本机设备列表选择 | -已建立 SSH 隧道:本机 18765 → tt@192.168.5.222 → 服务器 127.0.0.1:8765。该隧道不设为开机启动;重新连接可运行 `examples/connect-192.168.5.222.ps1`,终端保持开启。 +公钥证书经已验证 SSH 传递,插件仍校验地址和证书。私钥仅在服务器 `bin/tls/server.key`。Token 与部署文件位于 Git 忽略目录,不提交仓库。 -Ubuntu 192.168.5.224 的本机 8765 隧道和 Token 文件未被替换。 +## 升级与验收 -服务器 Token 在受 ACL 保护的 `bin\RemoteCompileService.xml`;给 tt 的副本在 `C:\Users\tt\.remotecompile-service-token.txt`。本机凭据在被 Git 忽略的 `.deployment/` 目录,不包含 SSH 密码。 +- 旧服务因遗留 active-build 标记进入重启循环。确认无服务所属 Java/Gradle 进程后,将旧任务 `34a5603bf45783027ded18c67685625e` 保存为 interrupted,归档标记,恢复工作区使用。未删除源码或缓存。 +- 认证 HTTPS 健康接口返回 version=0.2.0、os=windows、recovery=true。 +- 真实 Android 验收项目:AGP 8.9.1、Gradle 8.13、compileSdk 35、JDK17。 +- 验收 buildId:`41d3a2a21c7352d17ba068d8cc63b3e1`,`:app:assembleDebug` 成功;真实 APK 已下载到本机并验证 SHA-256。 +- APK 大小 7692 字节;摘要 `28948dd3133d95cf63c1f59ffb6347c9f4c8497f748409d7c5511106a4c18623`。 +- 前两次验收遇到 Google Maven/Maven Central TLS 握手失败,重试后成功;日志与失败任务均保留。第三次没有重下 Gradle 分发包。 +- 服务重启后,同一 taskId、成功状态与 APK 摘要仍可查询;HTTP 206 分段下载合并后的 SHA-256 一致。未认证环境接口返回 HTTP 401。服务器二进制 SHA-256 与本机发布文件一致。 +- 未在手机安装验收 APK;未执行用户实际业务项目构建。 -## 验证结果 - -- 认证健康接口通过;本机经 SSH 隧道返回 HTTP 200,os=windows。 -- 以 LocalService 账户启动 JDK,通过环境变量读取 SDK android-35 的 android.jar,并成功执行 Build Tools 35.0.0 的 aapt2。 -- 源码同步、模拟构建、独立 APK 产物下载与 SHA-256 校验通过。 -- 验收 buildId:`1063235cb4c172b6b725995b9cdd00be`。 -- 验收产物是模拟文件,不是真实 Android APK,不能安装。 - -## 实际项目构建前 - -JDK25 与旧版 Gradle 不兼容。根据实际项目的 Gradle/AGP 版本配置 JDK17 或 JDK21,然后编辑 `bin\RemoteCompileService.xml` 中的 JAVA_HOME 并重启服务。本次未安装新 JDK,也未执行实际项目构建或手机安装。 - -管理命令(管理员 PowerShell): +管理命令(服务器管理员 PowerShell): ```powershell Get-Service RemoteCompile Restart-Service RemoteCompile Get-Content 'C:\ProgramData\VibeCodingRemoteCompilation\logs\*.log' -Tail 30 ``` +## 0.3.0 升级(2026-11-24) + +- 根据用户指示升级 Windows 服务到 0.3.0,启动参数增加 `-workspace-root "E:\TongTongStudio"`。服务仍为自动启动的 LocalService,HTTPS 地址不变。 +- 保留 Token、证书、构建环境、Gradle 缓存、历史任务。替换前检查无活动构建;旧 XML 和程序在 bin 下按 before-0.3.0-时间戳备份。 +- 服务 PATH 显式加入已有 `C:\Program Files\Git\cmd`,避免 SCM/SSH 旧环境找不到 Git。 +- 服务器程序 SHA-256:`3D6EF75AB5AA527A61B35F08A8DD7E6024F0F0541CEC3FBDA17A5024E1576C8A`,与本机发布文件一致。 +- 使用原证书与 Token 访问健康接口,确认 version=0.3.0、workspaceSelection=true;目录浏览根目录为 `E:\TongTongStudio`,越界 C:\Windows 返回 HTTP 400。 +- 本机 `D:\TongTongStudio\TTSTD\TTSTDElderly\ElderlyDialer` 与服务端 `E:\TongTongStudio\TTSTD\TTSTDElderly\ElderlyDialer` 检查通过:master 分支、HEAD `a1d583fb1c2543a798aa9333be9e693d47219831` 相同,本机 dirty=true,服务端 dirty=false,现有上游引用差异均为 0/0。 +- 升级后可查询旧成功任务 `41d3a2a21c7352d17ba068d8cc63b3e1`。本次没有同步或修改业务源码,也未启动业务项目构建。 +- 插件可使用 0.3.1(含紧凑进度条),服务端仍为 0.3.0。 + +## 0.4.0 升级(2026-11-24) + +- 按用户要求升级到 0.4.0。升级前、停服后均检查无 active-build;旧程序和 XML 已按 before-0.4.0-时间戳备份。仅替换服务程序,未改现有配置。 +- 程序 SHA-256:`CBFFEF0F0C9DA5D8B70144185BB9B59FCF8BBAA4AC6C341860D13B1D2EB0F380`,上传后及部署后匹配。 +- Windows 服务 Running、Auto、LocalService;原 HTTPS 地址、Token、公钥证书与工程根目录 `E:\TongTongStudio` 保留。 +- 健康接口 version=0.4.0,textComparison=true,jdkSelection=true。目标工程清单的 1140 个文件中 1118 个返回文本摘要;抽样 5 个与本机规范化摘要一致。未修改业务源码或回滚已有 Git 换行修改。 +- `/jdks` 以服务账户成功检测到 JDK17.0.21.0.3、JDK21.0.13.0.3、JDK25.0.3,以及服务独立 JDK17.0.8。JDK21 安装目录为 `C:\Program Files\Java\jdk-21.0.13.0.3`,可在插件 0.4.0 中为 ElderlyDialer 选择并保存。 +- 默认仍沿用服务 JDK17.0.8;未替换全局 JAVA_HOME。缓存仍为 E:\.gradle。原失败任务 `e66e3bb5196eb3d8b9f33b7ac65fed75` 可正常查询。本次未重跑该任务或执行手机安装。 + +## 0.4.1 同步快照误判修复(2026-11-24) + +- 修复实际报错:SmsRecordEntity.java 的服务端原始摘要与旧快照不同,Git 规范化 blob 却与 HEAD 完全相同。实际为 LF/CRLF 差异,不是真实源码修改。 +- 升级到 0.4.1;程序 SHA-256 `A75787853AE3C07CBC869414D6A38391C1DADC8881E12601DF722083AE4D0A18` 已在上传快照、部署程序核对一致。传输曾断开,SFTP 断点续传后验证完整摘要才升级。 +- 服务继续 Auto、LocalService,配置、证书、Token、JDK 选择能力与 E:\TongTongStudio 根目录保留。 +- 实际工程 ID `7b3fbd7a6f572f726102342b54365140` 的检查返回 canSync=true、远端 dirty=false、双方 HEAD 相同。 +- 问题文件 raw SHA-256 `b605d1fbe2c7aa8ba8093678fcbd16c46a625c9a6cdb4af663def013b7ff3444`;规范化摘要 `4d7e84a40fea6ca0ba369b62624d970f783189b3ba2bea4ce2f661fe97ff46a3` 与旧记录及本机文本一致。 +- 新 manifest 正确返回当前字节和 textHash,并以空 revision 提示需完成新同步。检查未改动持久化业务快照,未上传或修改业务源码,未执行业务构建。 +- 17 项 Go 回归测试、HTTP/HTTPS 两条端到端测试通过;Linux/macOS 交叉编译通过。兼容现有 0.4.0 插件。 + +## 构建任务白名单更新(2026-11-25) + +- 用户使用 :app:assembleCrosshatchDebug 被 task not allowed 拒绝,确认原启动参数只允许 :app:assembleDebug。 +- 核对本机工程 buildTypes 后,将现有任务白名单扩展为 :app:assembleDebug、:app:assembleRelease、:app:assembleCrosshatchDebug、:app:assembleCrosshatchRelease、:app:assembleZhanRuiDebug、:app:assembleZhanRuiRelease,原有其他白名单条目保留。 +- 更新前确认无活动构建,备份 XML、更新参数后重启。服务继续 Running、Auto、LocalService、版本 0.4.1;Token、证书、JDK、缓存和工程根目录不变。 +- 对实际工程使用特意不匹配的探测 revision 验证:上述六个任务均进入版本校验并返回 HTTP409;未知任务仍返回 task not allowed HTTP400。没有启动业务构建或修改源码。 +- 插件 0.4.3 把任务选择放到构建日志面板左侧,提供静态常见 buildTypes 候选与可编辑历史,选择按工程保存。22 项插件测试通过;新增变体仍需列入服务白名单。 diff --git a/docs/deployment-local-windows.md b/docs/deployment-local-windows.md new file mode 100644 index 0000000..248bfc3 --- /dev/null +++ b/docs/deployment-local-windows.md @@ -0,0 +1,43 @@ +# 本机 Windows 部署与真实 APK 测试 + +日期:2026-11-24(Asia/Shanghai)。本次在开发电脑本机部署,不是远端 192.168.5.222。 + +## 服务与连接 + +- Windows 服务:`RemoteCompile`,Running、Automatic,WinSW 2.12.0 包装,以 `NT AUTHORITY\LocalService` 运行。 +- 服务目录:`C:\ProgramData\VibeCodingRemoteCompilation`。 +- JDK 17:`C:\Program Files\Java\jdk-17`。 +- Android SDK:`F:\AndroidSDK`。 +- HTTPS:`https://localhost:8765`,证书包含 localhost、127.0.0.1 和 ::1。 +- 仅监听本机 127.0.0.1,本次未开放局域网防火墙端口;无需 SSH 隧道。 +- Token:本项目 `.deployment/local-windows/client-token.txt`,文件 ACL 限制为当前用户、管理员和 SYSTEM,内容不进入 Git。 +- 公钥证书:本项目 `.deployment/local-windows/server.crt`。 +- 私钥:服务目录 `bin/tls/server.key`,不要复制到客户端。 +- 允许任务:`:app:assembleDebug`。 + +插件右侧填上述地址、Token 和公钥证书路径,保存一次即可。使用插件 0.1.4 或更新版本。本次未向 IDE 自动写入连接设置。 + +## 真实构建验证 + +独立测试工程位于 `.deployment/local-android-smoke`,采用 AGP 8.9.1、Gradle 8.13、compileSdk/targetSdk 35、minSdk 23,应用 ID `studio.tongtong.remote.smoke`。测试适配 gradlew.bat 调用本机已安装的 Gradle 8.13;没有修改现有应用源码或系统全局工具链配置。 + +1. HTTP 部署健康检查、低权限账户 JDK/aapt2 及模拟构建验收通过。 +2. 切换 HTTPS 后,带 Token 和证书的健康检查 HTTP 200。 +3. 首轮真实 APK:buildId `3ea58b9f2e262b9e74813e55ca54b3b4`,构建成功,约 2 分 51 秒,30 个任务执行。 +4. 修改 manifest 应用标签,第二轮只上传 1 个变更文件;buildId `7ee80c8f3c78c6a3d0ccf4971ff342c9`,约 49 秒,5 个任务执行、25 个复用缓存。 +5. 两轮均通过 HTTPS 下载并核对 SHA-256;不同源码版本生成不同摘要的 APK。 +6. 首轮 APK 通过 apksigner v1/v2 签名验证,aapt2 能解析应用 ID、版本、SDK 与标签。 + +第二轮 APK 复制到 `dist/local-smoke-debug.apk`,为无启动 Activity 的最小测试包。本次未安装到手机,未验证插件 UI 驱动的全流程。 + +## 管理 + +管理员 PowerShell: + +```powershell +Get-Service RemoteCompile +Restart-Service RemoteCompile +Get-Content 'C:\ProgramData\VibeCodingRemoteCompilation\logs\*.log' -Tail 50 +``` + +服务工作区、缓存和调试签名保留在 ProgramData 下。后续若要让其他局域网电脑连接,需为本机实际局域网 IP 配置证书和监听地址,并限制防火墙来源网段;当前 localhost 证书/监听配置仅用于本机测试。 diff --git a/docs/lan-direct.md b/docs/lan-direct.md index ea04ffc..14e70a1 100644 --- a/docs/lan-direct.md +++ b/docs/lan-direct.md @@ -1,6 +1,6 @@ -# 局域网 HTTPS 直连(插件 0.1.3) +# 局域网 HTTPS 直连 -2026-11-24 状态:代码与产物已完成,本机服务端测试、8 项插件测试、HTTP/HTTPS 两条端到端测试通过;Windows/Linux/macOS 服务均已编译。Windows 服务器 SSH 不可达,用户确认稍后测试,因此尚未执行远端升级与防火墙变更。服务器恢复后再部署,当前不要将旧服务地址直接改为 HTTPS。 +2026-11-24 状态:Windows 192.168.5.222 已升级为 0.2.0 并启用局域网 HTTPS,原 Token 与工作区保留。具体配置与验收结果见 [服务器部署记录](deployment-192.168.5.222.md)。 连接:Android Studio → `https://192.168.5.222:8765` → 编译服务。本机无需监听 18765 或运行 SSH 隧道。 @@ -27,7 +27,7 @@ ## 插件配置 -安装 `dist/remote-compilation-plugin-0.1.3.zip` 后重启 IDE。在右侧 Remote Configuration 设置: +安装 `dist/remote-compilation-plugin-0.2.0.zip` 后重启 IDE。在右侧 Remote Configuration 设置: - 服务地址:`https://192.168.5.222:8765`。 - Token:原 Windows 服务的 Token,地址变化后需要重新保存到该地址对应的 PasswordSafe 项。 diff --git a/docs/operations.md b/docs/operations.md index 91ce3e1..a636594 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -21,7 +21,7 @@ data/ artifacts//*.apk 独立 APK ``` -Ctrl+C 或 SIGTERM 会尝试取消执行中的任务并等待终态落盘。崩溃或强制终止后,如果仍有 `active-build`,服务拒绝启动,避免在残留 Gradle 进程还运行时覆盖源码。管理员须先确认并终止该工作区残留的 Gradle/Java 进程,再删除该工作区 `active-build` 文件后重启;不要随意结束其他项目的 Gradle Daemon。 +Ctrl+C 或 SIGTERM 会尝试取消执行中的任务并等待终态落盘。0.2.0 起,崩溃或强制终止后若仍有 `active-build`,服务可启动并查询历史任务,但会保留该工作区的锁,将原运行任务标为 interrupted,避免覆盖残留进程使用的源码。管理员须先确认并终止该工作区残留的 Gradle/Java 进程,再删除标记并重启;不要随意结束其他项目的 Gradle Daemon。 任务固定超时 30 分钟。取消按 Unix 进程组 / Windows taskkill 进程树执行;需在真实项目确认其插件启动的外部子进程遵守这一边界。 diff --git a/docs/project-workspaces.md b/docs/project-workspaces.md new file mode 100644 index 0000000..a196854 --- /dev/null +++ b/docs/project-workspaces.md @@ -0,0 +1,49 @@ +# 0.3.0 工程目录、Git 检查与同步排除 + +每个工程必须独立填写服务端已有工程文件夹的绝对路径。该字段不继承其他工程的默认值,更换地址或文件夹后重置工作区绑定。Token、证书等连接默认值仍可复用。 + +## 配置步骤 + +1. 先在服务器准备工程目录,需要比较 Git 时在该目录准备对应仓库,并使双方 HEAD 相同。服务不会自动 clone、fetch、pull 或覆盖 Git 元数据。 +2. 服务启动参数增加 `-workspace-root "D:\RemoteProjects"`(Linux/macOS 使用相应绝对路径),限制允许选择的父目录。默认只允许服务 data/projects 下已有的旧工作区。 +3. 为服务运行账户授予所选工程目录读写权限。Git 需在服务账户的 PATH 可见。Git 使用选定目录的作用域信任配置,不修改全局 safe.directory。 +4. 插件 Remote Configuration 填写连接信息,点击“选择服务端文件夹…”浏览服务器已有目录,或直接填完整路径。选择后自动检查,也可点击“检查远程工程”。 +5. 检查通过后保存配置,再 Remote Run。运行前会再次检查目录、Git 和远程修改情况。 + +浏览与检查不创建目录、不修改源码、不拉取仓库。目录必须位于允许的父目录中,不能经过符号链接或目录联接。服务数据和元数据目录不可作为工程目录;可精确选择旧的 `data/projects/<项目ID>/work`,首次绑定时保留原项目 ID。 + +## Git 检查 + +- 显示本机和服务端 HEAD、分支、工作树是否有修改,以及基于现有上游引用的 ahead/behind。检查不联网更新引用。 +- 双方都有仓库且 HEAD 不同:停止同步,先手动更新仓库。 +- 服务端仓库首次绑定时有未提交修改:停止,避免覆盖。 +- 本机未提交修改可以正常上传。远程因此产生的脏工作树不影响下一次同步;若有人在服务器额外改动或添加源码,则停止并提示具体路径。 +- 如果手动将服务端更新到与本机相同提交的干净工作树,可继续同步。 +- 服务端没有 `.git` 时明确提示无法比较 Git 提交;仍可同步源码。多个客户端不能同时绑定同一目录或互相嵌套的目录。 + +## 忽略与错误修复 + +插件和 Python 客户端调用 Git 原生规则,支持嵌套 `.gitignore`、`!` 反选、`.git/info/exclude` 和全局 excludes。未被忽略的未跟踪源码仍会上传。即使文件被强制加入 Git,若命中忽略规则,也不上传。 + +`.git`、`.gradle`、`.idea`、各模块 build、`.cxx`、`.externalNativeBuild`、本机 SDK 配置与凭据始终排除。服务器保留自己的构建缓存。升级前误传到清单里的 `.cxx` 文件会退出源码管理,不删除服务端缓存文件。 + +当前同步使用 HTTP 文件清单及增量上传;这些规则用于统一源码筛选,并未新增 rsync 传输适配器。 + +`missing content: app/.cxx/.../.ninja_deps` 的原因是构建修改了此前误传的缓存,而旧清单还宣称服务端内容未变。新版同时排除缓存、核验清单中的实际内容;失效哈希不会再诱导客户端省略上传。没有 Git 工作树却检测到 `.gitignore` 时,会停止并提示修复 Git 环境,避免忽略规则失效后误传。 + +## 产物与部署状态 + +安装包为 `dist/remote-compilation-plugin-0.3.0.zip`,服务端也需要更新到 0.3.0。旧 0.2.0 服务不支持目录浏览和 Git 检查,新插件会提示升级。 + +最初仅构建和测试安装包;随后按用户要求将 192.168.5.222 服务升级到 0.3.0,允许根目录为 `E:\TongTongStudio`,目标工程 Git 检查通过。已运行的本机服务未升级。Windows 运行测试与 Linux/macOS 交叉编译结果分别记录,不将交叉编译视为运行验证。 + +## 验证结果(2026-11-24) + +- Windows:14 项 Go 测试通过,覆盖遗留缓存清理、实际文件哈希、目录浏览越界、Git HEAD 不同、远程额外修改和旧版本构建拦截。 +- 插件:15 项测试通过,0.3.0 ZIP 已生成;包含配置持久化、目录变更重置绑定、嵌套/反选忽略规则、已跟踪忽略文件与原生缓存排除。 +- HTTP/HTTPS 两条真实服务端到端测试通过:绑定已有 Git 目录、未提交源码增量更新、文件删除、两次构建、产物下载;断言忽略文件与 .cxx 缓存未上传,远程 .git 保留。该测试使用模拟 Wrapper,未再次执行真实 Android 工具链或手机安装。 +- Linux amd64、macOS arm64 交叉编译通过;本次未在这两个系统运行服务。文件夹选择器尚未在用户实际 Android Studio 中手动验收。 + +0.3.1 插件仅调整进度区:进度条改为紧凑宽度,百分比独立显示;状态文字移到下方,支持换行、滚动、选中复制及悬停查看。仍配合 0.3.0 服务端使用。 + +0.3.2 插件允许无设备、离线或未授权设备时继续同步、编译和下载 APK。自动安装移至下载成功后检查;无可用目标、adb 不可用或安装失败时保留 APK,并单独提示安装结果。连接设置侧栏整体支持纵向滚动,窄窗口下仍可访问底部按钮与检查结果。服务端继续兼容 0.3.0。 diff --git a/docs/recovery-and-environment.md b/docs/recovery-and-environment.md new file mode 100644 index 0000000..7e560fa --- /dev/null +++ b/docs/recovery-and-environment.md @@ -0,0 +1,76 @@ +# 0.2.0:任务找回、环境复用、系统代理和进度 + +## 构建恢复与 APK 找回 + +- 插件在提交前将服务器、工作区、源码 revision、任务名和 clientRequestId 保存到项目 `.remotecompile/last-build.json`;收到响应后补充 buildId,不保存 Token。 +- 服务端按“工作区 + clientRequestId”去重,相同参数重试返回同一个 buildId;同一个请求 ID 搭配不同源码/任务会返回 409。 +- 断网不会取消服务端构建。插件会短暂重试,仍失败时保留记录;点击“恢复上次构建”继续查询同一任务。 +- “构建历史”列出本项目工作区最近 50 个任务,也可粘贴已知 buildId。老版本没有本地记录时,仍可按已有工作区查询最近任务。 +- “下载 APK”只获取成功任务的产物;下载途中断开会保留 `.apk.part`,下次通过 HTTP Range 续传,完成后核对大小和 SHA-256。已有完整且摘要正确的 APK 直接复用。 +- 恢复/下载不会自动安装旧版本。需要安装时选择设备,再点击“安装已下载 APK”;安装前再次校验文件摘要和设备状态。手动安装已下载文件不需要服务器在线。 +- 服务端从入队起持久化任务,执行期间定期更新日志和进度,结束时保存终态。正常重启后已完成任务及产物可以继续查询。 +- 如果服务异常退出,原运行任务标为 interrupted;残留 active-build 对应的工作区继续锁定,其他工作区仍可使用。管理员确认残留进程已经停止后移除该工作区标记并重启,不能把“恢复监控”当作恢复已经中断的 Gradle 进程。 + +## Gradle、Java、Android 环境复用 + +启动服务时可指定管理员维护的 JSON: + +```text +-environment-file C:\ProgramData\VibeCodingRemoteCompilation\build-environment.json +``` + +```json +{ + "gradleHome": "F:/gralde/wrapper/dists/gradle-8.13-all/54h0s9kvb6g2sinako7ub77ku/gradle-8.13", + "gradleUserHome": "F:/gralde", + "javaHome": "C:/Program Files/Java/jdk-17", + "androidHome": "F:/AndroidSDK", + "proxy": "http://127.0.0.1:7890", + "proxySource": "configured", + "preferWrapper": false +} +``` + +以上路径和代理端口仅为配置格式示例,使用自己的实际值。文件每次构建重新读取;不修改项目 Wrapper 文件或机器全局环境变量。未指定配置项时沿用服务进程的环境变量,Gradle 安装还可从 PATH 检测。 + +服务读取项目 Wrapper 要求的版本,依次检查指定/检测到的 GRADLE_HOME,以及 GRADLE_USER_HOME 中相同版本的 Wrapper 安装。确认 launcher 文件版本完全匹配时直接调用已有 Gradle,避免同版本的 all/bin 分发包再次下载;不同版本不会强行复用。 + +需要执行自定义 gradlew 前置逻辑时设置 preferWrapper=true,仍复用缓存,但始终执行项目 Wrapper。缓存不存在或版本不匹配时使用项目 Wrapper 下载其指定版本。 + +共享缓存前会检查服务账户能否创建文件;Java、Gradle 和 Android SDK 本身也需可读。缓存包含全局配置和初始化脚本,应仅复用可信目录。升级脚本默认不批量修改已有目录权限;确需授予 LocalService 权限时可以明确使用 -GrantCacheAccess,大目录的继承传播可能耗时。 + +## 系统代理 + +优先级:配置文件中的无认证代理 → HTTPS_PROXY/HTTP_PROXY 环境变量 → 系统代理检测。Windows 服务读取的是服务账户环境,交互登录用户的代理需在该用户下运行 `deploy/windows/capture-environment.ps1` 捕获,再交给服务使用。 + +该脚本通过 .NET 系统代理 API 对 Gradle 分发站点解析代理(包括系统/PAC 的解析结果),只保存协议、主机和端口;遇到 URL 用户名密码会停止,不落盘凭据,不输出完整配置。PAC 的结果在捕获时解析为静态代理,系统代理改变后需重新捕获。Linux/macOS 当前主要使用代理环境变量或明确配置,不读取所有桌面环境的专有设置。 + +检测结果用于 Gradle JVM 的 http/https 系统属性,以及服务端用于下载总大小探测的请求。源码中的代理测试通过受控代理确认探测请求确实经过代理。认证代理 URL 当前不支持,可使用本机无认证转发代理。proxy="direct" 可以明确关闭代理。 + +## 下载进度与路径 + +“查看构建环境”显示服务端有效路径及代理来源;每个任务还记录实际执行器、请求版本和 Gradle 可执行文件。 + +确实需要下载 Gradle 时,服务只监控 Wrapper 的 `.zip.part`,不自行写入或解压 Wrapper 缓存。状态条显示保存位置、已下载字节、可获取时的总大小/百分比以及采样速度;服务器不提供总大小时显示字节数,不伪造百分比。下载结束后显示解压/构建状态。进度可随任务重新查询。 + +Wrapper 缓存路径规则依据 [Gradle PathAssembler](https://raw.githubusercontent.com/gradle/gradle/v8.13.0/platforms/core-runtime/wrapper-shared/src/main/java/org/gradle/wrapper/PathAssembler.java) 和 [Install](https://raw.githubusercontent.com/gradle/gradle/v8.13.0/platforms/core-runtime/wrapper-shared/src/main/java/org/gradle/wrapper/Install.java)。此处进度针对 Gradle 分发包和 APK 下载,不是所有 Maven 依赖的逐文件下载仪表盘。 + +## Windows 本机升级 + +1. 用实际开发用户运行 capture-environment.ps1,生成 build-environment.json。 +2. 将配置、新版服务程序和 upgrade-service.ps1 放到同一目录,以管理员运行升级脚本。 +3. 脚本检测活动构建,繁忙时拒绝升级,不自动取消任务;空闲时备份并更新程序、保留 HTTPS/Token/SDK/工作区,加入 environment-file 参数。 +4. 安装插件 0.2.0 ZIP 并重启 IDE,沿用已有连接配置。 + +新插件会检查服务是否支持 recovery 能力;旧服务器需升级到 0.2.0,不能只更新插件。 + +## 2026-11-24 验证记录 + +- 服务端 11 项测试通过,覆盖入队幂等与响应丢失找回、任务/进度落盘、中断锁定、精确 Gradle 版本选择、受控代理请求及进度采样,并保留旧功能回归。 +- 插件 12 项测试通过,最终 ZIP 核对包含历史、恢复、下载续传、手动安装入口和大文件流式摘要代码,未重新引入 WriteIntentReadAction 的不兼容引用。 +- HTTP/HTTPS 两条参考客户端端到端测试通过。 +- 本机 Windows 服务已升级到最终 0.2.0,配置选择现有 Gradle 8.13 安装、F:\gralde 缓存、JDK17、F:\AndroidSDK,代理来源为交互用户系统代理。未修改全局注册表环境变量。 +- 真实 Android 测试工程已改用标准 8.13-bin Wrapper 文件,服务通过精确版本匹配直接执行现有 8.13 安装,没有重新下载分发包。 +- 真实 buildId:b4e80efc428a6a5679d7a7a41001758e。验证了忽略提交响应后按 clientRequestId 找回、重复提交返回同一 ID、客户端短暂断连不取消任务、HTTP 206 分片拼接及 SHA-256。 +- 服务正常重启后,同一请求和任务仍可查询,产物重新下载并校验通过。验证摘要保存在被 Git 忽略的 `.deployment/upgrade-0.2.0/live-summary.json`。 +- 未在 Android Studio 中自动安装新版插件;真实 IDE 界面及设备安装需更新 ZIP 后使用验证。Linux/macOS 为交叉编译验证;下载百分比的自动测试使用受控代理和模拟增长的 Wrapper 分片,未为测试故意重复下载已有 Gradle。 diff --git a/docs/text-comparison-and-jdks.md b/docs/text-comparison-and-jdks.md new file mode 100644 index 0000000..4e666a1 --- /dev/null +++ b/docs/text-comparison-and-jdks.md @@ -0,0 +1,51 @@ +# 0.4.0:换行比较和服务端 JDK + +同步一直使用 SHA-256,按文件相对路径原地写入。此前仅 CRLF/LF 不同也会上传,容易造成已有 Git 工作树出现大量修改;这些通常不是新增的文件副本。 + +## 换行比较 + +默认启用“忽略文本文件 CRLF / LF 换行差异”。同步先检查原始 SHA-256,再检查服务端提供的文本摘要。两边文本只差 CRLF/LF 时不上传、不重写,保留服务端字节;日志单独统计跳过数量。真正改动的文本仍上传全文,这是文件级增量,不是块级补丁传输。 + +仅针对已支持扩展名的有效 UTF-8 源码和配置文件。含 NUL、非法 UTF-8、UTF-16、JAR、图片等二进制按原始字节比较。gradlew、shell 等执行脚本也保留严格比较,避免改变可执行语义。空格、缩进、独立 CR、BOM 和末尾换行增删不忽略。该选项可关闭。 + +此前已经产生的 Git 换行修改不会自动回滚。避免误覆盖真实业务改动,本版不执行 git reset、checkout、restore 或修改全局 core.autocrlf。项目的长期换行约定可通过团队维护的 .gitattributes 统一。 + +## JDK 选择 + +在 Remote Configuration 点击“检测服务端 JDK(where / 安装目录)”,选择版本后保存配置。选择对当前工程有效;默认项继续使用服务 build-environment.json 中的 javaHome。 + +发现来源包括服务进程上下文的 where.exe java/javac(Unix 使用 which)、PATH、JAVA_HOME、服务已配置 JDK、toolchains、常见厂商安装目录和 macOS JavaVirtualMachines。不是检测本机开发电脑的 JDK。只列出含 java、javac、release 版本信息的 JDK,列表显示版本和路径;不会自动安装 JDK,也不会按最高版本自动替换当前选择。 + +例如依赖 Java 21 class 的 framework.jar,应在服务器安装 JDK21 后选择该版本;还需满足项目 Gradle/AGP 的兼容要求。系统只有 JDK17/JDK25 时,刷新列表不会凭空出现 JDK21。 + +构建请求携带选择,服务验证它属于发现列表,实际执行环境和历史记录保存 javaHome。重连/下载历史 APK 沿用原构建,不用新选择重跑旧任务。 + +Python 客户端可用 `--java-home "服务器上的JDK目录"`;使用 `--exact-line-endings` 关闭默认的换行等价比较。 + +## 安装 + +需要插件和服务端都升级到 0.4.0。安装包位于 dist/remote-compilation-plugin-0.4.0.zip;开发后已按用户要求部署到 192.168.5.222,健康接口、文本摘要及 JDK 列表验收通过;本机常驻服务未升级。 + +验证:Windows 16 项 Go 测试、17 项插件测试及 HTTP/HTTPS 两条端到端测试通过。端到端测试使用模拟 Wrapper,验证 CRLF 服务端原字节保留、真实内容变更上传、Git 元数据保留,以及 JDK 选择进入构建记录和环境;本次未执行真实 Android 编译。Linux amd64、macOS arm64 交叉编译通过,未运行验证。 + + +## 0.4.1:同步快照与 Git 干净检出 + +修复 Git 工作树干净、HEAD 一致,但磁盘字节不同于历史同步快照时被误判为远端源码冲突的问题。检查保持只读;允许下一次同步以当前干净检出为基准,清单返回当前文件的实际摘要与文本摘要。旧快照不再代表磁盘内容时,清单 revision 为空;构建提交仍按持久化同步快照精确核验,必须完成新同步后再构建。 + +同步删除同时覆盖历史管理文件和当前干净检出的源码,避免 checkout 恢复的已删除文件残留。新快照保存文本摘要;远端脏树中仅发生 CRLF/LF 变化的已管理文本可比较规范化摘要,真实内容变化仍拦截。不会执行 Git restore/reset 或更改业务源码来消除检查错误。 + +Windows 完整 17 项 Go 测试和 HTTP/HTTPS 两条端到端测试通过,Linux/macOS 交叉编译通过。兼容现有 0.4.0 插件。 + +## 0.4.2 插件日志显示 + +构建面板改为左侧设备、操作、构建恢复和进度,右侧构建日志;分隔条可拖动,左侧可纵向滚动。日志按窗口宽度自动换行,每条非空日志行显示 [HH:mm:ss.SSS] 本机接收时间。服务器分块日志跨行及 CRLF 被拆分时不会在同一行中间重复插入时间,也不再为每个网络块强加换行。历史日志恢复显示本次接收时间,不代表原始构建发生时间;服务端既有日志存储格式不变。兼容 0.4.1 服务端。 + + +## 0.4.3 插件快速选择构建变体 + +构建日志左侧增加“构建变体 / Gradle 任务”可编辑下拉框。选择后自动按工程保存,Remote Run 直接使用当前选择;重启 IDE 恢复上次任务,最近 20 个任务作为候选。连接侧栏移除任务输入,保存连接配置不会覆盖构建面板的新选择。 + +自动读取常见 Groovy/Kotlin Gradle 脚本中的 application 模块 buildTypes,提供 Debug/Release 及字面量自定义构建类型候选;不启动 Gradle,因此不会为刷新列表再跑一次配置。动态 DSL、别名插件、自定义 projectDir 和组合 flavor 的任务可能无法完整静态枚举,可直接输入完整任务,之后进入历史。刷新变体读取磁盘文件。 + +服务端仍执行任务白名单。当前 ElderlyDialer 已按工程定义配置 assembleDebug、assembleRelease、assembleCrosshatchDebug、assembleCrosshatchRelease、assembleZhanRuiDebug、assembleZhanRuiRelease。新增其他任务需由管理员补充 -tasks,而非开放任意命令。服务端保持 0.4.1,插件为 0.4.3;22 项插件测试通过。 diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index 4329a82..fc43258 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.1.4" +version = "0.4.3" repositories { mavenCentral() intellijPlatform { defaultRepositories() } diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/BuildTasks.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/BuildTasks.kt new file mode 100644 index 0000000..706923c --- /dev/null +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/BuildTasks.kt @@ -0,0 +1,73 @@ +package studio.tongtong.remotecompile + +import java.nio.file.* +import java.nio.file.attribute.BasicFileAttributes + +/** Read common literal Gradle declarations; never execute Gradle merely to populate the selector. */ +object BuildTasks { + private val name = Regex("[A-Za-z0-9_]+") + fun valid(task: String) = Regex(":?[A-Za-z0-9_]+(:[A-Za-z0-9_]+)*").matches(task) + private data class Token(val value: String, val string: Boolean = false) + private fun tokens(text: String): List { + val result = mutableListOf(); var i = 0 + while (i < text.length) { + val c = text[i] + when { + c.isWhitespace() -> i++ + text.startsWith("//", i) -> { i = text.indexOf('\n', i).let { if (it < 0) text.length else it } } + text.startsWith("/*", i) -> { i = text.indexOf("*/", i + 2).let { if (it < 0) text.length else it + 2 } } + c == '\'' || c == '"' -> { + val triple = text.startsWith("$c$c$c", i); val quote = if (triple) "$c$c$c" else "$c" + i += quote.length; val value = StringBuilder() + while (i < text.length && !text.startsWith(quote, i)) { + if (text[i] == '\\' && i + 1 < text.length) i++ + value.append(text[i++]) + } + i = minOf(text.length, i + quote.length); result.add(Token(value.toString(), true)) + } + c.isLetterOrDigit() || c == '_' -> { val start = i++; while (i < text.length && (text[i].isLetterOrDigit() || text[i] == '_')) i++; result.add(Token(text.substring(start, i))) } + else -> { result.add(Token(c.toString())); i++ } + } + } + return result + } + fun fromScript(module: String, text: String): List { + if (!module.split(':').filter { it.isNotEmpty() }.all { name.matches(it) }) return emptyList() + val tokens = tokens(text) + if (tokens.none { it.string && it.value == "com.android.application" }) return emptyList() + val types = linkedSetOf("debug", "release") + var i = 0 + while (i < tokens.size - 1) { + if (tokens[i].string || tokens[i].value != "buildTypes" || tokens[i + 1].value != "{") { i++; continue } + var depth = 1; i += 2 + while (i < tokens.size && depth > 0) { + val t = tokens[i] + if (depth == 1 && !t.string) { + val next = tokens.getOrNull(i + 1)?.value + if (name.matches(t.value) && (next == "{" || (next == "." && tokens.getOrNull(i + 2)?.value == "initWith"))) types.add(t.value) + if (t.value in setOf("create", "register", "maybeCreate", "getByName", "named") && next == "(") { + tokens.getOrNull(i + 2)?.takeIf { it.string && name.matches(it.value) }?.let { types.add(it.value) } + } + } + if (!t.string) { if (t.value == "{") depth++; if (t.value == "}") depth-- } + i++ + } + } + return types.map { "$module:assemble${it.replaceFirstChar(Char::uppercaseChar)}" }.distinct() + } + fun discover(root: Path): List { + val result = linkedSetOf() + Files.walkFileTree(root, emptySet(), 5, object : SimpleFileVisitor() { + override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes) = + if (dir != root && SourceFiles.reserved(root.relativize(dir).joinToString("/"))) FileVisitResult.SKIP_SUBTREE else FileVisitResult.CONTINUE + override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { + if (file.fileName.toString() in setOf("build.gradle", "build.gradle.kts") && attrs.isRegularFile && attrs.size() <= 2 * 1024 * 1024) { + val relative = root.relativize(file.parent).joinToString(":") + result.addAll(fromScript(if (relative.isEmpty()) "" else ":$relative", Files.readString(file))) + } + return FileVisitResult.CONTINUE + } + }) + return result.toList() + } +} diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/LastBuild.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/LastBuild.kt new file mode 100644 index 0000000..8699896 --- /dev/null +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/LastBuild.kt @@ -0,0 +1,20 @@ +package studio.tongtong.remotecompile +import com.google.gson.Gson +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 = "") +object LastBuildStore { + private val gson = Gson() + fun load(root: Path): LastBuild? { + val path = root.resolve(".remotecompile/last-build.json") + return if (Files.exists(path)) gson.fromJson(Files.readString(path), LastBuild::class.java) else null + } + fun save(root: Path, value: LastBuild) { + val path = root.resolve(".remotecompile/last-build.json"); Files.createDirectories(path.parent) + val temp = path.resolveSibling("last-build.json.tmp"); Files.writeString(temp, gson.toJson(value)) + try { Files.move(temp, path, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) } + catch (_: java.nio.file.AtomicMoveNotSupportedException) { Files.move(temp, path, StandardCopyOption.REPLACE_EXISTING) } + } +} diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/RemoteToolWindow.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/RemoteToolWindow.kt index 042e530..083667f 100644 --- a/plugin/src/main/kotlin/studio/tongtong/remotecompile/RemoteToolWindow.kt +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/RemoteToolWindow.kt @@ -17,6 +17,7 @@ import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.content.ContentFactory +import com.intellij.util.ui.JBUI import java.awt.BorderLayout import java.net.URI import java.net.URLEncoder @@ -64,6 +65,9 @@ class RemoteSettingsAction : AnAction() { class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Disposable { private val settings = project.getService(Settings::class.java) + private val taskSelector = JComboBox().apply { isEditable = true; maximumRowCount = 12 } + private var updatingTasks = false + private var discoveredTasks = emptyList() private val devices = JComboBox() private val refresh = JButton("刷新设备") private val deviceStatus = JLabel("正在读取本机设备…") @@ -72,7 +76,22 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos @Volatile private var disposed = false private val run = JButton("Remote Run") private val cancel = JButton("取消远程构建") - private val log = JTextArea().apply { isEditable = false } + private val buildIdField = JTextField(24) + private val progress = JProgressBar(0, 100).apply { + isStringPainted = false + preferredSize = JBUI.size(220, 12) + } + private val progressPercent = JLabel("—") + private val progressStatus = JTextArea("就绪", 2, 0).apply { + isEditable = false; isOpaque = false; lineWrap = true; wrapStyleWord = true + font = UIManager.getFont("Label.font") + foreground = UIManager.getColor("Label.foreground") + minimumSize = JBUI.size(0, 32) + } + private val resume = JButton("恢复上次构建") + private val fetch = JButton("下载 APK") + private val log = JTextArea().apply { isEditable = false; lineWrap = true; wrapStyleWord = true } + private val logFormat = TimestampedLog() @Volatile private var activeBuild = "" @Volatile private var cancelRequested = false @Volatile private var busy = false @@ -81,8 +100,23 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos private val polling = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay({ refreshDevices() }, 1, 5, TimeUnit.SECONDS) init { val configure = JButton("连接设置") - val buttons = JPanel().apply { add(JLabel("目标设备")); add(devices); add(refresh); add(run); add(cancel); add(configure) } - val top = JPanel(BorderLayout()).apply { add(buttons, BorderLayout.CENTER); add(deviceStatus, BorderLayout.SOUTH) } + val refreshTasks = JButton("刷新变体") + val variants = JPanel(BorderLayout(0, JBUI.scale(6))).apply { + add(JLabel("构建变体 / Gradle 任务"), BorderLayout.NORTH) + add(taskSelector, BorderLayout.CENTER); add(refreshTasks, BorderLayout.SOUTH) + } + taskSelector.toolTipText = "选择任务或直接输入;自动记住最近 20 个任务" + updateTaskChoices(settings.snapshot().task) + taskSelector.addActionListener { + if (!updatingTasks) { + val value = taskSelector.editor.item?.toString()?.trim().orEmpty() + if (BuildTasks.valid(value)) { settings.selectTask(value); updateTaskChoices(value) } + } + } + refreshTasks.addActionListener { refreshTaskChoices(refreshTasks) } + refreshTaskChoices(refreshTasks) + val buttons = JPanel(java.awt.GridLayout(0, 2, JBUI.scale(6), JBUI.scale(6))).apply { add(run); add(cancel); add(refresh); add(configure) } + 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 { @@ -94,10 +128,79 @@ 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() } configure.addActionListener { ToolWindowManager.getInstance(project).getToolWindow("Remote Configuration")?.show() } - add(top, BorderLayout.NORTH); add(JScrollPane(log), BorderLayout.CENTER) + val recovery = JPanel(java.awt.GridLayout(0, 1, 0, JBUI.scale(6))).apply { + add(JLabel("构建ID(留空找回上次)")); add(buildIdField); add(resume); add(fetch) + val history = JButton("构建历史"); history.addActionListener { showHistory() }; add(history) + val installLast = JButton("安装已下载 APK"); installLast.addActionListener { installDownloaded() }; add(installLast) + val environment = JButton("查看构建环境") + environment.addActionListener { showEnvironment() }; add(environment) + } + val progressArea = JPanel(BorderLayout(0, JBUI.scale(4))).apply { + border = JBUI.Borders.empty(4, 8, 6, 8) + add(JPanel(java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0)).apply { + add(progress) + add(JLabel(" ")) + add(progressPercent) + }, BorderLayout.NORTH) + add(JScrollPane(progressStatus).apply { + border = BorderFactory.createEmptyBorder() + isOpaque = false; viewport.isOpaque = false + horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER + }, BorderLayout.CENTER) + } + val sections = JPanel().apply { + layout = BoxLayout(this, BoxLayout.Y_AXIS) + listOf(top, variants, buttons, recovery, progressArea).forEach { section -> + section.alignmentX = java.awt.Component.LEFT_ALIGNMENT + section.maximumSize = java.awt.Dimension(Int.MAX_VALUE, section.preferredSize.height) + add(section); add(Box.createVerticalStrut(JBUI.scale(10))) + } + } + val controls = object : JPanel(BorderLayout()), Scrollable { + override fun getPreferredScrollableViewportSize() = preferredSize + override fun getScrollableTracksViewportWidth() = true + override fun getScrollableTracksViewportHeight() = false + override fun getScrollableUnitIncrement(rect: java.awt.Rectangle, orientation: Int, direction: Int) = JBUI.scale(20) + override fun getScrollableBlockIncrement(rect: java.awt.Rectangle, orientation: Int, direction: Int) = maxOf(JBUI.scale(20), rect.height - JBUI.scale(20)) + }.apply { border = JBUI.Borders.empty(10); add(sections, BorderLayout.NORTH) } + resume.addActionListener { recoverBuild(false) } + fetch.addActionListener { recoverBuild(true) } + val controlsScroll = JScrollPane(controls).apply { + horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER + minimumSize = JBUI.size(220, 0) + } + val logScroll = JScrollPane(log).apply { + horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER + minimumSize = JBUI.size(200, 0) + } + add(JSplitPane(JSplitPane.HORIZONTAL_SPLIT, controlsScroll, logScroll).apply { + isContinuousLayout = true; isOneTouchExpandable = true + resizeWeight = 0.0; dividerLocation = JBUI.scale(320) + border = BorderFactory.createEmptyBorder() + }, BorderLayout.CENTER) run.addActionListener { runBuild() } cancel.addActionListener { cancelRequested = true; append("已请求取消,等待当前网络操作结束…") } } + private fun updateTaskChoices(selected: String) { + val cfg = settings.snapshot() + val choices = (listOf(selected) + cfg.taskHistory + discoveredTasks + listOf(":app:assembleDebug")).filter { it.isNotBlank() }.distinct() + updatingTasks = true + try { taskSelector.model = DefaultComboBoxModel(choices.toTypedArray()); taskSelector.selectedItem = selected } + finally { updatingTasks = false } + } + private fun refreshTaskChoices(button: JButton) { + button.isEnabled = false + ApplicationManager.getApplication().executeOnPooledThread { + val result = runCatching { project.basePath?.let { BuildTasks.discover(Path.of(it)) }.orEmpty() } + ApplicationManager.getApplication().invokeLater { + if (!disposed && !project.isDisposed) { + button.isEnabled = true + result.onSuccess { discoveredTasks = it; updateTaskChoices(taskSelector.editor.item?.toString()?.trim().orEmpty().ifEmpty { settings.snapshot().task }) } + .onFailure { append("读取变体候选失败,可直接输入任务:${it.message}") } + } + } + } + } override fun dispose() { disposed = true; polling.cancel(false) if (!project.isDisposed && project.getService(PanelService::class.java).panel === this) project.getService(PanelService::class.java).panel = null @@ -126,9 +229,20 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos } } private fun append(text: String) = ApplicationManager.getApplication().invokeLater { - if (!disposed && !project.isDisposed) { log.append(text + "\n"); log.caretPosition = log.document.length } + if (!disposed && !project.isDisposed) { log.append(logFormat.message(text)); log.caretPosition = log.document.length } + } + private fun appendBuildChunk(text: String) = ApplicationManager.getApplication().invokeLater { + if (!disposed && !project.isDisposed) { log.append(logFormat.chunk(text)); log.caretPosition = log.document.length } } private fun hash(data: ByteArray) = MessageDigest.getInstance("SHA-256").digest(data).joinToString("") { "%02x".format(it) } + private fun fileHash(path: Path): String { + val digest = MessageDigest.getInstance("SHA-256") + Files.newInputStream(path).use { input -> + val buffer = ByteArray(128 * 1024) + while (true) { val count = input.read(buffer); if (count < 0) break; digest.update(buffer, 0, count) } + } + return digest.digest().joinToString("") { "%02x".format(it) } + } private fun request(base: String, secret: String, method: String, route: String, body: Any? = null): ByteArray { val publisher = if (body == null) HttpRequest.BodyPublishers.noBody() else HttpRequest.BodyPublishers.ofString(gson.toJson(body)) val req = HttpRequest.newBuilder(URI.create(base + "/api/v1" + route)).timeout(Duration.ofMinutes(5)) @@ -156,16 +270,16 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos } } private fun beginBuild() { + val selectedTask = taskSelector.editor.item?.toString()?.trim().orEmpty() + settings.selectTask(selectedTask) + updateTaskChoices(selectedTask) val cfg = settings.snapshot() val base = cfg.url.trim().trimEnd('/') validateEndpoint(base) + require(cfg.remoteFolder.isNotBlank()) { "请在 Remote Configuration 中填写服务端已有工程文件夹,并点击检查远程工程" } val selected = devices.selectedItem as? AdbDevice - if (cfg.install) { - require(selected == null || selected.online) { "请选择已连接且已授权的设备" } - if (selected != null) cfg.device = selected.serial - } val source = project.basePath?.let { Path.of(it) } ?: error("项目路径不存在") - cancelRequested = false; activeBuild = ""; log.text = "" + cancelRequested = false; activeBuild = ""; log.text = ""; logFormat.reset() object : Task.Backgroundable(project, "Remote Compilation", false) { override fun run(indicator: ProgressIndicator) { var secret = "" @@ -173,80 +287,67 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos http = ServerTls.client(cfg.serverCertificate) secret = PasswordSafe.instance.getPassword(credentials(base)) ?: "" check(secret.length >= 24) { "请在右侧 Remote Configuration 中保存服务 Token" } - if (cfg.install) { - val connected = AdbDevices.list(AdbDevices.resolve(source, cfg.adb)).filter { it.online } - val target = AdbDevices.choose(connected, selected?.serial ?: cfg.device, explicit = selected != null) - check(target != null) { "请从设备列表选择已连接且已授权的设备" } - cfg.device = target.serial - settings.selectDevice(target.serial) - refreshDevices() - append("目标设备:$target") - } - json(base, secret, "GET", "/health") + append("构建任务:${cfg.task}") + 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) + val inspection = json(base, secret, "POST", "/projects/check", checkBody) + append("远程位置:${inspection.get("workspacePath").asString}") + append("Git 检查:${inspection.get("message").asString};本机=$localGit;服务端=${inspection.get("git")}") + check(inspection.get("canSync").asBoolean) { inspection.get("message").asString } + val candidates = SourceFiles.collect(source, localGit) if (cfg.projectId.isBlank()) { - cfg.projectId = json(base, secret, "POST", "/projects").get("id").asString - settings.projectAllocated(base, cfg.projectId) + 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 files = linkedMapOf>() - val excludes = setOf(".git", ".gradle", ".idea", "build", ".remotecompile", "node_modules", ".kotlin") - var changed = 0 - Files.walk(source).use { paths -> paths.filter { path -> - val rel = source.relativize(path) - rel.none { it.toString() in excludes } && !Files.isDirectory(path) - }.forEach { path -> - check(!Files.isSymbolicLink(path)) { "暂不支持符号链接:$path" } + var changed = 0; var lineEndingsOnly = 0 + for (path in candidates) { val name = source.relativize(path).joinToString("/") - val leaf = path.fileName.toString() - if (leaf == "local.properties" || leaf.endsWith(".jks") || leaf.endsWith(".keystore") || leaf.startsWith(".env") || leaf in setOf("key.properties", "keystore.properties")) return@forEach check(Files.size(path) <= 64L * 1024 * 1024) { "文件超过首版 64MiB 上限:$name" } val bytes = Files.readAllBytes(path); val hash = hash(bytes) - files[name] = if (manifest?.getAsJsonObject(name)?.get("hash")?.asString == hash) mapOf("hash" to hash) - else { changed++; mapOf("hash" to hash, "data" to Base64.getEncoder().encodeToString(bytes)) } - } } + val remote = manifest?.getAsJsonObject(name) + val remoteHash = remote?.get("hash")?.asString + val remoteTextHash = remote?.get("textHash")?.asString + files[name] = when { + remoteHash == hash -> mapOf("hash" to hash) + cfg.ignoreLineEndings && remoteTextHash != null && remoteTextHash == SyncComparison.textHash(name, bytes) -> { + lineEndingsOnly++; mapOf("hash" to checkNotNull(remoteHash)) + } + else -> { changed++; mapOf("hash" to hash, "data" to Base64.getEncoder().encodeToString(bytes)) } + } + } + check(SourceFiles.snapshot(source).let { it?.head == localGit?.head && it?.branch == localGit?.branch }) { "扫描期间 Git 状态发生变化,请重新运行" } check(!cancelRequested) { "已取消" } val revision = UUID.randomUUID().toString() - append("同步 ${files.size} 个文件,上传 $changed 个变更文件…") - json(base, secret, "POST", "/projects/${cfg.projectId}/sync", mapOf("revision" to revision, "files" to files)) + append("同步 ${files.size} 个文件,上传 $changed 个变更文件,跳过 $lineEndingsOnly 个仅换行不同的文件…") + json(base, secret, "POST", "/projects/${cfg.projectId}/sync", mapOf("revision" to revision, "files" to files, "git" to localGit)) check(!cancelRequested) { "已取消" } - activeBuild = json(base, secret, "POST", "/projects/${cfg.projectId}/builds", mapOf("revision" to revision, "task" to cfg.task)).get("id").asString - var offset = 0 - var result: JsonObject - while (true) { - if (cancelRequested) { json(base, secret, "DELETE", "/builds/$activeBuild"); error("已请求取消远程构建") } - result = json(base, secret, "GET", "/builds/$activeBuild") - val lines = result.getAsJsonArray("logs") - while (offset < lines.size()) append(lines[offset++].asString) - if (result.get("status").asString !in listOf("queued", "running")) break - Thread.sleep(700) - } - check(result.get("status").asString == "success") { "构建状态:${result.get("status").asString}" } - val artifacts = result.getAsJsonArray("artifacts") - check(artifacts.size() == 1) { "首版要求恰好一个 APK,实际 ${artifacts.size()} 个;请调整构建任务" } - val artifact = artifacts[0].asJsonObject - val name = artifact.get("name").asString - val encodedName = URLEncoder.encode(name, Charsets.UTF_8).replace("+", "%20") - val bytes = request(base, secret, "GET", "/builds/$activeBuild/artifacts/$encodedName") - check(hash(bytes) == artifact.get("hash").asString) { "APK 校验失败" } - val output = source.resolve(".remotecompile").resolve("$activeBuild.apk") - Files.createDirectories(output.parent); Files.write(output, bytes) - append("APK 已保存:$output") + val record = LastBuild(base, cfg.projectId, revision, cfg.task, UUID.randomUUID().toString(), certificate = cfg.serverCertificate, javaHome = cfg.remoteJavaHome) + LastBuildStore.save(source, record) + activeBuild = json(base, secret, "POST", "/projects/${cfg.projectId}/builds", + mapOf("revision" to revision, "task" to cfg.task, "clientRequestId" to record.clientRequestId, "javaHome" to record.javaHome)).get("id").asString + record.buildId = activeBuild; LastBuildStore.save(source, record) + setBuildId(activeBuild) + append("构建ID:$activeBuild(已保存,断网后可恢复)") + val result = watchBuild(base, secret, activeBuild) + val output = downloadApk(base, secret, activeBuild, source, result) check(!cancelRequested) { "已取消安装" } if (cfg.install) { - val adb = AdbDevices.resolve(source, cfg.adb) - check(AdbDevices.list(adb).any { it.serial == cfg.device && it.online }) { "目标设备已断开或未授权,已保留 APK" } - val pb = ProcessBuilder(adb, "-s", cfg.device, "install", "-r", output.toString()).redirectErrorStream(true) - val outputLog = Files.createTempFile("remotecompile-adb-", ".log") - try { - val process = pb.redirectOutput(outputLog.toFile()).start() - if (!process.waitFor(120, TimeUnit.SECONDS)) { process.destroyForcibly(); error("adb 安装超时") } - append(Files.readString(outputLog)); check(process.exitValue() == 0) { "adb 安装失败" } - } finally { Files.deleteIfExists(outputLog) } + try { installApkWhenAvailable(source, cfg, selected, output) } + catch (e: Exception) { + append("编译和下载已成功,安装未完成:${e.message ?: e.javaClass.simpleName};APK 已保留,可稍后点击安装已下载 APK") + } } - append("Remote Run 完成") + append("远程编译和 APK 下载完成") } catch (e: Exception) { // Never print request headers or the token. - append("失败:" + (e.message ?: e.javaClass.simpleName).let { if (secret.isNotEmpty()) it.replace(secret, "***") else it }) + append((if (activeBuild.isNotEmpty()) "构建失败(记录已保留,可点击恢复上次构建):" else "同步或启动失败(尚未确认创建构建任务):") + (e.message ?: e.javaClass.simpleName).let { if (secret.isNotEmpty()) it.replace(secret, "***") else it }) } finally { activeBuild = ""; busy = false ApplicationManager.getApplication().invokeLater { if (!disposed && !project.isDisposed) run.isEnabled = true } @@ -254,4 +355,216 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos } }.queue() } + private fun installApkWhenAvailable(source: Path, cfg: Settings.Data, selected: AdbDevice?, output: Path) { + val adb = AdbDevices.resolve(source, cfg.adb) + val connected = AdbDevices.list(adb) + val target = AdbDevices.choose(connected, selected?.serial ?: cfg.device, explicit = selected != null) + if (target == null) { + append("编译成功,APK 已保存;没有可安装的目标设备或尚未明确选择,跳过自动安装。连接并选择设备后可点击安装已下载 APK") + return + } + settings.selectDevice(target.serial) + append("安装目标:$target") + val outputLog = Files.createTempFile("remotecompile-adb-", ".log") + try { + val process = ProcessBuilder(adb, "-s", target.serial, "install", "-r", output.toString()) + .redirectErrorStream(true).redirectOutput(outputLog.toFile()).start() + if (!process.waitFor(120, TimeUnit.SECONDS)) { process.destroyForcibly(); error("adb 安装超时") } + append(Files.readString(outputLog)); check(process.exitValue() == 0) { "adb 安装失败" } + } finally { Files.deleteIfExists(outputLog) } + } + private fun setBuildId(id: String) = ApplicationManager.getApplication().invokeLater { if (!disposed) buildIdField.text = id } + private fun showProgress(message: String, percent: Int = -1) = ApplicationManager.getApplication().invokeLater { + if (!disposed) { + progress.isIndeterminate = percent < 0 + if (percent >= 0) progress.value = percent.coerceIn(0, 100) + progressPercent.text = if (percent < 0) "进行中" else "${progress.value}%" + progressStatus.text = message; progressStatus.caretPosition = 0 + progressStatus.toolTipText = message; progress.toolTipText = message + } + } + private fun watchBuild(base: String, secret: String, id: String): JsonObject { + var offset = 0; var failures = 0; var environmentPrinted = false + while (true) { + check(!project.isDisposed && !disposed) { "项目已关闭,远端任务不受影响" } + if (cancelRequested) { json(base, secret, "DELETE", "/builds/$id"); error("已请求取消远程构建") } + val result = try { json(base, secret, "GET", "/builds/$id").also { failures = 0 } } + catch (e: java.io.IOException) { + failures++; showProgress("连接中断,重试 $failures/3;远端构建不会被取消") + if (failures >= 3) throw e + Thread.sleep(failures * 1500L); continue + } + val lines = result.getAsJsonArray("logs") + while (offset < lines.size()) appendBuildChunk(lines[offset++].asString) + if (!environmentPrinted && result.has("environment")) { + append("实际构建环境:" + result.get("environment")); environmentPrinted = true + } + val status = result.get("status").asString + val detail = result.getAsJsonObject("progress") + val message = detail?.get("message")?.asString.orEmpty() + val path = detail?.get("path")?.asString.orEmpty() + showProgress(if (message.isNotBlank()) "$message $path" else "构建 $id:$status", if (message.isNotBlank()) detail?.get("percent")?.asInt ?: -1 else -1) + if (status !in listOf("queued", "running")) { + showProgress("构建 $id:$status", if (status == "success") 100 else 0) + check(status == "success") { "构建状态:$status;可查看上方日志" } + return result + } + Thread.sleep(1000) + } + } + private fun downloadApk(base: String, secret: String, id: String, source: Path, result: JsonObject): Path { + require(id.matches(Regex("[a-f0-9]{32}"))) { "无效构建 ID" } + val artifacts = result.getAsJsonArray("artifacts") + check(artifacts.size() == 1) { "当前要求恰好一个 APK,实际 ${artifacts.size()} 个" } + val artifact = artifacts[0].asJsonObject + val expected = artifact.get("hash").asString + val size = artifact.get("size").asLong + val output = source.resolve(".remotecompile/$id.apk"); Files.createDirectories(output.parent) + if (Files.exists(output) && fileHash(output) == expected) { rememberArtifact(source, id, expected); append("复用已下载 APK:$output"); return output } + val part = output.resolveSibling("$id.apk.part") + var received = if (Files.exists(part)) Files.size(part) else 0L + if (received > size) { Files.delete(part); received = 0 } + if (received < size) { + val name = URLEncoder.encode(artifact.get("name").asString, Charsets.UTF_8).replace("+", "%20") + val builder = HttpRequest.newBuilder(URI.create("$base/api/v1/builds/$id/artifacts/$name")) + .header("Authorization", "Bearer $secret").timeout(Duration.ofMinutes(5)) + if (received > 0) builder.header("Range", "bytes=$received-") + val response = http.send(builder.GET().build(), HttpResponse.BodyHandlers.ofInputStream()) + response.body().use { input -> + check(response.statusCode() == 200 || response.statusCode() == 206) { "下载 HTTP ${response.statusCode()}" } + if (response.statusCode() == 200) received = 0 + else check(response.headers().firstValue("Content-Range").orElse("").startsWith("bytes $received-")) { "断点下载偏移不匹配" } + val options = if (received > 0) arrayOf(java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.APPEND) + else arrayOf(java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.TRUNCATE_EXISTING) + Files.newOutputStream(part, *options).use { out -> + val buffer = ByteArray(128 * 1024); var last = 0L + while (true) { + check(!cancelRequested) { "下载已停止,分片保留以便续传" } + val count = input.read(buffer); if (count < 0) break + out.write(buffer, 0, count); received += count + if (System.currentTimeMillis() - last > 300) { showProgress("APK 下载 $received / $size 字节", if (size > 0) (received * 100 / size).toInt() else -1); last = System.currentTimeMillis() } + } + } + } + } + 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) + showProgress("APK 下载完成", 100); append("APK 已保存:$output"); return output + } + private fun rememberArtifact(source: Path, id: String, expected: String) { + LastBuildStore.load(source)?.takeIf { it.buildId == id }?.let { it.artifactHash = expected; LastBuildStore.save(source, it) } + } + private fun installDownloaded() { + if (busy) return + val source = project.basePath?.let { Path.of(it) } ?: return + val record = try { LastBuildStore.load(source) ?: error("没有已下载构建记录") } + catch (e: Exception) { append(e.message ?: "读取记录失败"); return } + if (!record.buildId.matches(Regex("[a-f0-9]{32}")) || record.artifactHash.isBlank() || (buildIdField.text.isNotBlank() && buildIdField.text.trim() != record.buildId)) { append("请先下载并校验当前任务的 APK"); return } + val cfg = settings.snapshot(); val explicit = devices.selectedItem as? AdbDevice + busy = true; run.isEnabled = false + object : Task.Backgroundable(project, "安装已下载 APK", false) { + override fun run(indicator: ProgressIndicator) { + try { + val output = 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) + check(target != null) { "请选择在线且已授权的设备" } + append("安装构建 ${record.buildId} 到 $target") + val outputLog = Files.createTempFile("remote-install-", ".log") + try { + val process = ProcessBuilder(adb, "-s", target.serial, "install", "-r", output.toString()).redirectErrorStream(true).redirectOutput(outputLog.toFile()).start() + if (!process.waitFor(120, TimeUnit.SECONDS)) { process.destroyForcibly(); error("安装超时") } + append(Files.readString(outputLog)); check(process.exitValue() == 0) { "adb 安装失败" } + } finally { Files.deleteIfExists(outputLog) } + } catch (e: Exception) { append("安装失败:${e.message ?: e.javaClass.simpleName}") } + finally { busy = false; ApplicationManager.getApplication().invokeLater { if (!disposed && !project.isDisposed) run.isEnabled = true } } + } + }.queue() + } + private fun recoverBuild(downloadOnly: Boolean) { + if (busy) return + val source = project.basePath?.let { Path.of(it) } ?: return + val cfg = settings.snapshot(); val overrideId = buildIdField.text.trim() + val record = try { + val last = LastBuildStore.load(source) + if (overrideId.isNotBlank() && overrideId != last?.buildId) LastBuild(cfg.url, cfg.projectId, buildId = overrideId, certificate = cfg.serverCertificate) + else last ?: if (cfg.projectId.isNotBlank()) LastBuild(cfg.url, cfg.projectId, certificate = cfg.serverCertificate) else error("本项目没有上次构建记录;可填写构建 ID") + } catch (e: Exception) { append(e.message ?: "读取构建记录失败"); return } + try { validateEndpoint(record.server) } catch (e: Exception) { append(e.message ?: "地址无效"); return } + busy = true; cancelRequested = false; run.isEnabled = false; log.text = ""; logFormat.reset() + object : Task.Backgroundable(project, "恢复远程构建", false) { + override fun run(indicator: ProgressIndicator) { + var secret = "" + try { + http = ServerTls.client(record.certificate) + secret = PasswordSafe.instance.getPassword(credentials(record.server)).orEmpty() + check(secret.isNotBlank()) { "请先保存该服务器 Token:${record.server}" } + if (record.buildId.isBlank()) { + val found = json(record.server, secret, "GET", "/projects/${record.projectId}/builds?clientRequestId=${record.clientRequestId}").getAsJsonArray("builds") + check(found.size() > 0 && (record.clientRequestId.isBlank() || found.size() == 1)) { "服务器未找到该提交,可核对网络恢复后再次查询;不要重复提交" } + record.buildId = found[0].asJsonObject.get("id").asString + } + require(record.buildId.matches(Regex("[a-f0-9]{32}"))) { "构建 ID 格式错误" } + activeBuild = record.buildId; LastBuildStore.save(source, record); setBuildId(activeBuild) + append("恢复构建:$activeBuild;服务器:${record.server}") + val result = if (downloadOnly) json(record.server, secret, "GET", "/builds/$activeBuild").also { + check(it.get("status").asString == "success") { "构建尚未成功,请点击恢复上次构建继续查看" } + } else watchBuild(record.server, secret, activeBuild) + append("源码版本:${result.get("revision").asString};任务:${result.get("task").asString}") + downloadApk(record.server, secret, activeBuild, source, result) + append("恢复操作完成;已取回 APK,未自动安装旧版本") + } catch (e: Exception) { + append("恢复失败:" + (e.message ?: e.javaClass.simpleName).let { if (secret.isNotEmpty()) it.replace(secret, "***") else it }) + } finally { + activeBuild = ""; busy = false + ApplicationManager.getApplication().invokeLater { if (!disposed && !project.isDisposed) run.isEnabled = true } + } + } + }.queue() + } + private fun showEnvironment() { + val cfg = settings.snapshot() + ApplicationManager.getApplication().executeOnPooledThread { + try { + val client = ServerTls.client(cfg.serverCertificate) + val secret = PasswordSafe.instance.getPassword(credentials(cfg.url)).orEmpty() + val request = HttpRequest.newBuilder(URI.create("${cfg.url}/api/v1/environment")).header("Authorization", "Bearer $secret").build() + val response = client.send(request, HttpResponse.BodyHandlers.ofString()) + append("服务端环境:HTTP ${response.statusCode()} ${response.body()}") + } catch (e: Exception) { append("读取环境失败:${e.javaClass.simpleName}") } + } + } + private fun showHistory() { + if (busy) return + val cfg = settings.snapshot() + val source = project.basePath?.let { Path.of(it) } ?: return + val projectId = cfg.projectId.ifBlank { runCatching { LastBuildStore.load(source)?.takeIf { it.server == cfg.url }?.projectId.orEmpty() }.getOrDefault("") } + if (projectId.isBlank()) { append("本项目尚未关联远程工作区;可手动填写构建 ID"); return } + ApplicationManager.getApplication().executeOnPooledThread { + try { + val client = ServerTls.client(cfg.serverCertificate) + val secret = PasswordSafe.instance.getPassword(credentials(cfg.url)).orEmpty() + val request = HttpRequest.newBuilder(URI.create("${cfg.url}/api/v1/projects/$projectId/builds")).header("Authorization", "Bearer $secret").build() + val response = client.send(request, HttpResponse.BodyHandlers.ofString()) + check(response.statusCode() == 200) { "HTTP ${response.statusCode()}" } + val builds = gson.fromJson(response.body(), JsonObject::class.java).getAsJsonArray("builds") + val choices = builds.map { item -> + val b = item.asJsonObject + "${b.get("id").asString} · ${b.get("status").asString} · ${b.get("task").asString} · 源码 ${b.get("revision").asString.take(12)}" + }.toTypedArray() + ApplicationManager.getApplication().invokeLater { + if (!disposed && !project.isDisposed && !busy) { + if (choices.isEmpty()) append("此工作区暂无构建历史") + else { + val choice = JOptionPane.showInputDialog(this, "选择任务后点击恢复或下载", "构建历史(最近50条)", JOptionPane.PLAIN_MESSAGE, null, choices, choices.first()) as? String + if (choice != null) { buildIdField.text = choice.substringBefore(" · "); append("已选择:$choice") } + } + } + } + } catch (e: Exception) { append("读取历史失败:${e.javaClass.simpleName}") } + } + } + } diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/Settings.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/Settings.kt index 3043802..8bbd37b 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 = "") } + @Synchronized override fun loadState(state: Settings.Data) { data = state.copy(projectId = "", device = "", remoteFolder = "", remoteJavaHome = "", taskHistory = mutableListOf()) } } @State(name = "RemoteCompilation", storages = [Storage("remote-compilation.xml")]) @@ -29,7 +29,11 @@ class Settings : PersistentStateComponent { data class Data( var url: String = "http://127.0.0.1:8765", var projectId: String = "", + var remoteFolder: String = "", + var remoteJavaHome: String = "", + var ignoreLineEndings: Boolean = true, var task: String = ":app:assembleDebug", + var taskHistory: MutableList = mutableListOf(), var adb: String = "", var device: String = "", var install: Boolean = false, @@ -40,23 +44,28 @@ 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) else data.copy() + 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() } @Synchronized override fun getState(): Data = data.copy() @Synchronized override fun loadState(state: Data) { val initial = Data() - val legacy = state.url != initial.url || state.projectId.isNotBlank() || state.task != initial.task || state.adb.isNotBlank() || state.install || state.serverCertificate.isNotBlank() + val legacy = state.url != initial.url || state.projectId.isNotBlank() || state.remoteFolder.isNotBlank() || state.remoteJavaHome.isNotBlank() || state.task != initial.task || state.adb.isNotBlank() || state.install || state.serverCertificate.isNotBlank() data = state.copy(configured = state.configured || legacy) } - @Synchronized fun saveConfiguration(next: Data) { + @Synchronized fun saveConfiguration(next: Data, preserveTask: Boolean = false) { val current = snapshot() - data = next.copy(projectId = if (current.url == next.url) current.projectId else "", device = current.device, 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 "", device = current.device, taskHistory = current.taskHistory.toMutableList(), configured = true) defaults()?.loadState(data) } - @Synchronized fun selectDevice(serial: String) { data = data.copy(device = serial) } - @Synchronized fun projectAllocated(url: String, id: String) { + @Synchronized fun selectTask(task: String) { + require(BuildTasks.valid(task)) { "任务格式无效,请填写 :模块:assemble变体,不要添加命令行参数" } val current = snapshot() - if (current.url == url) data = current.copy(projectId = id, configured = true) + 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 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) } } @@ -81,18 +90,30 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL private val original = settings.snapshot() private val url = JTextField(original.url) private val token = JPasswordField() - private val task = JTextField(original.task) + private val remoteFolder = JTextField(original.remoteFolder) + private data class JdkChoice(val home: String, val label: String) { override fun toString() = label } + private val jdks = JComboBox().apply { addItem(JdkChoice("", "沿用服务端默认 JDK")); if (original.remoteJavaHome.isNotBlank()) { addItem(JdkChoice(original.remoteJavaHome, "已保存:${original.remoteJavaHome}")); selectedIndex = 1 } } + private val ignoreLineEndings = JCheckBox("忽略文本文件 CRLF / LF 换行差异", original.ignoreLineEndings) + private val checkRemote = JButton("检查远程工程") + private val checkResult = JTextArea(8, 32).apply { isEditable = false; lineWrap = true; wrapStyleWord = true } private val adb = JTextField(original.adb) private val certificate = JTextField(original.serverCertificate) - private val install = JCheckBox("构建成功后安装到所选设备", original.install) + private val install = JCheckBox("构建成功后自动安装(无可用设备时仅下载 APK)", original.install) private val save = JButton("保存配置") private val status = JLabel("Token 留空保留已保存值") private val tokenStatus = JLabel("正在读取已保存 Token…") private var tokenRequest = 0 init { val fields = JPanel(GridLayout(0, 1, 0, 5)) - listOf("服务地址" to url, "Token(留空保留)" to token, "Gradle 任务" to task, + listOf("服务地址" to url, "Token(留空保留)" to token, "服务端已有工程文件夹(必填绝对路径)" 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("构建变体请在构建日志面板左侧选择")) + fields.add(JLabel("服务端 JDK(按工程保存)")); fields.add(jdks) + val refreshJdks = JButton("检测服务端 JDK(where / 安装目录)") + refreshJdks.addActionListener { refreshRemoteJdks(refreshJdks) }; fields.add(refreshJdks); fields.add(ignoreLineEndings) fields.add(tokenStatus) fields.add(JLabel("服务器公钥证书(自签 HTTPS,留空使用默认信任库)")); fields.add(certificate) val choose = JButton("选择服务器证书 .crt / .pem") @@ -100,13 +121,29 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL val picker = JFileChooser().apply { fileFilter = javax.swing.filechooser.FileNameExtensionFilter("服务器证书", "crt", "pem", "cer") } if (picker.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) certificate.text = picker.selectedFile.absolutePath } - fields.add(choose); fields.add(install); fields.add(save); fields.add(status) - border = BorderFactory.createEmptyBorder(12, 12, 12, 12) - add(fields, BorderLayout.NORTH) + fields.add(choose); fields.add(install); fields.add(checkRemote); fields.add(save); fields.add(status) + checkRemote.addActionListener { checkRemoteProject() } + val content = object : JPanel(BorderLayout(0, 8)), Scrollable { + override fun getPreferredScrollableViewportSize() = preferredSize + override fun getScrollableTracksViewportWidth() = true + override fun getScrollableTracksViewportHeight() = false + override fun getScrollableUnitIncrement(visibleRect: java.awt.Rectangle, orientation: Int, direction: Int) = com.intellij.util.ui.JBUI.scale(20) + override fun getScrollableBlockIncrement(visibleRect: java.awt.Rectangle, orientation: Int, direction: Int) = maxOf(com.intellij.util.ui.JBUI.scale(20), visibleRect.height - com.intellij.util.ui.JBUI.scale(20)) + }.apply { + border = com.intellij.util.ui.JBUI.Borders.empty(12) + add(fields, BorderLayout.NORTH) + add(checkResult, BorderLayout.CENTER) + } + add(JScrollPane(content).apply { + border = BorderFactory.createEmptyBorder() + horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER + verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED + }, BorderLayout.CENTER) val tokenTimer = Timer(350) { restoreToken() }.apply { isRepeats = false } url.document.addDocumentListener(object : DocumentListener { private fun changed() { tokenRequest++; token.text = "" + jdks.removeAllItems(); jdks.addItem(JdkChoice("", "沿用服务端默认 JDK")) tokenStatus.text = "地址已改变,正在查找对应 Token…" tokenTimer.restart() } @@ -117,13 +154,13 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL restoreToken() save.addActionListener { val base = url.text.trim().trimEnd('/') - try { validateEndpoint(base); require(task.text.isNotBlank()) { "请填写 Gradle 任务" } } + try { validateEndpoint(base); require(remoteFolder.text.isNotBlank()) { "请填写服务端已有工程文件夹" } } catch (e: IllegalArgumentException) { status.text = e.message; return@addActionListener } tokenRequest++ // Discard a pending restore before replacing/saving this credential. val entered = String(token.password); token.text = "" val previous = settings.snapshot() - val next = previous.copy(url = base, task = task.text.trim(), adb = adb.text.trim(), install = install.isSelected, serverCertificate = certificate.text.trim(), - projectId = if (previous.url == base) previous.projectId else "") + val next = previous.copy(url = base, remoteFolder = remoteFolder.text.trim(), remoteJavaHome = (jdks.selectedItem as? JdkChoice)?.home.orEmpty(), ignoreLineEndings = ignoreLineEndings.isSelected, adb = adb.text.trim(), install = install.isSelected, serverCertificate = certificate.text.trim(), + projectId = if (previous.url == base && previous.remoteFolder == remoteFolder.text.trim()) previous.projectId else "") save.isEnabled = false; status.text = "正在保存…" ApplicationManager.getApplication().executeOnPooledThread { var fingerprint = "" @@ -133,7 +170,7 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL require(entered.length >= 24) { "Token 至少需要 24 个字符" } PasswordSafe.instance.setPassword(credentials(base), entered) } - settings.saveConfiguration(next) + settings.saveConfiguration(next, preserveTask = true) }.exceptionOrNull() ApplicationManager.getApplication().invokeLater { if (!project.isDisposed) { @@ -146,6 +183,113 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL } } } + private fun refreshRemoteJdks(button: JButton) { + val base = url.text.trim().trimEnd('/') + val cert = certificate.text.trim() + val entered = String(token.password) + val preferred = (jdks.selectedItem as? JdkChoice)?.home.orEmpty() + try { validateEndpoint(base) } catch (e: Exception) { checkResult.text = e.message; return } + button.isEnabled = false; checkResult.text = "正在检测服务端 where java/javac、JAVA_HOME 和已安装 JDK…" + ApplicationManager.getApplication().executeOnPooledThread { + var secret = "" + val response = runCatching { + secret = entered.ifEmpty { PasswordSafe.instance.getPassword(credentials(base)).orEmpty() } + require(secret.length >= 24) { "请填写或保存 Token" } + val req = java.net.http.HttpRequest.newBuilder(java.net.URI.create(base + "/api/v1/jdks")) + .timeout(java.time.Duration.ofSeconds(60)).header("Authorization", "Bearer $secret").GET().build() + val result = ServerTls.client(cert).send(req, java.net.http.HttpResponse.BodyHandlers.ofString()) + check(result.statusCode() != 404) { "服务端需升级到 0.4.0 才支持 JDK 检测与选择" } + check(result.statusCode() == 200) { "HTTP ${result.statusCode()}: ${result.body().take(500)}" } + com.google.gson.Gson().fromJson(result.body(), com.google.gson.JsonObject::class.java) + } + val failure = response.exceptionOrNull()?.let { (it.message ?: it.javaClass.simpleName).let { text -> if (secret.isEmpty()) text else text.replace(secret, "***") } } + ApplicationManager.getApplication().invokeLater { + if (!project.isDisposed) { + button.isEnabled = true + if (url.text.trim().trimEnd('/') != base) return@invokeLater + if (response.isFailure) { checkResult.text = failure; return@invokeLater } + val data = response.getOrThrow() + jdks.removeAllItems(); jdks.addItem(JdkChoice("", "沿用服务端默认:${data.get("defaultJavaHome").asString}")) + data.getAsJsonArray("jdks").forEach { value -> + val j = value.asJsonObject + jdks.addItem(JdkChoice(j.get("home").asString, "JDK ${j.get("version").asString} · ${j.get("home").asString} [${j.get("source").asString}]")) + } + val found = (0 until jdks.itemCount).firstOrNull { jdks.getItemAt(it).home == preferred } + if (found != null) jdks.selectedIndex = found + else if (preferred.isNotBlank()) { jdks.addItem(JdkChoice(preferred, "已保存但未检测到:$preferred")); jdks.selectedIndex = jdks.itemCount - 1 } + checkResult.text = "检测到 ${data.getAsJsonArray("jdks").size()} 个服务端 JDK;请选择与项目 Gradle、framework.jar 兼容的版本并保存。不会自动切换到最新版本。" + } + } + } + } + private data class FolderChoice(val label: String, val path: String, val select: Boolean = false) { override fun toString() = label } + private fun browseRemoteFolder(path: String) { + val base = url.text.trim().trimEnd('/') + val cert = certificate.text.trim() + val entered = String(token.password) + try { validateEndpoint(base) } catch (e: Exception) { checkResult.text = e.message; return } + checkResult.text = "正在读取服务端文件夹…" + ApplicationManager.getApplication().executeOnPooledThread { + var secret = "" + val response = runCatching { + secret = entered.ifEmpty { PasswordSafe.instance.getPassword(credentials(base)).orEmpty() } + require(secret.length >= 24) { "请填写或保存 Token" } + val route = base + "/api/v1/directories?path=" + java.net.URLEncoder.encode(path, Charsets.UTF_8) + val req = java.net.http.HttpRequest.newBuilder(java.net.URI.create(route)).timeout(java.time.Duration.ofSeconds(60)) + .header("Authorization", "Bearer $secret").GET().build() + val result = ServerTls.client(cert).send(req, java.net.http.HttpResponse.BodyHandlers.ofString()) + check(result.statusCode() == 200) { "HTTP ${result.statusCode()}: ${result.body().take(500)}" } + com.google.gson.Gson().fromJson(result.body(), com.google.gson.JsonObject::class.java) + } + val failure = response.exceptionOrNull()?.let { (it.message ?: it.javaClass.simpleName).let { text -> if (secret.isEmpty()) text else text.replace(secret, "***") } } + ApplicationManager.getApplication().invokeLater { + if (!project.isDisposed) { + if (response.isFailure) { checkResult.text = failure; return@invokeLater } + val listing = response.getOrThrow() + val current = listing.get("path").asString + val choices = mutableListOf() + if (listing.get("selectable").asBoolean) choices.add(FolderChoice("[选择此文件夹]", current, true)) + val parent = listing.get("parent").asString + if (parent.isNotEmpty()) choices.add(FolderChoice("[上一级]", parent)) + listing.getAsJsonArray("directories").forEach { val dir = it.asJsonObject; choices.add(FolderChoice(dir.get("name").asString, dir.get("path").asString)) } + checkResult.text = "服务端目录:$current(最多显示 1000 个子目录)" + if (choices.isEmpty()) { checkResult.append("\n没有可选择的工程目录,请先在服务器准备工程。"); return@invokeLater } + val choice = JOptionPane.showInputDialog(this, "服务端:$current", "选择已有工程文件夹", JOptionPane.PLAIN_MESSAGE, + null, choices.toTypedArray(), choices.first()) as? FolderChoice + if (choice != null) { if (choice.select) { remoteFolder.text = choice.path; checkRemoteProject() } else browseRemoteFolder(choice.path) } + } + } + } + } + private fun checkRemoteProject() { + val base = url.text.trim().trimEnd('/') + val folder = remoteFolder.text.trim() + val cert = certificate.text.trim() + val entered = String(token.password) + val saved = settings.snapshot() + try { validateEndpoint(base); require(folder.isNotEmpty()) { "请填写服务端已有工程文件夹" } } + catch (e: Exception) { checkResult.text = e.message; return } + checkRemote.isEnabled = false; checkResult.text = "正在检查服务端目录及双方 Git 状态…" + ApplicationManager.getApplication().executeOnPooledThread { + var secret = "" + val result = runCatching { + secret = entered.ifEmpty { PasswordSafe.instance.getPassword(credentials(base)).orEmpty() } + require(secret.length >= 24) { "请填写或保存 Token" } + val source = java.nio.file.Path.of(project.basePath ?: error("项目路径不存在")) + 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 "") + 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) { "HTTP ${response.statusCode()}: ${response.body().take(500)}" } + 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(上游差异使用已有本地引用,检查不会 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 } } + } + } private fun restoreToken() { val base = url.text.trim().trimEnd('/') val request = ++tokenRequest diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/SourceFiles.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/SourceFiles.kt new file mode 100644 index 0000000..9864a50 --- /dev/null +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/SourceFiles.kt @@ -0,0 +1,69 @@ +package studio.tongtong.remotecompile + +import java.nio.file.* +import java.nio.file.attribute.BasicFileAttributes +import java.util.concurrent.TimeUnit + +data class GitSnapshot(val head: String = "", val branch: String = "", val dirty: Boolean = false, val upstream: String = "", val aheadBehind: String = "") + +/** Ask Git itself to apply nested ignore rules, negation, info/exclude and global excludes. */ +object SourceFiles { + private val excluded = setOf(".git", ".gradle", ".idea", "build", ".remotecompile", "node_modules", ".kotlin", ".cxx", ".externalnativebuild") + fun reserved(relative: String): Boolean { + val parts = relative.lowercase().split('/') + val leaf = parts.last() + return parts.any { it in excluded } || leaf == "local.properties" || leaf.endsWith(".jks") || leaf.endsWith(".keystore") || + leaf.startsWith(".env") || leaf in setOf("key.properties", "keystore.properties") + } + internal fun git(root: Path, args: List, input: ByteArray = byteArrayOf()): Pair { + val output = Files.createTempFile("remotecompile-git-", ".out") + val stderr = Files.createTempFile("remotecompile-git-", ".err") + val stdin = Files.createTempFile("remotecompile-git-", ".in") + try { + Files.write(stdin, input) + val process = ProcessBuilder(listOf("git", "-C", root.toString()) + args) + .redirectInput(stdin.toFile()).redirectOutput(output.toFile()).redirectError(stderr.toFile()).start() + if (!process.waitFor(60, TimeUnit.SECONDS)) { process.destroyForcibly(); error("Git 检查超时") } + return process.exitValue() to Files.readString(output) + } finally { Files.deleteIfExists(output); Files.deleteIfExists(stderr); Files.deleteIfExists(stdin) } + } + fun snapshot(root: Path): GitSnapshot? { + val repo = try { git(root, listOf("rev-parse", "--is-inside-work-tree")) } catch (_: java.io.IOException) { return null } + if (repo.first != 0 || repo.second.trim() != "true") return null + fun read(vararg args: String) = git(root, args.toList()).let { if (it.first == 0) it.second.trim() else "" } + check(git(root, listOf("status", "--porcelain", "--untracked-files=normal")).first == 0) { "无法读取本机 Git 状态" } + return GitSnapshot(read("rev-parse", "--verify", "HEAD"), read("symbolic-ref", "--short", "-q", "HEAD"), + read("status", "--porcelain", "--untracked-files=normal").isNotEmpty(), + read("rev-parse", "--abbrev-ref", "@{upstream}"), read("rev-list", "--left-right", "--count", "HEAD...@{upstream}")) + } + fun collect(root: Path, gitSnapshot: GitSnapshot?): List { + val candidates = mutableListOf() + var hasIgnore = false + if (gitSnapshot != null) { + val listing = git(root, listOf("ls-files", "-z", "--cached", "--others", "--exclude-standard")) + check(listing.first == 0) { "Git 源码文件清单读取失败" } + listing.second.split('\u0000').filter { it.isNotEmpty() && !reserved(it) }.distinct().forEach { name -> + val file = root.resolve(name) + check(!Files.isDirectory(file)) { "暂不支持 Git 子模块或嵌套仓库:$name" } + if (Files.exists(file, LinkOption.NOFOLLOW_LINKS)) candidates.add(file) + } + } else Files.walkFileTree(root, object : SimpleFileVisitor() { + override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult = + if (dir != root && reserved(root.relativize(dir).joinToString("/"))) FileVisitResult.SKIP_SUBTREE else FileVisitResult.CONTINUE + override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { + if (!reserved(root.relativize(file).joinToString("/"))) { candidates.add(file); if (file.fileName.toString() == ".gitignore") hasIgnore = true } + return FileVisitResult.CONTINUE + } + }) + check(gitSnapshot != null || !hasIgnore) { "存在 .gitignore,但无法读取 Git 工作树;请安装 Git 并确认该工程属于 Git 仓库,避免误传忽略文件" } + val names = candidates.map { root.relativize(it).joinToString("/") } + val ignored = if (gitSnapshot == null || names.isEmpty()) emptySet() else { + val result = git(root, listOf("check-ignore", "--no-index", "-z", "--stdin"), (names.joinToString("\u0000") + "\u0000").toByteArray(Charsets.UTF_8)) + check(result.first in 0..1) { "Git 忽略规则检查失败,已停止同步" } + result.second.split('\u0000').filter { it.isNotEmpty() }.toSet() + } + return candidates.filterIndexed { i, path -> + if (names[i] in ignored) false else { check(!Files.isSymbolicLink(path)) { "暂不支持符号链接:$path" }; true } + } + } +} diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/SyncComparison.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/SyncComparison.kt new file mode 100644 index 0000000..e2c0903 --- /dev/null +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/SyncComparison.kt @@ -0,0 +1,18 @@ +package studio.tongtong.remotecompile + +import java.nio.ByteBuffer +import java.nio.charset.CharacterCodingException +import java.nio.file.Path +import java.security.MessageDigest + +object SyncComparison { + fun textHash(name: String, bytes: ByteArray): String? { + val leaf = Path.of(name).fileName.toString().lowercase() + val extension = leaf.substringAfterLast('.', "") + if (extension !in setOf("kt", "kts", "java", "xml", "gradle", "properties", "json", "toml", "yaml", "yml", "txt", "md", "proto", "c", "cc", "cpp", "h", "hpp", "cmake", "aidl", "pro", "cfg", "ini", "csv", "html", "css", "js", "ts", "svg") && leaf !in setOf(".gitignore", ".gitattributes", ".editorconfig", "cmakelists.txt")) return null + if (bytes.any { it == 0.toByte() }) return null + val text = try { Charsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString() } catch (_: CharacterCodingException) { return null } + val normalized = text.replace("\r\n", "\n").toByteArray(Charsets.UTF_8) + return MessageDigest.getInstance("SHA-256").digest(normalized).joinToString("") { "%02x".format(it) } + } +} diff --git a/plugin/src/main/kotlin/studio/tongtong/remotecompile/TimestampedLog.kt b/plugin/src/main/kotlin/studio/tongtong/remotecompile/TimestampedLog.kt new file mode 100644 index 0000000..06571a5 --- /dev/null +++ b/plugin/src/main/kotlin/studio/tongtong/remotecompile/TimestampedLog.kt @@ -0,0 +1,32 @@ +package studio.tongtong.remotecompile + +import java.time.Clock +import java.time.LocalTime +import java.time.format.DateTimeFormatter + +/** Timestamps refer to local receipt time; server chunks may split lines and CRLF pairs. */ +class TimestampedLog(private val clock: Clock = Clock.systemDefaultZone()) { + private val format = DateTimeFormatter.ofPattern("HH:mm:ss.SSS") + private var lineStart = true + private var previousCR = false + fun reset() { lineStart = true; previousCR = false } + fun chunk(text: String): String = buildString { + for (c in text) { + if (c == '\n' && previousCR) { previousCR = false; continue } + previousCR = c == '\r' + if (c == '\r' || c == '\n') { append('\n'); lineStart = true } + else { + if (lineStart) { append('[').append(LocalTime.now(clock).format(format)).append("] "); lineStart = false } + append(c) + } + } + } + fun message(text: String): String { + val separator = if (lineStart) "" else "\n" + lineStart = true; previousCR = false + val content = chunk(text) + val ending = if (lineStart) "" else "\n" + lineStart = true; previousCR = false + return separator + content + ending + } +} diff --git a/plugin/src/test/kotlin/studio/tongtong/remotecompile/BuildTasksTest.kt b/plugin/src/test/kotlin/studio/tongtong/remotecompile/BuildTasksTest.kt new file mode 100644 index 0000000..d7ce73a --- /dev/null +++ b/plugin/src/test/kotlin/studio/tongtong/remotecompile/BuildTasksTest.kt @@ -0,0 +1,28 @@ +package studio.tongtong.remotecompile + +import org.junit.Assert.* +import org.junit.Test + +class BuildTasksTest { + @Test fun detectsCustomBuildTypesWithoutReadingSigningBlocksOrComments() { + val script = """ + plugins { id 'com.android.application' } + signingConfigs { wrongSigningName {} } + // buildTypes { fake {} } + buildTypes { + CrosshatchDebug.initWith(debug) + CrosshatchDebug { debuggable = true; println("}") } + zhanRuiDebug { } + debug { } + } + """.trimIndent() + assertEquals(listOf(":app:assembleDebug", ":app:assembleRelease", ":app:assembleCrosshatchDebug", ":app:assembleZhanRuiDebug"), BuildTasks.fromScript(":app", script)) + } + @Test fun supportsLiteralKotlinDslAndRejectsShellArguments() { + assertTrue(BuildTasks.fromScript(":demo", """plugins { id("com.android.application") }; android { buildTypes { create("tabletDebug") { } } }""").contains(":demo:assembleTabletDebug")) + assertTrue(BuildTasks.valid(":app:assembleCrosshatchDebug")) + assertFalse(BuildTasks.valid(":app:assembleDebug --scan")) + assertFalse(BuildTasks.valid("task&command")) + assertTrue(BuildTasks.fromScript(":lib", "plugins { id 'com.android.library' }").isEmpty()) + } +} diff --git a/plugin/src/test/kotlin/studio/tongtong/remotecompile/LastBuildTest.kt b/plugin/src/test/kotlin/studio/tongtong/remotecompile/LastBuildTest.kt new file mode 100644 index 0000000..b822107 --- /dev/null +++ b/plugin/src/test/kotlin/studio/tongtong/remotecompile/LastBuildTest.kt @@ -0,0 +1,18 @@ +package studio.tongtong.remotecompile +import org.junit.Assert.* +import org.junit.Test +import java.nio.file.Files +class LastBuildTest { + @Test fun lostSubmissionResponseSurvivesClientRestart() { + val root=Files.createTempDirectory("last-build") + try { + val record=LastBuild(server="https://localhost:8765",projectId="project",revision="rev",task=":app:assembleDebug",clientRequestId="request-before-send",certificate="证书/server.crt") + LastBuildStore.save(root,record) + val reopened=LastBuildStore.load(root)!! + assertEquals("request-before-send",reopened.clientRequestId);assertEquals("",reopened.buildId) + reopened.buildId="1234567890abcdef1234567890abcdef";LastBuildStore.save(root,reopened) + assertEquals(reopened,LastBuildStore.load(root)) + assertFalse(Files.readString(root.resolve(".remotecompile/last-build.json")).contains("token")) + }finally{root.toFile().deleteRecursively()} + } +} diff --git a/plugin/src/test/kotlin/studio/tongtong/remotecompile/SettingsTest.kt b/plugin/src/test/kotlin/studio/tongtong/remotecompile/SettingsTest.kt index f038847..bd4d1b9 100644 --- a/plugin/src/test/kotlin/studio/tongtong/remotecompile/SettingsTest.kt +++ b/plugin/src/test/kotlin/studio/tongtong/remotecompile/SettingsTest.kt @@ -7,7 +7,7 @@ class SettingsTest { @Test fun allConnectionFieldsSurvivePlatformXmlSerialization() { val saved = Settings().apply { saveConfiguration(Settings.Data(url = "https://192.168.5.222:8765", task = ":app:assembleDebug", - adb = "D:/Android SDK/platform-tools/adb.exe", install = true, serverCertificate = "D:/证书/server.crt")) + remoteJavaHome = "C:/Program Files/Java/jdk-21", ignoreLineEndings = false, remoteFolder = "D:/Projects/中文工程", adb = "D:/Android SDK/platform-tools/adb.exe", install = true, serverCertificate = "D:/证书/server.crt")) selectDevice("USB123") projectAllocated("https://192.168.5.222:8765", "workspace-123") } @@ -20,9 +20,11 @@ class SettingsTest { @Test fun globalDefaultsNeverShareProjectWorkspaceOrDevice() { val shared = ConnectionDefaults() shared.loadState(Settings.Data(url = "https://192.168.5.222:8765", adb = "custom-adb", serverCertificate = "server.crt", configured = true, - projectId = "must-not-share", device = "must-not-share")) + projectId = "must-not-share", device = "must-not-share", remoteFolder = "D:/Projects/private", remoteJavaHome = "private-jdk")) assertEquals("", shared.getState().projectId) assertEquals("", shared.getState().device) + assertEquals("", shared.getState().remoteFolder) + assertEquals("", shared.getState().remoteJavaHome) assertEquals("custom-adb", shared.getState().adb) assertEquals("server.crt", shared.getState().serverCertificate) } @@ -41,6 +43,27 @@ class SettingsTest { assertEquals("allocated-during-edit", settings.snapshot().projectId) assertEquals("USB123", settings.snapshot().device) } + @Test fun quickTaskSelectionSurvivesRestartAndStaleConnectionSave() { + val settings = Settings() + val stale = settings.snapshot() + settings.selectTask(":app:assembleCrosshatchDebug") + settings.saveConfiguration(stale.copy(adb = "new-adb"), preserveTask = true) + val state = com.intellij.util.xmlb.XmlSerializer.deserialize(com.intellij.util.xmlb.XmlSerializer.serialize(settings.getState()), Settings.Data::class.java) + val reopened = Settings().apply { loadState(state) } + assertEquals(":app:assembleCrosshatchDebug", reopened.snapshot().task) + assertEquals(listOf(":app:assembleCrosshatchDebug"), reopened.snapshot().taskHistory) + assertEquals("new-adb", reopened.snapshot().adb) + } + @Test fun changingRemoteFolderResetsWorkspaceAndDiscardsLateAllocation() { + val settings = Settings() + settings.saveConfiguration(settings.snapshot().copy(remoteFolder = "D:/Projects/One")) + val original = settings.snapshot() + settings.projectAllocated(original.url, "one", original.remoteFolder) + settings.saveConfiguration(settings.snapshot().copy(remoteFolder = "D:/Projects/Two")) + settings.projectAllocated(original.url, "late-one", original.remoteFolder) + assertEquals("", settings.snapshot().projectId) + assertEquals("D:/Projects/Two", settings.snapshot().remoteFolder) + } @Test fun changingEndpointResetsWorkspaceAndOldBuildCannotOverwriteIt() { val settings = Settings() val oldUrl = settings.snapshot().url diff --git a/plugin/src/test/kotlin/studio/tongtong/remotecompile/SourceFilesTest.kt b/plugin/src/test/kotlin/studio/tongtong/remotecompile/SourceFilesTest.kt new file mode 100644 index 0000000..49fd566 --- /dev/null +++ b/plugin/src/test/kotlin/studio/tongtong/remotecompile/SourceFilesTest.kt @@ -0,0 +1,32 @@ +package studio.tongtong.remotecompile + +import org.junit.Assert.* +import org.junit.Test +import java.nio.file.Files +import java.nio.file.Path + +class SourceFilesTest { + @Test fun usesGitIgnoreNegationNestedRulesAndProtectsNativeCaches() { + val root = Files.createTempDirectory("remote 源码 ") + try { + assertEquals(0, SourceFiles.git(root, listOf("init", "-q")).first) + fun put(name: String, data: String = "test") { val path = root.resolve(name); Files.createDirectories(path.parent); Files.writeString(path, data) } + put(".gitignore", "ignored/*\n!ignored/keep.txt\n*.apk\n") + put("module/.gitignore", "secret.txt\n") + put("ignored/drop.txt"); put("ignored/keep.txt"); put("module/secret.txt") + put("app/.cxx/Debug/arm64-v8a/.ninja_deps"); put("app/build/output.apk"); put("app/.externalNativeBuild/cache") + put("app/src/中文 code.kt"); put("app-debug.apk"); put("local.properties"); put(".env.local") + // Even force-added ignored files follow the explicit sync ignore policy. + SourceFiles.git(root, listOf("add", "-f", "app-debug.apk")) + val names = SourceFiles.collect(root, SourceFiles.snapshot(root)).map { root.relativize(it).joinToString("/") }.toSet() + assertTrue(names.contains("ignored/keep.txt")); assertTrue(names.contains("app/src/中文 code.kt")) + assertFalse(names.contains("ignored/drop.txt")); assertFalse(names.contains("module/secret.txt")); assertFalse(names.contains("app-debug.apk")) + assertTrue(names.none { ".cxx" in it || "/build/" in it || ".externalNativeBuild" in it || it == "local.properties" || it.startsWith(".env") }) + } finally { root.toFile().deleteRecursively() } + } + @Test fun cannotSilentlyIgnoreGitIgnoreWithoutWorkingGitTree() { + val root = Files.createTempDirectory("remote-no-git") + try { Files.writeString(root.resolve(".gitignore"), "private/\n"); assertThrows(IllegalStateException::class.java) { SourceFiles.collect(root, null) } } + finally { root.toFile().deleteRecursively() } + } +} diff --git a/plugin/src/test/kotlin/studio/tongtong/remotecompile/SyncComparisonTest.kt b/plugin/src/test/kotlin/studio/tongtong/remotecompile/SyncComparisonTest.kt new file mode 100644 index 0000000..f0a8232 --- /dev/null +++ b/plugin/src/test/kotlin/studio/tongtong/remotecompile/SyncComparisonTest.kt @@ -0,0 +1,19 @@ +package studio.tongtong.remotecompile + +import org.junit.Assert.* +import org.junit.Test + +class SyncComparisonTest { + @Test fun onlyCrLfDifferencesAreEquivalent() { + val lf = "val 中文 = 1\nnext\n".toByteArray() + assertEquals(SyncComparison.textHash("Source.kt", lf), SyncComparison.textHash("Source.kt", "val 中文 = 1\r\nnext\r\n".toByteArray())) + assertNotEquals(SyncComparison.textHash("Source.kt", lf), SyncComparison.textHash("Source.kt", "val 中文 = 2\nnext\n".toByteArray())) + assertNotEquals(SyncComparison.textHash("Source.kt", lf), SyncComparison.textHash("Source.kt", "val 中文 = 1\nnext".toByteArray())) + assertNotEquals(SyncComparison.textHash("Source.kt", lf), SyncComparison.textHash("Source.kt", "val 中文 = 1 \nnext\n".toByteArray())) + } + @Test fun binariesScriptsInvalidUtf8AndUtf16StayExact() { + for (name in listOf("file.jar", "image.bin", "gradlew", "script.sh")) assertNull(SyncComparison.textHash(name, "a\r\nb".toByteArray())) + assertNull(SyncComparison.textHash("data.txt", byteArrayOf(0xff.toByte(), 0xfe.toByte()))) + assertNull(SyncComparison.textHash("data.txt", byteArrayOf(65, 0, 13, 10))) + } +} diff --git a/plugin/src/test/kotlin/studio/tongtong/remotecompile/TimestampedLogTest.kt b/plugin/src/test/kotlin/studio/tongtong/remotecompile/TimestampedLogTest.kt new file mode 100644 index 0000000..42fdbe9 --- /dev/null +++ b/plugin/src/test/kotlin/studio/tongtong/remotecompile/TimestampedLogTest.kt @@ -0,0 +1,23 @@ +package studio.tongtong.remotecompile + +import org.junit.Assert.* +import org.junit.Test +import java.time.Clock +import java.time.Instant +import java.time.ZoneId + +class TimestampedLogTest { + private fun formatter() = TimestampedLog(Clock.fixed(Instant.parse("2026-11-25T01:02:03.456Z"), ZoneId.of("Asia/Shanghai"))) + @Test fun preservesChunkedLinesAndSplitCrLfWithoutExtraTimestamps() { + val log = formatter() + val text = log.chunk("编译") + log.chunk("中\r") + log.chunk("\n完成\n") + assertEquals("[09:02:03.456] 编译中\n[09:02:03.456] 完成\n", text) + } + @Test fun multilineMessagesResetAndPartialStreamRemainReadable() { + val log = formatter() + assertEquals("[09:02:03.456] 下载", log.chunk("下载")) + assertEquals("\n[09:02:03.456] 状态\n[09:02:03.456] 下一行\n", log.message("状态\r\n下一行\n")) + log.reset() + assertEquals("[09:02:03.456] 新构建\n", log.message("新构建")) + } +} diff --git a/protocol/api.md b/protocol/api.md index afe3874..b5ae5db 100644 --- a/protocol/api.md +++ b/protocol/api.md @@ -5,10 +5,15 @@ | 方法 | 路径(前缀 `/api/v1`) | 说明 | | --- | --- | --- | | GET | `/health` | 版本、OS 和同步能力 | -| POST | `/projects` | 分配独立工作区,返回 `{ "id": "..." }` | +| GET | `/jdks` | 发现服务端 JDK:where/which、PATH、JAVA_HOME、服务配置、常见安装目录 | +| GET | `/environment` | 有效工具、缓存路径和代理来源(不含 Token) | +| GET | `/directories?path=...` | 浏览管理员允许根目录下的已有子目录,空 path 从根目录开始 | +| POST | `/projects/check` | 只读检查 workspacePath、projectId 和 git,返回 canSync、message、服务端 Git | +| POST | `/projects` | 绑定 workspacePath 指定的已有工程目录,返回 id 与实际 workspacePath | | GET | `/projects/{id}/manifest` | 当前 revision 与 files 清单 | | POST | `/projects/{id}/sync` | 同步完整清单、变更内容并提交新版本 | | POST | `/projects/{id}/builds` | 请求构建,返回 build | +| GET | `/projects/{id}/builds` | 最近50条构建;可按 clientRequestId 精确查询 | | GET | `/builds/{id}` | 状态、日志块与产物 | | DELETE | `/builds/{id}` | 请求取消;继续查询直到终态 | | GET | `/builds/{id}/logs` | SSE 日志,支持 Last-Event-ID 从上次块之后继续 | @@ -28,16 +33,45 @@ `files` 是完整源码清单;上一版本存在、本次未出现的文件会删除。内容变化时提供 data,未变化时省略。所有内容先校验,再使旧 revision 失效并落盘,成功才提交新 revision。写入失败会保留不可构建状态,下次完整同步可恢复;不是文件系统事务回滚。首版一次请求最多 256MiB(包含 Base64 和 JSON),客户端单文件限制 64MiB。 -路径使用 `/`,拒绝路径穿越、绝对路径、Windows 保留名、大小写重复、符号链接和保留目录。服务器不信任客户端提供的 hash,必须校验实际内容。插件和参考客户端使用相同排除约定;`.gitignore` 不会自动套用,确实需要构建的未跟踪文件仍可上传。 +路径使用 `/`,拒绝路径穿越、绝对路径、Windows 保留名、大小写重复、符号链接和保留目录。服务器不信任客户端提供的 hash,必须校验实际内容。插件和参考客户端使用相同排除约定;0.3.0 插件与参考客户端通过 Git 原生 `ls-files` 和 `check-ignore --no-index` 遵循嵌套 `.gitignore`、反选规则、info/exclude 和全局排除;被忽略的已跟踪文件也不上传。`.cxx`、`.externalNativeBuild` 等缓存强制排除。没有 Git 工作树却存在 `.gitignore` 时停止同步,避免误传。 构建请求: ```json -{ "revision": "刚提交的版本号", "task": ":app:assembleDebug" } +{ "revision": "刚提交的版本号", "task": ":app:assembleDebug", "clientRequestId": "客户端提交前保存的唯一请求ID" } ``` -状态:`queued → running → success | failed | cancelled`。同一工作区只能有一个任务,忙时返回 409;首版没有跨工作区全局限流或持久队列。任务必须命中服务端白名单。源码、工作区与 buildId 绑定,构建中不接受该工作区同步。 +状态:`queued → running → success | failed | cancelled`;服务重启发现未结束任务时标为 `interrupted`。任务从入队开始持久化,但进程中断不支持自动重跑。相同工作区和 clientRequestId 的相同参数重试返回原任务,不同参数返回 409;字段省略时兼容旧客户端,不提供该请求的幂等保证。同一工作区只能有一个任务,忙时拒绝新任务,重复幂等查询仍可返回原任务。源码、工作区与 buildId 绑定,构建中不接受该工作区同步。 + +Build 的 progress 包含 phase/message/path/current/total/percent;total 不可获取时 percent=-1,客户端显示已下载字节和不定进度。environment 包含实际执行器和有效路径、代理来源。日志和进度定期落盘,终态立即保存。历史产物下载支持 HTTP Range,客户端仍需完成后核对完整摘要。 产物记录:`{ "name": "0-app-debug.apk", "hash": "SHA-256", "size": 12345 }`。客户端必须验证摘要后安装。构建前仅删除各模块 `build/outputs/` 下的旧 APK,保留其他编译缓存。服务端成功收集本次 APK 后才报告 success。 SSE data 是 JSON 编码的日志文本块,不保证以行或 UTF-8 字符边界分块;首版插件通过 GET build 每 700ms 轮询日志,而非消费 SSE。日志 ID 为从 1 开始的块编号。终态发送完所有日志后连接关闭。 + +## 工程目录与 Git(0.3.0) + +`POST /projects/check` 和 `POST /projects` 请求: + +```json +{"workspacePath":"D:\\RemoteProjects\\MyApp","projectId":"已有ID,首次可省略","git":{"head":"完整提交哈希","branch":"main","dirty":true,"upstream":"origin/main","aheadBehind":"0\t0"}} +``` + +插件和参考客户端强制填写已有目录;服务用 `-workspace-root` 限定可选父目录,默认 data/projects。目录必须是已有的普通目录,拒绝越界、链接及工作区重叠。旧客户端省略 workspacePath 时仍按旧协议分配内部目录;0.3.0 客户端不走该兼容分支。 + +检查返回 workspacePath、git(无仓库时为 null)、canSync、message,不分配项目、不拉取仓库、不改变源码。已有双方 Git 仓库的 HEAD 不同会阻止运行;首次绑定远程脏工作树会阻止覆盖。后续允许远程因上次同步而产生的脏状态,但检测远程额外修改;手动更新到与本机相同提交的干净 Git 工作树后可继续。 + +同步请求可包含同结构的 git;服务再次检查后才写入,成功提交时保存 Git 信息。只有同步清单中管理过的源码会参与删除;保留目录中的服务端构建缓存不随清单删除。GET manifest 核验磁盘内容,失效文件省略 hash 条目以要求客户端重新上传,避免旧清单导致 missing content。 + +上游差异依据现有引用,不执行 fetch。服务端无 .git 时明确提示无法比较 Git 提交。Git 目录不经 HTTP 上传。 + +## 文本换行比较与 JDK(0.4.0) + +健康接口增加 textComparison 和 jdkSelection。GET manifest 在已核验的 raw hash 旁为支持的 UTF-8 源码/配置文本返回 textHash:仅将 CRLF 转为 LF 后计算 SHA-256,不修改磁盘。含 NUL、非法 UTF-8、UTF-16、二进制及执行脚本不提供等价比较。客户端默认先比 raw hash,再比 textHash;若仅换行不同,提交服务端 raw hash 且省略 data,保留服务端原始字节。可关闭此选项恢复严格字节同步;文本真实变化、空白变化和末尾换行增删仍触发上传。 + +GET /jdks 返回 jdks 数组(home、version、source)和 defaultJavaHome。Windows 运行服务上下文的 where.exe java/javac,其他平台使用 which;补充 JAVA_HOME、服务配置、服务 toolchains 和常见安装目录。仅列出同时有 java、javac 和 release 版本信息的 JDK,目录去重,不自动选择最新版本。 + +POST /projects/{id}/builds 可携带 javaHome;为空沿用服务配置,否则须匹配服务器发现列表。选择记录在 Build.javaHome 和实际 environment 中,并参与 clientRequestId 参数一致性检查。插件按工程保存选择,历史恢复沿用原任务的 JDK;不会修改其他工程或服务全局 JAVA_HOME。 + + +0.4.1:干净 Git 工作树的 manifest 反映当前磁盘源码,允许同 HEAD 的重新检出/恢复作为下次同步基准;若与已持久化快照不一致,响应 revision 为空。GET 和检查接口不修改服务快照。构建仍要求与已成功同步的原始字节清单完全匹配,发现恢复文件、额外源码或不同字节时返回 409,要求重新同步。 diff --git a/server/environment.go b/server/environment.go new file mode 100644 index 0000000..ddaa1da --- /dev/null +++ b/server/environment.go @@ -0,0 +1,353 @@ +package main + +import ( + "context" + "crypto/md5" + "encoding/json" + "fmt" + "math/big" + "net" + "net/http" + "net/url" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "strings" + "time" +) + +type BuildEnvironment struct { + GradleHome string `json:"gradleHome"` + GradleUserHome string `json:"gradleUserHome"` + JavaHome string `json:"javaHome"` + AndroidHome string `json:"androidHome"` + Proxy string `json:"proxy"` + ProxySource string `json:"proxySource"` + PreferWrapper bool `json:"preferWrapper"` +} + +func (s *Server) buildEnvironment() (BuildEnvironment, error) { + c := BuildEnvironment{GradleHome: os.Getenv("GRADLE_HOME"), GradleUserHome: os.Getenv("GRADLE_USER_HOME"), JavaHome: os.Getenv("JAVA_HOME"), AndroidHome: os.Getenv("ANDROID_HOME")} + if c.AndroidHome == "" { + c.AndroidHome = os.Getenv("ANDROID_SDK_ROOT") + } + if s.environmentFile != "" { + data, e := os.ReadFile(s.environmentFile) + if e != nil { + return c, fmt.Errorf("read environment config: %w", e) + } + if e = json.Unmarshal(data, &c); e != nil { + return c, e + } + } + if c.GradleUserHome == "" { + home, _ := os.UserHomeDir() + c.GradleUserHome = filepath.Join(home, ".gradle") + } + if c.GradleHome == "" { + name := "gradle" + if runtime.GOOS == "windows" { + name = "gradle.bat" + } + if p, e := exec.LookPath(name); e == nil { + c.GradleHome = filepath.Dir(filepath.Dir(p)) + } + } + if c.Proxy == "direct" { + c.Proxy = "" + c.ProxySource = "disabled" + } + if c.Proxy != "" { + if c.ProxySource == "" { + c.ProxySource = "configured" + } + } else if c.ProxySource != "disabled" { + for _, key := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"} { + if p := os.Getenv(key); p != "" { + c.Proxy = p + c.ProxySource = key + break + } + } + if c.Proxy == "" { + c.Proxy = systemProxy() + if c.Proxy != "" { + c.ProxySource = "system" + } + } + } + if c.Proxy != "" { + p, e := url.Parse(c.Proxy) + if e != nil || p.Hostname() == "" || (p.Scheme != "http" && p.Scheme != "https") { + return c, fmt.Errorf("invalid HTTP proxy URL") + } + if p.User != nil || p.RawQuery != "" || p.Fragment != "" || (p.Path != "" && p.Path != "/") { + return c, fmt.Errorf("authenticated proxy URLs are not supported; use system-integrated credentials or a local proxy without URL credentials") + } + if net.ParseIP(p.Hostname()) == nil && !regexp.MustCompile(`^[A-Za-z0-9.-]+$`).MatchString(p.Hostname()) { + return c, fmt.Errorf("unsupported proxy hostname") + } + } + if c.ProxySource == "" { + c.ProxySource = "direct" + } + return c, nil +} +func (c BuildEnvironment) summary() map[string]string { + return map[string]string{"gradleHome": c.GradleHome, "gradleUserHome": c.GradleUserHome, "javaHome": c.JavaHome, "androidHome": c.AndroidHome, "proxy": c.Proxy, "proxySource": c.ProxySource, "preferWrapper": fmt.Sprint(c.PreferWrapper)} +} +func (c BuildEnvironment) environ() []string { + env := os.Environ() + put := func(k, v string) { + if v == "" { + return + } + prefix := strings.ToUpper(k) + "=" + filtered := env[:0] + for _, entry := range env { + if !strings.HasPrefix(strings.ToUpper(entry), prefix) { + filtered = append(filtered, entry) + } + } + env = append(filtered, k+"="+v) + } + put("GRADLE_USER_HOME", c.GradleUserHome) + put("GRADLE_HOME", c.GradleHome) + put("JAVA_HOME", c.JavaHome) + put("ANDROID_HOME", c.AndroidHome) + put("ANDROID_SDK_ROOT", c.AndroidHome) + opts := os.Getenv("GRADLE_OPTS") + " -Djava.net.useSystemProxies=true" + if c.ProxySource == "disabled" { + opts = os.Getenv("GRADLE_OPTS") + " -Djava.net.useSystemProxies=false -Dhttp.proxyHost= -Dhttps.proxyHost=" + filtered := env[:0] + for _, entry := range env { + k, _, _ := strings.Cut(entry, "=") + if strings.ToUpper(k) != "HTTP_PROXY" && strings.ToUpper(k) != "HTTPS_PROXY" { + filtered = append(filtered, entry) + } + } + env = filtered + } + if c.Proxy != "" { + p, _ := url.Parse(c.Proxy) + port := p.Port() + if port == "" { + port = "80" + if p.Scheme == "https" { + port = "443" + } + } + opts += " -Dhttp.proxyHost=" + p.Hostname() + " -Dhttp.proxyPort=" + port + " -Dhttps.proxyHost=" + p.Hostname() + " -Dhttps.proxyPort=" + port + put("HTTP_PROXY", c.Proxy) + put("HTTPS_PROXY", c.Proxy) + } + put("GRADLE_OPTS", opts) + return env +} +func wrapperProperties(work string) map[string]string { + props := map[string]string{} + data, _ := os.ReadFile(filepath.Join(work, "gradle", "wrapper", "gradle-wrapper.properties")) + for _, line := range strings.Split(string(data), "\n") { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + k, v, ok := strings.Cut(line, "=") + if ok { + v = strings.ReplaceAll(v, `\:`, ":") + v = strings.ReplaceAll(v, `\=`, "=") + v = strings.ReplaceAll(v, `\\`, `\`) + props[strings.TrimSpace(k)] = strings.TrimSpace(v) + } + } + return props +} + +var distributionVersion = regexp.MustCompile(`gradle-([0-9][A-Za-z0-9.\-]*)-(?:bin|all)\.zip$`) + +func wrapperVersion(work string) string { + u, e := url.Parse(wrapperProperties(work)["distributionUrl"]) + if e != nil { + return "" + } + matches := distributionVersion.FindStringSubmatch(filepath.Base(u.Path)) + if len(matches) > 1 { + return matches[1] + } + return "" +} +func nativeGradle(home, version string) string { + if home == "" || version == "" { + return "" + } + if _, e := os.Stat(filepath.Join(home, "lib", "gradle-launcher-"+version+".jar")); e != nil { + return "" + } + name := "gradle" + if runtime.GOOS == "windows" { + name = "gradle.bat" + } + p := filepath.Join(home, "bin", name) + if _, e := os.Stat(p); e != nil { + return "" + } + return p +} +func (s *Server) prepareCommand(work, task string, c BuildEnvironment) (*exec.Cmd, map[string]string, error) { + if e := os.MkdirAll(c.GradleUserHome, 0700); e != nil { + return nil, nil, fmt.Errorf("Gradle cache not writable: %s: %w", c.GradleUserHome, e) + } + f, e := os.CreateTemp(c.GradleUserHome, ".remotecompile-write-check-") + if e != nil { + return nil, nil, fmt.Errorf("service account cannot write Gradle cache %s: %w", c.GradleUserHome, e) + } + f.Close() + os.Remove(f.Name()) + info := c.summary() + version := wrapperVersion(work) + info["requestedGradleVersion"] = version + info["execution"] = "project-wrapper" + if raw, target := distributionTarget(work, c); raw != "" { + u, _ := url.Parse(raw) + info["distributionUrl"] = u.Scheme + "://" + u.Host + u.EscapedPath() + info["distributionFile"] = strings.TrimSuffix(target, ".part") + } + homes := []string{c.GradleHome} + if version != "" { + for _, kind := range []string{"bin", "all"} { + matches, _ := filepath.Glob(filepath.Join(c.GradleUserHome, "wrapper", "dists", "gradle-"+version+"-"+kind, "*", "gradle-"+version)) + homes = append(homes, matches...) + } + } + for _, home := range homes { + if c.PreferWrapper { + break + } + if binary := nativeGradle(home, version); binary != "" { + if strings.ContainsAny(binary, "\"\r\n&|<>^%!") { + return nil, nil, fmt.Errorf("unsupported shell characters in configured Gradle path") + } + info["execution"] = "installed-gradle" + info["configuredGradleHome"] = c.GradleHome + info["gradleHome"] = home + delete(info, "distributionFile") + info["executable"] = binary + return gradleExecutableCommand(binary, task), info, nil + } + } + return gradleCommand(work, task), info, nil +} +func distributionTarget(work string, c BuildEnvironment) (string, string) { + p := wrapperProperties(work) + raw := p["distributionUrl"] + u, e := url.Parse(raw) + if e != nil || u.Host == "" || u.Scheme != "https" { + return "", "" + } + name := filepath.Base(u.Path) + if !distributionVersion.MatchString(name) { + return "", "" + } + base := c.GradleUserHome + if p["zipStoreBase"] == "PROJECT" { + base = work + } + rel := p["zipStorePath"] + if rel == "" { + rel = "wrapper/dists" + } + if filepath.IsAbs(rel) || strings.Contains(rel, "..") { + return "", "" + } + safeURL := *u + safeURL.User = nil + sum := md5.Sum([]byte(safeURL.String())) + hash := new(big.Int).SetBytes(sum[:]).Text(36) + return raw, filepath.Join(base, rel, strings.TrimSuffix(name, ".zip"), hash, name+".part") +} +func (s *Server) monitorDistribution(b *Build, work string, c BuildEnvironment, stop <-chan struct{}) { + raw, path := distributionTarget(work, c) + if raw == "" { + return + } + s.mu.Lock() + native := b.Environment["execution"] == "installed-gradle" + s.mu.Unlock() + if native { + return + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { + select { + case <-stop: + cancel() + case <-ctx.Done(): + } + }() + total := int64(0) + client := &http.Client{Timeout: 8 * time.Second} + if c.Proxy != "" { + p, _ := url.Parse(c.Proxy) + client.Transport = &http.Transport{Proxy: http.ProxyURL(p)} + } else { + client.Transport = &http.Transport{} + } + req, _ := http.NewRequestWithContext(ctx, "HEAD", raw, nil) + if response, e := client.Do(req); e == nil { + if response.StatusCode >= 200 && response.StatusCode < 300 { + total = response.ContentLength + } + response.Body.Close() + } + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + started := time.Now() + seen := false + baseline := int64(0) + for { + select { + case <-stop: + return + case <-ticker.C: + st, e := os.Stat(path) + if e != nil { + if seen { + s.mu.Lock() + if b.Status == "running" { + b.Progress = Progress{Phase: "building", Message: "Gradle 分发包下载已结束,正在解压或构建", Path: strings.TrimSuffix(path, ".part")} + _ = s.persistBuild(b) + } + s.mu.Unlock() + } + continue + } + current := st.Size() + if !seen { + baseline = current + started = time.Now() + seen = true + } + percent := -1 + if total > 0 { + percent = int(current * 100 / total) + if percent > 100 { + percent = 100 + } + } + msg := fmt.Sprintf("Gradle 下载 %.1f MiB", float64(current)/(1024*1024)) + if total > 0 { + msg += fmt.Sprintf(" / %.1f MiB (%d%%)", float64(total)/(1024*1024), percent) + } + msg += fmt.Sprintf(",平均 %.1f KiB/s", float64(current-baseline)/1024/(time.Since(started).Seconds()+0.001)) + s.mu.Lock() + if b.Status == "running" { + b.Progress = Progress{Phase: "downloading-gradle", Message: msg, Path: path, Current: current, Total: total, Percent: percent} + _ = s.persistBuild(b) + } + s.mu.Unlock() + } + } +} diff --git a/server/features_test.go b/server/features_test.go new file mode 100644 index 0000000..75dd9ac --- /dev/null +++ b/server/features_test.go @@ -0,0 +1,154 @@ +package main + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestIdempotentBuildCanBeFoundAfterLostResponse(t *testing.T) { + s := testServer(t) + p := project(t, s) + wrapper := "#!/bin/sh\nexit 1\n" + name := "gradlew" + if strings.Contains(os.Getenv("OS"), "Windows") { + name = "gradlew.bat" + wrapper = "@exit /b 1\r\n" + } + call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "rev", Files: map[string]File{name: file(wrapper)}}) + body := map[string]string{"revision": "rev", "task": ":app:assembleDebug", "clientRequestId": "persisted-before-submit"} + first := call(t, s, "POST", "/projects/"+p+"/builds", body) + if first.Code != 200 { + t.Fatal(first.Body.String()) + } + var b Build + json.Unmarshal(first.Body.Bytes(), &b) + again := call(t, s, "POST", "/projects/"+p+"/builds", body) + var repeated Build + json.Unmarshal(again.Body.Bytes(), &repeated) + if repeated.ID != b.ID { + t.Fatal("duplicate build submitted") + } + found := call(t, s, "GET", "/projects/"+p+"/builds?clientRequestId=persisted-before-submit", nil) + if !strings.Contains(found.Body.String(), b.ID) { + t.Fatal("lost response cannot be recovered") + } + body["revision"] = "different" + if call(t, s, "POST", "/projects/"+p+"/builds", body).Code != 409 { + t.Fatal("idempotency key accepted different source") + } + deadline := time.Now().Add(5 * time.Second) + for { + var state Build + json.Unmarshal(call(t, s, "GET", "/builds/"+b.ID, nil).Body.Bytes(), &state) + if state.Status != "queued" && state.Status != "running" { + break + } + if time.Now().After(deadline) { + t.Fatal("test build stuck") + } + time.Sleep(20 * time.Millisecond) + } + data, e := os.ReadFile(filepath.Join(s.root, "artifacts", b.ID, "build.json")) + if e != nil { + t.Fatal(e) + } + var stored Build + if json.Unmarshal(data, &stored) != nil || stored.RequestID != "persisted-before-submit" { + t.Fatal("submission not durable") + } +} +func TestInterruptedBuildRecoverableButWorkspaceLocked(t *testing.T) { + s := testServer(t) + p := project(t, s) + b := &Build{ID: id(), Project: p, Status: "running", RequestID: "recover-me", Logs: []string{"previous log"}} + s.builds[b.ID] = b + s.persistBuild(b) + os.WriteFile(filepath.Join(s.root, "projects", p, "active-build"), []byte(b.ID), 0600) + s.recoverBuilds() + if b.Status != "interrupted" || !s.projects[p].Busy { + t.Fatal("unsafe recovery state") + } + if w := call(t, s, "GET", "/builds/"+b.ID, nil); w.Code != 200 { + t.Fatal(w.Code) + } + if w := call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "new", Files: map[string]File{}}); w.Code != 409 { + t.Fatal("locked workspace accepted sync") + } +} +func TestExactInstalledGradleReusedAndDifferentVersionRejected(t *testing.T) { + s := testServer(t) + p := project(t, s) + work := s.work(p) + os.MkdirAll(filepath.Join(work, "gradle", "wrapper"), 0700) + os.WriteFile(filepath.Join(work, "gradle", "wrapper", "gradle-wrapper.properties"), []byte("distributionUrl=https\\://services.gradle.org/distributions/gradle-8.13-bin.zip\n"), 0600) + home := filepath.Join(s.root, "Gradle home 中文") + os.MkdirAll(filepath.Join(home, "lib"), 0700) + os.MkdirAll(filepath.Join(home, "bin"), 0700) + os.WriteFile(filepath.Join(home, "lib", "gradle-launcher-8.13.jar"), nil, 0600) + for _, n := range []string{"gradle", "gradle.bat"} { + os.WriteFile(filepath.Join(home, "bin", n), nil, 0700) + } + cfg := BuildEnvironment{GradleHome: home, GradleUserHome: filepath.Join(s.root, "cache")} + _, info, e := s.prepareCommand(work, ":app:assembleDebug", cfg) + if e != nil || info["execution"] != "installed-gradle" { + t.Fatalf("%v %v", e, info) + } + os.Rename(filepath.Join(home, "lib", "gradle-launcher-8.13.jar"), filepath.Join(home, "lib", "gradle-launcher-8.12.jar")) + _, info, e = s.prepareCommand(work, ":app:assembleDebug", cfg) + if e != nil || info["execution"] != "project-wrapper" { + t.Fatal("wrong Gradle version reused") + } +} +func TestProxyAppliedToGradleAndProgressPersists(t *testing.T) { + proxyHit := make(chan bool, 1) + proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case proxyHit <- true: + default: + } + http.Error(w, "test proxy denies external network", 403) + })) + defer proxy.Close() + s := testServer(t) + p := project(t, s) + work := s.work(p) + os.MkdirAll(filepath.Join(work, "gradle", "wrapper"), 0700) + os.WriteFile(filepath.Join(work, "gradle", "wrapper", "gradle-wrapper.properties"), []byte("distributionUrl=https\\://services.gradle.org/distributions/gradle-8.13-bin.zip\n"), 0600) + cfg := BuildEnvironment{GradleUserHome: filepath.Join(s.root, "cache"), Proxy: proxy.URL} + raw, target := distributionTarget(work, cfg) + if raw == "" { + t.Fatal("distribution not detected") + } + os.MkdirAll(filepath.Dir(target), 0700) + os.WriteFile(target, make([]byte, 128*1024), 0600) + b := &Build{ID: id(), Project: p, Status: "running", Environment: map[string]string{"execution": "project-wrapper"}} + stop := make(chan struct{}) + done := make(chan struct{}) + go func() { s.monitorDistribution(b, work, cfg, stop); close(done) }() + select { + case <-proxyHit: + case <-time.After(4 * time.Second): + t.Fatal("system/configured proxy not used") + } + time.Sleep(1500 * time.Millisecond) + close(stop) + <-done + s.mu.Lock() + progress := b.Progress + s.mu.Unlock() + if progress.Current != 128*1024 || progress.Path != target { + t.Fatalf("missing live progress: %+v", progress) + } + if _, e := os.Stat(filepath.Join(s.root, "artifacts", b.ID, "build.json")); e != nil { + t.Fatal("progress not persisted") + } + if !strings.Contains(strings.Join(cfg.environ(), "\n"), "-Dhttps.proxyHost=127.0.0.1") { + t.Fatal("proxy not forwarded to Gradle JVM") + } +} diff --git a/server/jdks.go b/server/jdks.go new file mode 100644 index 0000000..84b9015 --- /dev/null +++ b/server/jdks.go @@ -0,0 +1,147 @@ +package main + +import ( + "context" + "fmt" + "net/http" + "os" + "os/exec" + "path/filepath" + "runtime" + "sort" + "strings" + "time" +) + +type JDK struct { + Home string `json:"home"` + Version string `json:"version"` + Source string `json:"source"` +} + +func javaExecutable(name string) string { + if runtime.GOOS == "windows" { + return name + ".exe" + } + return name +} +func inspectJDK(home, source string) (JDK, bool) { + home, e := filepath.Abs(home) + if e != nil { + return JDK{}, false + } + if resolved, e := filepath.EvalSymlinks(home); e == nil { + home = resolved + } + for _, name := range []string{"java", "javac"} { + if i, e := os.Stat(filepath.Join(home, "bin", javaExecutable(name))); e != nil || !i.Mode().IsRegular() { + return JDK{}, false + } + } + data, e := os.ReadFile(filepath.Join(home, "release")) + if e != nil { + return JDK{}, false + } + version := "" + for _, line := range strings.Split(string(data), "\n") { + if strings.HasPrefix(line, "JAVA_VERSION=") { + version = strings.Trim(strings.TrimSpace(strings.TrimPrefix(line, "JAVA_VERSION=")), `"`) + } + } + if version == "" { + return JDK{}, false + } + return JDK{home, version, source}, true +} +func (s *Server) discoverJDKs() ([]JDK, string) { + result := []JDK{} + seen := map[string]bool{} + add := func(home, source string) { + if home == "" { + return + } + if j, ok := inspectJDK(home, source); ok { + key := j.Home + if runtime.GOOS == "windows" { + key = strings.ToLower(key) + } + if !seen[key] { + seen[key] = true + result = append(result, j) + } + } + } + c, _ := s.buildEnvironment() + add(c.JavaHome, "service-config") + add(os.Getenv("JAVA_HOME"), "JAVA_HOME") + fromBinary := func(path, source string) { + path = strings.TrimSpace(path) + if resolved, e := filepath.EvalSymlinks(path); e == nil { + path = resolved + } + add(filepath.Dir(filepath.Dir(path)), source) + } + for _, name := range []string{"java", "javac"} { + if path, e := exec.LookPath(javaExecutable(name)); e == nil { + fromBinary(path, "PATH") + } + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + var out []byte + if runtime.GOOS == "windows" { + out, _ = exec.CommandContext(ctx, "where.exe", "java", "javac").Output() + } else { + out, _ = exec.CommandContext(ctx, "which", "-a", "java", "javac").Output() + } + for _, line := range strings.Split(string(out), "\n") { + if strings.TrimSpace(line) != "" { + fromBinary(line, "where/which") + } + } + roots := []string{filepath.Join(filepath.Dir(s.root), "toolchains")} + if home, e := os.UserHomeDir(); e == nil { + roots = append(roots, filepath.Join(home, ".jdks")) + } + if runtime.GOOS == "windows" { + for _, base := range []string{os.Getenv("ProgramFiles"), os.Getenv("ProgramFiles(x86)")} { + if base != "" { + for _, dir := range []string{"Java", "Eclipse Adoptium", "Microsoft", "Amazon Corretto"} { + roots = append(roots, filepath.Join(base, dir)) + } + add(filepath.Join(base, "Android", "Android Studio", "jbr"), "Android Studio") + } + } + } else { + roots = append(roots, "/usr/lib/jvm", "/Library/Java/JavaVirtualMachines") + } + for _, root := range roots { + entries, _ := os.ReadDir(root) + for i, entry := range entries { + if i >= 64 { + break + } + p := filepath.Join(root, entry.Name()) + add(p, "installed") + add(filepath.Join(p, "Contents", "Home"), "installed") + } + } + sort.Slice(result, func(i, j int) bool { return result[i].Home < result[j].Home }) + return result, c.JavaHome +} +func (s *Server) selectedJDK(home string) (string, error) { + if home == "" { + return "", nil + } + choices, _ := s.discoverJDKs() + for _, j := range choices { + if j.Home == home || (runtime.GOOS == "windows" && strings.EqualFold(j.Home, home)) { + return j.Home, nil + } + } + return "", fmt.Errorf("指定 JDK 不在服务端发现列表中,请刷新服务端 JDK 后重新选择:%s", home) +} +func (s *Server) jdks(w http.ResponseWriter, r *http.Request) { + choices, current := s.discoverJDKs() + jsonOut(w, map[string]any{"jdks": choices, "defaultJavaHome": current}) +} diff --git a/server/main.go b/server/main.go index 629ce3d..87920fd 100644 --- a/server/main.go +++ b/server/main.go @@ -22,6 +22,7 @@ import ( "path/filepath" "regexp" "runtime" + "sort" "strconv" "strings" "sync" @@ -30,12 +31,14 @@ import ( ) type File struct { - Hash string `json:"hash"` - Data *string `json:"data,omitempty"` + Hash string `json:"hash"` + TextHash string `json:"textHash,omitempty"` + Data *string `json:"data,omitempty"` } type SyncRequest struct { Revision string `json:"revision"` Files map[string]File `json:"files"` + Git *GitSnapshot `json:"git,omitempty"` } type Artifact struct { Name string `json:"name"` @@ -43,27 +46,37 @@ type Artifact struct { Size int64 `json:"size"` } type Build struct { - ID string `json:"id"` - Project string `json:"project"` - Revision string `json:"revision"` - Task string `json:"task"` - Status string `json:"status"` - Logs []string `json:"logs"` - Artifacts []Artifact `json:"artifacts"` - cmd *exec.Cmd - cancelled bool + JavaHome string `json:"javaHome,omitempty"` + RequestID string `json:"clientRequestId,omitempty"` + CreatedAt int64 `json:"createdAt"` + Progress Progress `json:"progress"` + Environment map[string]string `json:"environment,omitempty"` + lastPersist time.Time + ID string `json:"id"` + Project string `json:"project"` + Revision string `json:"revision"` + Task string `json:"task"` + Status string `json:"status"` + Logs []string `json:"logs"` + Artifacts []Artifact `json:"artifacts"` + cmd *exec.Cmd + cancelled bool } type Project struct { - Revision string `json:"revision"` - Files map[string]File `json:"files"` - Busy bool `json:"-"` + WorkspacePath string `json:"workspacePath,omitempty"` + Git *GitSnapshot `json:"git,omitempty"` + Revision string `json:"revision"` + Files map[string]File `json:"files"` + Busy bool `json:"busy"` } type Server struct { - mu sync.Mutex - root, token string - tasks map[string]bool - projects map[string]*Project - builds map[string]*Build + mu sync.Mutex + root, token string + tasks map[string]bool + projects map[string]*Project + builds map[string]*Build + workspaceRoot string + environmentFile string } var safeID = regexp.MustCompile(`^[a-f0-9]{32}$`) @@ -91,7 +104,7 @@ func validPath(p string) bool { } } for _, part := range strings.Split(p, "/") { - if part == ".git" || part == ".gradle" || part == "build" || part == ".idea" || part == "local.properties" { + if reservedSource(part) { return false } } @@ -102,6 +115,9 @@ func noLinks(root string) error { if e != nil { return e } + if d.IsDir() && p != root && reservedSource(filepath.Base(p)) { + return filepath.SkipDir + } if d.Type()&os.ModeSymlink != 0 { return fmt.Errorf("symlink forbidden: %s", p) } @@ -118,7 +134,12 @@ func decode(w http.ResponseWriter, r *http.Request, v any) error { d.DisallowUnknownFields() return d.Decode(v) } -func (s *Server) work(p string) string { return filepath.Join(s.root, "projects", p, "work") } +func (s *Server) work(p string) string { + if pr := s.projects[p]; pr != nil && pr.WorkspacePath != "" { + return pr.WorkspacePath + } + return filepath.Join(s.root, "projects", p, "work") +} func (s *Server) save(p string) error { b, e := json.Marshal(s.projects[p]) if e != nil { @@ -144,7 +165,24 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/") fail := func(e error) { http.Error(w, e.Error(), 400) } if r.URL.Path == "/api/v1/health" { - jsonOut(w, map[string]any{"version": "0.1.1", "os": runtime.GOOS, "sync": "http-manifest"}) + jsonOut(w, map[string]any{"version": "0.4.1", "textComparison": true, "jdkSelection": true, "workspaceSelection": true, "os": runtime.GOOS, "sync": "http-manifest", "recovery": true}) + return + } + if r.URL.Path == "/api/v1/environment" && r.Method == "GET" { + cfg, e := s.buildEnvironment() + if e != nil { + fail(e) + return + } + jsonOut(w, cfg.summary()) + return + } + if r.URL.Path == "/api/v1/jdks" && r.Method == "GET" { + s.jdks(w, r) + return + } + if r.URL.Path == "/api/v1/directories" && r.Method == "GET" { + s.browseDirectories(w, r) return } if len(parts) < 3 || parts[0] != "api" || parts[1] != "v1" { @@ -152,20 +190,15 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } if parts[2] == "projects" { - if len(parts) == 3 && r.Method == "POST" { - p := id() - if e := os.MkdirAll(s.work(p), 0700); e != nil { - fail(e) - return - } - s.projects[p] = &Project{Files: map[string]File{}} - if e := s.save(p); e != nil { - fail(e) - return - } - jsonOut(w, map[string]string{"id": p}) + if len(parts) == 4 && parts[3] == "check" && r.Method == "POST" { + s.checkWorkspace(w, r) return } + if len(parts) == 3 && r.Method == "POST" { + s.createProject(w, r) + return + } + if len(parts) != 5 || !safeID.MatchString(parts[3]) { http.NotFound(w, r) return @@ -176,8 +209,28 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) return } + if pr.WorkspacePath != "" { + if _, e := s.validateWorkspace(pr.WorkspacePath); e != nil { + fail(e) + return + } + } if parts[4] == "manifest" && r.Method == "GET" { - jsonOut(w, pr) + jsonOut(w, s.manifest(p)) + return + } + if parts[4] == "builds" && r.Method == "GET" { + items := []*Build{} + for _, b := range s.builds { + if b.Project == p && (r.URL.Query().Get("clientRequestId") == "" || b.RequestID == r.URL.Query().Get("clientRequestId")) { + items = append(items, b) + } + } + sort.Slice(items, func(i, j int) bool { return items[i].CreatedAt > items[j].CreatedAt }) + if len(items) > 50 { + items = items[:50] + } + jsonOut(w, map[string]any{"builds": items}) return } if parts[4] == "sync" && r.Method == "POST" { @@ -194,6 +247,10 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { fail(errors.New("revision and files required")) return } + if e := s.checkGit(p, req.Git); e != nil { + http.Error(w, e.Error(), 409) + return + } if e := noLinks(s.work(p)); e != nil { fail(e) return @@ -242,6 +299,11 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } } + previousFiles, baseErr := s.syncBase(p) + if baseErr != nil { + fail(baseErr) + return + } // Validate the entire request before touching the working tree. Invalidate first: // an interrupted commit must never permit building a mixed source revision. pr.Revision = "" @@ -249,8 +311,8 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { fail(e) return } - for path := range pr.Files { - if _, ok := req.Files[path]; !ok { + for path := range previousFiles { + if _, ok := req.Files[path]; !ok && validPath(path) { if e := os.Remove(filepath.Join(s.work(p), filepath.FromSlash(path))); e != nil && !os.IsNotExist(e) { fail(e) return @@ -270,9 +332,15 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { } pr.Files = map[string]File{} for path, f := range req.Files { - pr.Files[path] = File{Hash: f.Hash} + actual, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path))) + if e != nil || actual.Hash != f.Hash { + fail(fmt.Errorf("source changed during sync: %s", path)) + return + } + pr.Files[path] = actual } pr.Revision = req.Revision + pr.Git = req.Git if e := s.save(p); e != nil { pr.Revision = "" fail(e) @@ -283,8 +351,10 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { } if parts[4] == "builds" && r.Method == "POST" { var req struct { - Revision string `json:"revision"` - Task string `json:"task"` + Revision string `json:"revision"` + Task string `json:"task"` + RequestID string `json:"clientRequestId"` + JavaHome string `json:"javaHome,omitempty"` } if e := decode(w, r, &req); e != nil { fail(e) @@ -294,11 +364,51 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { fail(errors.New("task not allowed")) return } + if req.RequestID != "" { + if !regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`).MatchString(req.RequestID) { + fail(errors.New("invalid clientRequestId")) + return + } + for _, old := range s.builds { + if old.Project == p && old.RequestID == req.RequestID { + if old.Task != req.Task || old.Revision != req.Revision || old.JavaHome != req.JavaHome { + http.Error(w, "request ID already used with different parameters", 409) + return + } + jsonOut(w, old) + return + } + } + } if pr.Busy || req.Revision == "" || pr.Revision != req.Revision { http.Error(w, "busy or revision mismatch", 409) return } - b := &Build{ID: id(), Project: p, Revision: req.Revision, Task: req.Task, Status: "queued", Logs: []string{}, Artifacts: []Artifact{}} + if pr.WorkspacePath != "" { + if e := s.checkGit(p, pr.Git); e != nil { + http.Error(w, e.Error(), 409) + return + } + actual, e := sourceInventory(s.work(p)) + if e != nil { + fail(e) + return + } + if !sameSourceHashes(pr.Files, actual) { + http.Error(w, "source changed after sync; sync again", 409) + return + } + } + javaHome, jdkErr := s.selectedJDK(req.JavaHome) + if jdkErr != nil { + fail(jdkErr) + return + } + b := &Build{JavaHome: javaHome, ID: id(), Project: p, Revision: req.Revision, Task: req.Task, RequestID: req.RequestID, CreatedAt: time.Now().UnixMilli(), Status: "queued", Logs: []string{}, Artifacts: []Artifact{}} + if e := s.persistBuild(b); e != nil { + fail(e) + return + } if e := os.WriteFile(filepath.Join(s.root, "projects", p, "active-build"), []byte(b.ID), 0600); e != nil { fail(e) return @@ -406,6 +516,9 @@ func (w buildWriter) Write(p []byte) (int, error) { w.s.mu.Lock() defer w.s.mu.Unlock() w.b.Logs = append(w.b.Logs, string(p)) + if time.Since(w.b.lastPersist) > time.Second { + _ = w.s.persistBuild(w.b) + } return len(p), nil } func (s *Server) run(b *Build) { @@ -413,11 +526,14 @@ func (s *Server) run(b *Build) { if b.cancelled { b.Status = "cancelled" s.projects[b.Project].Busy = false + _ = s.persistBuild(b) os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build")) s.mu.Unlock() return } b.Status = "running" + b.Progress = Progress{Phase: "preparing", Message: "正在检测工具版本、缓存及系统代理", Percent: -1} + _ = s.persistBuild(b) s.mu.Unlock() work := s.work(b.Project) // Remove old APKs only. Retain compilation caches and all other Gradle outputs. @@ -434,8 +550,31 @@ func (s *Server) run(b *Build) { }) } if err == nil { - cmd := gradleCommand(work, b.Task) + cfg, configErr := s.buildEnvironment() + if configErr != nil { + s.finishFailed(b, configErr) + return + } + if b.JavaHome != "" { + cfg.JavaHome = b.JavaHome + } + cmd, info, prepErr := s.prepareCommand(work, b.Task, cfg) + if prepErr != nil { + s.finishFailed(b, prepErr) + return + } + s.mu.Lock() + b.Environment = info + b.Progress = Progress{Phase: "building", Message: "执行项目 Wrapper,准备 Gradle 分发包", Path: info["distributionFile"], Percent: -1} + if info["execution"] == "installed-gradle" { + b.Progress.Message = "已复用 Gradle " + info["requestedGradleVersion"] + ";正在构建" + b.Progress.Path = info["executable"] + } + _ = s.persistBuild(b) + s.mu.Unlock() + buildWriter{s, b}.Write([]byte("构建环境: " + mustJSON(info) + "\n")) cmd.Dir = work + cmd.Env = cfg.environ() cmd.Stdout = buildWriter{s, b} cmd.Stderr = cmd.Stdout s.mu.Lock() @@ -447,6 +586,8 @@ func (s *Server) run(b *Build) { } s.mu.Unlock() if err == nil { + stopProgress := make(chan struct{}) + go s.monitorDistribution(b, work, cfg, stopProgress) done := make(chan error, 1) go func() { done <- cmd.Wait() }() select { @@ -458,6 +599,7 @@ func (s *Server) run(b *Build) { err = errors.New("build timeout") } } + close(stopProgress) } } artifacts := []Artifact{} @@ -488,6 +630,7 @@ func (s *Server) run(b *Build) { s.mu.Lock() defer s.mu.Unlock() b.cmd = nil + b.Progress.Phase = "finished" b.Artifacts = artifacts b.Status = "success" if len(artifacts) == 0 && err == nil { @@ -501,10 +644,7 @@ func (s *Server) run(b *Build) { b.Status = "cancelled" } s.projects[b.Project].Busy = false - dir := filepath.Join(s.root, "artifacts", b.ID) - os.MkdirAll(dir, 0700) - data, _ := json.MarshalIndent(b, "", " ") - os.WriteFile(filepath.Join(dir, "build.json"), data, 0600) + _ = s.persistBuild(b) os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build")) } func main() { @@ -515,6 +655,8 @@ func main() { key := flag.String("tls-key", "", "PEM private key path") initHost := flag.String("init-tls-host", "", "generate a local certificate for this IP/hostname and exit") tlsDir := flag.String("tls-dir", "./tls", "certificate output directory") + workspaceRoot := flag.String("workspace-root", "", "administrator allowed root for existing project folders; defaults to data/projects") + environmentFile := flag.String("environment-file", "", "trusted build environment JSON; reloaded for each build") flag.Parse() if *initHost != "" { if e := initCertificate(*initHost, *tlsDir); e != nil { @@ -541,6 +683,14 @@ func main() { log.Fatal(e) } s := &Server{root: abs, token: token, tasks: map[string]bool{}, projects: map[string]*Project{}, builds: map[string]*Build{}} + s.environmentFile = *environmentFile + s.workspaceRoot = *workspaceRoot + if s.workspaceRoot == "" { + s.workspaceRoot = filepath.Join(abs, "projects") + } + if s.workspaceRoot, e = filepath.Abs(s.workspaceRoot); e != nil { + log.Fatal(e) + } for _, t := range strings.Split(*tasks, ",") { if !safeTask.MatchString(t) { log.Fatal("invalid task") @@ -552,15 +702,17 @@ func main() { if !safeID.MatchString(entry.Name()) { continue } - if _, e := os.Stat(filepath.Join(abs, "projects", entry.Name(), "active-build")); e == nil { - log.Fatalf("unfinished build in project %s: stop its remaining Gradle processes, then remove active-build marker before restarting", entry.Name()) - } data, e := os.ReadFile(filepath.Join(abs, "projects", entry.Name(), "state.json")) if e != nil { continue } var p Project if json.Unmarshal(data, &p) == nil { + if p.WorkspacePath != "" { + if _, e := s.validateWorkspace(p.WorkspacePath); e != nil { + log.Fatalf("workspace %s: %v", entry.Name(), e) + } + } s.projects[entry.Name()] = &p } } @@ -572,9 +724,15 @@ func main() { } var b Build if json.Unmarshal(data, &b) == nil { + if b.CreatedAt == 0 { + if info, e := os.Stat(filepath.Join(abs, "artifacts", entry.Name(), "build.json")); e == nil { + b.CreatedAt = info.ModTime().UnixMilli() + } + } s.builds[b.ID] = &b } } + s.recoverBuilds() log.Printf("remotecompile listening on %s (%s)", *addr, runtime.GOOS) srv := &http.Server{Addr: *addr, Handler: s, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 5 * time.Minute, IdleTimeout: 60 * time.Second} srv.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} diff --git a/server/main_test.go b/server/main_test.go index d570b26..42df33b 100644 --- a/server/main_test.go +++ b/server/main_test.go @@ -15,7 +15,11 @@ import ( func testServer(t *testing.T) *Server { t.Helper() - return &Server{root: t.TempDir(), token: "test-token-abcdefghijklmnopqrstuvwxyz", tasks: map[string]bool{":app:assembleDebug": true}, projects: map[string]*Project{}, builds: map[string]*Build{}} + root := t.TempDir() + config := filepath.Join(root, "environment.json") + data, _ := json.Marshal(BuildEnvironment{GradleUserHome: filepath.Join(root, "gradle-cache"), Proxy: "direct"}) + os.WriteFile(config, data, 0600) + return &Server{root: root, environmentFile: config, token: "test-token-abcdefghijklmnopqrstuvwxyz", tasks: map[string]bool{":app:assembleDebug": true}, projects: map[string]*Project{}, builds: map[string]*Build{}} } func TestRunningCancellation(t *testing.T) { @@ -114,18 +118,18 @@ func TestSyncAndRevision(t *testing.T) { s := testServer(t) p := project(t, s) path := "/projects/" + p + "/sync" - req := SyncRequest{"one", map[string]File{"a.txt": file("hello"), "b.txt": file("remove me")}} + req := SyncRequest{Revision: "one", Files: map[string]File{"a.txt": file("hello"), "b.txt": file("remove me")}} if w := call(t, s, "POST", path, req); w.Code != 200 { t.Fatal(w.Body.String()) } - bad := SyncRequest{"bad", map[string]File{"a.txt": {Hash: "wrong"}}} + bad := SyncRequest{Revision: "bad", Files: map[string]File{"a.txt": {Hash: "wrong"}}} if w := call(t, s, "POST", path, bad); w.Code != 400 { t.Fatal(w.Code) } if s.projects[p].Revision != "one" { t.Fatal("invalid sync changed revision") } - req = SyncRequest{"two", map[string]File{"a.txt": {Hash: digest([]byte("hello"))}}} + req = SyncRequest{Revision: "two", Files: map[string]File{"a.txt": {Hash: digest([]byte("hello"))}}} if w := call(t, s, "POST", path, req); w.Code != 200 { t.Fatal(w.Body.String()) } @@ -153,7 +157,7 @@ func TestBuildArtifactAndFailure(t *testing.T) { name = "gradlew.bat" wrapper = "@echo off\r\nmkdir app\\build\\outputs\\apk\\debug 2>nul\r\necho fresh>app\\build\\outputs\\apk\\debug\\app-debug.apk\r\nexit /b 0\r\n" } - req := SyncRequest{"one", map[string]File{name: file(wrapper)}} + req := SyncRequest{Revision: "one", Files: map[string]File{name: file(wrapper)}} if w := call(t, s, "POST", "/projects/"+p+"/sync", req); w.Code != 200 { t.Fatal(w.Body.String()) } diff --git a/server/process_unix.go b/server/process_unix.go index 14b80e2..47dfafe 100644 --- a/server/process_unix.go +++ b/server/process_unix.go @@ -9,7 +9,10 @@ import ( ) func gradleCommand(work, task string) *exec.Cmd { - c := exec.Command("sh", filepath.Join(work, "gradlew"), task, "--console=plain", "--no-daemon") + return gradleExecutableCommand(filepath.Join(work, "gradlew"), task) +} +func gradleExecutableCommand(binary, task string) *exec.Cmd { + c := exec.Command("sh", binary, task, "--console=plain", "--no-daemon") c.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} return c } diff --git a/server/process_windows.go b/server/process_windows.go index a74e658..178a23c 100644 --- a/server/process_windows.go +++ b/server/process_windows.go @@ -3,11 +3,17 @@ package main import ( "os/exec" "strconv" + "syscall" ) func gradleCommand(work, task string) *exec.Cmd { return exec.Command("cmd.exe", "/d", "/c", "gradlew.bat", task, "--console=plain", "--no-daemon") } +func gradleExecutableCommand(binary, task string) *exec.Cmd { + c := exec.Command("cmd.exe") + c.SysProcAttr = &syscall.SysProcAttr{CmdLine: `cmd.exe /d /s /c ""` + binary + `" ` + task + ` --console=plain --no-daemon"`} + return c +} func killTree(c *exec.Cmd) { if c.Process != nil { _ = exec.Command("taskkill.exe", "/PID", strconv.Itoa(c.Process.Pid), "/T", "/F").Run() diff --git a/server/proxy_unix.go b/server/proxy_unix.go new file mode 100644 index 0000000..8cf7a91 --- /dev/null +++ b/server/proxy_unix.go @@ -0,0 +1,5 @@ +//go:build !windows + +package main + +func systemProxy() string { return "" } diff --git a/server/proxy_windows.go b/server/proxy_windows.go new file mode 100644 index 0000000..3cb4a83 --- /dev/null +++ b/server/proxy_windows.go @@ -0,0 +1,18 @@ +package main + +import ( + "context" + "os/exec" + "strings" + "time" +) + +func systemProxy() string { + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + out, e := exec.CommandContext(ctx, "powershell.exe", "-NoProfile", "-NonInteractive", "-Command", `$u=[uri]'https://services.gradle.org';$p=[System.Net.WebRequest]::GetSystemWebProxy();if(-not $p.IsBypassed($u)){$p.GetProxy($u).AbsoluteUri}`).Output() + if e != nil { + return "" + } + return strings.TrimSpace(string(out)) +} diff --git a/server/recovery.go b/server/recovery.go new file mode 100644 index 0000000..d243d46 --- /dev/null +++ b/server/recovery.go @@ -0,0 +1,74 @@ +package main + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "time" +) + +type Progress struct { + Phase string `json:"phase"` + Message string `json:"message"` + Path string `json:"path"` + Current int64 `json:"current"` + Total int64 `json:"total"` + Percent int `json:"percent"` +} + +func (s *Server) persistBuild(b *Build) error { + dir := filepath.Join(s.root, "artifacts", b.ID) + if e := os.MkdirAll(dir, 0700); e != nil { + return e + } + data, e := json.Marshal(b) + if e != nil { + return e + } + target := filepath.Join(dir, "build.json") + if e = os.WriteFile(target+".tmp", data, 0600); e != nil { + return e + } + if e = os.Rename(target+".tmp", target); e == nil { + b.lastPersist = time.Now() + } + return e +} +func (s *Server) finishFailed(b *Build, e error) { + s.mu.Lock() + defer s.mu.Unlock() + b.Status = "failed" + if b.cancelled { + b.Status = "cancelled" + } + b.Logs = append(b.Logs, e.Error()) + b.Progress.Phase = "finished" + s.projects[b.Project].Busy = false + _ = s.persistBuild(b) + os.Remove(filepath.Join(s.root, "projects", b.Project, "active-build")) +} +func (s *Server) recoverBuilds() { + for p, pr := range s.projects { + pr.Busy = false + marker, e := os.ReadFile(filepath.Join(s.root, "projects", p, "active-build")) + if e == nil { + pr.Busy = true + bid := strings.TrimSpace(string(marker)) + if safeID.MatchString(bid) && s.builds[bid] == nil { + s.builds[bid] = &Build{ID: bid, Project: p, Revision: pr.Revision, Status: "running", Logs: []string{}, Artifacts: []Artifact{}} + } + } + } + for _, b := range s.builds { + if b.Status == "running" || b.Status == "queued" { + b.Status = "interrupted" + b.Progress.Phase = "interrupted" + b.Logs = append(b.Logs, "服务曾重启,构建已中断。若工作区仍锁定,管理员需确认残留 Gradle 进程已停止,再移除 active-build 并重启服务。") + if e := s.persistBuild(b); e != nil { + fmt.Println("build recovery persistence failed:", e) + } + } + } +} diff --git a/server/snapshot_rebase_test.go b/server/snapshot_rebase_test.go new file mode 100644 index 0000000..0d36029 --- /dev/null +++ b/server/snapshot_rebase_test.go @@ -0,0 +1,89 @@ +package main + +import ( + "encoding/json" + "os" + "os/exec" + "path/filepath" + "testing" +) + +func TestCleanSameHeadCanResyncWithoutAcceptingStaleBuild(t *testing.T) { + if _, e := exec.LookPath("git"); e != nil { + t.Skip("Git unavailable") + } + s := testServer(t) + s.workspaceRoot = t.TempDir() + work := filepath.Join(s.workspaceRoot, "checkout") + os.MkdirAll(work, 0700) + git := func(args ...string) { + t.Helper() + if out, e := exec.Command("git", append([]string{"-C", work}, args...)...).CombinedOutput(); e != nil { + t.Fatalf("git: %v %s", e, out) + } + } + git("init", "-q") + git("config", "core.autocrlf", "false") + os.WriteFile(filepath.Join(work, "a.txt"), []byte("original\n"), 0600) + os.WriteFile(filepath.Join(work, "restored.txt"), []byte("tracked\n"), 0600) + git("add", ".") + git("-c", "user.name=Test", "-c", "user.email=test@example.invalid", "commit", "-qm", "base") + g, e := gitSnapshot(work) + if e != nil { + t.Fatal(e) + } + w := call(t, s, "POST", "/projects", WorkspaceRequest{WorkspacePath: work, Git: g}) + if w.Code != 200 { + t.Fatal(w.Body.String()) + } + var out map[string]string + json.Unmarshal(w.Body.Bytes(), &out) + p := out["id"] + // A successful sync intentionally removed a tracked file; later checkout restores it. + w = call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "old", Files: map[string]File{"a.txt": file("original\n")}, Git: g}) + if w.Code != 200 { + t.Fatal(w.Body.String()) + } + git("restore", "--worktree", "--", "restored.txt") + // CRLF checkout is Git-clean, even though raw bytes no longer match the old snapshot. + git("config", "core.autocrlf", "true") + os.WriteFile(filepath.Join(work, "a.txt"), []byte("original\r\n"), 0600) + git("add", "--renormalize", ".") + g, e = gitSnapshot(work) + if e != nil || g.Dirty { + out, _ := gitCommand(work, nil, "status", "--porcelain") + diff, _ := gitCommand(work, nil, "diff", "--numstat") + t.Fatalf("fixture not Git-clean: %v %v status=%s diff=%s", g, e, out, diff) + } + originalRevision := s.projects[p].Revision + if e = s.checkGit(p, g); e != nil { + t.Fatal("clean same-HEAD checkout blocked", e) + } + manifest := s.manifest(p) + if manifest.Files["a.txt"].Hash != digest([]byte("original\r\n")) || manifest.Files["restored.txt"].Hash == "" || manifest.Revision != "" { + t.Fatal("manifest did not expose current checkout", manifest) + } + if s.projects[p].Revision != originalRevision || len(s.projects[p].Files) != 1 { + t.Fatal("read-only check rebased persistent snapshot") + } + w = call(t, s, "POST", "/projects/"+p+"/builds", map[string]string{"revision": "old", "task": ":app:assembleDebug"}) + if w.Code != 409 { + t.Fatal("stale revision built", w.Body.String()) + } + // Reuse the remote raw hash, preserving CRLF, while applying local deletion again. + w = call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "new", Files: map[string]File{"a.txt": {Hash: manifest.Files["a.txt"].Hash}}, Git: g}) + if w.Code != 200 { + t.Fatal(w.Body.String()) + } + if _, e = os.Stat(filepath.Join(work, "restored.txt")); !os.IsNotExist(e) { + t.Fatal("restored tracked deletion not synchronized") + } + if s.projects[p].Files["a.txt"].TextHash == "" { + t.Fatal("normalized baseline not persisted") + } + // A later real remote edit must remain protected. + os.WriteFile(filepath.Join(work, "a.txt"), []byte("remote real edit\n"), 0600) + if e = s.checkGit(p, g); e == nil { + t.Fatal("real remote edit was accepted") + } +} diff --git a/server/text_compare.go b/server/text_compare.go new file mode 100644 index 0000000..f103d17 --- /dev/null +++ b/server/text_compare.go @@ -0,0 +1,43 @@ +package main + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "unicode/utf8" +) + +// Restrict EOL equivalence to source/config text. Executable scripts remain byte-exact. +func comparableText(path string) bool { + switch strings.ToLower(filepath.Ext(path)) { + case ".kt", ".kts", ".java", ".xml", ".gradle", ".properties", ".json", ".toml", ".yaml", ".yml", ".txt", ".md", ".proto", ".c", ".cc", ".cpp", ".h", ".hpp", ".cmake", ".aidl", ".pro", ".cfg", ".ini", ".csv", ".html", ".css", ".js", ".ts", ".svg": + return true + } + switch strings.ToLower(filepath.Base(path)) { + case ".gitignore", ".gitattributes", ".editorconfig", "cmakelists.txt": + return true + } + return false +} +func comparisonFile(path string) (File, error) { + if comparableText(path) { + info, e := os.Stat(path) + if e != nil { + return File{}, e + } + if info.Size() <= 64<<20 { + b, e := os.ReadFile(path) + if e != nil { + return File{}, e + } + f := File{Hash: digest(b)} + if utf8.Valid(b) && !bytes.ContainsRune(b, 0) { + f.TextHash = digest(bytes.ReplaceAll(b, []byte("\r\n"), []byte("\n"))) + } + return f, nil + } + } + h, e := fileDigest(path) + return File{Hash: h}, e +} diff --git a/server/text_compare_test.go b/server/text_compare_test.go new file mode 100644 index 0000000..9727aed --- /dev/null +++ b/server/text_compare_test.go @@ -0,0 +1,68 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestTextComparisonPreservesRemoteBytes(t *testing.T) { + s := testServer(t) + p := project(t, s) + path := filepath.Join(s.work(p), "Source.kt") + original := []byte("val x = 1\r\nval y = 2\r\n") + os.WriteFile(path, original, 0600) + s.projects[p].Files["Source.kt"] = File{Hash: digest(original)} + f := s.manifest(p).Files["Source.kt"] + if f.TextHash != digest([]byte("val x = 1\nval y = 2\n")) || f.Hash != digest(original) { + t.Fatal("EOL or raw digest incorrect", f) + } + w := call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "equivalent", Files: map[string]File{"Source.kt": {Hash: f.Hash}}}) + if w.Code != 200 { + t.Fatal(w.Body.String()) + } + b, _ := os.ReadFile(path) + if string(b) != string(original) { + t.Fatal("remote EOL rewritten") + } + for _, name := range []string{"image.bin", "script.sh", "gradlew"} { + q := filepath.Join(s.work(p), name) + os.WriteFile(q, original, 0600) + actual, _ := comparisonFile(q) + if actual.TextHash != "" { + t.Fatalf("binary/script normalized: %s", name) + } + } + for _, b := range [][]byte{{0xff, 0xfe, 13, 10}, []byte("a\x00\r\n")} { + os.WriteFile(path, b, 0600) + actual, _ := comparisonFile(path) + if actual.TextHash != "" { + t.Fatal("non-UTF8/NUL data normalized") + } + } +} +func TestDiscoveredJDKRequiredAndReleaseParsed(t *testing.T) { + s := testServer(t) + if _, e := s.selectedJDK(filepath.Join(t.TempDir(), "arbitrary")); e == nil { + t.Fatal("undiscovered executable accepted") + } + home := t.TempDir() + os.MkdirAll(filepath.Join(home, "bin"), 0700) + for _, n := range []string{"java", "javac"} { + os.WriteFile(filepath.Join(home, "bin", javaExecutable(n)), []byte("placeholder"), 0600) + } + os.WriteFile(filepath.Join(home, "release"), []byte("JAVA_VERSION=\"21.0.8\"\n"), 0600) + j, ok := inspectJDK(home, "test") + if !ok || j.Version != "21.0.8" { + t.Fatal("installed JDK release not recognized") + } + os.Remove(filepath.Join(home, "bin", javaExecutable("javac"))) + if _, ok := inspectJDK(home, "test"); ok { + t.Fatal("JRE without javac offered as JDK") + } + w := call(t, s, "GET", "/jdks", nil) + if w.Code != 200 || !strings.Contains(w.Body.String(), `"defaultJavaHome"`) { + t.Fatal(w.Body.String()) + } +} diff --git a/server/workspace.go b/server/workspace.go new file mode 100644 index 0000000..132fd5a --- /dev/null +++ b/server/workspace.go @@ -0,0 +1,539 @@ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "strings" + "time" +) + +type GitSnapshot struct { + Head string `json:"head"` + Branch string `json:"branch"` + Dirty bool `json:"dirty"` + Upstream string `json:"upstream"` + AheadBehind string `json:"aheadBehind"` +} +type WorkspaceRequest struct { + WorkspacePath string `json:"workspacePath"` + ProjectID string `json:"projectId,omitempty"` + Git *GitSnapshot `json:"git,omitempty"` +} + +func reservedSource(path string) bool { + for _, part := range strings.Split(filepath.ToSlash(path), "/") { + switch strings.ToLower(part) { + case ".git", ".gradle", ".idea", "build", ".remotecompile", ".kotlin", ".cxx", ".externalnativebuild", "node_modules", "local.properties", "key.properties", "keystore.properties": + return true + } + lower := strings.ToLower(part) + if strings.HasPrefix(lower, ".env") || strings.HasSuffix(lower, ".jks") || strings.HasSuffix(lower, ".keystore") { + return true + } + } + return false +} +func fileDigest(path string) (string, error) { + f, e := os.Open(path) + if e != nil { + return "", e + } + defer f.Close() + h := sha256.New() + if _, e = io.Copy(h, f); e != nil { + return "", e + } + return hex.EncodeToString(h.Sum(nil)), nil +} +func (s *Server) strictManifest(p string) *Project { + pr := *s.projects[p] + pr.Files = map[string]File{} + // Never advertise a stale hash: Gradle or a human may have changed/removed a file. + for path, f := range s.projects[p].Files { + if !validPath(path) { + continue + } + if actual, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path))); e == nil && actual.Hash == f.Hash { + pr.Files[path] = actual + } + } + pr.WorkspacePath = s.work(p) + return &pr +} + +// A clean checkout is a valid new sync base, even if HEAD did not move. +// Keep this read-only: a build must still match the last committed sync snapshot. +func (s *Server) manifest(p string) *Project { + result := s.strictManifest(p) + if s.projects[p].WorkspacePath == "" { + return result + } + remote, e := gitSnapshot(s.work(p)) + if e != nil || remote == nil { + return result + } + if remote.Dirty { + for path, f := range s.projects[p].Files { + if !validPath(path) || f.TextHash == "" { + continue + } + if _, ok := result.Files[path]; ok { + continue + } + current, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path))) + if e == nil && current.TextHash == f.TextHash { + result.Files[path] = current + result.Revision = "" + } + } + return result + } + actual, e := sourceInventory(s.work(p)) + if e != nil { + return result + } + result.Files = map[string]File{} + for path := range actual { + f, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path))) + if e != nil { + return s.strictManifest(p) + } + result.Files[path] = f + } + if !sameSourceHashes(s.projects[p].Files, result.Files) { + result.Revision = "" + } + result.Git = remote + return result +} +func sameSourceHashes(a, b map[string]File) bool { + count := 0 + for path, f := range a { + if !validPath(path) { + continue + } + count++ + if b[path].Hash != f.Hash { + return false + } + } + return count == len(b) +} + +// Include restored/deleted tracked files when syncing after a clean reset/checkout. +func (s *Server) syncBase(p string) (map[string]File, error) { + old := s.projects[p].Files + if s.projects[p].WorkspacePath == "" { + return old, nil + } + remote, e := gitSnapshot(s.work(p)) + if e != nil { + return nil, e + } + if remote == nil || remote.Dirty { + return old, nil + } + actual, e := sourceInventory(s.work(p)) + if e != nil { + return nil, e + } + base := map[string]File{} + for path, f := range old { + base[path] = f + } + for path, f := range actual { + base[path] = f + } + return base, nil +} +func (s *Server) validateWorkspace(path string) (string, error) { + if !filepath.IsAbs(path) { + return "", fmt.Errorf("请填写服务端已有文件夹的绝对路径") + } + root := s.workspaceRoot + if root == "" { + root = filepath.Join(s.root, "projects") + } + root, e := filepath.Abs(root) + if e != nil { + return "", e + } + path = filepath.Clean(path) + dataRel, dataErr := filepath.Rel(s.root, path) + if dataErr == nil && dataRel != ".." && !strings.HasPrefix(dataRel, ".."+string(filepath.Separator)) { + parts := strings.Split(filepath.ToSlash(dataRel), "/") + if len(parts) != 3 || parts[0] != "projects" || !safeID.MatchString(parts[1]) || parts[2] != "work" { + return "", fmt.Errorf("不能选择服务数据或元数据目录;旧工作区请精确选择 projects//work") + } + } + rel, e := filepath.Rel(root, path) + if e != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return "", fmt.Errorf("远程文件夹必须位于管理员允许的根目录内:%s", root) + } + // Reject both final and ancestor symlink/junction redirection. + for current := path; ; current = filepath.Dir(current) { + i, e := os.Lstat(current) + if e != nil { + return "", fmt.Errorf("服务端文件夹不存在或不可访问:%s", current) + } + if !i.IsDir() || i.Mode()&os.ModeSymlink != 0 { + return "", fmt.Errorf("远程文件夹不允许符号链接或重解析路径") + } + if current == filepath.Dir(current) { + break + } + } + resolved, e := filepath.EvalSymlinks(path) + if e != nil { + return "", e + } + if !strings.EqualFold(filepath.Clean(resolved), path) { + return "", fmt.Errorf("远程文件夹经过链接重定向") + } + return path, nil +} + +// Directory browsing is confined to the administrator's root. Files are never listed. +func (s *Server) browseDirectories(w http.ResponseWriter, r *http.Request) { + root := s.workspaceRoot + if root == "" { + root = filepath.Join(s.root, "projects") + } + root, _ = filepath.Abs(root) + path := r.URL.Query().Get("path") + if path == "" { + path = root + } + path = filepath.Clean(path) + rel, e := filepath.Rel(root, path) + if e != nil || !filepath.IsAbs(path) || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + http.Error(w, "目录超出管理员允许的根目录", 400) + return + } + resolved, e := filepath.EvalSymlinks(path) + if e != nil || !strings.EqualFold(filepath.Clean(resolved), path) { + http.Error(w, "目录不存在或经过链接重定向", 400) + return + } + entries, e := os.ReadDir(path) + if e != nil { + http.Error(w, "服务账户无法读取该目录", 400) + return + } + dirs := []map[string]string{} + for _, entry := range entries { + if entry.IsDir() && !reservedSource(entry.Name()) { + dirs = append(dirs, map[string]string{"name": entry.Name(), "path": filepath.Join(path, entry.Name())}) + } + if len(dirs) >= 1000 { + break + } + } + parent := "" + if rel != "." { + parent = filepath.Dir(path) + } + _, selectErr := s.validateWorkspace(path) + jsonOut(w, map[string]any{"path": path, "root": root, "parent": parent, "selectable": selectErr == nil, "directories": dirs, "limit": 1000}) +} +func gitCommand(work string, input []byte, args ...string) ([]byte, error) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, "git", append([]string{"-c", "safe.directory=" + work, "-C", work}, args...)...) + cmd.Stdin = bytes.NewReader(input) + cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0", "GIT_OPTIONAL_LOCKS=0") + return cmd.Output() +} +func gitSnapshot(work string) (*GitSnapshot, error) { + // Only inspect the selected repository, never silently inherit its parent repository. + if _, e := os.Stat(filepath.Join(work, ".git")); os.IsNotExist(e) { + return nil, nil + } + if _, e := gitCommand(work, nil, "rev-parse", "--is-inside-work-tree"); e != nil { + return nil, fmt.Errorf("服务端 Git 仓库无法读取;请检查 Git 安装、仓库所有者及服务账户权限") + } + if _, e := gitCommand(work, nil, "status", "--porcelain", "--untracked-files=normal"); e != nil { + return nil, fmt.Errorf("无法读取服务端 Git 状态") + } + read := func(args ...string) string { + b, _ := gitCommand(work, nil, args...) + return strings.TrimSpace(string(b)) + } + return &GitSnapshot{Head: read("rev-parse", "--verify", "HEAD"), Branch: read("symbolic-ref", "--short", "-q", "HEAD"), Dirty: read("status", "--porcelain", "--untracked-files=normal") != "", Upstream: read("rev-parse", "--abbrev-ref", "@{upstream}"), AheadBehind: read("rev-list", "--left-right", "--count", "HEAD...@{upstream}")}, nil +} +func sourceInventory(work string) (map[string]File, error) { + if e := noLinks(work); e != nil { + return nil, e + } + result := map[string]File{} + git, e := gitSnapshot(work) + if e != nil { + return nil, e + } + var paths []string + if git != nil { + b, e := gitCommand(work, nil, "ls-files", "-z", "--cached", "--others", "--exclude-standard") + if e != nil { + return nil, fmt.Errorf("无法读取服务端 Git 文件清单") + } + paths = strings.Split(strings.TrimSuffix(string(b), "\x00"), "\x00") + ignored, e := gitCommand(work, b, "check-ignore", "--no-index", "-z", "--stdin") + if e != nil { + if exit, ok := e.(*exec.ExitError); !ok || exit.ExitCode() != 1 { + return nil, fmt.Errorf("服务端 Git 忽略规则检查失败") + } + } + skip := map[string]bool{} + for _, p := range strings.Split(string(ignored), "\x00") { + skip[p] = true + } + filtered := paths[:0] + for _, p := range paths { + if !skip[p] { + filtered = append(filtered, p) + } + } + paths = filtered + } else { + e = filepath.WalkDir(work, func(path string, d os.DirEntry, e error) error { + if e != nil { + return e + } + rel, _ := filepath.Rel(work, path) + if rel == "." { + return nil + } + if reservedSource(rel) { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + if !d.IsDir() { + paths = append(paths, filepath.ToSlash(rel)) + } + return nil + }) + if e != nil { + return nil, e + } + } + for _, p := range paths { + if p == "" || reservedSource(p) { + continue + } + if !validPath(p) { + return nil, fmt.Errorf("服务端存在无法同步的路径:%s", p) + } + path := filepath.Join(work, filepath.FromSlash(p)) + i, e := os.Lstat(path) + if os.IsNotExist(e) { + continue + } + if e != nil { + return nil, e + } + if !i.Mode().IsRegular() { + return nil, fmt.Errorf("服务端源码包含链接或特殊文件:%s", p) + } + h, e := fileDigest(path) + if e != nil { + return nil, e + } + result[p] = File{Hash: h} + } + return result, nil +} +func compareGit(local, remote *GitSnapshot) error { + if remote != nil && local == nil { + return fmt.Errorf("服务端存在 Git 仓库,但本机无法读取 Git 状态") + } + if local != nil && remote != nil && local.Head != remote.Head { + return fmt.Errorf("两边 Git 提交不同,请先手动同步仓库;本机 HEAD=%s,服务端 HEAD=%s", local.Head, remote.Head) + } + return nil +} +func (s *Server) checkGit(p string, local *GitSnapshot) error { + remote, e := gitSnapshot(s.work(p)) + if e != nil { + return e + } + if e = compareGit(local, remote); e != nil { + return e + } + if s.projects[p].WorkspacePath == "" { + return nil + } + // A clean matching Git checkout may have been deliberately updated by its owner. + if remote != nil && !remote.Dirty { + return nil + } + // Detect remote edits even after a previous sync intentionally made the remote Git tree dirty. + actual, e := sourceInventory(s.work(p)) + if e != nil { + return e + } + for path, f := range s.projects[p].Files { + if !validPath(path) { + continue + } + if actual[path].Hash != f.Hash { + if f.TextHash != "" { + if current, e := comparisonFile(filepath.Join(s.work(p), filepath.FromSlash(path))); e == nil && current.TextHash == f.TextHash { + continue + } + } + return fmt.Errorf("服务端源码已变化:%s;为避免覆盖,请先处理服务端修改", path) + } + } + for path := range actual { + if _, ok := s.projects[p].Files[path]; !ok { + return fmt.Errorf("服务端新增源码:%s;请先处理服务端修改", path) + } + } + return nil +} +func (s *Server) checkWorkspace(w http.ResponseWriter, r *http.Request) { + var req WorkspaceRequest + if e := decode(w, r, &req); e != nil { + http.Error(w, e.Error(), 400) + return + } + path, e := s.validateWorkspace(req.WorkspacePath) + if e != nil { + http.Error(w, e.Error(), 400) + return + } + remote, e := gitSnapshot(path) + if e != nil { + http.Error(w, e.Error(), 400) + return + } + e = compareGit(req.Git, remote) + if pr := s.projects[req.ProjectID]; pr != nil && filepath.Clean(s.work(req.ProjectID)) != path { + e = fmt.Errorf("工程ID与服务端文件夹不匹配,请重新保存配置以分配工作区") + } + if e == nil { + if pr := s.projects[req.ProjectID]; pr != nil && pr.Busy { + e = fmt.Errorf("工作区正在构建,请等待完成") + } + } + if e == nil { + if pr := s.projects[req.ProjectID]; pr != nil && filepath.Clean(s.work(req.ProjectID)) == path { + e = s.checkGit(req.ProjectID, req.Git) + } else if remote != nil && remote.Dirty { + e = fmt.Errorf("服务端仓库有未提交修改;首次绑定前请先处理,避免覆盖") + } + } + message := "检查通过;双方 Git HEAD 相同,未提交的本机源码将增量同步" + if remote == nil { + message = "服务端没有 .git,无法比较 Git 提交;同步时使用本机 Git 忽略规则" + } + if e != nil { + message = e.Error() + } + jsonOut(w, map[string]any{"workspacePath": path, "git": remote, "canSync": e == nil, "message": message}) +} +func (s *Server) createProject(w http.ResponseWriter, r *http.Request) { + var req WorkspaceRequest + if e := decode(w, r, &req); e != nil && e != io.EOF { + http.Error(w, e.Error(), 400) + return + } + p := id() + pr := &Project{Files: map[string]File{}} + if req.WorkspacePath != "" { + path, e := s.validateWorkspace(req.WorkspacePath) + if e != nil { + http.Error(w, e.Error(), 400) + return + } + for other := range s.projects { + if strings.EqualFold(s.work(other), path) { + if s.projects[other].WorkspacePath == "" && !s.projects[other].Busy { + remote, e := gitSnapshot(path) + if e == nil { + e = compareGit(req.Git, remote) + } + if e == nil && remote != nil && remote.Dirty { + e = fmt.Errorf("服务端仓库有未提交修改,首次绑定前请先处理") + } + if e != nil { + http.Error(w, e.Error(), 409) + return + } + files, e := sourceInventory(path) + if e != nil { + http.Error(w, e.Error(), 400) + return + } + s.projects[other].WorkspacePath = path + s.projects[other].Files = files + s.projects[other].Git = req.Git + if e = s.save(other); e != nil { + http.Error(w, e.Error(), 400) + return + } + jsonOut(w, map[string]string{"id": other, "workspacePath": path}) + return + } + http.Error(w, "该服务端文件夹已绑定另一个工程,请选择独立工作区", 409) + return + } + } + for other := range s.projects { + a := strings.ToLower(filepath.Clean(s.work(other))) + string(filepath.Separator) + b := strings.ToLower(path) + string(filepath.Separator) + if strings.HasPrefix(a, b) || strings.HasPrefix(b, a) { + http.Error(w, "服务端工程目录不能与其他工作区重叠", 409) + return + } + } + remote, e := gitSnapshot(path) + if e == nil { + e = compareGit(req.Git, remote) + } + if e == nil && remote != nil && remote.Dirty { + e = fmt.Errorf("服务端仓库有未提交修改,首次绑定前请先处理") + } + if e != nil { + http.Error(w, e.Error(), 409) + return + } + files, e := sourceInventory(path) + if e != nil { + http.Error(w, e.Error(), 400) + return + } + pr.WorkspacePath = path + pr.Files = files + pr.Git = req.Git + } + s.projects[p] = pr + if e := os.MkdirAll(filepath.Join(s.root, "projects", p), 0700); e != nil { + delete(s.projects, p) + http.Error(w, e.Error(), 400) + return + } + if req.WorkspacePath == "" { + if e := os.MkdirAll(s.work(p), 0700); e != nil { + delete(s.projects, p) + http.Error(w, e.Error(), 400) + return + } + } + if e := s.save(p); e != nil { + delete(s.projects, p) + http.Error(w, e.Error(), 400) + return + } + jsonOut(w, map[string]string{"id": p, "workspacePath": s.work(p)}) +} diff --git a/server/workspace_test.go b/server/workspace_test.go new file mode 100644 index 0000000..ffdb7d6 --- /dev/null +++ b/server/workspace_test.go @@ -0,0 +1,136 @@ +package main + +import ( + "encoding/json" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +func TestManifestRechecksActualContent(t *testing.T) { + s := testServer(t) + p := project(t, s) + call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "r", Files: map[string]File{"a.txt": file("source")}}) + os.WriteFile(filepath.Join(s.work(p), "a.txt"), []byte("changed by build"), 0600) + w := call(t, s, "GET", "/projects/"+p+"/manifest", nil) + var actual Project + json.Unmarshal(w.Body.Bytes(), &actual) + if len(actual.Files) != 0 { + t.Fatal("advertised stale hash, causing missing content") + } + if w = call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "r2", Files: map[string]File{"a.txt": file("source")}}); w.Code != 200 { + t.Fatal(w.Body.String()) + } +} +func TestExistingWorkspaceBoundaryAndGitProtection(t *testing.T) { + if _, e := exec.LookPath("git"); e != nil { + t.Skip("git unavailable") + } + s := testServer(t) + s.workspaceRoot = t.TempDir() + work := filepath.Join(s.workspaceRoot, "中文 project") + os.MkdirAll(work, 0700) + git := func(args ...string) { + t.Helper() + if out, e := exec.Command("git", append([]string{"-C", work}, args...)...).CombinedOutput(); e != nil { + t.Fatalf("git: %v %s", e, out) + } + } + git("init", "-q") + os.WriteFile(filepath.Join(work, "a.txt"), []byte("base"), 0600) + os.WriteFile(filepath.Join(work, ".gitignore"), []byte("ignored/\n"), 0600) + git("add", ".") + git("-c", "user.name=Test", "-c", "user.email=test@example.invalid", "commit", "-qm", "base") + snapshot, e := gitSnapshot(work) + if e != nil { + t.Fatal(e) + } + req := WorkspaceRequest{WorkspacePath: work, Git: snapshot} + w := call(t, s, "POST", "/projects/check", req) + if w.Code != 200 || !strings.Contains(w.Body.String(), `"canSync":true`) { + t.Fatal(w.Body.String()) + } + if len(s.projects) != 0 { + t.Fatal("manual check mutated server projects") + } + mismatch := *snapshot + mismatch.Head = "different" + req.Git = &mismatch + w = call(t, s, "POST", "/projects/check", req) + if !strings.Contains(w.Body.String(), `"canSync":false`) { + t.Fatal("mismatched HEAD accepted") + } + req.Git = snapshot + w = call(t, s, "POST", "/projects", req) + if w.Code != 200 { + t.Fatal(w.Body.String()) + } + var allocated map[string]string + json.Unmarshal(w.Body.Bytes(), &allocated) + p := allocated["id"] + if s.work(p) != work { + t.Fatal("selected existing path not used") + } + // Local dirty content is intentional; the server must accept subsequent syncs of its own snapshot. + files := map[string]File{} + for path, f := range s.projects[p].Files { + files[path] = f + } + files["a.txt"] = file("local edit") + w = call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "new", Files: files, Git: snapshot}) + if w.Code != 200 { + t.Fatal(w.Body.String()) + } + req.ProjectID = p + w = call(t, s, "POST", "/projects/check", req) + if !strings.Contains(w.Body.String(), `"canSync":true`) { + t.Fatal(w.Body.String()) + } + os.WriteFile(filepath.Join(work, "a.txt"), []byte("remote edit"), 0600) + w = call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "next", Files: files, Git: snapshot}) + if w.Code != 409 { + t.Fatal("remote edit overwritten", w.Body.String()) + } + if w = call(t, s, "POST", "/projects/"+p+"/builds", map[string]string{"revision": "new", "task": ":app:assembleDebug"}); w.Code != 409 { + t.Fatal("built changed source under stale revision", w.Body.String()) + } + req.WorkspacePath = t.TempDir() + if w = call(t, s, "POST", "/projects/check", req); w.Code != 400 { + t.Fatal("allowed root escaped") + } + req.WorkspacePath = filepath.Join(s.workspaceRoot, "missing") + if w = call(t, s, "POST", "/projects/check", req); w.Code != 400 { + t.Fatal("missing folder accepted") + } + // Directory browsing lists folders within the configured root without binding them. + w = call(t, s, "GET", "/directories", nil) + if w.Code != 200 || !strings.Contains(w.Body.String(), "中文 project") { + t.Fatal(w.Body.String()) + } + if w = call(t, s, "GET", "/directories?path="+filepath.ToSlash(t.TempDir()), nil); w.Code != 400 { + t.Fatal("directory browser escaped root") + } +} +func TestNativeBuildCachesCannotBeSyncedOrDeleted(t *testing.T) { + s := testServer(t) + p := project(t, s) + path := "app/.cxx/Debug/arm64-v8a/.ninja_deps" + if validPath(path) { + t.Fatal("native cache accepted") + } + os.MkdirAll(filepath.Dir(filepath.Join(s.work(p), filepath.FromSlash(path))), 0700) + os.WriteFile(filepath.Join(s.work(p), filepath.FromSlash(path)), []byte("server cache"), 0600) + s.projects[p].Files[path] = File{Hash: digest([]byte("old upload"))} + w := call(t, s, "POST", "/projects/"+p+"/sync", SyncRequest{Revision: "clean", Files: map[string]File{}}) + if w.Code != 200 { + t.Fatal(w.Body.String()) + } + if _, e := os.Stat(filepath.Join(s.work(p), filepath.FromSlash(path))); e != nil { + t.Fatal("server cache deleted", e) + } + if len(s.projects[p].Files) != 0 { + t.Fatal("cache stayed in source manifest") + } +}