Files
breeze/scripts/prepare-package-assets.py
T

153 lines
7.8 KiB
Python

#!/usr/bin/env python3
"""Stage deterministic package resources, keeping large practice art in Practices."""
from pathlib import Path
import argparse
import json
import shutil
import zipfile
import os
import hashlib
import re
from animation_inventory import inventory
from achievement_icons import icon_shape
from practice_media import MEDIA, PREFIX
ROOT = Path(__file__).resolve().parent.parent
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', default='build/package-assets',
help='Build directory for staged package assets')
parser.add_argument('--apps-controller', type=Path, default=ROOT / 'build/apps-ui/apps.zx',
help='Reviewed Apps controller to include in the root package')
options = parser.parse_args()
OUTPUT = (ROOT / options.output).resolve()
if not OUTPUT.is_relative_to(ROOT / 'build') or OUTPUT == ROOT / 'build':
parser.error('output must be a directory below the project build directory')
_, _, unique_animation = inventory()
unique_animation = set(unique_animation)
# Apps the node offers each keep their assets/<name>/ in their own package.
NODE_APPS = tuple(sorted(json.loads((ROOT / 'apps/versions.json').read_text()).get('node_apps', {})))
if OUTPUT.exists():
shutil.rmtree(OUTPUT)
for name in ('inbe', 'lists', 'habits', 'practices', 'diary', 'lumi', 'leaderboard',
'practice-whm', 'practice-meditation', 'practice-sunsalutation',
'practice-patterns', 'practice-taichi', 'practice-astral_projection',
'practice-workout') + NODE_APPS:
(OUTPUT / name / 'assets').mkdir(parents=True)
patterns = (
'assets/mcp/*.json', 'assets/app/icon.webp', 'assets/app/icon-sky-cradle.webp',
'assets/app/icon-ink-and-air.webp', 'assets/easteregg/*.png', 'assets/easteregg/*.webp', 'assets/pet/*.png',
'assets/apps/icons/*.png',
'assets/social/*.png', 'assets/social/*.webp',
'assets/sounds/*.ogg',
'assets/habits/**/*', 'assets/lists/**/*', 'assets/diary/**/*', 'assets/lumi/**/*',
'assets/fonts/subset/*-App-Regular.*', 'assets/styles/*.kss',
'locales/*.txt', 'themes/catalog_*.kss',
'build/packages/kss/styles/*.kss', 'build/packages/kryon/icons/ui.png',
'build/packages/kryon/icons/pfp.png',
) + tuple(f'assets/{name}/**/*' for name in NODE_APPS)
# The practice media comes from the practices package and is packaged
# under assets/practices/.
practice_patterns = (
'whm/1.png', 'whm/2.png', 'meditation/1.png', '*/banner-light.png', '*/banner-dark.png',
'sunsalutation/characters/*/*.png', 'sunsalutation/flat-edge.png',
'sunsalutation/voice/**/*', 'sunsalutation/voice-male/**/*',
'astral_projection/**/*', 'workout/**/*', 'taichi/**/*', 'guide/voice/**/*',
)
sources = {p: p.relative_to(ROOT).as_posix()
for pattern in patterns for p in ROOT.glob(pattern) if p.is_file()}
sources.update({p: PREFIX + p.relative_to(MEDIA).as_posix()
for pattern in practice_patterns for p in MEDIA.glob(pattern) if p.is_file()})
if not any(path.startswith(PREFIX) for path in sources.values()):
raise SystemExit(f'no practice media in {MEDIA}; run make packages')
for file, path in sorted(sources.items(), key=lambda source: source[1]):
if '-prompt.' in file.name:
continue
if '/sunsalutation/characters/' in path and file not in unique_animation:
continue
owner = 'inbe'
if path.startswith(('assets/practices/', 'assets/sounds/')):
owner = 'practices'
# Each practice's pictures ship only in its pack. Its banners ship with
# Practices, whose tabs show every practice before it is downloaded.
if path.startswith('assets/practices/') and '/banner-' not in path:
practice = path.split('/')[2]
owner = 'practice-' + practice
if '/voice/' in path:
code = path.split('/voice/', 1)[1].split('/')[0]
owner += '-voice-' + code
elif '/voice-male/' in path:
# The male recording is its own pack per language.
code = path.split('/voice-male/', 1)[1].split('/')[0]
owner += '-voice-' + code + '-male'
for feature in ('habits', 'lists', 'diary', 'lumi') + NODE_APPS:
if path.startswith('assets/' + feature + '/'):
owner = feature
for prefix in ('build/packages/kss/', 'build/packages/kryon/'):
if path.startswith(prefix):
path = path.removeprefix(prefix)
target = OUTPUT / owner / path
target.parent.mkdir(parents=True, exist_ok=True)
if path == 'assets/practices/taichi/course.tch':
# Keep the exported data exact; only its packaged representation is
# compressed. Fixed metadata makes repeated builds byte-identical.
member = zipfile.ZipInfo('course.tch', (1980, 1, 1, 0, 0, 0))
member.create_system = 3
member.compress_type = zipfile.ZIP_DEFLATED
member.external_attr = 0o644 << 16
with zipfile.ZipFile(target.with_suffix('.zip'), 'w') as archive:
archive.writestr(member, file.read_bytes(), compresslevel=9)
continue
shutil.copyfile(file, target)
# Catalog outlines are small metadata, available before an app is installed.
# The app retains its own copy for standalone and embedded use.
for name in NODE_APPS:
source = ROOT / 'assets' / name / 'sidebar.shape'
if source.is_file():
destination = OUTPUT / 'inbe/assets/apps/icons' / (name + '.shape')
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, destination)
# Root launcher cards share the reviewed Apps controller. The host reads it
# from its own apps.zx asset beside the root package, so the root package
# does not carry a second copy. A node-only build can omit it.
apps_bundle = options.apps_controller.resolve()
if apps_bundle.is_file():
controller = apps_bundle.read_bytes()
source = (ROOT / 'src/apps/apps_controller.zi').read_text()
expected = re.search(r'AppsControllerSha256\s*::\s*"([0-9a-f]{64})"', source)
if not expected or hashlib.sha256(controller).hexdigest() != expected[1]:
raise SystemExit('Apps controller differs from the reviewed native digest')
# Each app owns its bounded achievement catalog and translations, including
# optional node apps. Source presence never determines device visibility.
for catalog in sorted((ROOT / 'apps').glob('*/achievements.json')):
source_name = catalog.parent.name
owner = 'practices' if source_name == 'practice' else source_name
resource_name = 'app' if owner == 'inbe' else owner
destination = OUTPUT / owner / 'assets' / resource_name
destination.mkdir(parents=True, exist_ok=True)
shutil.copyfile(catalog, destination / 'achievements.json')
icons = destination / 'icons'
icons.mkdir(parents=True, exist_ok=True)
for achievement in json.loads(catalog.read_text())['achievements']:
shape = icon_shape(ROOT / 'build/packages/mingcute', achievement['icon_source'])
(icons / (achievement['id'] + '.shape')).write_text(shape)
shutil.copyfile(ROOT / 'build/packages/mingcute/LICENSE', icons / 'LICENSE')
for translation in sorted((catalog.parent / 'achievement-locales').glob('*.json')):
target = destination / 'achievement-locales' / translation.name
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(translation, target)
# Diary's own translations travel with its bundle for other harnesses and
# the generic player; it does not need the Inner Breeze root package.
for locale in sorted((ROOT / 'locales').glob('*.txt')):
entries = []
for block in locale.read_text().split('---\n'):
first = block.splitlines()[0] if block.splitlines() else ''
if first.startswith(('[diary_', '[tab_diary', '[habit_day_', '[habit_month_')):
entries.append(block.rstrip() + '\n---\n')
target = OUTPUT / 'diary/locales' / locale.name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(''.join(entries))