Files
booksprite/booksprite/build.py
T
Shelley e04b22b359
macos / macOS 15 x86-64 🔨16.4 🎯10.15 (push) Canceled after 0s
macos / macOS 15 ARM64 🔨16.4 🎯11.0 (push) Canceled after 0s
Introduce BookSprite with isolated Kobo install, verified OTA and snapshot recovery
Co-authored-by: Shelley <shelley@exe.dev>
2026-10-30 20:03:54 +00:00

131 lines
6.1 KiB
Python
Executable File

#!/usr/bin/env python3
"""Reproducible Lua-overlay build using verified official KOReader ARM binaries."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import shutil
import stat
import subprocess
import tarfile
import urllib.request
import zipfile
ROOT = Path(__file__).resolve().parent.parent
HERE = ROOT / 'booksprite'
UPSTREAM_TAG = 'v2026.07.1'
UPSTREAM_ZIP = 'https://github.com/koreader/koreader/releases/download/v2026.07.1/koreader-kobo-v2026.07.1.zip'
UPSTREAM_SHA256 = '0f36a62ce73b12516f969e4ad7862cc06920afb03c7bd4db29a0d990bdd84b2f'
RELEASE_BASE = 'https://gitea.jameshall.xyz/exe.dev/booksprite/releases/download'
OVERLAY = [
'frontend/ui/otamanager.lua',
'frontend/ui/elements/common_info_menu_table.lua',
'frontend/ui/elements/common_exit_menu_table.lua',
'frontend/apps/filemanager/filemanager.lua',
]
EPOCH = 1793318400 # 2026-10-30 00:00 UTC, fixed for deterministic archive metadata.
def sha256(path):
h = hashlib.sha256()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(1024 * 1024), b''):
h.update(chunk)
return h.hexdigest()
def build(source_zip=None):
version = (HERE / 'VERSION').read_text().strip()
if not __import__('re').fullmatch(r'\d+\.\d+\.\d+', version):
raise ValueError('VERSION must be major.minor.patch')
work = HERE / 'build'
out = HERE / 'dist'
work.mkdir(exist_ok=True)
out.mkdir(exist_ok=True)
source_zip = Path(source_zip) if source_zip else work / f'upstream-{UPSTREAM_TAG}.zip'
if not source_zip.exists():
urllib.request.urlretrieve(UPSTREAM_ZIP, source_zip)
if sha256(source_zip) != UPSTREAM_SHA256:
raise ValueError('Upstream ZIP checksum mismatch')
stage = work / 'usb'
if stage.exists():
shutil.rmtree(stage)
app = stage / '.adds/booksprite/koreader'
app.mkdir(parents=True)
with zipfile.ZipFile(source_zip) as z:
for info in z.infolist():
if not info.filename.startswith('koreader/') or info.is_dir():
continue
rel = Path(info.filename).relative_to('koreader')
if '..' in rel.parts or rel.is_absolute():
raise ValueError('Unsafe upstream ZIP')
dest = app / rel
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(z.read(info))
os.chmod(dest, (info.external_attr >> 16) & 0o777 or 0o644)
for rel in OVERLAY:
shutil.copyfile(ROOT / rel, app / rel)
shutil.copyfile(ROOT / 'platform/kobo/koreader.sh', app / 'koreader.sh')
os.chmod(app / 'koreader.sh', 0o755)
(app / 'booksprite-version').write_text(version + '\n')
shutil.copyfile(HERE / 'README.md', app / 'BOOKSPRITE.md')
shutil.copyfile(HERE / 'INSTALL.txt', app / 'BOOKSPRITE-INSTALL.txt')
# No upstream updater metadata or unexpected leftover update is ever shipped.
shutil.rmtree(app / 'ota')
(app / 'ota').mkdir()
receipt = dict(name='BookSprite', version=version, upstream_tag=UPSTREAM_TAG,
upstream_zip=UPSTREAM_ZIP, upstream_sha256=UPSTREAM_SHA256,
upstream_commit=subprocess.check_output(['git', 'rev-list', '-n', '1', UPSTREAM_TAG], cwd=ROOT, text=True).strip(),
source_commit=subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip(),
source_url='https://gitea.jameshall.xyz/exe.dev/booksprite', target='kobo')
(app / 'booksprite-build.json').write_text(json.dumps(receipt, indent=2) + '\n')
tracked = sorted([str(p.relative_to(app)) for p in app.rglob('*') if p.is_file()] + ['booksprite-files.txt'])
(app / 'booksprite-files.txt').write_text('\n'.join(tracked) + '\n')
launcher = stage / '.adds/booksprite/launch.sh'
shutil.copyfile(HERE / 'launch.sh', launcher)
os.chmod(launcher, 0o755)
nm = stage / '.adds/nm/booksprite'
nm.parent.mkdir(parents=True)
shutil.copyfile(HERE / 'nickelmenu.conf', nm)
shutil.copyfile(HERE / 'INSTALL.txt', stage / 'BOOKSPRITE-INSTALL.txt')
archive = out / f'booksprite-kobo-v{version}.tar.gz'
# Stable gzip metadata + tar ordering and numeric owners.
import gzip
with open(archive, 'wb') as raw, gzip.GzipFile(filename='', mode='wb', fileobj=raw, mtime=EPOCH) as gz:
with tarfile.open(fileobj=gz, mode='w', format=tarfile.USTAR_FORMAT) as tar:
for path in sorted(app.rglob('*')):
info = tar.gettarinfo(str(path), 'koreader/' + str(path.relative_to(app)))
info.uid = info.gid = 0
info.uname = info.gname = ''
info.mtime = EPOCH
if path.is_file():
with path.open('rb') as f:
tar.addfile(info, f)
else:
tar.addfile(info)
usb = out / f'booksprite-kobo-v{version}-usb.zip'
import datetime
date_time = datetime.datetime.fromtimestamp(EPOCH, datetime.timezone.utc).timetuple()[:6]
with zipfile.ZipFile(usb, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as z:
for path in sorted(stage.rglob('*')):
if path.is_file():
info = zipfile.ZipInfo(str(path.relative_to(stage)), date_time)
info.external_attr = (stat.S_IFREG | stat.S_IMODE(path.stat().st_mode)) << 16
info.compress_type = zipfile.ZIP_DEFLATED
z.writestr(info, path.read_bytes())
manifest = dict(version=version, target='kobo', url=f'{RELEASE_BASE}/booksprite-v{version}/{archive.name}',
sha256=sha256(archive), size=archive.stat().st_size)
(out / 'stable.json').write_text(json.dumps(manifest, indent=2) + '\n')
sums = ''.join(f'{sha256(p)} {p.name}\n' for p in [usb, archive])
(out / 'SHA256SUMS').write_text(sums)
(out / 'provenance.json').write_text(json.dumps(receipt, indent=2) + '\n')
print(json.dumps(dict(usb=str(usb), ota=str(archive), manifest=manifest), indent=2))
return usb, archive
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--upstream-zip', help='Use a local, checksum-verified upstream ZIP')
build(parser.parse_args().upstream_zip)