Branchwell

Jotley / app · jotley.ai / scripts / capture-app-store.py

Raw 9.4 KB on d2c8e7812d9b8c1cc5857eb6dc912d99bc5c9048
1#!/usr/bin/env python3
2"""Capture Jotley's localized storefront images with Xcode UI tests."""
3
4import argparse
5import hashlib
6import json
7import os
8from pathlib import Path
9import plistlib
10import re
11import subprocess
12
13
14ROOT = Path(__file__).resolve().parents[1]
15EXPAND = Path("/Volumes/Expand")
16STORE_LOCALES = {
17 "en": "en-US", "da": "da", "nl": "nl-NL", "fr": "fr-FR", "de": "de-DE",
18 "it": "it", "nb": "no", "pt-BR": "pt-BR", "es": "es-ES", "sv": "sv",
19 "tr": "tr", "vi": "vi", "zh-Hans": "zh-Hans", "zh-Hant": "zh-Hant",
20 "ja": "ja", "ko": "ko",
21}
22DEVICES = {
23 "iphone": ("iPhone 17 Pro", (1206, 2622)),
24 "iphone-large": ("iPhone 17 Pro Max", (1320, 2868)),
25 "ipad": ("iPad Pro 13-inch", (2064, 2752)),
26 "mac": ("Mac", (1440, 900)),
27}
28MOBILE_SCENES = ("01-library", "02-summary", "03-transcript")
29LARGE_SCREEN_SCENES = ("01-summary", "02-transcript", "03-folders")
30
31
32def fixtures() -> dict[str, dict[str, str]]:
33 catalog = json.loads((ROOT / "Shared/Localizable.xcstrings").read_text())["strings"]
34 results = {}
35 for row in (ROOT / "scripts/app-store-screenshot-fixtures.txt").read_text().splitlines():
36 locale, country, title, *fields = row.split("|")
37 design, weekly, feedback, folder, launch, design_tag, first, second, summary, task1, task2 = fields
38
39 def label(key: str) -> str:
40 if locale == "en":
41 return key
42 return catalog[key]["localizations"][locale]["stringUnit"]["value"]
43
44 notes = [
45 {
46 "title": title, "folder": folder, "tags": [launch, design_tag],
47 "transcript": f"{first}\n\n{second}",
48 "summary": f"{summary}\n\n- {task1}\n- {task2}",
49 },
50 *(
51 {"title": name, "folder": folder, "tags": [], "transcript": body, "summary": ""}
52 for name, body in ((design, second), (weekly, summary), (feedback, first))
53 ),
54 ]
55 results[locale] = {
56 "notes": json.dumps(notes, ensure_ascii=False),
57 "region": f"{('pt' if locale == 'pt-BR' else locale.replace('-', '_'))}_{country}",
58 "title": title,
59 "libraryLabel": label("Notes"),
60 "transcriptLabel": label("Transcript"),
61 "foldersLabel": label("Folders"),
62 }
63 if results.keys() != STORE_LOCALES.keys():
64 raise ValueError("The screenshot fixtures must cover all storefront localizations.")
65 return results
66
67
68def run(command: list[str], log: Path, env: dict[str, str]) -> None:
69 print(f"{command[0]} {command[1]} → {log}", flush=True)
70 with log.open("w") as output:
71 subprocess.run(command, cwd=ROOT, env=env, stdout=output, stderr=subprocess.STDOUT, check=True)
72
73
74def capture(args: argparse.Namespace, samples: dict[str, dict[str, str]]) -> None:
75 if not EXPAND.is_mount():
76 raise SystemExit("Mount the Expand drive before capturing screenshots.")
77 output = args.output.expanduser().resolve()
78 if not output.is_relative_to(EXPAND):
79 raise SystemExit("Choose an output directory on /Volumes/Expand.")
80 output.mkdir(parents=True, exist_ok=False)
81 temp = output / "tmp"
82 temp.mkdir()
83 env = {**os.environ, "TMPDIR": str(temp)}
84 mac = args.device == "mac"
85 target = "JotleyUITests-macOS/JotleyLocalUITests" if mac else "Jotley-iOSUITests/Jotley_iOSUITests"
86 destination = "platform=macOS,arch=arm64" if mac else f"platform=iOS Simulator,id={args.udid}"
87 if not mac:
88 subprocess.run(
89 ["xcrun", "simctl", "status_bar", args.udid, "override", "--time", "9:41",
90 "--dataNetwork", "wifi", "--wifiMode", "active", "--wifiBars", "3",
91 "--cellularMode", "active", "--cellularBars", "4", "--batteryState", "discharging",
92 "--batteryLevel", "100"],
93 env=env, check=True,
94 )
95 if args.xctestrun:
96 source_run = args.xctestrun.resolve()
97 else:
98 products = output / "build"
99 settings = ["CODE_SIGN_IDENTITY=-", "CODE_SIGN_STYLE=Manual", "DEVELOPMENT_TEAM=",
100 "CODE_SIGN_ENTITLEMENTS="] if mac else ["CODE_SIGNING_ALLOWED=NO"]
101 command = [
102 "xcodebuild", "-project", "Jotley.xcodeproj", "-scheme", "Jotley" if mac else "Jotley-iOS",
103 "-configuration", "Debug", "-destination", destination,
104 "-derivedDataPath", str(products), "-jobs", "6",
105 ]
106 if args.packages:
107 command += ["-clonedSourcePackagesDirPath", str(args.packages), "-disableAutomaticPackageResolution"]
108 run([*command, *settings, "build-for-testing"], output / "build.log", env)
109 source_run, = (products / "Build/Products").glob("*.xctestrun")
110
111 config = plistlib.loads(source_run.read_bytes())
112 test_targets = [entry for group in config["TestConfigurations"] for entry in group["TestTargets"]
113 if entry["BlueprintName"] == target.split("/")[0]]
114 if not test_targets:
115 raise ValueError(f"{source_run} does not contain {target}.")
116 for entry in test_targets:
117 entry.setdefault("EnvironmentVariables", {})["JOTLEY_STORE_SCREENSHOT_FIXTURE"] = json.dumps(samples)
118 # Xcode resolves __TESTROOT__ relative to the xctestrun file.
119 run_path = source_run.with_name(f"{source_run.stem}-store-{os.getpid()}.xctestrun")
120 with run_path.open("xb") as file:
121 plistlib.dump(config, file)
122 result = output / "capture.xcresult"
123 try:
124 run(
125 ["xcodebuild", "test-without-building", "-xctestrun", str(run_path), "-destination",
126 destination, "-parallel-testing-enabled", "NO",
127 f"-only-testing:{target}/testLocalizedStorefrontCaptures", "-resultBundlePath", str(result)],
128 output / "capture.log", env,
129 )
130 finally:
131 run_path.unlink()
132 export(result, output, args.device, samples, env)
133
134
135def export(result: Path, output: Path, device: str, samples: dict[str, dict[str, str]],
136 env: dict[str, str]) -> None:
137 raw = output / "attachments"
138 subprocess.run(["xcrun", "xcresulttool", "export", "attachments", "--path", str(result),
139 "--output-path", str(raw)], env=env, check=True)
140 scenes = LARGE_SCREEN_SCENES if device in {"mac", "ipad"} else MOBILE_SCENES
141 pattern = re.compile(r"^JotleyStore-(.+?)-(" + "|".join(map(re.escape, scenes)) + r")(?=[_.]|$)")
142 manifest = json.loads((raw / "manifest.json").read_text())
143 actual = {}
144 for test in manifest:
145 for attachment in test["attachments"]:
146 if match := pattern.match(attachment["suggestedHumanReadableName"].removesuffix(".png")):
147 key = tuple(match.groups())
148 if key in actual:
149 raise ValueError(f"Duplicate capture {key}")
150 actual[key] = raw / attachment["exportedFileName"]
151 expected = {(locale, scene) for locale in samples for scene in scenes}
152 if actual.keys() != expected:
153 raise ValueError(f"Capture mismatch. Missing {expected - actual.keys()}. Extra {actual.keys() - expected}.")
154 for locale in samples:
155 checksums = {hashlib.sha256(actual[(locale, scene)].read_bytes()).digest() for scene in scenes}
156 if len(checksums) != len(scenes):
157 raise ValueError(f"{locale} contains identical screenshots for different scenes.")
158 width, height = DEVICES[device][1]
159 for (locale, scene), source in sorted(actual.items()):
160 dimensions = subprocess.check_output(["magick", "identify", "-format", "%w %h", str(source)], env=env, text=True)
161 if device != "mac" and dimensions != f"{width} {height}":
162 raise ValueError(f"{locale} {scene} is {dimensions}, expected {width} {height}.")
163 destination = output / "store" / STORE_LOCALES[locale] / f"{device}-{scene}.png"
164 destination.parent.mkdir(parents=True, exist_ok=True)
165 convert = ["magick", str(source), "-background", "#f6f6f6", "-alpha", "remove", "-alpha", "off"]
166 if device == "mac":
167 capture_width, capture_height = map(int, dimensions.split())
168 if abs(capture_width / capture_height - 3 / 2) > 0.01:
169 raise ValueError(f"{locale} {scene} has a non-3:2 Mac window: {dimensions}.")
170 native = output / "mac-3x2" / STORE_LOCALES[locale] / destination.name
171 native.parent.mkdir(parents=True, exist_ok=True)
172 subprocess.run([*convert, f"PNG24:{native}"], env=env, check=True)
173 convert += ["-resize", f"{width}x{height}", "-gravity", "center", "-extent", f"{width}x{height}"]
174 subprocess.run([*convert, f"PNG24:{destination}"], env=env, check=True)
175 print(f"Exported {len(actual)} images to {output / 'store'}", flush=True)
176
177
178def main() -> None:
179 parser = argparse.ArgumentParser(description=__doc__)
180 parser.add_argument("device", choices=DEVICES)
181 parser.add_argument("output", type=Path, help="New output directory on Expand")
182 parser.add_argument("--udid", help="Booted Apple simulator UDID")
183 parser.add_argument("--packages", type=Path, help="Existing Swift package checkout cache")
184 parser.add_argument("--xctestrun", type=Path, help="Reuse a compatible build-for-testing")
185 parser.add_argument("--locale", action="append", choices=STORE_LOCALES, help="Capture a subset of locales")
186 args = parser.parse_args()
187 if args.device != "mac" and not args.udid:
188 parser.error("--udid is required for simulator captures")
189 samples = fixtures()
190 capture(args, {locale: samples[locale] for locale in (args.locale or samples)})
191
192
193if __name__ == "__main__":
194 main()