Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / check_preview_metadata.sh

check_preview_metadata.sh251 lines · 11.9 KiBRaw
1#!/usr/bin/env bash
2# Verification script: check the Compose-preview store-screenshot setup is coherent.
3#
4# None of this needs a compiler, which is the point — it catches the mechanical mistakes
5# that are otherwise only found by a full Gradle run:
6#
7# - a @Preview that is missing @PreviewTest (renders in Studio, silently not collected,
8# surfaces as the unhelpful "did not discover any tests")
9# - previews declared as top-level functions instead of class members (same symptom)
10# - preview functions not named Preview<N>… (listing order comes from sorting the
11# generated filenames, so a stray name silently reshuffles the store listing)
12# - a @Preview without group = "phone|tablet|large-tablet|tv|wear" (the
13# form-factor bucket the collector routes it to; Triple-T spellings verbatim)
14# - duplicate Preview<N> numbers inside one bucket (per-bucket 1.png… order
15# comes from the function-name sort, so a clash reshuffles that bucket)
16# - a chrome-owning screen rendered bare (a screen that ships under a tab bar,
17# rail or drawer on device, shown without it — the listing misses the chrome
18# users actually see; see CHROME_SCREENS below)
19# - a leftover src/androidTest MetadataScreenshots.kt from the old on-device generator
20# - a module that opted into previews but has no @Preview at all
21#
22# On-device capture is gone. A module either renders its listing from previews, or its
23# images are hand-captured and committed under metadata_data/photos/ (camera and
24# games/voxels: a live viewfinder and a Vulkan surface, neither of which Layoutlib draws).
25#
26# Exit 0 = clean, non-zero = problems found.
27
28set -uo pipefail
29
30REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
31cd "$REPO_ROOT"
32
33problems=0
34
35note() { printf ' %s\n' "$1"; }
36fail() { printf ' ✗ %s\n' "$1"; problems=$((problems + 1)); }
37
38# Screens that ship under tab/rail/drawer chrome on device: a preview calling one
39# outside chrome (a ChromePreview/Tabbed wrapper or drawer call in the same
40# function) renders chrome-less. Format: "module:Screen,Screen module:Screen ...".
41# Only screens with an existing chrome-wrapped precedent are listed — wrapping a
42# new module means adding its screens here. Drawer-closed shells (files) need no
43# entry: a closed drawer is invisible. Screens on pushed routes (no chrome on
44# device) are deliberately absent: app detail/trust, contact details, office
45# documents, hub Yuu, VPN now-playing/album/expanded, email conversation/compose.
46CHROME_SCREENS="calculator:CalculatorScreen,GraphScreen,UnitConverterScreen clock:AlarmScreen,ClockScreen,TimerScreen,StopwatchScreen appstore:HomeScreen,SearchScreen,UpdatesScreen,LibraryScreen contacts:ContactListScreen,GroupsScreen office:HomeScreen vpn:ConfigListContent,LoggingContent games/chess:ChessGameScreen,PuzzleBoardScreen games/hub:DashboardScreen,GamesListScreen,ProfileScreen health:TodayScreen,NutritionScreen,BarChartDetailsScreen youpipe:SearchScreen,SubscriptionVideosScreen securemail:InboxScreen"
47
48# True when every Preview in $1 that calls one of $2 (the module's chrome
49# screens) also hosts chrome in the same function body — a ChromePreview/Tabbed
50# wrapper or drawer call — i.e. the screen reaches the listing only through
51# chrome. A preview proving a pushed route (no chrome on device) opts out with
52# a `// CHROME EXEMPT: <reason>` comment above or inside its function. Prints
53# the offending preview's line and returns non-zero otherwise. POSIX awk only
54# (no gawk extensions — this also runs on macOS).
55chrome_wrapped() {
56 local file="$1" screens="$2"
57 local screen_pat
58 screen_pat=$(printf '%s' "$screens" | sed 's/,/|/g')
59 awk -v pat="($screen_pat)\\(" '
60 function flush() {
61 if (in_preview && has_screen && !has_chrome && !exempt) {
62 print FILENAME":"start": preview renders chrome screen without chrome"
63 failed = 1
64 }
65 }
66 /CHROME EXEMPT/ { exempt_next = 1; next }
67 /^[[:space:]]*((private|internal)[[:space:]]+)?fun / {
68 flush()
69 in_preview = ($0 ~ /fun Preview[0-9]/)
70 exempt = exempt_next; exempt_next = 0
71 start = FNR
72 has_screen = 0; has_chrome = 0
73 next
74 }
75 /CHROME EXEMPT/ { exempt = 1 }
76 /ChromePreview\(|TabbedPagerScaffold\(|ModalNavigationDrawer\(|MusicTabsBar\(/ { has_chrome = 1 }
77 $0 ~ pat { has_screen = 1 }
78 END { flush(); if (failed) exit 1 }
79 ' "$file"
80}
81
82echo "=== Compose preview metadata audit ==="
83echo
84
85# Sapling keeps copies of build files under .git/sl/origbackups; they are not modules.
86app_modules() {
87 grep -rl "common-conventions-app" --include="build.gradle.kts" . 2>/dev/null \
88 | grep -v '/build/' | grep -v '^\./\.git/' | sed 's|^\./||' | sort
89}
90
91for gradle_file in $(app_modules); do
92 module="${gradle_file%/build.gradle.kts}"
93 # Match the id(...) declaration only — a module can legitimately *mention* the other
94 # convention in a comment explaining why it is not using it (games/voxels does).
95 uses_preview=$(grep -cE '^[[:space:]]*id\("common-conventions-preview-metadata"\)' "$gradle_file" || true)
96 preview_dir="$module/src/screenshotTest"
97 old_gen=$(find "$module/src/androidTest" -name 'MetadataScreenshots.kt' 2>/dev/null | head -1)
98
99 if [[ "$uses_preview" -eq 0 ]]; then
100 # Manual or unpublished. Either way it must not carry preview sources that nothing
101 # renders.
102 if [[ -d "$preview_dir" ]]; then
103 echo "$module"
104 fail "has src/screenshotTest but does not apply common-conventions-preview-metadata"
105 fi
106 continue
107 fi
108
109 header_shown=0
110 show() { [[ $header_shown -eq 0 ]] && echo "$module" && header_shown=1; }
111
112 if [[ ! -d "$preview_dir" ]]; then
113 show; fail "applies preview-metadata but has no src/screenshotTest"
114 continue
115 fi
116
117 if [[ -n "$old_gen" ]]; then
118 show; fail "leftover on-device generator: $old_gen"
119 fi
120
121 files=$(find "$preview_dir" -name '*.kt' 2>/dev/null)
122 if [[ -z "$files" ]]; then
123 show; fail "src/screenshotTest contains no Kotlin sources"
124 continue
125 fi
126
127 n_preview=0
128 n_previewtest=0
129 # "N:group" entries — N from the Preview<N> function name, group from the
130 # @Preview(group = "...") on the annotation block above it. Per-bucket
131 # ordering means the numbers must be unique within each group.
132 bucket_numbers=""
133 for f in $files; do
134 # Count annotations only where they annotate a declaration, not in prose/KDoc.
135 p=$(grep -cE '^[[:space:]]*@Preview\(' "$f" || true)
136 t=$(grep -cE '^[[:space:]]*@PreviewTest[[:space:]]*$' "$f" || true)
137 n_preview=$((n_preview + p))
138 n_previewtest=$((n_previewtest + t))
139
140 # The bucket: the group = "..." on the @Preview line (annotations are
141 # single-line repo-wide). Matches CollectPreviewScreenshots.readPreviewGroups.
142 groups_in_file=$(grep -E '^[[:space:]]*@Preview\(' "$f" \
143 | grep -oE 'group[[:space:]]*=[[:space:]]*"[^"]*"' \
144 | sed -E 's/.*group[[:space:]]*=[[:space:]]*"([^"]*)".*/\1/' || true)
145 n_grouped=$(printf '%s\n' "$groups_in_file" | grep -c . || true)
146 if [[ "$n_grouped" -ne "$p" ]]; then
147 show; fail "$((p - n_grouped)) of $p @Preview(s) in ${f#"$module"/} have no group = \"...\"; the collector routes everything ungrouped to phone/"
148 fi
149 bad_group=$(printf '%s\n' "$groups_in_file" \
150 | grep -vE '^(phone|tablet|large-tablet|tv|wear)$' || true)
151 for g in $bad_group; do
152 show; fail "unknown screenshot bucket \"$g\" in ${f#"$module"/}; expected phone, tablet, large-tablet, tv or wear"
153 done
154
155 # Preview functions must be class members; a top-level one lands in a synthetic
156 # ...Kt facade the engine does not scan.
157 if grep -qE '^fun Preview[0-9]' "$f"; then
158 show; fail "top-level preview function in ${f#"$module"/}; must be a class member"
159 fi
160
161 # Listing order is filename order, which embeds the function name.
162 # BSD sed (macOS) has no \s, so use POSIX classes throughout.
163 badly_named=$(grep -oE '^[[:space:]]+fun [A-Za-z0-9_]+\(\)' "$f" \
164 | sed -E 's/^[[:space:]]+fun //; s/\(\)//' \
165 | grep -vE '^Preview[0-9]' || true)
166 for name in $badly_named; do
167 # Only complain about functions that are actually previews.
168 if grep -B4 -E "fun $name\(\)" "$f" | grep -q '@Preview('; then
169 show; fail "preview function '$name' is not named Preview<N>…; listing order will be wrong"
170 fi
171 done
172
173 # Pair each Preview<N> function with its bucket: walk the file keeping the
174 # last-seen group, like the collector does. Well-named preview functions
175 # only — badly-named ones are already flagged above. (The group is NOT
176 # cleared on @Composable: it always sits between @Preview and fun.)
177 pending=""
178 while IFS= read -r line; do
179 case "$line" in
180 *'@Preview('*)
181 g=$(printf '%s' "$line" | grep -oE 'group[[:space:]]*=[[:space:]]*"[^"]*"' \
182 | sed -E 's/.*group[[:space:]]*=[[:space:]]*"([^"]*)".*/\1/' || true)
183 [[ -n "$g" ]] && pending="$g"
184 ;;
185 esac
186 if [[ "$line" =~ ^[[:space:]]*fun\ (Preview[0-9]+[A-Za-z0-9_]*)\(\) ]]; then
187 if [[ -n "$pending" ]]; then
188 n="${BASH_REMATCH[1]}"
189 bucket_numbers="$bucket_numbers
190${pending}:${n}"
191 fi
192 pending=""
193 fi
194 done < "$f"
195 done
196
197 # Numbers must be unique within each bucket — per-bucket 1.png… numbering
198 # sorts by function name, so a clash reshuffles that bucket's listing.
199 dupes=$(printf '%s\n' "$bucket_numbers" | grep . | sort | uniq -d || true)
200 for d in $dupes; do
201 show; fail "duplicate screenshot number in bucket \"${d%%:*}\" (${d##*:} twice); per-bucket order will be wrong"
202 done
203
204 # Chrome-owning screens must reach the listing through chrome, not bare.
205 for entry in $CHROME_SCREENS; do
206 entry_module="${entry%%:*}"
207 if [[ "$module" == "$entry_module" ]]; then
208 entry_screens="${entry#*:}"
209 for f in $files; do
210 if ! chrome_wrapped "$f" "$entry_screens"; then
211 show; fail "chrome-owning screen rendered bare in ${f#"$module"/} (see line above); wrap it in ChromePreview"
212 fi
213 done
214 fi
215 done
216
217 if [[ "$n_preview" -eq 0 ]]; then
218 show; fail "no @Preview found under src/screenshotTest"
219 elif [[ "$n_previewtest" -ne "$n_preview" ]]; then
220 show; fail "$n_preview @Preview but $n_previewtest @PreviewTest — every preview needs both"
221 fi
222
223 [[ $header_shown -eq 1 ]] || printf '%-24s %s preview(s)\n' "$module" "$n_preview"
224done
225
226echo
227echo "--- shared infrastructure ---"
228for f in build-logic/src/main/kotlin/common-conventions-preview-metadata.gradle.kts \
229 gradle/libs.versions.toml gradle.properties .gitignore; do
230 [[ -f "$f" ]] || fail "missing $f"
231done
232grep -q 'android.experimental.enableScreenshotTest=true' gradle.properties \
233 || fail "gradle.properties is missing android.experimental.enableScreenshotTest=true"
234grep -q 'screenshot-validation-api' gradle/libs.versions.toml \
235 || fail "libs.versions.toml is missing screenshot-validation-api (supplies @PreviewTest)"
236grep -q 'src/screenshotTest\*/reference/' .gitignore \
237 || fail ".gitignore is not ignoring the rendered reference images"
238
239echo
240preview_modules=0
241while read -r gf; do
242 if grep -qE '^[[:space:]]*id\("common-conventions-preview-metadata"\)' "$gf"; then
243 preview_modules=$((preview_modules + 1))
244 fi
245done < <(app_modules)
246echo "=== $preview_modules module(s) render their listing from Compose previews ==="
247if [[ $problems -gt 0 ]]; then
248 echo "=== $problems problem(s) found ==="
249 exit 1
250fi
251echo "=== clean ==="