#!/usr/bin/env python3"""Give an iPhone flavour only the painted pictures it carries. python3 scripts/ios-flavour-pictures.py (a build phase of every app target) python3 scripts/ios-flavour-pictures.py --list <flavour> (the names it would carry, one a line)WHY. Loom's catalogue (apps/loom/Sources/CottonPaper/Media.xcassets) is everyapp's pictures: trips' wallets, the amps, the cassettes, the cheques. SwiftPMcompiles it whole into `Loom_CottonPaper.bundle/Assets.car`, so Books build 11carried 105 MB of other apps' pictures (14 Nov 2026), where Books on Androidcarries its own ~10 MB. SwiftPM cannot vary a package's resources by the appthat links it, so this phase, run after the bundle is copied into the app,compiles the flavour's own catalogue and puts it in the bundle's place.WHAT A FLAVOUR CARRIES is apps/loom/materials.json, the one list the Androidbuild reads too (apps/android/app/build.gradle.kts): `everyApp`, the iPhoneshell's own (`iphoneShell`) and the app's list under `apps`. A flavour with nolist there carries the whole catalogue and this phase leaves its bundle alone.A name that is no imageset stops the build. The names left out are writtenbeside the catalogue (`left-out-pictures.json`), and a debug build stops at thedraw of any of them (`CottonMedia.image`), naming it: a picture a flavour drawsand does not carry is a crash in a walk or a test, never an empty hole.The palette (`Generated/Palette.xcassets`) is compiled into the same Assets.caras SwiftPM does (the package's two `.process` catalogues), with the flagsXcode's own CompileAssetCatalog step passes for the bundle, so every picturekept is the same compiled picture as before."""from __future__ import annotationsimport hashlibimport jsonimport osimport shutilimport subprocessimport sysfrom pathlib importPathROOT = Path(__file__).resolve().parent.parentPAPER = ROOT / "apps/loom/Sources/CottonPaper"CATALOGUE = PAPER / "Media.xcassets"PALETTE = PAPER / "Generated/Palette.xcassets"MATERIALS = ROOT / "apps/loom/materials.json"BUNDLE = "Loom_CottonPaper.bundle"LEFT_OUT = "left-out-pictures.json"def fail(message: str) -> None: print(f"error: ios-flavour-pictures: {message}", file=sys.stderr) sys.exit(1)def imagesets() -> list[str]:return sorted(p.name.removesuffix(".imageset") for p in CATALOGUE.iterdir() if p.name.endswith(".imageset"))def expand(names: list[str], owner: str, every: list[str]) -> list[str]: found: list[str] = []for name in names:if name.endswith("*"): hits = [n for n in every if n.startswith(name[:-1])]else: hits = [n for n in every if n == name]ifnot hits: fail(f"apps/loom/materials.json: {owner} names {name}, which is no imageset of Loom's Media.xcassets") found += hitsreturn founddef carried(flavour: str) -> list[str] | None:"""The imagesets `flavour` carries, or None when it carries the whole catalogue.""" lists = json.loads(MATERIALS.read_text()) own = lists["apps"].get(flavour)if own isNone:returnNone every = imagesets() names = expand(lists["everyApp"], "everyApp", every) + expand(lists["iphoneShell"], "iphoneShell", every) + expand(own, flavour, every)return sorted(set(names))def link_tree(source: Path, target: Path) -> None:"""`source` copied to `target` by hard links (same volume) or by copies.""" target.mkdir(parents=True)for entry in source.iterdir():if entry.is_dir(): link_tree(entry, target / entry.name)else:try: os.link(entry, target / entry.name)except OSError: shutil.copy2(entry, target / entry.name)def compile_catalogue(names: list[str], work: Path, env: dict[str, str]) -> Path:"""The flavour's Assets.car, compiled once per set of pictures and kept in `work`.""" digest = hashlib.sha256()for name in names: imageset = CATALOGUE / f"{name}.imageset"for file in sorted(imageset.iterdir()): stat = file.stat() digest.update(f"{name}/{file.name}:{stat.st_size}:{stat.st_mtime_ns}\n".encode())for file in sorted(PALETTE.rglob("*")):if file.is_file(): digest.update(f"palette/{file.relative_to(PALETTE)}:{file.stat().st_size}:{file.stat().st_mtime_ns}\n".encode()) platform = env.get("PLATFORM_NAME", "iphoneos") floor = env.get("IPHONEOS_DEPLOYMENT_TARGET", "26.0") digest.update(f"{platform}:{floor}".encode()) kept = work / digest.hexdigest()[:16] car = kept / "out/Assets.car"if car.is_file():return carif work.exists(): shutil.rmtree(work) media = kept / "Media.xcassets" media.mkdir(parents=True) shutil.copy2(CATALOGUE / "Contents.json", media / "Contents.json")for name in names: link_tree(CATALOGUE / f"{name}.imageset", media / f"{name}.imageset") (kept / "out").mkdir() command = ["xcrun", "actool","--output-format", "human-readable-text", "--notices", "--warnings","--output-partial-info-plist", str(kept / "partial.plist"),"--compress-pngs","--enable-on-demand-resources", "NO","--development-region", "en","--target-device", "iphone", "--target-device", "ipad","--minimum-deployment-target", floor,"--platform", platform,"--compile", str(kept / "out"), str(PALETTE), str(media), ] run = subprocess.run(command, capture_output=True, text=True)if run.returncode != 0ornot car.is_file(): fail(f"actool failed ({run.returncode}):\n{run.stdout}\n{run.stderr}")return cardef build_phase() -> None: env = dict(os.environ) app = Path(env["TARGET_BUILD_DIR"]) / env["UNLOCALIZED_RESOURCES_FOLDER_PATH"] manifest = app / "flavour.json"ifnot manifest.is_file(): fail(f"{manifest} is not in the app: the flavour's manifest rides in every app target") flavour = json.loads(manifest.read_text())["flavour"] bundle = app / BUNDLEifnot bundle.is_dir(): fail(f"{bundle} is not in the app: this phase runs after the package's bundle is copied") names = carried(flavour) left_out = bundle / LEFT_OUTif names isNone:# Whole: SwiftPM's own Assets.car stands. A list from an earlier build of# this flavour (one that had a list) goes with it. left_out.unlink(missing_ok=True) print(f"ios-flavour-pictures: {flavour} carries the whole catalogue (no list in apps/loom/materials.json)")return car = compile_catalogue(names, Path(env["DERIVED_FILE_DIR"]) / "flavour-pictures", env) target = bundle / "Assets.car" target.unlink(missing_ok=True) shutil.copy2(car, target) every = imagesets() gone = sorted(set(every) - set(names)) left_out.write_text(json.dumps(gone, indent=0) + "\n") print(f"ios-flavour-pictures: {flavour} carries {len(names)} of {len(every)} pictures ({target.stat().st_size / 1e6:.1f} MB)")def main() -> None:if len(sys.argv) == 3and sys.argv[1] == "--list": names = carried(sys.argv[2]) print("\n".join(names if names isnotNoneelse imagesets()))returnif len(sys.argv) != 1: fail("usage: ios-flavour-pictures.py [--list <flavour>]") build_phase()if __name__ == "__main__": main()