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

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

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

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

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

No files matched your search

+41 -27
View File
@@ -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:
+70
View File
@@ -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()
+40 -9
View File
@@ -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)