feat: 初始化跨平台远程编译服务与 Android Studio 插件
This commit is contained in:
commit
9eba4556db
44 files changed
+2802
No files matched your search
@@ -0,0 +1,110 @@
|
||||
"""Dependency-free reference client: Python 3.10+, token via environment only."""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.request
|
||||
import urllib.parse
|
||||
import uuid
|
||||
|
||||
EXCLUDE = {'.git', '.gradle', '.idea', '.remotecompile', '.kotlin', 'build', 'node_modules', '__pycache__'}
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Sync, remote build, download and optionally install an APK')
|
||||
parser.add_argument('source', type=Path)
|
||||
parser.add_argument('--url', default='http://127.0.0.1:8765')
|
||||
parser.add_argument('--task', default=':app:assembleDebug')
|
||||
parser.add_argument('--adb', default='adb')
|
||||
parser.add_argument('--device', help='Explicit adb device serial; omit to download only')
|
||||
args = parser.parse_args()
|
||||
token = os.environ.get('REMOTE_BUILD_TOKEN', '')
|
||||
if len(token) < 24:
|
||||
parser.error('Set REMOTE_BUILD_TOKEN to at least 24 characters')
|
||||
endpoint = args.url.rstrip('/')
|
||||
url = urllib.parse.urlparse(endpoint)
|
||||
if url.scheme not in ('https', 'http') or not url.hostname or url.username or url.query or url.fragment:
|
||||
parser.error('Invalid endpoint')
|
||||
if url.scheme == 'http' and url.hostname not in ('127.0.0.1', 'localhost', '::1'):
|
||||
parser.error('Use HTTPS or an SSH tunnel for remote connections')
|
||||
source = args.source.resolve(strict=True)
|
||||
output = source / '.remotecompile'
|
||||
output.mkdir(exist_ok=True)
|
||||
|
||||
def request(method, path, body=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
req = urllib.request.Request(endpoint + '/api/v1' + path, data=data, method=method,
|
||||
headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'})
|
||||
with urllib.request.urlopen(req, timeout=300) as response:
|
||||
result = response.read()
|
||||
return result if '/artifacts/' in path else json.loads(result)
|
||||
|
||||
request('GET', '/health')
|
||||
state_file = output / 'client.json'
|
||||
state = json.loads(state_file.read_text()) if state_file.exists() else {}
|
||||
if state.get('url') != endpoint:
|
||||
state = {'url': endpoint, 'project': request('POST', '/projects')['id']}
|
||||
state_file.write_text(json.dumps(state), encoding='utf-8')
|
||||
project = state['project']
|
||||
remote = request('GET', f'/projects/{project}/manifest')['files']
|
||||
manifest = {}
|
||||
changed = 0
|
||||
for directory, dirs, names in os.walk(source, followlinks=False):
|
||||
for name in list(dirs):
|
||||
if name in EXCLUDE:
|
||||
dirs.remove(name)
|
||||
elif (Path(directory) / name).is_symlink():
|
||||
raise RuntimeError('Symbolic links are unsupported')
|
||||
for name in names:
|
||||
if name == 'local.properties' or name.startswith('.env') or name.endswith(('.jks', '.keystore')) or name in ('key.properties', 'keystore.properties'):
|
||||
continue
|
||||
path = Path(directory) / name
|
||||
if path.is_symlink():
|
||||
raise RuntimeError(f'Symbolic link: {path}')
|
||||
if path.stat().st_size > 64 * 1024 * 1024:
|
||||
raise RuntimeError(f'File exceeds 64 MiB: {path}')
|
||||
content = path.read_bytes()
|
||||
sha = hashlib.sha256(content).hexdigest()
|
||||
relative = path.relative_to(source).as_posix()
|
||||
entry = {'hash': sha}
|
||||
if remote.get(relative, {}).get('hash') != sha:
|
||||
entry['data'] = base64.b64encode(content).decode()
|
||||
changed += 1
|
||||
manifest[relative] = entry
|
||||
revision = str(uuid.uuid4())
|
||||
print(f'Syncing {changed} changed files ({len(manifest)} total)', flush=True)
|
||||
request('POST', f'/projects/{project}/sync', {'revision': revision, 'files': manifest})
|
||||
build = request('POST', f'/projects/{project}/builds', {'revision': revision, 'task': args.task})
|
||||
build_id = build['id']
|
||||
offset = 0
|
||||
try:
|
||||
while True:
|
||||
build = request('GET', f'/builds/{build_id}')
|
||||
for line in build['logs'][offset:]:
|
||||
print(line, end='', flush=True)
|
||||
offset = len(build['logs'])
|
||||
if build['status'] not in ('queued', 'running'):
|
||||
break
|
||||
time.sleep(0.7)
|
||||
except KeyboardInterrupt:
|
||||
request('DELETE', f'/builds/{build_id}')
|
||||
raise
|
||||
if build['status'] != 'success':
|
||||
raise RuntimeError('Build ' + build['status'])
|
||||
if len(build['artifacts']) != 1:
|
||||
raise RuntimeError('Expected exactly one APK; split APKs unsupported in v0.1')
|
||||
artifact = build['artifacts'][0]
|
||||
content = request('GET', f'/builds/{build_id}/artifacts/' + urllib.parse.quote(artifact['name']))
|
||||
if hashlib.sha256(content).hexdigest() != artifact['hash']:
|
||||
raise RuntimeError('APK checksum mismatch')
|
||||
destination = output / (build_id + '.apk')
|
||||
destination.write_bytes(content)
|
||||
print(f'\nAPK: {destination}')
|
||||
if args.device:
|
||||
subprocess.run([args.adb, '-s', args.device, 'install', '-r', str(destination)], check=True, timeout=120)
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Exercises the real service binary and CLI using a simulated Gradle Wrapper.
|
||||
|
||||
This validates transport/lifecycle; it does not validate an Android toolchain.
|
||||
Run: python -m unittest discover -s client -p test_smoke.py -v
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
class SmokeTest(unittest.TestCase):
|
||||
def test_sync_build_download_and_second_revision(self):
|
||||
binary = ROOT / 'dist' / ('remotecompile-windows-amd64.exe' if os.name == 'nt' else 'remotecompile')
|
||||
if not binary.exists():
|
||||
self.skipTest(f'Build service binary first: {binary}')
|
||||
with tempfile.TemporaryDirectory(dir=ROOT) as temp:
|
||||
root = Path(temp)
|
||||
source = root / '中文 project'
|
||||
source.mkdir()
|
||||
(source / 'input.txt').write_text('first')
|
||||
(source / 'deleted.txt').write_text('remove')
|
||||
if os.name == 'nt':
|
||||
(source / 'gradlew.bat').write_text('@echo off\nmkdir app\\build\\outputs\\apk\\debug 2>nul\ncopy /y input.txt app\\build\\outputs\\apk\\debug\\app-debug.apk >nul\nexit /b 0\n')
|
||||
else:
|
||||
(source / 'gradlew').write_text('#!/bin/sh\nmkdir -p app/build/outputs/apk/debug\ncp input.txt app/build/outputs/apk/debug/app-debug.apk\n')
|
||||
with socket.socket() as sock:
|
||||
sock.bind(('127.0.0.1', 0))
|
||||
port = sock.getsockname()[1]
|
||||
endpoint = f'http://127.0.0.1:{port}'
|
||||
env = dict(os.environ, REMOTE_BUILD_TOKEN='test-only-token-abcdefghijklmnopqrstuvwxyz')
|
||||
process = subprocess.Popen([str(binary), '-listen', f'127.0.0.1:{port}', '-data', str(root / 'data')], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
try:
|
||||
for _ in range(100):
|
||||
try:
|
||||
req = urllib.request.Request(endpoint + '/api/v1/health', headers={'Authorization': 'Bearer ' + env['REMOTE_BUILD_TOKEN']})
|
||||
with urllib.request.urlopen(req, timeout=1):
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(.05)
|
||||
else:
|
||||
self.fail('Service did not start')
|
||||
command = [sys.executable, str(ROOT / 'client' / 'remote_run.py'), str(source), '--url', endpoint]
|
||||
first = subprocess.run(command, env=env, capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(first.returncode, 0, first.stderr)
|
||||
self.assertEqual(next((source / '.remotecompile').glob('*.apk')).read_bytes(), b'first')
|
||||
(source / 'input.txt').write_text('second')
|
||||
(source / 'deleted.txt').unlink()
|
||||
second = subprocess.run(command, env=env, capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(second.returncode, 0, second.stderr)
|
||||
self.assertIn('Syncing 1 changed files', second.stdout)
|
||||
artifacts = [p.read_bytes() for p in (source / '.remotecompile').glob('*.apk')]
|
||||
self.assertCountEqual(artifacts, [b'first', b'second'])
|
||||
state = json.loads((source / '.remotecompile' / 'client.json').read_text())
|
||||
self.assertFalse((root / 'data' / 'projects' / state['project'] / 'work' / 'deleted.txt').exists())
|
||||
finally:
|
||||
process.terminate()
|
||||
process.wait(timeout=15)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user