`com.it.curated.{compose,android,desktop}` becomes `to.curare.{compose,android,desktop}`
across 700 file moves, and the app is Curare everywhere a user can read it. This is the
third rename this tree has been through, so the question was never how to spell the new
name but which of the 5074 occurrences of the old one were the brand. `3bc8be53` and
`d26cf6c7` had already sorted most of that, which is why this rename is mechanical where
those two were not -- and why the interesting part is the one place it is still not.
**`APP_DIR_NAME` keeps the old brand, and is the only thing that does.** It names the
desktop app's data directory -- `~/.local/share/curated`, `Application Support/curated`,
`%LOCALAPPDATA%\curated` -- and that single directory holds the Room database, the marmot
group state and the phoenix wallet. Renaming it does not move an install: it silently
starts an empty one beside it and leaves the old chat history and the old seed sitting
where nothing reads them any more. That is the same class of silent failure as the
`mantra/` hash prefixes, so it gets the same treatment -- it stays, with a comment saying
what renaming it would cost and that doing it properly is a first-run migration rather
than a rebrand. The desktop app is `curated` on disk and `Curare` everywhere a user can
read.
**The applicationId and the namespace are one value again, at `to.curare.android`.**
`3bc8be53` split them precisely so `com.it.curated` could land verbatim as the store
identity while the namespace kept `.android`; the decision here was to collapse them, so
both read `to.curare.android` and the manifest's relative `android:name=".CurareApplication"`
and `BuildConfig` resolve against the same package they always did. Debug is
`to.curare.android.debug` through the existing suffix. Worth stating plainly because
nothing in the build will: an applicationId *is* the app's identity to Play, so this is a
new listing rather than an update, and no installed Curated can update into it.
**`CuratedDatabase` -> `CurareDatabase` moves a directory, never a table.** The `@Database`
class name picks the schema *directory*, so
`composeApp/schemas/com.it.curated.compose.database.CuratedDatabase/` becomes
`to.curare.compose.database.CurareDatabase/` and its 19 files move unmodified. What makes
that safe has not changed since last time: the 12 entity classes are still `Mantra*` and
still declare no `tableName`, so Room still takes their class names as the SQLite table
names -- and this rename does not touch one of them. The check is that Room found all 19
schemas at the new directory and generated no twentieth.
**The generated resources package moved because `rootProject.name` did, again.** Compose
Resources derives it from the root project, so `Curated` -> `Curare` silently turns
`curated.composeapp.generated.resources` into `curare.composeapp.generated.resources` and
breaks 72 files' imports at once. Rewritten with them: the two string keys that carried
the brand -- `curated` and `sign_in_is_not_yet_available_while_curated_is` -- their three
call sites, and the eight `docs/scripts/` tools that hardcode the UI source path. The
audit reporting 582 `stringResource` sites and 178 `Icon(` call sites is the evidence
those tools still see the whole tree rather than an empty directory.
**A global rename edits the sentences that describe the previous rename, and two of them
came out false.** `material-design-conformance.md` recorded that `TorchTheme` became
`CuratedTheme` and that `UserAgent` was moved off Torch "when the app was rebranded to
Curated" -- which a blanket sweep turns into a claim about a change that had not happened
when it was written. Same in `HomeScreen`, where "the brand before that one" meant Torch
while Curated was current, and quietly came to mean Curated while still naming
`TorchTheme`. Both now say what happened, in order. The three deliberate Torch records --
the finding at :278, that note, and `NavigationRoutingTest`'s fixture -- are intact.
**What was protected stays protected, and now says "two rebrands".** `TWEAK_TAG`,
`HOST_KEY_DERIVATION_TAG` and `wss://ephemeral.mantra.press` are byte-identical; only the
prose around them moved, because "survived the rebrand to Curated" had stopped being the
whole story. The tree's 1668 `Mantra` and 17 `Torch` tokens differ from the 1666 and 16
before this change only by the words those comments added.
**iOS is `Curare` / `to.curare.ios`**, with the three pbxproj product references renamed
to match, and is unverified here for the same reason as last time -- the build gates the
ios targets behind `isMacOsX` and this was built on linux. The bundle id takes a platform
segment rather than the bare base it translates from, so that it reads alongside an
android applicationId that now carries one: `to.curare.android` and `to.curare.ios`, and
`to.curare` left as the base neither store claims.
1226 tests pass -- 787 in `:composeApp:jvmTest`, 439 in `:composeApp:testDebugUnitTest` --
`:composeApp:compileDebugKotlinAndroid` is clean, and `m3Audit` meets every budget.
Three stale things are left alone, because none of them is branding.
`.gitea/workflows/material-design-conformance.yml` still triggers on `branches: [mantra]`,
which stopped naming a branch that exists somewhere before this change and is now two
brands out; the three `torch_*` string keys still carry a brand two renames old, though
every value they hold reads Curare; and `androidMain/res/values/strings.xml` has opened
`<resources>a` since well before this. Each wants its own change.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
240 lines
9.4 KiB
Python
Executable File
240 lines
9.4 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Move interpolated UI strings into the catalogue as format strings.
|
|
|
|
Companion to m3-extract-strings.py, which handles literals with no interpolation. Here a
|
|
|
|
Text("Add chapter to ${uiState.artifact.name}")
|
|
|
|
becomes a resource holding `Add chapter to %1$s` and a call
|
|
|
|
Text(stringResource(Res.string.add_chapter_to, uiState.artifact.name))
|
|
|
|
**Only standalone literals.** A literal that is one term of a `+` concatenation is left
|
|
alone: reassembling `"a " + x + " b"` into a single format string means deciding what the
|
|
whole sentence is, and that is per-site reading rather than a rewrite. Those are listed by
|
|
--remaining.
|
|
|
|
Usage:
|
|
m3-extract-formatted.py dry run
|
|
m3-extract-formatted.py --apply
|
|
m3-extract-formatted.py --remaining list what is deliberately left
|
|
"""
|
|
import os, re, sys, io, collections
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
_helpers = open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
|
'm3-extract-strings.py')).read()
|
|
exec(_helpers.split('def resource_name(')[0]) # UI, STRINGS, kotlin_strings, ...
|
|
exec('def resource_name(' + _helpers.split('def resource_name(')[1].split('def xml_escape')[0])
|
|
|
|
DRY = '--apply' not in sys.argv
|
|
|
|
|
|
def split_template(body):
|
|
"""Kotlin template body -> (segments, expressions).
|
|
|
|
segments is the literal text with each interpolation replaced by a placeholder index.
|
|
"""
|
|
parts, exprs, i, buf = [], [], 0, ''
|
|
while i < len(body):
|
|
c = body[i]
|
|
if c == '\\':
|
|
buf += body[i:i + 2]
|
|
i += 2
|
|
continue
|
|
if c == '$' and i + 1 < len(body):
|
|
if body[i + 1] == '{':
|
|
depth, j = 1, i + 2
|
|
while j < len(body) and depth:
|
|
if body[j] == '{':
|
|
depth += 1
|
|
elif body[j] == '}':
|
|
depth -= 1
|
|
j += 1
|
|
parts.append(buf)
|
|
buf = ''
|
|
exprs.append(body[i + 2:j - 1])
|
|
i = j
|
|
continue
|
|
m = re.match(r'\$([A-Za-z_][A-Za-z0-9_]*)', body[i:])
|
|
if m:
|
|
parts.append(buf)
|
|
buf = ''
|
|
exprs.append(m.group(1))
|
|
i += m.end()
|
|
continue
|
|
buf += c
|
|
i += 1
|
|
parts.append(buf)
|
|
return parts, exprs
|
|
|
|
|
|
def unescape_for_xml(text):
|
|
"""Kotlin escapes -> what belongs in the resource file.
|
|
|
|
`\\uXXXX` and `\\"` are Kotlin source syntax with no meaning in XML, so they are
|
|
decoded: a resource file is UTF-8 and can hold the character itself. `\\n` is left
|
|
alone, because StringCatalogueJvmTest shows Compose Resources processes it and a
|
|
real newline in an XML value would be reflowed by the parser.
|
|
"""
|
|
out, i = '', 0
|
|
while i < len(text):
|
|
if text[i] == '\\' and i + 1 < len(text):
|
|
nxt = text[i + 1]
|
|
if nxt == 'u' and i + 6 <= len(text):
|
|
out += chr(int(text[i + 2:i + 6], 16))
|
|
i += 6
|
|
continue
|
|
if nxt in '"\'':
|
|
out += nxt
|
|
i += 2
|
|
continue
|
|
out += text[i]
|
|
i += 1
|
|
return out
|
|
|
|
|
|
def format_string(parts, exprs):
|
|
out = unescape_for_xml(parts[0]).replace('%', '%%')
|
|
for n, tail in enumerate(parts[1:], start=1):
|
|
out += f'%{n}$s' + unescape_for_xml(tail).replace('%', '%%')
|
|
return out
|
|
|
|
|
|
def candidates(source):
|
|
"""(start, end, body, exprs, format_string) for standalone interpolated literals."""
|
|
spans = text_call_spans(source)
|
|
found = []
|
|
for start, end, body, interpolated in kotlin_strings(source):
|
|
if not interpolated or not body.strip():
|
|
continue
|
|
if not any(a <= start <= b for a, b in spans):
|
|
continue
|
|
line_start = source.rfind('\n', 0, start) + 1
|
|
line = source[line_start:source.find('\n', start)]
|
|
if line.lstrip().startswith(('//', '*', '/*')):
|
|
continue
|
|
before, after = source[:start].rstrip(), source[end:].lstrip()
|
|
stripped = line.strip()
|
|
if before.endswith('+') or after.startswith('+') or \
|
|
stripped.endswith('+') or stripped.startswith('+'):
|
|
continue
|
|
parts, exprs = split_template(body)
|
|
if not exprs:
|
|
continue
|
|
# A template that is *only* interpolation has nothing to translate.
|
|
# `Text("$name")` would become `stringResource(Res.string.string, name)`, which is
|
|
# a resource holding "%1$s" -- longer, slower and no more localisable than the
|
|
# code it replaced. Same for one whose literal half is punctuation or a spacer.
|
|
literal = unescape_for_xml(''.join(parts))
|
|
if not any(c.isalpha() for c in literal):
|
|
continue
|
|
fmt = format_string(parts, exprs)
|
|
# A leading or trailing space means the string is being glued to a neighbour --
|
|
# " \u00b7 %1$s" is a separator, not a sentence. The test is on the *format
|
|
# string*, not on the literal halves: a template that opens with an interpolation
|
|
# leaves parts[0] empty and parts[1] starting with the space that separates them,
|
|
# so joining the halves makes "%1$s Key packages" look like a fragment when it is
|
|
# a whole label.
|
|
if fmt != fmt.strip():
|
|
continue
|
|
found.append((start, end, body, exprs, fmt))
|
|
return found
|
|
|
|
|
|
|
|
def has_import(source, statement):
|
|
"""Whole-line match.
|
|
|
|
`statement in source` is wrong here and silently so: the accessors are named after
|
|
their strings, so `...resources.translate` is a prefix of
|
|
`...resources.translate_into_which_dialect`, and a substring test decides the import
|
|
is already present. The compiler then reports "Unresolved reference 'translate'" in a
|
|
file whose imports look complete.
|
|
"""
|
|
return any(line.strip() == statement for line in source.split('\n'))
|
|
|
|
def main():
|
|
if '--remaining' in sys.argv:
|
|
for root, _, files in os.walk(UI):
|
|
for f in sorted(files):
|
|
if not f.endswith('.kt'):
|
|
continue
|
|
path = os.path.join(root, f)
|
|
src = open(path, encoding='utf-8').read()
|
|
spans = text_call_spans(src)
|
|
done = {(a, b) for a, b, *_ in candidates(src)}
|
|
for a, b, body, _i in kotlin_strings(src):
|
|
if not body.strip() or (a, b) in done:
|
|
continue
|
|
if not any(x <= a <= y for x, y in spans):
|
|
continue
|
|
line_start = src.rfind('\n', 0, a) + 1
|
|
line = src[line_start:src.find('\n', a)]
|
|
if line.lstrip().startswith(('//', '*', '/*')):
|
|
continue
|
|
print(f' {path.replace(UI + "/", "")}:{src[:a].count(chr(10)) + 1} {body[:70]!r}')
|
|
return 0
|
|
|
|
plan = {}
|
|
for root, _, files in os.walk(UI):
|
|
for f in sorted(files):
|
|
if not f.endswith('.kt'):
|
|
continue
|
|
path = os.path.join(root, f)
|
|
for _s, _e, body, exprs, fmt in candidates(open(path, encoding='utf-8').read()):
|
|
plan[fmt] = plan.get(fmt, 0) + 1
|
|
|
|
existing = io.open(STRINGS, encoding='utf-8').read()
|
|
taken = set(re.findall(r'<string name="([^"]+)"', existing))
|
|
names = {}
|
|
for fmt in sorted(plan):
|
|
# name from the literal half only -- "%1$s" contributes nothing readable
|
|
names[fmt] = resource_name(re.sub(r'%\d+\$s', ' ', fmt), taken)
|
|
taken.add(names[fmt])
|
|
|
|
print(f'{len(plan)} distinct format strings, {sum(plan.values())} occurrences')
|
|
if DRY:
|
|
for fmt in sorted(plan)[:12]:
|
|
print(f' {names[fmt]:44s} {fmt[:64]!r}')
|
|
return 0
|
|
|
|
rewritten = 0
|
|
for root, _, files in os.walk(UI):
|
|
for f in sorted(files):
|
|
if not f.endswith('.kt'):
|
|
continue
|
|
path = os.path.join(root, f)
|
|
src = io.open(path, encoding='utf-8').read()
|
|
found = candidates(src)
|
|
if not found:
|
|
continue
|
|
for start, end, _body, exprs, fmt in reversed(found):
|
|
args = ', '.join(exprs)
|
|
src = src[:start] + f'stringResource(Res.string.{names[fmt]}, {args})' + src[end:]
|
|
rewritten += 1
|
|
need = sorted({names[fmt] for *_x, fmt in [(c[0], c[4]) for c in found]})
|
|
for imp in (['import curare.composeapp.generated.resources.Res',
|
|
'import org.jetbrains.compose.resources.stringResource']
|
|
+ [f'import curare.composeapp.generated.resources.{n}' for n in need]):
|
|
if not has_import(src, imp):
|
|
lines = src.split('\n')
|
|
idx = max(i for i, l in enumerate(lines) if l.startswith('import '))
|
|
lines.insert(idx + 1, imp)
|
|
src = '\n'.join(lines)
|
|
io.open(path, 'w', encoding='utf-8').write(src)
|
|
print(f'{rewritten} call sites rewritten')
|
|
|
|
entries = '\n'.join(
|
|
f' <string name="{names[fmt]}">'
|
|
f'{fmt.replace("&", "&").replace("<", "<").replace(">", ">")}</string>'
|
|
for fmt in sorted(plan, key=lambda x: names[x]))
|
|
io.open(STRINGS, 'w', encoding='utf-8').write(
|
|
existing.replace('</resources>', entries + '\n</resources>'))
|
|
print(f'{len(plan)} entries written')
|
|
return 0
|
|
|
|
|
|
if __name__ == '__main__':
|
|
sys.exit(main())
|