Files
cutdex/tool/gitea/prepare_dependencies.py
lingjhf 06f1c26681
Gitea CI / Assemble and validate CI artifacts (push) Successful in 1m47s
Gitea CI / Check code and tests (push) Successful in 7m15s
Gitea CI / Build Android APK (push) Successful in 4m6s
Gitea CI / Build Windows x64 app (push) Successful in 3m34s
Gitea CI / Audit and package Windows x64 (push) Successful in 1m29s
Gitea CI / Gitea CI passed (push) Successful in 1s
Gitea Release / Prepare draft Release (push) Failing after 8s
Gitea Release / Upload Android to draft Release (push) Skipped
Gitea Release / Upload Windows to draft Release (push) Skipped
Gitea Release / Verify and publish Release (push) Skipped
Move editor UI into the app and release verified Core dependencies (#14)
2026-10-11 19:59:40 +00:00

142 lines
7.2 KiB
Python

"""Resolve the application's verified, self-contained Core source release."""
import argparse
import hashlib
import io
import json
import os
from pathlib import Path, PurePosixPath
import posixpath
import re
import shutil
import sys
import tempfile
import zipfile
from read_dependencies import ROOT, validate_pins
from release_transport import SERVER, attachment_url, request
def verify_archive(data, pins):
validate_pins(pins)
core, native = pins['core'], pins['nativeFlutter']
artifact = core['artifact']
if not re.fullmatch(r'[a-f0-9]{64}', artifact['sha256']):
raise ValueError('Core archive must pin a complete SHA256 digest.')
if hashlib.sha256(data).hexdigest() != artifact['sha256']:
raise ValueError('Core archive SHA256 does not match the application dependency lock.')
prefix = f"cutdex-core-{core['version']}/"
if artifact['file'] != f"cutdex-core-{core['version']}.zip" or core.get('ref') != 'v' + core['version']:
raise ValueError('Core archive must refer to the exact recorded release version.')
with zipfile.ZipFile(io.BytesIO(data)) as archive:
names = archive.namelist()
if len(names) != len(set(names)):
raise ValueError('Duplicate Core archive paths.')
for item in archive.infolist():
path = PurePosixPath(item.filename)
if not item.filename.startswith(prefix) or '..' in path.parts or ':' in item.filename or '\\' in item.filename:
raise ValueError('Unsafe Core archive path.')
if (item.external_attr >> 16) & 0o170000 == 0o120000:
target = archive.read(item).decode()
resolved = posixpath.normpath(posixpath.join(str(path.parent), target))
if target.startswith('/') or '\\' in target or ':' in target or not resolved.startswith(prefix):
raise ValueError('Core symlink escapes its source directory.')
manifest = json.loads(archive.read(prefix + 'RELEASE.json'))
if manifest['version'] != core['version'] or manifest['source_commit'] != core['revision']:
raise ValueError('Core release manifest differs from the recorded commit/version.')
bundled = manifest['native_flutter']
if bundled['version'] != native['version'] or bundled['source_commit'] != native['revision'] or bundled['path'] != 'native_flutter':
raise ValueError('Bundled native Flutter differs from the recorded release commit/version.')
for package, version in (('', core['version']), ('native_flutter/', native['version'])):
text = archive.read(prefix + package + 'pubspec.yaml').decode()
if re.search(r'^version:\s*(\S+)\s*$', text, re.M)[1] != version:
raise ValueError('Bundled package version differs from release metadata.')
platform_pins = json.loads(archive.read(prefix + 'native_flutter/native-dependencies.json'))
if bundled['platform_dependencies'] != platform_pins:
raise ValueError('Bundled platform pins differ from release metadata.')
core_pin = json.loads(archive.read(prefix + 'native-flutter-dependency.json'))
if (core_pin['revision'] != native['revision'] or core_pin['version'] != native['version']
or core_pin['repository'] != native['repository']):
raise ValueError('Core native Flutter pin differs from the application release pin.')
return prefix, manifest
def extract_archive(data, prefix, destination):
"""Materialize internal aliases as copies, including on Windows without symlink privileges."""
links = []
with zipfile.ZipFile(io.BytesIO(data)) as archive:
for item in archive.infolist():
relative = PurePosixPath(item.filename).relative_to(PurePosixPath(prefix))
path = destination.joinpath(*relative.parts)
if item.is_dir():
path.mkdir(parents=True, exist_ok=True)
elif (item.external_attr >> 16) & 0o170000 == 0o120000:
target = posixpath.normpath(posixpath.join(str(relative.parent), archive.read(item).decode()))
links.append((path, destination.joinpath(*PurePosixPath(target).parts)))
else:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(archive.read(item))
path.chmod((item.external_attr >> 16) & 0o777 or 0o644)
for path, target in links:
if not target.exists():
raise ValueError('Core archive alias target is missing.')
path.parent.mkdir(parents=True, exist_ok=True)
if target.is_dir():
shutil.copytree(target, path)
else:
shutil.copy2(target, path)
def release_archive(pins):
core = pins['core']
release = request(f"{SERVER}/api/v1/repos/{core['repository']}/releases/tags/{core['ref']}")
if release.get('draft') or release.get('prerelease') or release['tag_name'] != core['ref']:
raise ValueError('Core dependency must be a published stable release.')
assets = [asset for asset in release['assets'] if asset['name'] == core['artifact']['file']]
if len(assets) != 1:
raise ValueError('Expected exactly one Core release source archive.')
return request(attachment_url(assets[0]))
def prepare(pins, root=ROOT):
validate_pins(pins)
cache_root = Path(os.environ.get('CUTDEX_CORE_ARCHIVE_CACHE', Path.home() / '.cache/cutdex/core'))
cache_root.mkdir(parents=True, exist_ok=True)
digest = pins['core']['artifact']['sha256']
archive_path = cache_root / (digest + '.zip')
data = archive_path.read_bytes() if archive_path.is_file() else release_archive(pins)
prefix, manifest = verify_archive(data, pins)
if not archive_path.is_file():
with tempfile.NamedTemporaryFile(dir=cache_root, delete=False) as stream:
temporary_archive = Path(stream.name)
stream.write(data)
temporary_archive.replace(archive_path)
dependencies = root / '.dependencies'
dependencies.mkdir(exist_ok=True)
destination = dependencies / 'cutdex_core'
if destination.is_symlink() or (destination / '.git').exists():
raise ValueError('Core source checkout is for development; use the local dependency overrides.')
if destination.exists() and not (destination / 'RELEASE.json').is_file():
raise ValueError('Refusing to replace an unmanaged Core directory.')
with tempfile.TemporaryDirectory(prefix='core-release-', dir=dependencies) as directory:
staged = Path(directory) / 'cutdex_core'
staged.mkdir()
extract_archive(data, prefix, staged)
if destination.exists():
shutil.rmtree(destination)
staged.rename(destination)
print(f"Prepared Core {manifest['version']} with native Flutter {manifest['native_flutter']['version']}; archive SHA256 verified.")
def main():
argparse.ArgumentParser(description=__doc__).parse_args()
os.environ['GITEA_TOKEN'] = os.environ.get('CUTDEX_GITEA_TOKEN', os.environ.get('GITEA_TOKEN', ''))
prepare(json.loads((ROOT / 'dependencies.json').read_text()))
if __name__ == '__main__':
try:
main()
except (ValueError, OSError, KeyError, zipfile.BadZipFile) as error:
print(f'Core dependency preparation failed: {error}', file=sys.stderr)
sys.exit(1)