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

Modern-Apps.git / scripts / migrate_text_inner.py

migrate_text_inner.py394 lines · 17.1 KiBRaw
1#!/usr/bin/env python3
2"""
3Comprehensive migration: extract ALL string constants inside Text() composables,
4including fallback constants like ifBlank { "Hotel" }, ?: "Anonymous", if (c) "A" else "B",
5and interpolated strings like "Goal $ml mL", "Original: ${name}".
6"""
7import pathlib, re, collections, hashlib
8
9root = pathlib.Path("/Users/vayun/Documents/Modern-Apps")
10
11MODULES = [
12 ("astronomy", "com.vayunmathur.astronomy"),
13 ("calendar", "com.vayunmathur.calendar"),
14 ("camera", "com.vayunmathur.camera"),
15 ("clock", "com.vayunmathur.clock"),
16 ("contacts", "com.vayunmathur.contacts"),
17 ("dooraccess", "com.vayunmathur.dooraccess"),
18 ("education", "com.vayunmathur.education"),
19 ("email", "com.vayunmathur.email"),
20 ("everysync", "com.vayunmathur.everysync"),
21 ("files", "com.vayunmathur.files"),
22 ("findfamily", "com.vayunmathur.findfamily"),
23 ("health", "com.vayunmathur.health"),
24 ("library", "com.vayunmathur.library"),
25 ("library/ui", "com.vayunmathur.library.ui"),
26 ("library/downloadservice", "com.vayunmathur.library.downloadservice"),
27 ("library/biometric", "com.vayunmathur.library.biometric"),
28 ("library/network", "com.vayunmathur.library.network"),
29 ("library/room", "com.vayunmathur.library.room"),
30 ("library/ink", "com.vayunmathur.library.ink"),
31 ("library/e2ee-p2p", "com.vayunmathur.library.e2ee-p2p"),
32 ("library/widgets", "com.vayunmathur.library.widgets"),
33 ("library/work", "com.vayunmathur.library.work"),
34 ("library/ocr", "com.vayunmathur.library.ocr"),
35 ("maps", "com.vayunmathur.maps"),
36 ("messages", "com.vayunmathur.messages"),
37 ("music", "com.vayunmathur.music"),
38 ("notes", "com.vayunmathur.notes"),
39 ("office", "com.vayunmathur.office"),
40 ("openassistant", "com.vayunmathur.openassistant"),
41 ("passwords", "com.vayunmathur.passwords"),
42 ("pdf", "com.vayunmathur.pdf"),
43 ("photos", "com.vayunmathur.photos"),
44 ("things", "com.vayunmathur.things"),
45 ("travel", "com.vayunmathur.travel"),
46 ("weather", "com.vayunmathur.weather"),
47 ("youpipe", "com.vayunmathur.youpipe"),
48 ("games/hub", "com.vayunmathur.games.hub"),
49 ("games/chess", "com.vayunmathur.games.chess"),
50 ("games/unblockjam", "com.vayunmathur.games.unblockjam"),
51 ("games/wordmaker", "com.vayunmathur.games.wordmaker"),
52 ("games/alchemist", "com.vayunmathur.games.alchemist"),
53 ("games/pipes", "com.vayunmathur.games.pipes"),
54 ("games/solitaire", "com.vayunmathur.games.solitaire"),
55 ("games/logicgate", "com.vayunmathur.games.logicgate"),
56]
57
58def snake_key(s, max_len=40):
59 tmp = re.sub(r'%(\d+)\$[sd]|\s*%\d*\$?[sd]|\s*%[sd]', '', s)
60 tmp = re.sub(r'\$\{[^}]+\}|\$[A-Za-z_][A-Za-z0-9_\.]*', '', tmp)
61 tmp = tmp.lower()
62 tmp = re.sub(r'[^a-z0-9]+', '_', tmp)
63 tmp = re.sub(r'_+', '_', tmp).strip('_')
64 if not tmp or len(tmp) < 2:
65 tmp = "text"
66 if re.match(r'^\d', tmp):
67 tmp = "n_" + tmp
68 if len(tmp) > max_len:
69 tmp = tmp[:max_len].rstrip('_')
70 return tmp
71
72def deterministic_suffix(lit):
73 h = hashlib.md5(lit.encode('utf-8')).hexdigest()
74 num = int(h[:8], 16) % 10000
75 return f"{num:04d}"
76
77def xml_escape(s):
78 out = s.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace("'", "\\'")
79 return out
80
81def extract_args(lit):
82 pattern = re.compile(r'\$\{([^}]+)\}|\$([A-Za-z_][A-Za-z0-9_\.]*)')
83 args = []
84 for m in pattern.finditer(lit):
85 expr = m.group(1) if m.group(1) is not None else m.group(2)
86 args.append(expr.strip())
87 return args
88
89def to_xml_value(lit):
90 args = extract_args(lit)
91 xml = lit
92 counter = [1]
93 def repl(m):
94 ph = f"%{counter[0]}$s"
95 counter[0] += 1
96 return ph
97 xml = re.sub(r'\$\{[^}]+\}|\$[A-Za-z_][A-Za-z0-9_\.]*', repl, xml)
98 def repl_percent(m):
99 spec = m.group(1)
100 ph = f"%{counter[0]}${spec}"
101 counter[0] += 1
102 return ph
103 percent_pat = re.compile(r'%(?!%)(?!\d+\$)([0-9\.\-]*[sdif])')
104 xml = percent_pat.sub(repl_percent, xml)
105 return xml, args
106
107def get_existing_keys_values(strings_path):
108 content = strings_path.read_text(encoding='utf-8')
109 keys = set(re.findall(r'<string name="([^"]+)"', content))
110 value_to_key = {}
111 for m in re.finditer(r'<string name="([^"]+)">([^<]*)</string>', content, re.DOTALL):
112 k = m.group(1)
113 v = m.group(2)
114 v_unesc = v.replace("\\'", "'").replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", '"')
115 value_to_key[v_unesc] = k
116 return keys, value_to_key
117
118skip_exact = {
119 'A','T', '\u0192', '\u270e', '\u2013', '\u2713', '\u2717', '\u00d7', '\u2192', '\u2190', '\u232b',
120 '\u25cf', '\u25cb', '\u2014', '\u2022', '\u00b7', '.', '+', '\u2191', '\u2193', '\u25be', '\u2205',
121 'Aa', '\u21bb', '?', '-', '—', '–', '•', '·', '…'
122}
123
124def is_valid_literal(lit, line_context=""):
125 s = lit.strip()
126 if not s:
127 return False
128 if s in skip_exact:
129 return False
130 if len(s) <= 2 and ' ' not in s and not re.search(r'[A-Za-z]{2,}', s):
131 return False
132 if s == 'A' and ('bodySmall' in line_context or 'headlineSmall' in line_context):
133 return False
134 if s == 'T' and ('sp' in line_context):
135 return False
136 # ClipData MIME labels - not UI
137 if s in ('date','note','detail','QR') and ('newPlainText' in line_context or 'ClipData' in line_context):
138 return False
139 stripped = re.sub(r'\$\{[^}]+\}|\$[A-Za-z_][A-Za-z0-9_\.]*|\\u[0-9A-Fa-f]{4}|%\d*\$?[sdif]|%[sdif]|\\n|\\t|\\r', '', lit)
140 stripped = stripped.strip()
141 if len(stripped) < 2:
142 return False
143 if not re.search(r'[A-Za-z]{2,}', stripped):
144 return False
145 # Exclude purely numbers with symbols like "360°" - keep? It has numbers but should be translatable maybe "360°"? It has no letters, so would be skipped by letter check - but "360°" is UI but not letters, we skip for now (symbolic)
146 return True
147
148def find_text_regions(file_text):
149 regions = []
150 pat = re.compile(r'\bText\s*\(')
151 pos = 0
152 while True:
153 m = pat.search(file_text, pos)
154 if not m:
155 break
156 paren_start = m.end() - 1 # '('
157 depth = 0
158 end = -1
159 in_str = False
160 escape_next = False
161 # iterate from paren_start
162 for j in range(paren_start, min(len(file_text), paren_start+5000)):
163 c = file_text[j]
164 if escape_next:
165 escape_next = False
166 continue
167 if c == '\\' and in_str:
168 escape_next = True
169 continue
170 if c == '"' and not in_str:
171 in_str = True
172 continue
173 if c == '"' and in_str:
174 in_str = False
175 continue
176 if in_str:
177 continue
178 if c == '(':
179 depth += 1
180 elif c == ')':
181 depth -= 1
182 if depth == 0:
183 end = j
184 break
185 if end == -1:
186 pos = m.end()
187 continue
188 call_with_parens = file_text[paren_start:end+1]
189 line_no = file_text[:m.start()].count('\n') + 1
190 ls = file_text.rfind('\n', 0, m.start()) + 1
191 le = file_text.find('\n', end)
192 if le == -1:
193 le = len(file_text)
194 ctx = file_text[ls:le]
195 regions.append((m.start(), paren_start, end, call_with_parens, line_no, ctx))
196 pos = end + 1
197 return regions
198
199total_added = 0
200
201for mod, pkg in MODULES:
202 mod_path = root / mod
203 if not mod_path.exists():
204 continue
205 java_dir = mod_path / "src/main/java"
206 if not java_dir.exists():
207 continue
208 strings_path = mod_path / "src/main/res/values/strings.xml"
209 if not strings_path.exists():
210 strings_path.parent.mkdir(parents=True, exist_ok=True)
211 strings_path.write_text('<resources>\n <string name="app_name">App</string>\n</resources>\n')
212 print(f"Created {strings_path}")
213
214 try:
215 keys, value_to_key = get_existing_keys_values(strings_path)
216 except Exception as e:
217 print(f"Failed parsing {strings_path}: {e}")
218 continue
219
220 kt_files = list(java_dir.rglob("*.kt"))
221 if not kt_files:
222 continue
223
224 literal_to_occurrences = collections.defaultdict(list)
225 # Gather
226 for kf in kt_files:
227 try:
228 file_text = kf.read_text(encoding='utf-8')
229 except:
230 continue
231 if 'Text(' not in file_text:
232 continue
233 regions = find_text_regions(file_text)
234 for _, _, _, call_text, line_no, line_ctx in regions:
235 # If call already has stringResource and no fallback pattern, we still want to check for inner ?: "lit" not yet migrated
236 # Find quoted lits inside call_text
237 for qm in re.finditer(r'"((?:\\.|[^"\\])*)"', call_text):
238 lit = qm.group(1)
239 if not is_valid_literal(lit, line_ctx + " " + call_text):
240 continue
241 # Skip if this literal is already inside stringResource or R.string? our call_text may contain stringResource(R.string.xxx) and also a literal elsewhere; we already skip those lits that are part of R.string? No, R.string is not quoted.
242 # But if the region already contains stringResource for same literal? We still add occurrence, dedup later via value_to_key
243 literal_to_occurrences[lit].append((kf, line_no, line_ctx))
244
245 if not literal_to_occurrences:
246 continue
247
248 # Determine keys
249 new_entries_by_file = collections.defaultdict(list)
250 lit_to_key = {}
251
252 # Existing lits reuse
253 for lit in list(literal_to_occurrences.keys()):
254 if lit in value_to_key:
255 lit_to_key[lit] = value_to_key[lit]
256 continue
257 if lit.strip() in value_to_key:
258 lit_to_key[lit] = value_to_key[lit.strip()]
259 continue
260 xml_val, args = to_xml_value(lit)
261 if xml_val in value_to_key:
262 lit_to_key[lit] = value_to_key[xml_val]
263 continue
264 if xml_val.strip() in value_to_key:
265 lit_to_key[lit] = value_to_key[xml_val.strip()]
266 continue
267
268 # Need new keys for remaining
269 for lit, occs in literal_to_occurrences.items():
270 if lit in lit_to_key:
271 continue
272 xml_val, args = to_xml_value(lit)
273 base = snake_key(lit)
274 key = base
275 suffix = 1
276 while key in keys:
277 key = f"{base}_{suffix}"
278 suffix += 1
279 if suffix > 100:
280 fallback_key = f"{base}_{deterministic_suffix(lit)}"
281 extra = 1
282 while fallback_key in keys and extra < 20:
283 fallback_key = f"{base}_{deterministic_suffix(lit + str(extra))}"
284 extra += 1
285 key = fallback_key if fallback_key not in keys else f"{base}_{deterministic_suffix(lit + '_final')}"
286 break
287 keys.add(key)
288 lit_to_key[lit] = key
289 first_file = occs[0][0]
290 try:
291 rel = first_file.relative_to(java_dir)
292 stem = rel.parts[-1].replace('.kt','')
293 except:
294 stem = "common"
295 new_entries_by_file[stem].append((key, xml_val, lit, args))
296
297 if new_entries_by_file:
298 insert_text = "\n <!-- Migrated inner Text constants (auto) -->\n"
299 for stem, entries in sorted(new_entries_by_file.items()):
300 insert_text += f" <!-- {stem} -->\n"
301 for key, xml_val, orig_lit, args in entries:
302 esc = xml_escape(xml_val)
303 insert_text += f' <string name="{key}">{esc}</string>\n'
304 current = strings_path.read_text(encoding='utf-8')
305 new_content = current.replace('</resources>', insert_text + '</resources>')
306 strings_path.write_text(new_content, encoding='utf-8')
307 added = sum(len(v) for v in new_entries_by_file.values())
308 total_added += added
309 print(f"{mod}: added {added} new keys")
310
311 # Replace in files - process per file, regions descending
312 sorted_lits = sorted(literal_to_occurrences.keys(), key=lambda x: len(x), reverse=True)
313 for kf in kt_files:
314 try:
315 orig_content = kf.read_text(encoding='utf-8')
316 except:
317 continue
318 content = orig_content
319 if not any(lit in content for lit in sorted_lits):
320 continue
321 # Will need to check if file contains Text
322 if 'Text(' not in content:
323 continue
324 # Find regions in current content (not orig) each iteration? We'll recompute each time from scratch by scanning descending
325 regions = find_text_regions(content)
326 if not regions:
327 continue
328 # Sort regions by paren_start descending to avoid index shift
329 regions_sorted = sorted(regions, key=lambda x: x[1], reverse=True)
330 file_changed = False
331 for r_start_text, paren_start, paren_end, call_text, line_no, line_ctx in regions_sorted:
332 # Re-extract call_text from current content at this point (since content may have been modified for later regions)
333 # But since we go descending, content up to paren_start is unchanged for earlier regions, and our stored call_text corresponds to original slice at that location? After modifications of later regions (higher indices), earlier indices remain valid, but call_text we stored is from original content for that region? However if we modified later regions, the current content's slice from paren_start:paren_end+1 might differ in length if we replaced lits in later regions? No, because later regions are after this region, so their modifications affect indices after paren_end, not before. So current content[paren_start:paren_end+1] should still be the original call_text for this region unless previous replacements inside this same region changed its length? But we haven't yet replaced inside this region in this loop (we process one region at a time). So we can use current content slice.
334 cur_call = content[paren_start:paren_end+1]
335 # Quick skip if no lits inside
336 if not any(lit in cur_call for lit in sorted_lits):
337 continue
338 # Skip if call is already fully using stringResource and contains no remaining valid literals that are not already replaced? We'll still scan
339 # Avoid replacing inside lines that are ClipData already handled? Already filtered in is_valid
340 new_call = cur_call
341 for lit in sorted_lits:
342 if lit not in new_call:
343 continue
344 key = lit_to_key.get(lit)
345 if not key:
346 continue
347 # Build replacement
348 args = extract_args(lit)
349 if args:
350 args_str = ", ".join(args)
351 repl = f'stringResource(R.string.{key}, {args_str})'
352 else:
353 repl = f'stringResource(R.string.{key})'
354 # Replace quoted literal with repl - must match exact quoted literal
355 esc_lit = re.escape(lit)
356 pat_q = re.compile(r'"' + esc_lit + r'"')
357 # Only replace if not already replaced? If new_call already contains repl for same key, still allow if still has quoted lit
358 if pat_q.search(new_call):
359 new_call_new = pat_q.sub(repl, new_call)
360 if new_call_new != new_call:
361 file_changed = True
362 new_call = new_call_new
363 if new_call != cur_call:
364 # Replace in content
365 content = content[:paren_start] + new_call + content[paren_end+1:]
366 # After replacement, need to adjust subsequent regions? Since we go descending, earlier regions (smaller start) indices remain valid
367 # No need to recalc, but paren_end for earlier regions unchanged
368
369 if file_changed:
370 # Add imports if needed
371 if 'import androidx.compose.ui.res.stringResource' not in content:
372 m = list(re.finditer(r'^import .+', content, re.MULTILINE))
373 if m:
374 last = m[-1]
375 pos = last.end()
376 content = content[:pos] + '\nimport androidx.compose.ui.res.stringResource' + content[pos:]
377 else:
378 content = re.sub(r'(package .+\n)', r'\1import androidx.compose.ui.res.stringResource\n', content, count=1)
379 r_import = f'import {pkg}.R'
380 if r_import not in content:
381 if 'import androidx.compose.ui.res.stringResource' in content:
382 content = content.replace('import androidx.compose.ui.res.stringResource', f'import androidx.compose.ui.res.stringResource\n{r_import}')
383 else:
384 m = list(re.finditer(r'^import .+', content, re.MULTILINE))
385 if m:
386 last = m[-1]
387 pos = last.end()
388 content = content[:pos] + f'\n{r_import}' + content[pos:]
389 else:
390 content = re.sub(r'(package .+\n)', rf'\1{r_import}\n', content, count=1)
391 kf.write_text(content, encoding='utf-8')
392 print(f" Migrated {kf.relative_to(root)}")
393
394print(f"Done, total added {total_added}")