Files
RemoteCompilation/client/remote_run.py
T
tongtong 6f9cc7e7ea feat: 增加独立构建工作区、服务端ADB与私有文件清单
支持Git提交导入及未提交源码叠加,APK原名下载和完成通知。新增服务端设备安装与按工程维护的私有文件清单,修复Wrapper预检查、布局及IDE读锁和保存状态问题。更新协议、测试和部署记录;服务端0.7.0,插件0.7.1。
2026-11-27 11:04:58 +08:00

167 lines
9.2 KiB
Python

"""Dependency-free reference client: Python 3.10+, token via environment only."""
import argparse
import base64
import hashlib
import json
import os
import re
from pathlib import Path
import subprocess
import ssl
import time
import tempfile
from datetime import datetime
import urllib.request
import urllib.parse
import uuid
from source_files import git_snapshot, collect, text_hash
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')
parser.add_argument('--device', help='Explicit adb device serial; omit to download only')
parser.add_argument('--artifact', help='APK artifact name or sourcePath when the build produces multiple APKs')
args = parser.parse_args()
token = os.environ.get('REMOTE_BUILD_TOKEN', '')
if len(token) < 24:
parser.error('Set REMOTE_BUILD_TOKEN to at least 24 characters')
endpoint = args.url.rstrip('/')
url = urllib.parse.urlparse(endpoint)
if url.scheme not in ('https', 'http') or not url.hostname or url.username or url.query or url.fragment:
parser.error('Invalid endpoint')
if url.scheme == 'http' and url.hostname not in ('127.0.0.1', 'localhost', '::1'):
parser.error('Use HTTPS or an SSH tunnel for remote connections')
source = args.source.resolve(strict=True)
output = source / '.remotecompile'
output.mkdir(exist_ok=True)
def request(method, path, body=None):
upload = body.open('rb') if isinstance(body, Path) else None
data = upload if upload else (json.dumps(body).encode() if body is not None else None)
headers = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/octet-stream' if upload else 'application/json'}
if upload: headers['Content-Length'] = str(body.stat().st_size)
req = urllib.request.Request(endpoint + '/api/v1' + path, data=data, method=method, headers=headers)
context = ssl.create_default_context(cafile=args.server_cert) if args.server_cert else None
try:
with urllib.request.urlopen(req, timeout=600, context=context) as response: result = response.read()
finally:
if upload: upload.close()
return result if '/artifacts/' in path else json.loads(result)
health = request('GET', '/health')
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 or state.get('remoteFolder') != args.remote_folder:
state = {'url': endpoint, 'remoteFolder': args.remote_folder}
dedicated = bool(local_git)
if dedicated and not health.get('dedicatedGit'): raise RuntimeError('Upgrade service to 0.5.0 for dedicated Git workspaces')
binding = {'workspacePath': args.remote_folder, 'projectId': state.get('project', ''), 'git': local_git, 'dedicated': dedicated}
inspection = request('POST', '/projects/check', binding)
print('Git check: '+inspection['message'], flush=True)
if not inspection['canSync']:
raise RuntimeError(inspection['message'])
paths = collect(source, local_git)
if not state.get('project') or dedicated:
state['project'] = request('POST', '/projects', binding)['id']
state_file.write_text(json.dumps(state), encoding='utf-8')
project = state['project']
remote_state = request('GET', f'/projects/{project}/manifest')
previous = (remote_state.get('git') or {}).get('head')
if dedicated and previous != local_git['head']:
def send_bundle(base):
with tempfile.TemporaryDirectory(prefix='remotecompile-bundle-') as directory:
bundle = Path(directory) / 'source.bundle'
command = ['git', '-C', str(source), 'bundle', 'create', '--version=3', str(bundle), 'HEAD', '--filter=blob:none']
if base and subprocess.run(['git', '-C', str(source), 'merge-base', '--is-ancestor', base, local_git['head']], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0: command.append('^' + base)
subprocess.run(command, check=True, timeout=300, stdout=subprocess.DEVNULL)
if git_snapshot(source)['head'] != local_git['head']: raise RuntimeError('HEAD changed while creating bundle; retry')
request('POST', f'/projects/{project}/git?head=' + local_git['head'], bundle)
try: send_bundle(previous)
except urllib.error.HTTPError as error:
if previous and error.code == 400: send_bundle(None)
else: raise
remote = remote_state['files']
manifest = {}
changed = 0
eol_only = 0
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
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), 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:
while True:
build = request('GET', f'/builds/{build_id}')
for line in build['logs'][offset:]:
print(line, end='', flush=True)
offset = len(build['logs'])
if build['status'] not in ('queued', 'running'):
break
time.sleep(0.7)
except KeyboardInterrupt:
request('DELETE', f'/builds/{build_id}')
raise
if build['status'] != 'success':
raise RuntimeError('Build ' + build['status'])
artifacts = [a for a in build['artifacts'] if a['name'].lower().endswith('.apk')]
selected = [a for a in artifacts if args.artifact in (a['name'], a.get('sourcePath'))] if args.artifact else artifacts
if len(selected) != 1:
choices = '\n'.join(a['name'] + ' ' + a.get('sourcePath', '') for a in artifacts)
raise RuntimeError(f'Build succeeded ({build_id}); select one full APK with --artifact. Split APK installation is unsupported.\n{choices}')
artifact = selected[0]
content = request('GET', f'/builds/{build_id}/artifacts/' + urllib.parse.quote(artifact['name']))
if hashlib.sha256(content).hexdigest() != artifact['hash']:
raise RuntimeError('APK checksum mismatch')
filename = artifact.get('fileName') or (artifact.get('sourcePath') or artifact['name']).replace('\\', '/').split('/')[-1]
if not artifact.get('fileName') and not artifact.get('sourcePath'):
filename = re.sub(r'^\d+-', '', filename)
if re.match(r'(?i)^(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])(?:\.|$)', filename) or not filename.lower().endswith('.apk') or any(c in filename for c in '/\\:*?"<>|') or any(ord(c)<32 for c in filename): raise RuntimeError('Invalid APK filename')
stamp = datetime.now().strftime('%Y%m%d_%H%M%S'); attempt = 0
while True:
name = filename if attempt == 0 else filename[:-4] + '_' + stamp + ('' if attempt == 1 else '_' + str(attempt)) + '.apk'
destination = output / name
try:
with destination.open('xb') as f: f.write(content)
break
except FileExistsError: attempt += 1
print(f'\nAPK: {destination}')
if args.device:
subprocess.run([args.adb, '-s', args.device, 'install', '-r', str(destination)], check=True, timeout=120)
if __name__ == '__main__':
main()