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

Modern-Apps.git / scripts / check_icons_parity.py

check_icons_parity.py154 lines · 5.5 KiBRaw
1#!/usr/bin/env python3
2"""Parity check for the generated IconXxx() wrappers.
3
4Compares the public icon API (name + normalized signature + icon source +
5content description) of a reference Icons.kt against one or more replacement
6Kotlin files (the hand-written Icons.kt plus the build-generated
7IconsGenerated.kt). Every reference entry must appear exactly once in the
8replacements, with an identical signature and the same icon/description.
9
10Usage:
11 git show HEAD:library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt > /tmp/Icons.kt.old
12 python3 scripts/check_icons_parity.py /tmp/Icons.kt.old \
13 library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt \
14 library/ui/build/generated/source/icons/debug/IconsGenerated.kt
15
16Exits 0 only on an exact multiset match (334/334 for the original file).
17Stdlib only.
18"""
19
20import re
21import sys
22from collections import Counter
23from pathlib import Path
24
25
26def extract(path):
27 lines = Path(path).read_text().splitlines()
28 rows = []
29 i = 0
30 while i < len(lines):
31 line = lines[i]
32 if line.strip() == "@Composable" and i + 1 < len(lines) and re.match(
33 r"fun (Icon\w+|AppIcon)\b", lines[i + 1].strip()
34 ):
35 sig_lines = []
36 j = i + 1
37 text = ""
38 endpos = None
39 while j < len(lines):
40 sig_lines.append(lines[j])
41 j += 1
42 text = "\n".join(sig_lines)
43 depth = 0
44 started = False
45 in_str = False
46 esc = False
47 for idx, ch in enumerate(text):
48 if in_str:
49 if esc:
50 esc = False
51 elif ch == "\\":
52 esc = True
53 elif ch == '"':
54 in_str = False
55 continue
56 if ch == '"':
57 in_str = True
58 elif ch == "(":
59 depth += 1
60 started = True
61 elif ch == ")":
62 depth -= 1
63 if started and depth == 0:
64 endpos = idx
65 break
66 if endpos is not None:
67 break
68 name = re.match(r"\s*fun (Icon\w+|AppIcon)\b", text).group(1)
69 params = " ".join(text[text.find("(") + 1 : endpos].split()).rstrip(",")
70 params = re.sub(r",\s*\)", ")", params)
71 tail = text[endpos + 1 :].strip()
72 if tail.startswith("="):
73 stmt = tail[1:].strip()
74 if not stmt:
75 stmt = lines[j].strip()
76 j += 1
77 body = " ".join(stmt.split())
78 elif tail.startswith("{"):
79 body_lines = [tail]
80 k = j
81 while k < len(lines):
82 body_lines.append(lines[k])
83 if lines[k] == "}":
84 k += 1
85 break
86 k += 1
87 body = "\n".join(body_lines)
88 j = k
89 else:
90 body = tail
91 if name.startswith("Icon"):
92 rows.append((name, params, semantics(name, params, body)))
93 i = j
94 continue
95 i += 1
96 return rows
97
98
99def semantics(name, params, body):
100 """(kind, source, description) for a wrapper; NAV for the back buttons."""
101 if name == "IconNavigation":
102 return ("NAV", "", "")
103 flat = " ".join(body.split())
104 pm = re.match(
105 r'Icon\(painterResource\(R\.drawable\.(\w+)\),\s*("(?:[^"\\]|\\.)*"),\s*modifier = modifier, tint = tint\)',
106 flat,
107 )
108 if pm:
109 return ("S", f"drawable:{pm.group(1)}", pm.group(2))
110 am = re.match(
111 r'AppIcon\(([^,]+),\s*("(?:[^"\\]|\\.)*"|contentDescription),\s*modifier, tint\)$', flat
112 )
113 if not am:
114 return ("??", flat[:120], "")
115 ref = am.group(1).strip()
116 desc = am.group(2).strip()
117 source = ref[len("Icons.") :] if ref.startswith("Icons.") else f"vector:{ref}"
118 if params.rstrip(",") == "modifier: Modifier = Modifier, tint: Color = LocalContentColor.current":
119 return ("S", source, desc)
120 if "contentDescription: String?" in params and params.startswith("modifier:"):
121 mm = re.search(r'contentDescription: String\? = ("(?:[^"\\]|\\.)*"),?$', params)
122 return ("T", source, mm.group(1) if mm else "FAIL")
123 if params.startswith("contentDescription: String?"):
124 return ("F", source, "")
125 return ("??", params, "")
126
127
128def main(argv):
129 if len(argv) < 3:
130 print(__doc__)
131 return 2
132 reference = extract(argv[1])
133 candidate = []
134 for path in argv[2:]:
135 candidate.extend(extract(path))
136 ref_counts = Counter(reference)
137 cand_counts = Counter(candidate)
138 missing = ref_counts - cand_counts
139 extra = cand_counts - ref_counts
140 print(f"reference: {len(reference)} wrappers ({sum(ref_counts.values())} entries)")
141 print(f"candidate: {len(candidate)} wrappers ({sum(cand_counts.values())} entries)")
142 for entry, count in sorted(missing.items()):
143 print(f"MISSING x{count}: {entry}")
144 for entry, count in sorted(extra.items()):
145 print(f"EXTRA x{count}: {entry}")
146 if missing or extra:
147 print("PARITY: FAIL")
148 return 1
149 print(f"PARITY: OK — {len(reference)}/{len(reference)} wrappers identical (name, signature, source, description)")
150 return 0
151
152
153if __name__ == "__main__":
154 sys.exit(main(sys.argv))