#!/usr/bin/env python3"""Write Loom's face registry from the face files.Every face is one file under `apps/loom/Sources/CottonFaces/<App>/`, in itsapp's folder (Cotton, Sharmila, Nancy, Rigby, Shared), declaring its faceonce, beside the view, in the face's catalogue entry (an enum, since ageneric face can hold no static of its own) or an extension of the face,with the stock it is printed on (`FaceStock`), which its body lays(`.onCardPaper(PhotoFaceCatalogue.stock.laid(card.pace))`), and the ground itlies on (`FaceGround`: the paper ground, or a ground of its own, as thecassette lies on the music's felt, the split-flap board on thecalendar's baize, the torn page on the notebook's linen, the index card'stray on the todos' steel, the rolodex on the people's blue felt, thevideo's sleeve on the films' claret baize, a lab print on the Photostool's bookcloth and a till receipt on the money's navy felt, a show'sradio on the podcasts' oxblood felt, a standing hardback and ahighlight's paper card on the books' navy felt, a hi-fi deck on themusic's black tolex, the party's turntable on its dance floor, and afilm's one-sheet in its lobby frame on the Picture House's velvet): public enum PhotoFaceCatalogue { public static let stock: FaceStock = .framed public static let ground: FaceGround = .paper public static let face = Face(id: "photo", specimens: [...]) { card, picture, taps in ... } }The registry keeps each face's stock and ground by its id(`FaceRegistry.stock(_:)`, `FaceRegistry.ground(_:)`), so whatever stacks acard lays the sheets under it, and whatever stands it on a screen lays theground behind it, before the card is drawn.From those declarations this writes, sorted by id so two lanes adding facesnever conflict in them: apps/loom/Sources/CottonFaces/Generated/FaceRegistry.swift the lookup by id, each face's stock and ground apps/loom/faces.json id, app folder, file apps/loom/faces-pending.json the faces CottonUI still draws crates/cotton-core/src/definitions/face_ids.json every id a kit may nameA face id is the open id a kit names in `card.face`: lowercase words ofletters, digits and `_`, each a letter first, joined by `.` (`todo`,`kitchen.dish`). The ids a kit may name are faces.json's andfaces-pending.json's: the core refuses any other when a definition isauthored (`card::FaceId`), and so does the Worker (`apps/business/src/faces.ts`).faces-pending.json is written by hand only to add a face CottonUI draws thathas not moved; a face that moves into Loom leaves it here, when its file isgenerated into faces.json. IT DIES WHEN THE LAST FACE MOVES: once it is `[]`,delete the file, `PENDING` and `pending()` below, and the core's ids arefaces.json's alone. python3 scripts/gen-faces-registry.py write them python3 scripts/gen-faces-registry.py --check fail when any is staleGuards: `scripts/__tests__/faces-registry.test.ts` runs `--check`;`scripts/__tests__/kit-faces.test.ts` holds every kit to the known ids."""import jsonimport pathlibimport reimport sysROOT = pathlib.Path(__file__).resolve().parent.parentFACES = ROOT / 'apps/loom/Sources/CottonFaces'REGISTRY = FACES / 'Generated/FaceRegistry.swift'CATALOGUE = ROOT / 'apps/loom/faces.json'PENDING = ROOT / 'apps/loom/faces-pending.json'KNOWN = ROOT / 'crates/cotton-core/src/definitions/face_ids.json'APPS = ('Cotton', 'Sharmila', 'Nancy', 'Rigby', 'Shared')FACE_ID = re.compile(r'[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*')DECLARATION = re.compile(r'static\s+let\s+face\s*=\s*Face\(\s*id:\s*"([^"]+)"')OWNER = re.compile(r'^(?:public\s+)?(?:extension|enum)\s+(\w+)\b', re.M)STOCK = re.compile(r'static\s+let\s+stock\s*:\s*FaceStock\s*=\s*\.(\w+)\b')STOCKS = ('cream', 'ornamented', 'framed', 'pace', 'own')GROUND = re.compile(r'static\s+let\s+ground\s*:\s*FaceGround\s*=\s*\.(\w+)\b')GROUNDS = ('paper', 'felt', 'claret', 'bookcloth', 'feltNavy', 'tolex', 'partyFloor', 'velvet', 'kitchenTile', 'amethystDesk', 'pegboard', 'roseLinen', 'feltOrange', 'baizeTeal', 'terrazzo', 'tealLeather', 'checker', 'deskMat', 'formicaCounter', 'darkroomBench', 'bedsideTable', 'cobaltEnamel', 'leatherDesk', 'slate', 'blank')LAYS = re.compile(r'\.onCardPaper\(([^\n]*)\)')LAID = re.compile(r'\b(\w+)\.stock\b')def code(source):"""The source with comments blanked, so a face named in prose is not a face.""" source = re.sub(r'/\*.*?\*/', lambda m: re.sub(r'[^\n]', ' ', m.group(0)), source, flags=re.S)return re.sub(r'//[^\n]*', '', source)def faces(root=FACES):"""Every declared face as (id, type, app, file, stock, ground), sorted by id; a broken rule raises.""" found, problems = [], []for app in APPS:for path in sorted((root / app).glob('**/*.swift')): relative = path.relative_to(root).as_posix() text = code(path.read_text()) ids = DECLARATION.findall(text)ifnot ids:continueif len(ids) > 1: problems.append(f'{relative} declares {len(ids)} faces: one file per face')continue at = DECLARATION.search(text).start() owners = [m for m in OWNER.finditer(text) if m.start() < at]ifnot owners: problems.append(f'{relative} declares its face outside an `enum <Face>Catalogue {{ … }}` or `extension <Face> {{ … }}`')continue owner = owners[-1]def beside(pattern, owner=owner, text=text):"""`pattern`'s declarations in the face's own catalogue entry or extension."""return [m for m in pattern.finditer(text)if [o.start() for o in OWNER.finditer(text) if o.start() < m.start()][-1:] == [owner.start()]] stocks = beside(STOCK)if len(stocks) != 1: problems.append(f'{relative} declares {len(stocks)} stocks beside its face in `{owner.group(1)}`: one `static let stock: FaceStock = .<{"|".join(STOCKS)}>`')continueif stocks[0].group(1) notin STOCKS: problems.append(f'{relative} declares stock .{stocks[0].group(1)}: a face is printed on {", ".join(STOCKS)}')continue grounds = beside(GROUND)if len(grounds) != 1: problems.append(f'{relative} declares {len(grounds)} grounds beside its face in `{owner.group(1)}`: one `static let ground: FaceGround = .<{"|".join(GROUNDS)}>`')continueif grounds[0].group(1) notin GROUNDS: problems.append(f'{relative} declares ground .{grounds[0].group(1)}: a face lies on {", ".join(GROUNDS)}')continue found.append((ids[0], owner.group(1), app, relative, stocks[0].group(1), grounds[0].group(1)))for path in sorted(root.glob('**/*.swift')): relative = path.relative_to(root).as_posix()if relative.split('/')[0] notin APPS and DECLARATION.search(code(path.read_text())): problems.append(f'{relative} declares a face outside an app folder ({", ".join(APPS)})') laid = {owner for path in sorted(root.glob('**/*.swift'))for call in LAYS.findall(code(path.read_text())) for owner in LAID.findall(call)}for _, owner, _, relative, stock, _ in found: lays = LAYS.search(code((root / relative).read_text()))if stock == 'own'and lays: problems.append(f'{relative} declares stock .own but lays paper: a face that draws its own sheet calls no `.onCardPaper`')if stock != 'own'and owner notin laid: problems.append(f'{relative} declares stock .{stock} but nothing lays it: its body lays `.onCardPaper({owner}.stock.laid(card.pace))`') seen = {}for face_id, _, _, relative, _, _ in found:ifnot FACE_ID.fullmatch(face_id): problems.append(f'{relative} declares face id "{face_id}": an id is lowercase words of letters, digits and _, each a letter first, joined by .')if face_id in seen: problems.append(f'face id "{face_id}" is declared twice: {seen[face_id]} and {relative}') seen[face_id] = relativeif problems:raiseSystemExit('gen-faces-registry:\n ' + '\n '.join(problems))return sorted(found)def render_registry(found): lines = ['// Generated by scripts/gen-faces-registry.py from the face files — never edit','// by hand: add a face file under its app\'s folder and run `pnpm gen:faces`.','','import CottonValues','','public enum FaceRegistry {',' /// Every face this build draws, by id.',' @MainActor public static let all: [Face] = [', *[f' {type_name}.face,'for _, type_name, _, _, _, _ in found],' ]','',' /// The id of every face in `all`, read off the main actor: whether this',' /// build draws a kit\'s face is asked where no face is drawn.',' public static let ids: Set<String> = [', *[f' "{face_id}",'for face_id, _, _, _, _, _ in found],' ]','',' /// The stock the face a kit names by `id` is printed on, as its file',' /// declares it (`static let stock`), or nil when this build has no face',' /// by that id: whatever stacks a card lays the sheets under it from',' /// here, before the card is drawn.',' public static func stock(_ id: String) -> FaceStock? {',' stocks[id]',' }','',' private static let stocks: [String: FaceStock] = [', *[f' "{face_id}": .{stock},'for face_id, _, _, _, stock, _ in found],' ]','',' /// The ground the face a kit names by `id` lies on, as its file declares',' /// it (`static let ground`), or nil when this build has no face by that',' /// id: whatever stands a card on a screen lays the ground behind it from',' /// here, before the card is drawn.',' public static func ground(_ id: String) -> FaceGround? {',' grounds[id]',' }','',' private static let grounds: [String: FaceGround] = [', *[f' "{face_id}": .{ground},'for face_id, _, _, _, _, ground in found],' ]','',' /// The offered faces’ spoken titles, resolved from the kit; every face a',' /// table offers has one (guard: `every_offered_face_has_a_title`), so a raw',' /// face id is never said.',' public static func title(_ id: String) -> String {',' ShellLines.line("cards", ["faces", "titles", id.replacingOccurrences(of: ".", with: "_")].joined(separator: "."))',' }',' /// The face a kit names by `id`, or nil when this build has none by that id.',' @MainActor public static func face(_ id: String) -> Face? {',' byID[id]',' }','',' @MainActor private static let byID = Dictionary(uniqueKeysWithValues: all.map { ($0.id, $0) })','}','', ]return'\n'.join(lines)def render_catalogue(found): rows = [{'id': face_id, 'app': app, 'file': f'Sources/CottonFaces/{relative}'} for face_id, _, app, relative, _, _ in found]return json.dumps(rows, indent=2) + '\n'def pending(found, held):"""The pending ids as they stand: `held` less every id that has moved, sorted; a bad id raises.""" bad = [face_id for face_id in held ifnot isinstance(face_id, str) ornot FACE_ID.fullmatch(face_id)]if bad:raiseSystemExit(f'gen-faces-registry: faces-pending.json holds ids that are not face ids: {bad}') moved = {face_id for face_id, _, _, _, _, _ in found}return sorted(set(held) - moved)def render_ids(ids):return json.dumps(ids, indent=2) + '\n'def outputs(root=FACES, pending_path=PENDING): found = faces(root) waiting = pending(found, json.loads(pending_path.read_text()) if pending_path.exists() else []) known = sorted({face_id for face_id, _, _, _, _, _ in found} | set(waiting))return { REGISTRY: render_registry(found), CATALOGUE: render_catalogue(found), PENDING: render_ids(waiting), KNOWN: render_ids(known), }def main(argv): check = '--check'in argv stale = []for path, text in outputs().items(): current = path.read_text() if path.exists() elseNoneif current == text:continueif check: stale.append(path.relative_to(ROOT).as_posix())else: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text)if stale: print('gen-faces-registry: stale — run `pnpm gen:faces`:\n ' + '\n '.join(stale), file=sys.stderr)return1return0if __name__ == '__main__': sys.exit(main(sys.argv[1:]))