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

Modern-Apps.git / scripts / migrate_all.py

migrate_all.py487 lines · 21.6 KiBRaw
1#!/usr/bin/env python3
2import pathlib, re, collections, os, hashlib
3
4root = pathlib.Path("/Users/vayun/Documents/Modern-Apps")
5
6MODULES = [
7 ("office", "com.vayunmathur.office"),
8 ("photos", "com.vayunmathur.photos"),
9 ("astronomy", "com.vayunmathur.astronomy"),
10 ("email", "com.vayunmathur.email"),
11 ("pdf", "com.vayunmathur.pdf"),
12 ("contacts", "com.vayunmathur.contacts"),
13 ("calendar", "com.vayunmathur.calendar"),
14 ("messages", "com.vayunmathur.messages"),
15 ("games/hub", "com.vayunmathur.games.hub"),
16 ("travel", "com.vayunmathur.travel"),
17 ("clock", "com.vayunmathur.clock"),
18 ("weather", "com.vayunmathur.weather"),
19 ("openassistant", "com.vayunmathur.openassistant"),
20 ("notes", "com.vayunmathur.notes"),
21 ("music", "com.vayunmathur.music"),
22 ("camera", "com.vayunmathur.camera"),
23 ("passwords", "com.vayunmathur.passwords"),
24 ("everysync", "com.vayunmathur.everysync"),
25 ("library", "com.vayunmathur.library"),
26 ("library/ui", "com.vayunmathur.library.ui"),
27 ("games/solitaire", "com.vayunmathur.games.solitaire"),
28 ("things", "com.vayunmathur.things"),
29 ("health", "com.vayunmathur.health"),
30 ("findfamily", "com.vayunmathur.findfamily"),
31 ("youpipe", "com.vayunmathur.youpipe"),
32 ("dooraccess", "com.vayunmathur.dooraccess"),
33 ("education", "com.vayunmathur.education"),
34 ("files", "com.vayunmathur.files"),
35 ("maps", "com.vayunmathur.maps"),
36]
37
38def snake_key(s, max_len=40):
39 # remove xml placeholders %n$s etc
40 tmp = re.sub(r'%(\d+)\$[sd]|\s*%\d*\$?[sd]|\s*%[sd]', '', s)
41 tmp = re.sub(r'\$\{[^}]+\}|\$[A-Za-z_][A-Za-z0-9_\.]*', '', tmp)
42 tmp = tmp.lower()
43 tmp = re.sub(r'[^a-z0-9]+', '_', tmp)
44 tmp = re.sub(r'_+', '_', tmp).strip('_')
45 if not tmp or len(tmp) < 2:
46 tmp = "text"
47 if re.match(r'^\d', tmp):
48 tmp = "n_" + tmp
49 if len(tmp) > max_len:
50 tmp = tmp[:max_len].rstrip('_')
51 return tmp
52
53def deterministic_suffix(lit):
54 """Deterministic hash-based suffix for collision resolution (replaces non-deterministic hash())."""
55 h = hashlib.md5(lit.encode('utf-8')).hexdigest()
56 num = int(h[:8], 16) % 10000
57 return f"{num:04d}"
58
59def xml_escape(s):
60 # Escape &, <, >, ' . Android strings use \' for '
61 # Do & first, but avoid double escaping if already &amp; ? Input is raw kotlin literal, not escaped.
62 out = s
63 out = out.replace('&', '&amp;')
64 out = out.replace('<', '&lt;')
65 out = out.replace('>', '&gt;')
66 # Escape ' as \'
67 # Replace ' with \'
68 out = out.replace("'", "\\'")
69 # For " inside? Usually not needed, but &quot; could be used. Keep as is, Android allows ".
70 return out
71
72def extract_args(lit):
73 # Returns list of args expressions in order: from ${expr} and $var
74 # Use finditer to preserve order
75 pattern = re.compile(r'\$\{([^}]+)\}|\$([A-Za-z_][A-Za-z0-9_\.]*)')
76 args = []
77 for m in pattern.finditer(lit):
78 expr = m.group(1) if m.group(1) is not None else m.group(2)
79 args.append(expr.strip())
80 return args
81
82def to_xml_value(lit):
83 # Convert kotlin interpolated string to Android format with %n$s placeholders
84 # Also handle existing %d formatting without positional -> make positional
85 # Step 1: replace ${} and $var with %n$s placeholders sequentially
86 args = extract_args(lit)
87 xml = lit
88 # Replace placeholders sequentially
89 # Use a function that increments
90 counter = [1]
91 def repl(m):
92 ph = f"%{counter[0]}$s"
93 counter[0] += 1
94 return ph
95 xml = re.sub(r'\$\{[^}]+\}|\$[A-Za-z_][A-Za-z0-9_\.]*', repl, xml)
96
97 # Now convert any remaining non-positional % format specifiers like %02d, %d, %.1f etc
98 # Pattern: % (optional 0, width, .precision) [sdif] not followed by $ and not preceded by % (escape)
99 # We need to make them positional, continuing counter
100 # Example: "%02d:%02d" -> "%1$02d:%2$02d" assuming counter starts at 1 if no previous args
101 # If we already replaced ${} args, counter continues
102 # Let's find all % patterns that are not %% and not positional
103 # Use regex: % (?!%) ([0-9\.\-+]* ) [sdif] -> but ensure not already %n$
104 # We'll replace sequentially
105 def repl_percent(m):
106 # m groups: width+type
107 spec = m.group(1) # e.g. "02d" or "s"
108 ph = f"%{counter[0]}${spec}"
109 counter[0] += 1
110 return ph
111
112 # Pattern for percent without positional: % not followed by digit + $
113 # Need to avoid %%
114 # Use negative lookahead for digit+$ and for second %
115 percent_pat = re.compile(r'%(?!%)(?!\d+\$)([0-9\.\-]*[sdif])')
116 # To avoid replacing %% we skip if next char is %
117 # We'll loop
118 # For safety, replace only if not already positional
119 xml = percent_pat.sub(repl_percent, xml)
120
121 return xml, args
122
123def get_existing_keys_values(strings_path):
124 content = strings_path.read_text()
125 keys = set(re.findall(r'<string name="([^"]+)"', content))
126 value_to_key = {}
127 # value unescaped mapping
128 for m in re.finditer(r'<string name="([^"]+)">([^<]*)</string>', content, re.DOTALL):
129 k = m.group(1)
130 v = m.group(2)
131 # unescape
132 v_unesc = v.replace("\\'", "'").replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", '"')
133 # Also replace %1$s -> placeholder normalization? Keep raw
134 value_to_key[v_unesc] = k
135 # also try stripped version without positional? For reuse detection we match raw literal stripped of ${}?
136 # Not needed
137 return keys, value_to_key, content
138
139# For each module
140for mod, pkg in MODULES:
141 mod_path = root / mod
142 if not mod_path.exists():
143 continue
144 java_dir = mod_path / "src/main/java"
145 if not java_dir.exists():
146 continue
147 strings_path = mod_path / "src/main/res/values/strings.xml"
148 if not strings_path.exists():
149 # create
150 strings_path.parent.mkdir(parents=True, exist_ok=True)
151 strings_path.write_text('<resources>\n <string name="app_name">App</string>\n</resources>\n')
152 print(f"Created {strings_path}")
153
154 kt_files = list(java_dir.rglob("*.kt"))
155 if not kt_files:
156 continue
157
158 keys, value_to_key, strings_content = get_existing_keys_values(strings_path)
159
160 # Gather all Text("...") occurrences across files
161 # Use regex for Text\s*\(\s*(?:text\s*=\s*)?"([^"]+)"
162 # We need to also capture Text("...") where ... may contain escaped \" – rare
163 text_pat = re.compile(r'Text\s*\(\s*(?:text\s*=\s*)?"([^"]+)"')
164 # Additive: Toast pattern for i18n migration – captures context and literal
165 toast_pat = re.compile(r'(?:android\.widget\.)?Toast\.makeText\s*\(\s*([^,]+?)\s*,\s*"([^"]+)"')
166
167 def is_valid_literal(lit):
168 """Shared validation used for both Text and Toast literals – ensures at least letters and not symbolic."""
169 if not lit.strip():
170 return False
171 if len(lit.strip()) <= 1:
172 return False
173 tmp_stripped = re.sub(r'\$\{[^}]+\}|\$[A-Za-z_][A-Za-z0-9_\.]*|%\d*\$?[sdif]|%[sdif]|\\u[0-9A-Fa-f]+|\\n|\\t', '', lit)
174 if not re.search(r'[A-Za-z]', tmp_stripped):
175 return False
176 if lit.strip() in ['×','→','←','⌫','●','○','✓','✗','—','–','•','·','.','+','↑','↓','▾','∅','—','–','…']:
177 return False
178 return True
179
180 literal_to_occurrences = collections.defaultdict(list) # literal -> list of (file, line_no, line_text)
181 toast_literal_to_occurrences = collections.defaultdict(list) # Additive: Toast literals -> list of (file, line_no, line, ctx)
182
183 for kf in kt_files:
184 try:
185 file_text = kf.read_text()
186 except Exception as e:
187 continue
188 has_text = 'Text("' in file_text or 'Text(text' in file_text
189 has_toast = 'Toast.makeText' in file_text
190 # Quick filter: must contain Text(" or Toast.makeText
191 if not has_text and not has_toast:
192 continue
193 lines = file_text.splitlines()
194 for idx, line in enumerate(lines, 1):
195 # --- Text gathering (preserved original logic) ---
196 if has_text:
197 if 'stringResource' in line or 'R.string' in line:
198 pass
199 elif 'contentDescription' in line or 'Log.' in line:
200 pass
201 elif 'Text("' in line or 'Text(text' in line:
202 for m in text_pat.finditer(line):
203 lit = m.group(1)
204 # Skip if empty or only whitespace
205 if not lit.strip():
206 continue
207 # Must contain at least one letter after removing placeholders and % formats
208 stripped = re.sub(r'\$\{[^}]+\}|\$[A-Za-z_][A-Za-z0-9_\.]*|%\d*\$?[sdif]|%[sdif]|\\u[0-9A-Fa-f]+|\\n|\\t', '', lit)
209 if not re.search(r'[A-Za-z]', stripped):
210 continue
211 if len(lit.strip()) <= 1:
212 continue
213 # Skip symbolic etc
214 if lit.strip() in ['×','→','←','⌫','●','○','✓','✗','—','–','•','·','.','+','↑','↓','▾','∅','—','–','…']:
215 continue
216 literal_to_occurrences[lit].append((kf, idx, line))
217 # --- Toast gathering (additive enhancement) ---
218 if has_toast and 'Toast.makeText' in line:
219 if re.search(r'Toast\.makeText.*R\.string', line) or re.search(r'Toast\.makeText.*getString', line):
220 continue
221 # Only process lines with quoted literal after context comma
222 for m in toast_pat.finditer(line):
223 ctx_expr = m.group(1).strip()
224 lit = m.group(2)
225 if not is_valid_literal(lit):
226 continue
227 # Must have at least 2 letters for Toast as well
228 stripped = re.sub(r'\$\{[^}]+\}|\$[A-Za-z_][A-Za-z0-9_\.]*', '', lit)
229 if not re.search(r'[A-Za-z]{2,}', stripped):
230 if len(re.sub(r'[^A-Za-z]', '', stripped)) < 2:
231 continue
232 toast_literal_to_occurrences[lit].append((kf, idx, line, ctx_expr))
233
234 if not literal_to_occurrences and not toast_literal_to_occurrences:
235 # print(f"{mod}: no hardcoded left")
236 continue
237
238 # Determine new entries – unified for Text and Toast to reuse keys (additive)
239 new_entries_by_file = collections.defaultdict(list) # file stem -> list of (key, xml_value, original_lit, args)
240 lit_to_key = {}
241 all_lits = set(literal_to_occurrences.keys()) | set(toast_literal_to_occurrences.keys())
242
243 for lit in all_lits:
244 occs = literal_to_occurrences.get(lit) or toast_literal_to_occurrences.get(lit)
245 # Check if exact literal already mapped via value_to_key
246 if lit in value_to_key:
247 lit_to_key[lit] = value_to_key[lit]
248 continue
249 if lit.strip() in value_to_key:
250 lit_to_key[lit] = value_to_key[lit.strip()]
251 continue
252 # For interpolated, try to see if xml_value already exists
253 xml_val, args = to_xml_value(lit)
254 if xml_val in value_to_key:
255 lit_to_key[lit] = value_to_key[xml_val]
256 continue
257 if xml_val.strip() in value_to_key:
258 lit_to_key[lit] = value_to_key[xml_val.strip()]
259 continue
260 # Need new key
261 base = snake_key(lit)
262 key = base
263 suffix = 1
264 while key in keys:
265 key = f"{base}_{suffix}"
266 suffix += 1
267 if suffix > 100:
268 fallback_key = f"{base}_{deterministic_suffix(lit)}"
269 extra = 1
270 while fallback_key in keys and extra < 20:
271 fallback_key = f"{base}_{deterministic_suffix(lit + str(extra))}"
272 extra += 1
273 key = fallback_key if fallback_key not in keys else f"{base}_{deterministic_suffix(lit + '_final')}"
274 break
275 keys.add(key)
276 lit_to_key[lit] = key
277 # Group by file for XML comment
278 first_file = occs[0][0] if occs else None
279 try:
280 rel = first_file.relative_to(java_dir) if first_file else pathlib.Path("common")
281 stem = rel.parts[-1].replace('.kt','') if hasattr(rel, 'parts') else "common"
282 except:
283 stem = "common"
284 new_entries_by_file[stem].append((key, xml_val, lit, args))
285
286 # Add new entries to strings.xml
287 if new_entries_by_file:
288 insert_text = "\n <!-- Migrated hardcoded UI strings (auto) -->\n"
289 for stem, entries in sorted(new_entries_by_file.items()):
290 insert_text += f" <!-- {stem} -->\n"
291 for key, xml_val, orig_lit, args in entries:
292 esc = xml_escape(xml_val)
293 insert_text += f' <string name="{key}">{esc}</string>\n'
294 # Reload fresh content (in case previous loop modified? we have strings_content variable)
295 current = strings_path.read_text()
296 new_content = current.replace('</resources>', insert_text + '</resources>')
297 strings_path.write_text(new_content)
298 print(f"{mod}: added {sum(len(v) for v in new_entries_by_file.values())} new keys")
299
300 # Now replace in Kotlin files – preserved original Text() logic
301 # Sort literals by length descending for safe replacement
302 sorted_lits = sorted(literal_to_occurrences.keys(), key=lambda x: len(x), reverse=True)
303 for kf in kt_files:
304 try:
305 orig_content = kf.read_text()
306 except:
307 continue
308 content = orig_content
309 # Check if file contains any of the lits
310 if not any(lit in content for lit in sorted_lits):
311 continue
312
313 # Add imports if needed and file will be changed
314 will_change = False
315 for lit in sorted_lits:
316 if f'Text("{lit}")' in content:
317 # check line not already has stringResource
318 # quick
319 will_change = True
320 break
321 if not will_change:
322 continue
323
324 # Add imports
325 if 'import androidx.compose.ui.res.stringResource' not in content:
326 # Insert after last import
327 m = list(re.finditer(r'^import .+', content, re.MULTILINE))
328 if m:
329 last = m[-1]
330 pos = last.end()
331 content = content[:pos] + '\nimport androidx.compose.ui.res.stringResource' + content[pos:]
332 else:
333 # after package
334 content = re.sub(r'(package .+\n)', r'\1import androidx.compose.ui.res.stringResource\n', content, count=1)
335
336 r_import = f'import {pkg}.R'
337 if r_import not in content:
338 # Add after stringResource import
339 if 'import androidx.compose.ui.res.stringResource' in content:
340 content = content.replace('import androidx.compose.ui.res.stringResource', f'import androidx.compose.ui.res.stringResource\n{r_import}')
341 else:
342 # fallback add after package
343 content = re.sub(r'(package .+\n)', rf'\1{r_import}\n', content, count=1)
344
345 # Replace line by line
346 lines = content.splitlines()
347 new_lines = []
348 file_changed = False
349 for line in lines:
350 orig_line = line
351 # Quick skip
352 if 'Text("' not in line:
353 new_lines.append(line)
354 continue
355 if 'stringResource' in line or 'R.string' in line:
356 new_lines.append(line)
357 continue
358 if 'contentDescription' in line or 'Log.' in line:
359 new_lines.append(line)
360 continue
361 # For each lit, replace in this line (multiple different lits could be on same line? unlikely but handle)
362 new_line = line
363 for lit in sorted_lits:
364 if lit not in new_line:
365 continue
366 key = lit_to_key.get(lit)
367 if not key:
368 continue
369 # Re-check after partial replacements
370 if 'stringResource' in new_line and key in new_line:
371 # already replaced? skip
372 pass
373 # Extract args again for this lit
374 args = extract_args(lit)
375 # Build replacement Text(...)
376 # Escape lit for regex
377 esc_lit = re.escape(lit)
378 pat = re.compile(r'Text\s*\(\s*(?:text\s*=\s*)?"' + esc_lit + r'"\s*\)')
379 if args:
380 args_str = ", ".join(args)
381 repl = f'Text(stringResource(R.string.{key}, {args_str}))'
382 else:
383 repl = f'Text(stringResource(R.string.{key}))'
384 # Only replace one occurrence at a time to allow multiple different lits
385 # Use sub
386 # To avoid replacing inside already replaced, check not containing stringResource in immediate match
387 # Perform sub
388 new_line_candidate = pat.sub(repl, new_line)
389 if new_line_candidate != new_line:
390 file_changed = True
391 new_line = new_line_candidate
392 new_lines.append(new_line)
393
394 if file_changed:
395 new_content = "\n".join(new_lines)
396 if orig_content.endswith("\n"):
397 new_content += "\n"
398 kf.write_text(new_content)
399 print(f" Migrated file {kf.relative_to(root)}")
400
401 # Additive: Toast.makeText literal migration – new functionality preserving Text behavior above
402 sorted_toast_lits = sorted(toast_literal_to_occurrences.keys(), key=lambda x: len(x), reverse=True)
403 if sorted_toast_lits:
404 for kf in kt_files:
405 try:
406 orig_content = kf.read_text()
407 except:
408 continue
409 content = orig_content
410 if 'Toast.makeText' not in content:
411 continue
412 if not any(lit in content for lit in sorted_toast_lits):
413 continue
414 # Skip if all Toast lines already migrated – quick check
415 will_change_toast = False
416 for lit in sorted_toast_lits:
417 if lit in content and 'Toast.makeText' in content:
418 # Ensure not already containing getString for this literal context
419 will_change_toast = True
420 break
421 if not will_change_toast:
422 continue
423
424 # Ensure R import exists for Toast-only files
425 r_import = f'import {pkg}.R'
426 if r_import not in content:
427 # Prefer adding after existing R or stringResource import, else after last import
428 if 'import androidx.compose.ui.res.stringResource' in content:
429 content = content.replace('import androidx.compose.ui.res.stringResource', f'import androidx.compose.ui.res.stringResource\n{r_import}')
430 else:
431 m = list(re.finditer(r'^import .+', content, re.MULTILINE))
432 if m:
433 last = m[-1]
434 pos = last.end()
435 content = content[:pos] + f'\n{r_import}' + content[pos:]
436 else:
437 content = re.sub(r'(package .+\n)', rf'\1{r_import}\n', content, count=1)
438
439 lines = content.splitlines()
440 new_lines = []
441 file_changed = False
442 for line in lines:
443 new_line = line
444 if 'Toast.makeText' not in new_line:
445 new_lines.append(new_line)
446 continue
447 if 'getString' in new_line and 'R.string' in new_line:
448 # Already migrated this line
449 # But still allow other lits on same line – check via loop below (skip if contains getString for simplicity)
450 # To preserve safety, we will attempt replacement even if getString present, but pattern will not match already migrated
451 pass
452 if re.search(r'Toast\.makeText.*R\.string', new_line):
453 # Contains already migrated – skip if also contains getString
454 if 'getString' in new_line:
455 new_lines.append(new_line)
456 continue
457 for lit in sorted_toast_lits:
458 if lit not in new_line:
459 continue
460 key = lit_to_key.get(lit)
461 if not key:
462 continue
463 esc_lit = re.escape(lit)
464 toast_repl_pat = re.compile(r'((?:android\.widget\.)?Toast\.makeText\s*\(\s*)([^,]+?)\s*,\s*"' + esc_lit + r'"\s*,')
465 def toast_repl_func(m, _key=key, _lit=lit):
466 prefix = m.group(1)
467 ctx = m.group(2).strip()
468 args = extract_args(_lit)
469 if args:
470 args_str = ", ".join(args)
471 return f'{prefix}{ctx}, {ctx}.getString(R.string.{_key}, {args_str}),'
472 else:
473 return f'{prefix}{ctx}, {ctx}.getString(R.string.{_key}),'
474 candidate = toast_repl_pat.sub(toast_repl_func, new_line)
475 if candidate != new_line:
476 file_changed = True
477 new_line = candidate
478 new_lines.append(new_line)
479
480 if file_changed:
481 new_content = "\n".join(new_lines)
482 if orig_content.endswith("\n"):
483 new_content += "\n"
484 kf.write_text(new_content)
485 print(f" Migrated Toast in file {kf.relative_to(root)}")
486
487print("Done")