Files
thoughtsync/android/tools/check-strings.py
T
bvandeusen 452c66c8ef
Desktop (Tauri) / Windows installer (cross-compiled) (push) Successful in 3m3s
Desktop (Tauri) / Tauri desktop (Linux) (push) Successful in 5m15s
Desktop (Tauri) / Update manifest (push) Successful in 4s
Android / Kotlin + Rust (debug APK) (push) Canceled after 6m32s
android: sync without being asked (M12 step 6)
Until now every sync was a button press. Pull-to-refresh made asking cheaper; it
did not stop the app needing to be asked, which on a phone means a note written
on the bus reaches the desktop whenever you next happen to open the app.

Three moments, and they are deliberately not the same job:

  * **Coming to the front**, if the last sync is over five minutes old or there
    is unsent work. Not on every foreground: stepping out to copy a link and
    stepping back is not a request for fresh notes, and syncing on every app
    switch spends someone's mobile data telling them what they are looking at.
  * **Going away with unsent work** — handed to WorkManager rather than run
    inline, because the process is about to stop being a priority and a sync
    started there would be killed halfway. This is the one that matters most: it
    is what gets a note off a phone that then goes into a pocket for the night.
  * **Every fifteen minutes**, network-constrained. Fifteen is not a preference,
    it is WorkManager's floor for periodic work; asking for less gets fifteen.

**An automatic sync must not raise an error banner.** Someone who pulled the
board down is owed an answer; someone who merely opened the app did not ask a
question, and answering it with a red banner about an unreachable server makes
their own notes look broken when nothing of theirs is. So `syncNow` and
`syncQuietly` differ in exactly one thing — whether failure is announced. The
quiet channel for a persistent problem is the drawer badge, from `has_pending`,
which does not care how the attempt was made.

**There is a switch, defaulting to on.** Linking a server IS the consent; a
person who paired a device and then had to find a second toggle before anything
moved would reasonably call that broken. It lives in SharedPreferences rather
than the store: everything else in sync state describes the PAIRING and must
survive a reinstall, while this describes how one handset behaves, and someone
turning it off on their phone is not asking their laptop to stop. The copy says
what "automatically" means in minutes and says that off is not off — a switch
next to a Disconnect button invites exactly that misreading.

The schedule is DECLARED as a function of (linked, switch) in a LaunchedEffect
rather than toggled from the places that change them. There are four routes to
"should not be syncing on its own" and a call at each is four chances to leave a
phone quietly syncing after it was told to stop.

`ON_START`/`ON_STOP`, not resume/pause — the same choice the editor's save-on-
leave makes, because pause fires for anything covering the window and a sync per
notification-shade pull is not automatic sync, it is a stutter.

RECEIVE_BOOT_COMPLETED now appears in the merged manifest. WorkManager
contributes it so the schedule survives a restart; commented in AndroidManifest
because it shows in the app's permission list and nothing else in that file
would explain it.

Two things read from artifacts rather than recalled, both of which memory would
have got wrong: `work-runtime-ktx` is an empty 6 KB stub as of 2.11 with
`CoroutineWorker` and `PeriodicWorkRequestBuilder` moved into `work-runtime`, so
the dependency is on the latter alone; and `Switch` is not experimental in
material3 1.4.0, so no `@OptIn` — an unnecessary one is itself a warning.

Also adds `android/tools/check-strings.py`, after this change added three
strings: `R` is generated, so `R.string.typo` type-checks whether or not the
string exists. It catches a missing name, `stringResource` on a plural or the
reverse, and a format taking more arguments than the call passes. Verified
against a tree with one of each fault — its first version counted Kotlin's
trailing commas as arguments and called three correct sites broken, which is the
failure that teaches you to ignore a tool.

Two comments in this change were wrong when written and are corrected here
rather than left: the flag check in SyncWorker does NOT avoid opening the store,
because Application.onCreate has already run by the time any Worker starts.
2026-08-19 19:04:45 -04:00

112 lines
3.6 KiB
Python
Executable File

#!/usr/bin/env python3
"""Check every R.string / R.plurals reference against strings.xml.
Three ways a resource reference compiles and then fails, none of which ktlint,
detekt or the Kotlin compiler will catch:
1. the name does not exist -> resource-not-found at runtime
2. `stringResource` on a plural (or the reverse) -> wrong overload, wrong text
3. the format string takes more arguments than the call passes -> the format
silently renders `%2$s` as literal text, or throws
python3 android/tools/check-strings.py
Exits non-zero on any problem.
"""
import glob
import os
import re
import sys
import xml.etree.ElementTree as ET
BASE = (
sys.argv[1]
if len(sys.argv) > 1
else os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
)
STRINGS = os.path.join(BASE, "app", "src", "main", "res", "values", "strings.xml")
SOURCES = os.path.join(BASE, "app", "src", "main", "java", "**", "*.kt")
CALL = re.compile(
r"(stringResource|pluralStringResource)\(\s*R\.(string|plurals)\.(\w+)"
r"((?:[^()]|\([^()]*\))*)\)"
)
def arity(text):
"""How many distinct arguments a format string consumes."""
numbered = set(re.findall(r"%(\d)\$", text))
return len(numbered) if numbered else len(re.findall(r"%[sd]", text))
def supplied_args(rest):
"""Count top-level commas in an argument tail.
Kotlin permits a TRAILING comma before the closing paren, which is not an
argument — counting it inflated every multi-line call by one the first time
this was written, and made three correct call sites look broken. Braces count
toward depth as well as parens, or a comma inside a lambda would be read as
another argument.
"""
rest = rest.rstrip()
if rest.endswith(","):
rest = rest[:-1]
depth = 0
count = 0
for ch in rest:
if ch in "([{":
depth += 1
elif ch in ")]}":
depth -= 1
elif ch == "," and depth == 0:
count += 1
return count
def main():
root = ET.parse(STRINGS).getroot()
strings = {e.get("name"): "".join(e.itertext()) for e in root.findall("string")}
plurals = {
e.get("name"): max(
(arity("".join(i.itertext())) for i in e.findall("item")), default=0
)
for e in root.findall("plurals")
}
problems = 0
for path in glob.glob(SOURCES, recursive=True):
with open(path, encoding="utf-8") as fh:
src = fh.read()
for match in CALL.finditer(src):
fn, kind, name, rest = match.groups()
line = src[: match.start()].count("\n") + 1
where = f"{os.path.basename(path)}:{line} {name}"
if kind == "string" and name not in strings:
print(f"MISSING {where}: no such string")
problems += 1
continue
if kind == "plurals" and name not in plurals:
print(f"MISSING {where}: no such plural")
problems += 1
continue
if (fn == "pluralStringResource") != (kind == "plurals"):
print(f"KIND {where}: {fn} used on R.{kind}")
problems += 1
continue
passed = supplied_args(rest)
# A plural call passes the count first, then the format arguments.
wanted = arity(strings[name]) if kind == "string" else plurals[name] + 1
if passed != wanted:
print(f"ARITY {where}: wants {wanted}, call passes {passed}")
problems += 1
print(f"\n{len(strings)} strings, {len(plurals)} plurals, {problems} problems")
return 1 if problems else 0
if __name__ == "__main__":
sys.exit(main())