mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-12-02 04:44:18 +08:00
Prepare one-shot stable and testing channel migration
This commit is contained in:
@@ -0,0 +1,133 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline, commit-bound channel migration; never checks out or downloads code."""
|
||||
import argparse
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
PLAN = 'scripts/branch-migration.json'
|
||||
|
||||
|
||||
def git(repo, *args):
|
||||
return subprocess.check_output(['git', '--no-optional-locks', '-c', 'gc.auto=0', '-c',
|
||||
'maintenance.auto=false', '-C', str(repo), *args],
|
||||
text=True, timeout=15).strip()
|
||||
|
||||
|
||||
def atomic_json(path, value):
|
||||
atomic_write(path, json.dumps(value, sort_keys=True).encode() + b'\n')
|
||||
|
||||
|
||||
def atomic_write(path, value):
|
||||
fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent)
|
||||
try:
|
||||
os.fchmod(fd, stat.S_IMODE(path.stat().st_mode) if path.exists() else 0o644)
|
||||
with os.fdopen(fd, 'wb') as stream:
|
||||
stream.write(value)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
directory = os.open(path.parent, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
finally:
|
||||
Path(temporary).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def migrate(repo, params, checkpoint=lambda step: None):
|
||||
repo, params = Path(repo).resolve(), Path(params)
|
||||
plan_path = repo / PLAN
|
||||
if not plan_path.is_file() or plan_path.is_symlink():
|
||||
return 'no plan'
|
||||
plan = json.loads(plan_path.read_text())
|
||||
if (type(plan) is not dict or set(plan) != {'source', 'destination', 'parent', 'token'} or
|
||||
any(type(value) is not str for value in plan.values()) or
|
||||
(plan['source'], plan['destination']) not in (('Dom', 'testing'), ('StarPilot', 'stable')) or
|
||||
not re.fullmatch('[0-9a-f]{40}', plan['parent']) or not re.fullmatch('[0-9a-f]{32}', plan['token'])):
|
||||
raise ValueError('Invalid channel migration plan')
|
||||
head = git(repo, 'rev-parse', '--verify', 'HEAD')
|
||||
raw = git(repo, 'cat-file', 'commit', head)
|
||||
headers, message = raw.split('\n\n', 1)
|
||||
parents = [line[7:] for line in headers.splitlines() if line.startswith('parent ')]
|
||||
title = f"Branch-Migration: {plan['source']} -> {plan['destination']} ({plan['token']})"
|
||||
if parents != [plan['parent']] or message != title:
|
||||
return 'not migration release'
|
||||
gitdir = Path(git(repo, 'rev-parse', '--absolute-git-dir'))
|
||||
with (gitdir / 'starpilot-branch-migration.lock').open('a') as lease:
|
||||
try:
|
||||
fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return 'migration busy'
|
||||
completed = gitdir / ('starpilot-branch-migration-' + plan['token'] + '.done')
|
||||
pending = gitdir / 'starpilot-branch-migration.pending'
|
||||
record = {**plan, 'commit': head}
|
||||
if completed.exists():
|
||||
if completed.is_symlink() or json.loads(completed.read_text()) != record:
|
||||
raise ValueError('Migration completion does not match release')
|
||||
if pending.exists() and not pending.is_symlink() and json.loads(pending.read_text()) == record:
|
||||
pending.unlink()
|
||||
return 'already migrated'
|
||||
if pending.exists() and (pending.is_symlink() or json.loads(pending.read_text()) != record):
|
||||
raise ValueError('Another migration is pending')
|
||||
branch = git(repo, 'symbolic-ref', '--short', 'HEAD')
|
||||
if branch != plan['source'] and not (pending.exists() and branch == plan['destination']):
|
||||
return 'manual branch selection'
|
||||
target = params / 'UpdaterTargetBranch'
|
||||
saved = target.read_bytes() if target.exists() else b''
|
||||
if saved not in (b'', plan['source'].encode(), plan['destination'].encode()):
|
||||
return 'manual updater selection'
|
||||
if not params.is_dir() or target.is_symlink():
|
||||
raise ValueError('Updater Params directory is unavailable or unsafe')
|
||||
destination = 'refs/heads/' + plan['destination']
|
||||
existing = subprocess.run(['git', '-C', str(repo), 'rev-parse', '--verify', '--quiet', destination],
|
||||
text=True, capture_output=True, timeout=15)
|
||||
if existing.returncode not in (0, 1):
|
||||
raise ValueError('Cannot inspect destination ref')
|
||||
if existing.returncode == 0 and existing.stdout.strip() != head:
|
||||
raise ValueError('Destination local branch already contains different work')
|
||||
atomic_json(pending, record)
|
||||
checkpoint('pending')
|
||||
if existing.returncode == 1:
|
||||
git(repo, 'update-ref', destination, head, '0' * 40)
|
||||
checkpoint('destination')
|
||||
git(repo, 'symbolic-ref', 'HEAD', destination)
|
||||
checkpoint('head')
|
||||
git(repo, 'config', 'branch.' + plan['destination'] + '.remote', 'origin')
|
||||
checkpoint('remote')
|
||||
git(repo, 'config', 'branch.' + plan['destination'] + '.merge', destination)
|
||||
checkpoint('upstream')
|
||||
fetch = subprocess.run(['git', '-C', str(repo), 'config', '--get-all', 'remote.origin.fetch'],
|
||||
text=True, capture_output=True, timeout=15)
|
||||
if fetch.returncode not in (0, 1):
|
||||
raise ValueError('Cannot inspect origin fetch configuration')
|
||||
refspec = '+' + destination + ':refs/remotes/origin/' + plan['destination']
|
||||
if refspec not in fetch.stdout.splitlines() and '+refs/heads/*:refs/remotes/origin/*' not in fetch.stdout.splitlines():
|
||||
git(repo, 'config', '--add', 'remote.origin.fetch', refspec)
|
||||
checkpoint('fetch')
|
||||
if (target.read_bytes() if target.exists() else b'') != saved:
|
||||
raise ValueError('Updater selection changed during migration')
|
||||
atomic_write(target, plan['destination'].encode())
|
||||
checkpoint('params')
|
||||
atomic_json(completed, record)
|
||||
checkpoint('completed')
|
||||
pending.unlink()
|
||||
return 'migrated to ' + plan['destination']
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--repo', type=Path, default=Path(__file__).resolve().parents[1])
|
||||
parser.add_argument('--params', type=Path, default=Path('/data/params/d'))
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
print(migrate(args.repo, args.params))
|
||||
except (OSError, ValueError, subprocess.SubprocessError) as error:
|
||||
parser.exit(1, f'Channel migration deferred: {error}\n')
|
||||
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare a pinned, title-only migration commit in a local review ref; never push."""
|
||||
import argparse
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import uuid
|
||||
|
||||
|
||||
HOOK = '''
|
||||
if [ -f "$DIR/scripts/branch-migration.json" ]; then
|
||||
python3 "$DIR/scripts/branch_migration.py" --repo "$DIR" || echo "Branch migration deferred; keeping installed software."
|
||||
fi
|
||||
'''
|
||||
|
||||
|
||||
def prepare(repo, source, destination, base, review_ref, token=None):
|
||||
repo = Path(repo).resolve()
|
||||
if (source, destination) not in (('Dom', 'testing'), ('StarPilot', 'stable')):
|
||||
raise ValueError('Only Dom -> testing and StarPilot -> stable are supported')
|
||||
token = token or uuid.uuid4().hex
|
||||
with tempfile.TemporaryDirectory(prefix='branch-migration-index-') as temporary:
|
||||
env = dict(os.environ, GIT_INDEX_FILE=str(Path(temporary) / 'index'))
|
||||
|
||||
def git(*args, data=None):
|
||||
return subprocess.check_output(['git', '--no-optional-locks', '-c', 'gc.auto=0', '-c',
|
||||
'maintenance.auto=false', '-C', str(repo), *args],
|
||||
input=data, env=env, timeout=30).decode().strip()
|
||||
|
||||
git('check-ref-format', review_ref)
|
||||
if not review_ref.startswith('refs/heads/review/'):
|
||||
raise ValueError('Use a new local refs/heads/review/ ref')
|
||||
parent = git('rev-parse', '--verify', base + '^{commit}')
|
||||
if source == 'StarPilot':
|
||||
version = git('show', parent + ':selfdrive/ui/lib/starpilot_version.py')
|
||||
if not re.search(r'^STARPILOT_DISPLAY_VERSION = [\"\']6\.\d+\.\d+[\"\']$', version, re.MULTILINE):
|
||||
raise ValueError('The stable bridge must preserve a reviewed StarPilot 6.x release')
|
||||
elif not git('ls-tree', parent, '--', 'prebuilt.json'):
|
||||
raise ValueError('The testing bridge requires the reviewed rebase build receipt')
|
||||
if git('ls-tree', parent, '--', 'prebuilt').split()[:1] != ['100644']:
|
||||
raise ValueError('The source must be a precompiled release')
|
||||
git('read-tree', parent)
|
||||
launch = git('show', parent + ':launch_chffrplus.sh') + '\n'
|
||||
anchor = 'source "$DIR/launch_env.sh"\n'
|
||||
if launch.count(anchor) != 1 or 'scripts/branch-migration.json' in launch:
|
||||
raise ValueError('Review the source launcher before creating its migration')
|
||||
files = {
|
||||
'launch_chffrplus.sh': ('100755', launch.replace(anchor, anchor + HOOK)),
|
||||
'scripts/branch_migration.py': ('100644', Path(__file__).with_name('branch_migration.py').read_text()),
|
||||
'scripts/branch-migration.json': ('100644', json.dumps({
|
||||
'source': source, 'destination': destination, 'parent': parent, 'token': token,
|
||||
}, sort_keys=True) + '\n'),
|
||||
}
|
||||
for name, (mode, content) in files.items():
|
||||
blob = git('hash-object', '-w', '--stdin', data=content.encode())
|
||||
git('update-index', '--add', '--cacheinfo', mode + ',' + blob + ',' + name)
|
||||
tree = git('write-tree', '--missing-ok')
|
||||
if git('ls-tree', parent, '--', 'prebuilt.json'):
|
||||
# Use the canonical inventory rules, including modes and exact Git blobs.
|
||||
spec = importlib.util.spec_from_file_location('canonical_receipt', Path(__file__).parents[1] / 'openpilot/common/prebuilt_manifest.py')
|
||||
canonical = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(canonical)
|
||||
if not canonical.valid_receipt(git, parent):
|
||||
raise ValueError('Source release has no valid canonical receipt')
|
||||
receipt = {'schema_version': 1, 'protected_inventory_sha256': canonical.revision_digest(git, tree)}
|
||||
blob = git('hash-object', '-w', '--stdin', data=(json.dumps(receipt, sort_keys=True) + '\n').encode())
|
||||
git('update-index', '--add', '--cacheinfo', '100644,' + blob + ',prebuilt.json')
|
||||
tree = git('write-tree', '--missing-ok')
|
||||
title = f'Branch-Migration: {source} -> {destination} ({token})'
|
||||
commit = git('commit-tree', tree, '-p', parent, data=(title + '\n').encode())
|
||||
git('update-ref', review_ref, commit, '0' * 40)
|
||||
return {'source': source, 'destination': destination, 'parent': parent,
|
||||
'commit': commit, 'review_ref': review_ref, 'token': token}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--repo', type=Path, default=Path.cwd())
|
||||
parser.add_argument('--source', choices=['Dom', 'StarPilot'], required=True)
|
||||
parser.add_argument('--destination', choices=['testing', 'stable'], required=True)
|
||||
parser.add_argument('--base', required=True, help='Exact reviewed source commit')
|
||||
parser.add_argument('--review-ref', required=True)
|
||||
args = parser.parse_args()
|
||||
print(json.dumps(prepare(args.repo, args.source, args.destination, args.base, args.review_ref), indent=2))
|
||||
@@ -0,0 +1,248 @@
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
SCRIPTS = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def load(name):
|
||||
spec = importlib.util.spec_from_file_location(name, SCRIPTS / (name + '.py'))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
runtime = load('branch_migration')
|
||||
creator = load('create_branch_migration')
|
||||
|
||||
|
||||
class BranchMigrationTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.root = Path(self.temporary.name)
|
||||
|
||||
def git(self, repo, *args):
|
||||
return subprocess.check_output(['git', '-c', 'core.hooksPath=/dev/null', '-C', str(repo), *args],
|
||||
stderr=subprocess.STDOUT, text=True).strip()
|
||||
|
||||
def fixture(self, source='Dom', destination='testing', modern=None):
|
||||
modern = source == 'Dom' if modern is None else modern
|
||||
remote = self.root / ('remote-' + source)
|
||||
remote.mkdir()
|
||||
self.git(remote, 'init', '-b', source)
|
||||
self.git(remote, 'config', 'user.name', 'Migration test')
|
||||
self.git(remote, 'config', 'user.email', 'test@example.invalid')
|
||||
(remote / 'launch_chffrplus.sh').write_text('#!/bin/bash\nDIR="."\nsource "$DIR/launch_env.sh"\n')
|
||||
(remote / 'launch_chffrplus.sh').chmod(0o755)
|
||||
(remote / 'payload').write_text('existing software and data')
|
||||
(remote / 'prebuilt').write_text('')
|
||||
if source == 'StarPilot':
|
||||
version = remote / 'selfdrive/ui/lib/starpilot_version.py'
|
||||
version.parent.mkdir(parents=True)
|
||||
version.write_text('STARPILOT_DISPLAY_VERSION = "6.7.9"\n')
|
||||
self.git(remote, 'add', '.')
|
||||
if modern:
|
||||
spec = importlib.util.spec_from_file_location('receipt', SCRIPTS.parent / 'openpilot/common/prebuilt_manifest.py')
|
||||
receipt = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(receipt)
|
||||
tree = self.git(remote, 'write-tree')
|
||||
(remote / 'prebuilt.json').write_text(json.dumps({'schema_version': 1,
|
||||
'protected_inventory_sha256': receipt.revision_digest(lambda *args: self.git(remote, *args), tree)}))
|
||||
self.git(remote, 'add', 'prebuilt.json')
|
||||
self.git(remote, 'commit', '-m', 'Existing release')
|
||||
parent = self.git(remote, 'rev-parse', 'HEAD')
|
||||
migration = creator.prepare(remote, source, destination, parent, 'refs/heads/review/' + destination)
|
||||
self.git(remote, 'update-ref', 'refs/heads/' + source, migration['commit'], parent)
|
||||
self.git(remote, 'update-ref', 'refs/heads/' + destination, migration['commit'])
|
||||
self.git(remote, 'reset', '--hard', migration['commit'])
|
||||
repo = self.root / ('device-' + source)
|
||||
self.git(self.root, 'clone', '--depth=1', '--single-branch', '--branch', source, remote.as_uri(), str(repo))
|
||||
params = self.root / ('params-' + source)
|
||||
params.mkdir()
|
||||
(params / 'UpdaterTargetBranch').write_text(source)
|
||||
(params / 'preserved-settings-models-recordings').write_bytes(b'unchanged')
|
||||
return remote, repo, params, migration
|
||||
|
||||
def assert_migrated(self, repo, params, migration):
|
||||
self.assertEqual(self.git(repo, 'symbolic-ref', '--short', 'HEAD'), migration['destination'])
|
||||
self.assertEqual(self.git(repo, 'rev-parse', 'HEAD'), migration['commit'])
|
||||
self.assertEqual(self.git(repo, 'rev-parse', 'refs/heads/' + migration['source']), migration['commit'])
|
||||
self.assertEqual(self.git(repo, 'config', 'branch.' + migration['destination'] + '.remote'), 'origin')
|
||||
self.assertEqual(self.git(repo, 'config', 'branch.' + migration['destination'] + '.merge'), 'refs/heads/' + migration['destination'])
|
||||
self.assertIn('+refs/heads/' + migration['destination'] + ':refs/remotes/origin/' + migration['destination'],
|
||||
self.git(repo, 'config', '--get-all', 'remote.origin.fetch'))
|
||||
self.assertEqual((params / 'UpdaterTargetBranch').read_text(), migration['destination'])
|
||||
self.assertEqual((params / 'preserved-settings-models-recordings').read_bytes(), b'unchanged')
|
||||
self.assertEqual(self.git(repo, 'status', '--porcelain'), '')
|
||||
|
||||
def test_both_channels_depth_one_without_parent_and_offline(self):
|
||||
for source, destination in (('Dom', 'testing'), ('StarPilot', 'stable')):
|
||||
with self.subTest(source=source):
|
||||
remote, repo, params, migration = self.fixture(source, destination)
|
||||
parent = subprocess.run(['git', '-C', str(repo), 'cat-file', '-e', migration['parent']], capture_output=True)
|
||||
self.assertNotEqual(parent.returncode, 0)
|
||||
self.git(repo, 'remote', 'set-url', 'origin', str(self.root / 'offline'))
|
||||
self.assertEqual(runtime.migrate(repo, params), 'migrated to ' + destination)
|
||||
self.assert_migrated(repo, params, migration)
|
||||
self.assertEqual(runtime.migrate(repo, params), 'already migrated')
|
||||
self.assertFalse((repo / '.git/starpilot-branch-migration.pending').exists())
|
||||
|
||||
def test_every_interrupted_step_retries_without_data_loss(self):
|
||||
for step in ('pending', 'destination', 'head', 'remote', 'upstream', 'fetch', 'params', 'completed'):
|
||||
with self.subTest(step=step):
|
||||
case = self.root / step
|
||||
case.mkdir()
|
||||
original = self.root
|
||||
self.root = case
|
||||
try:
|
||||
_, repo, params, migration = self.fixture()
|
||||
def interrupt(current, interrupted_step=step):
|
||||
if current == interrupted_step:
|
||||
raise RuntimeError('simulated interruption')
|
||||
with self.assertRaisesRegex(RuntimeError, 'simulated interruption'):
|
||||
runtime.migrate(repo, params, interrupt)
|
||||
runtime.migrate(repo, params)
|
||||
self.assert_migrated(repo, params, migration)
|
||||
self.assertFalse((repo / '.git/starpilot-branch-migration.pending').exists())
|
||||
finally:
|
||||
self.root = original
|
||||
|
||||
def test_destination_advance_is_fetched_without_resetting_installed_code(self):
|
||||
remote, repo, params, migration = self.fixture()
|
||||
self.git(remote, 'checkout', 'testing')
|
||||
(remote / 'payload').write_text('new testing release')
|
||||
self.git(remote, 'commit', '-am', 'Later destination release')
|
||||
latest = self.git(remote, 'rev-parse', 'HEAD')
|
||||
runtime.migrate(repo, params)
|
||||
self.assert_migrated(repo, params, migration)
|
||||
self.git(repo, 'fetch', 'origin')
|
||||
self.assertEqual(self.git(repo, 'rev-parse', '@{upstream}'), latest)
|
||||
self.assertEqual(self.git(repo, 'rev-parse', 'HEAD'), migration['commit'])
|
||||
|
||||
def test_rollback_or_manual_switch_never_chains(self):
|
||||
_, repo, params, migration = self.fixture()
|
||||
runtime.migrate(repo, params)
|
||||
self.git(repo, 'checkout', 'Dom')
|
||||
(params / 'UpdaterTargetBranch').write_text('Dom')
|
||||
self.assertEqual(runtime.migrate(repo, params), 'already migrated')
|
||||
self.assertEqual(self.git(repo, 'symbolic-ref', '--short', 'HEAD'), 'Dom')
|
||||
self.git(repo, 'checkout', '-b', 'StarPilot')
|
||||
(params / 'UpdaterTargetBranch').write_text('StarPilot')
|
||||
self.assertEqual(runtime.migrate(repo, params), 'already migrated')
|
||||
self.assertEqual(self.git(repo, 'symbolic-ref', '--short', 'HEAD'), 'StarPilot')
|
||||
self.assertFalse((repo / '.git/refs/heads/stable').exists())
|
||||
|
||||
def test_inherited_plan_is_inert_even_after_future_force_push(self):
|
||||
_, repo, params, _ = self.fixture()
|
||||
self.git(repo, 'config', 'user.name', 'Test')
|
||||
self.git(repo, 'config', 'user.email', 'test@example.invalid')
|
||||
(repo / 'payload').write_text('future rebase')
|
||||
self.git(repo, 'commit', '-am', 'Future rebase release')
|
||||
self.git(repo, 'branch', '-m', 'StarPilot')
|
||||
(params / 'UpdaterTargetBranch').write_text('StarPilot')
|
||||
self.assertEqual(runtime.migrate(repo, params), 'not migration release')
|
||||
self.assertEqual(self.git(repo, 'symbolic-ref', '--short', 'HEAD'), 'StarPilot')
|
||||
|
||||
def test_manual_updater_target_is_preserved(self):
|
||||
_, repo, params, _ = self.fixture()
|
||||
(params / 'UpdaterTargetBranch').write_text('dev')
|
||||
self.assertEqual(runtime.migrate(repo, params), 'manual updater selection')
|
||||
self.assertEqual((params / 'UpdaterTargetBranch').read_text(), 'dev')
|
||||
self.assertEqual(self.git(repo, 'symbolic-ref', '--short', 'HEAD'), 'Dom')
|
||||
|
||||
def test_existing_different_destination_is_not_overwritten(self):
|
||||
_, repo, params, migration = self.fixture()
|
||||
tree = self.git(repo, 'rev-parse', 'HEAD^{tree}')
|
||||
other = subprocess.check_output(['git', '-C', str(repo), '-c', 'user.name=Test', '-c',
|
||||
'user.email=test@example.invalid', 'commit-tree', tree], input=b'Other work\n').decode().strip()
|
||||
self.git(repo, 'update-ref', 'refs/heads/testing', other)
|
||||
with self.assertRaisesRegex(ValueError, 'different work'):
|
||||
runtime.migrate(repo, params)
|
||||
self.assertEqual(self.git(repo, 'rev-parse', 'refs/heads/testing'), other)
|
||||
|
||||
def test_missing_plan_is_inert(self):
|
||||
repo = self.root / 'no-plan'
|
||||
repo.mkdir()
|
||||
self.assertEqual(runtime.migrate(repo, self.root / 'no-params'), 'no plan')
|
||||
|
||||
def test_changed_target_during_migration_is_not_overwritten(self):
|
||||
_, repo, params, _ = self.fixture()
|
||||
def change(step):
|
||||
if step == 'fetch':
|
||||
(params / 'UpdaterTargetBranch').write_text('dev')
|
||||
with self.assertRaisesRegex(ValueError, 'selection changed'):
|
||||
runtime.migrate(repo, params, change)
|
||||
self.assertEqual((params / 'UpdaterTargetBranch').read_text(), 'dev')
|
||||
self.assertEqual(runtime.migrate(repo, params), 'manual updater selection')
|
||||
|
||||
def test_generator_refreshes_canonical_modern_receipt(self):
|
||||
_, repo, params, migration = self.fixture(modern=True)
|
||||
spec = importlib.util.spec_from_file_location('receipt', SCRIPTS.parent / 'openpilot/common/prebuilt_manifest.py')
|
||||
receipt = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(receipt)
|
||||
self.assertTrue(receipt.valid_receipt(lambda *args: self.git(repo, *args), 'HEAD'))
|
||||
self.assertEqual(self.git(repo, 'log', '-1', '--format=%B').splitlines(),
|
||||
[f"Branch-Migration: Dom -> testing ({migration['token']})"])
|
||||
runtime.migrate(repo, params)
|
||||
self.assert_migrated(repo, params, migration)
|
||||
|
||||
def test_local_source_edits_and_param_mode_survive(self):
|
||||
_, repo, params, _ = self.fixture()
|
||||
(repo / 'payload').write_text('local work')
|
||||
(params / 'UpdaterTargetBranch').chmod(0o640)
|
||||
runtime.migrate(repo, params)
|
||||
self.assertEqual((repo / 'payload').read_text(), 'local work')
|
||||
self.assertEqual((params / 'UpdaterTargetBranch').stat().st_mode & 0o777, 0o640)
|
||||
|
||||
def test_wrong_parent_or_title_cannot_trigger_migration(self):
|
||||
_, repo, params, _ = self.fixture()
|
||||
plan = json.loads((repo / runtime.PLAN).read_text())
|
||||
plan['parent'] = '0' * 40
|
||||
(repo / runtime.PLAN).write_text(json.dumps(plan))
|
||||
self.assertEqual(runtime.migrate(repo, params), 'not migration release')
|
||||
self.assertEqual(self.git(repo, 'symbolic-ref', '--short', 'HEAD'), 'Dom')
|
||||
|
||||
def test_pending_does_not_follow_manual_branch_switch(self):
|
||||
_, repo, params, _ = self.fixture()
|
||||
def stop(step):
|
||||
if step == 'pending':
|
||||
raise RuntimeError('interrupted')
|
||||
with self.assertRaises(RuntimeError):
|
||||
runtime.migrate(repo, params, stop)
|
||||
self.git(repo, 'checkout', '-b', 'dev')
|
||||
self.assertEqual(runtime.migrate(repo, params), 'manual branch selection')
|
||||
self.assertEqual(self.git(repo, 'symbolic-ref', '--short', 'HEAD'), 'dev')
|
||||
|
||||
def test_conflicting_pending_marker_is_not_overwritten(self):
|
||||
_, repo, params, _ = self.fixture()
|
||||
marker = repo / '.git/starpilot-branch-migration.pending'
|
||||
marker.write_text('{"different": true}')
|
||||
with self.assertRaisesRegex(ValueError, 'Another migration'):
|
||||
runtime.migrate(repo, params)
|
||||
self.assertEqual(marker.read_text(), '{"different": true}')
|
||||
|
||||
def test_old_installs_without_updater_preference_are_supported(self):
|
||||
_, repo, params, migration = self.fixture('StarPilot', 'stable')
|
||||
(params / 'UpdaterTargetBranch').unlink()
|
||||
runtime.migrate(repo, params)
|
||||
self.assert_migrated(repo, params, migration)
|
||||
|
||||
def test_generator_refuses_cross_channel_plan(self):
|
||||
with self.assertRaisesRegex(ValueError, 'Only Dom'):
|
||||
creator.prepare(self.root, 'testing', 'stable', 'HEAD', 'refs/heads/review/bad')
|
||||
|
||||
def test_malformed_plan_is_refused_without_moving_branch(self):
|
||||
_, repo, params, _ = self.fixture()
|
||||
(repo / runtime.PLAN).write_text('[]')
|
||||
with self.assertRaisesRegex(ValueError, 'Invalid channel'):
|
||||
runtime.migrate(repo, params)
|
||||
self.assertEqual(self.git(repo, 'symbolic-ref', '--short', 'HEAD'), 'Dom')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,49 @@
|
||||
import ast
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class ChannelConfigurationTest(unittest.TestCase):
|
||||
def test_old_and_new_channels_keep_ci_and_published_receipt_gate(self):
|
||||
for name in ('tests.yaml', 'safety.yaml', 'docs.yaml', 'flm-offroad.yaml', 'galaxy-phone-bridge.yaml'):
|
||||
source = (ROOT / '.github/workflows' / name).read_text().split('pull_request:', 1)[0]
|
||||
for branch in ('StarPilot', 'Dom', 'stable', 'testing', 'dev'):
|
||||
with self.subTest(workflow=name, branch=branch):
|
||||
self.assertRegex(source, rf'\b{branch}\b')
|
||||
tests = (ROOT / '.github/workflows/tests.yaml').read_text()
|
||||
guard = next(line for line in tests.splitlines() if "github.event_name == 'push' && (github.ref" in line)
|
||||
for branch in ('StarPilot', 'Dom', 'stable', 'testing', 'dev'):
|
||||
self.assertIn(f"refs/heads/{branch}'", guard)
|
||||
self.assertIn('tools/ci/check_prebuilt_receipt.py --revision HEAD', tests)
|
||||
|
||||
def test_pretty_channel_names_do_not_change_release_or_tested_policy(self):
|
||||
source = ast.parse((ROOT / 'openpilot/common/version.py').read_text())
|
||||
assignments = [node for node in source.body if isinstance(node, ast.Assign) and
|
||||
any(isinstance(target, ast.Name) and target.id in ('RELEASE_BRANCHES', 'TESTED_BRANCHES')
|
||||
for target in node.targets)]
|
||||
values = {}
|
||||
exec(compile(ast.Module(body=assignments, type_ignores=[]), '<release-policy>', 'exec'), {}, values)
|
||||
for name in ('RELEASE_BRANCHES', 'TESTED_BRANCHES'):
|
||||
self.assertTrue(set(values[name]).isdisjoint({'stable', 'testing', 'dev', 'Dom', 'StarPilot'}))
|
||||
|
||||
def test_launcher_and_updater_share_exact_legacy_pins(self):
|
||||
source = ast.parse((ROOT / 'openpilot/system/updated/updated.py').read_text())
|
||||
assignment = next(node for node in source.body if isinstance(node, ast.Assign) and
|
||||
any(isinstance(target, ast.Name) and target.id == 'TRUSTED_LEGACY_RELEASES' for target in node.targets))
|
||||
values = {}
|
||||
exec(compile(ast.Module(body=[assignment], type_ignores=[]), '<legacy-pins>', 'exec'), {}, values)
|
||||
pins = values['TRUSTED_LEGACY_RELEASES']
|
||||
launcher = (ROOT / 'launch_chffrplus.sh').read_text()
|
||||
declared = set(re.findall(r'TRUSTED_LEGACY_(?:STARPILOT_COMMIT|STABLE_MIGRATION)="([0-9a-f]{40})"', launcher))
|
||||
self.assertEqual(declared, set().union(*pins.values()))
|
||||
self.assertEqual(set(pins), {'StarPilot', 'stable'})
|
||||
self.assertEqual(len(pins['stable']), 1)
|
||||
self.assertLessEqual(pins['stable'], pins['StarPilot'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user