Cotton code
246 lines · 10.5 KB · TypeScriptRaw
#!/usr/bin/env node// Keep `Localizable.xcstrings` in step with what `CottonStrings` actually says.//// The design system's rule is that every user-visible sentence goes through// `CottonStrings.local(_:)`, and the catalogue is keyed by the ENGLISH TEXT// itself — so a sentence with no catalogue entry still renders correctly, and// the catalogue is a place to READ the app's language rather than a lookup the// app depends on. That is exactly why it drifts silently: nothing goes red when// a lane adds thirty sentences and forgets it.//// This script closes that by DERIVING the catalogue from the sources. It is not// a formatter and it never rewrites an existing entry: it adds the keys that are// missing and leaves everything else alone, so a hand-written plural variation// or a corrected wording survives a run.//// The one subtle part is the key. Swift turns `local("\(n) days late")` into the// format string `"%lld days late"` — the specifier comes from the interpolated// value's TYPE, not from its name — so the script reads the enclosing function's// parameter list to type each interpolation. An interpolation it cannot type is// a sentence it refuses to add, and it says which, because a guessed specifier// would mint a near-duplicate key differing only in `%@` vs `%lld`, which is the// exact mess this replaced (two runs of an earlier ad-hoc version left the file// carrying `"%@ MB so far"` beside `"%lld MB so far"`).//// Since I4 the app's copy lives at the CALL SITE as a literal, and a member// survives in a `Strings*.swift` table only when the same sentence is said in// three or more places. So the catalogue drifts in the other direction too — an// entry whose sentence has left the tables is an entry nothing says any more —// and `--stale` reports those, deleting them when `--write` is passed with it.////   node scripts/ios-strings-catalogue.mjs                    # what is missing//   node scripts/ios-strings-catalogue.mjs --write            # add it//   node scripts/ios-strings-catalogue.mjs --stale            # + what is dead//   node scripts/ios-strings-catalogue.mjs --stale --write    # add and pruneimport { readFileSync, writeFileSync, readdirSync } from "node:fs";import { join } from "node:path";import { fileURLToPath } from "node:url";const ROOT = fileURLToPath(new URL("..", import.meta.url));const SOURCES = join(ROOT, "apps/cotton/Sources/CottonUI");const CATALOGUE = join(SOURCES, "Resources/Localizable.xcstrings");/** Swift's own mapping from an interpolated type to a format specifier. */const SPECIFIER = { Int: "%lld", Double: "%lf", String: "%@" };/** * Every `Strings*.swift` — and ONLY those, on purpose. * * The catalogue is derived from `local("…")`, and `local` is an internal static * func of the `CottonStrings` enum, so the only file that can write one is a * file extending that enum: a table. Copy at a call site is a bare literal * (`Text("Done")`) which goes through no lookup at all and so has no catalogue * key to derive — walking `Screens/` for it would mint keys for sentences the * catalogue is never asked about. */export function stringFiles(dir = SOURCES) {  return readdirSync(dir)    .filter((n) => n.startsWith("Strings") && n.endsWith(".swift"))    .map((n) => join(dir, n));}/** * The catalogue key for one `local("…")` literal. * * `types` maps an identifier to its Swift type, taken from the enclosing * function's parameters. Returns `null` when an interpolation cannot be typed — * the caller reports it rather than guessing. */export function keyFor(literal, types) {  let out = "";  let i = 0;  while (i < literal.length) {    if (literal.startsWith("\\(", i)) {      let depth = 1;      let j = i + 2;      while (j < literal.length && depth > 0) {        if (literal[j] === "(") depth += 1;        else if (literal[j] === ")") depth -= 1;        j += 1;      }      const expr = literal.slice(i + 2, j - 1).trim();      const specifier = SPECIFIER[types.get(expr)];      if (!specifier) return { key: null, untyped: expr };      out += specifier;      i = j;      continue;    }    // `\u{00B7}` and friends: a Swift escape, not an interpolation.    if (literal.startsWith("\\u{", i)) {      const j = literal.indexOf("}", i) + 1;      out += String.fromCodePoint(parseInt(literal.slice(i + 3, j - 1), 16));      i = j;      continue;    }    if (literal[i] === "\\") {      const next = literal[i + 1];      out += next === "n" ? "\n" : next === "t" ? "\t" : next;      i += 2;      continue;    }    out += literal[i];    i += 1;  }  return { key: out, untyped: null };}/** * Every sentence one file says, with each interpolation typed from the function * it sits in. A `var` declaration has no parameters, which is why an untypeable * interpolation is almost always a sentence written in the wrong shape. */export function sentencesIn(text) {  const found = [];  const untyped = [];  // Split on declarations so each literal is read under its own signature.  const decls = text.split(/\n(?=\s*(?:public|internal|private)\s+static\s)/);  for (const decl of decls) {    const types = new Map();    const signature = decl.match(/\(([^)]*)\)\s*->/);    if (signature) {      for (const part of signature[1].split(",")) {        const m = part.trim().match(/^(?:([A-Za-z_]\w*)\s+)?([A-Za-z_]\w*)\s*:\s*([A-Za-z]\w*)/);        if (m) types.set(m[2], m[3]);      }    }    // The literal may sit on its own line — `local(\n  "…"\n)` is how    // swift-format wraps a long sentence — so the pattern spans the wrap.    // Measured 2026-09-10 on phone-4h-swift: the single-line form reported    // "0 sentences missing" while 91 wrapped literals were invisible to it and    // 59 of them had no catalogue entry (the privacy policy and terms, the join    // and refusal screens, the keyboard setup line).    for (const m of decl.matchAll(/local\(\s*"((?:[^"\\]|\\.)*)"\s*\)/g)) {      const { key, untyped: bad } = keyFor(m[1], types);      if (key === null) untyped.push({ literal: m[1], expr: bad });      else found.push(key);    }  }  return { found, untyped };}/** Every specifier blanked, so a variant of an existing key is never added. */export function shape(key) {  // The blank is a NUL, which no sentence can contain, written as an ESCAPE:  // a raw one in the source makes git read this whole file as binary, and a  // script nobody can diff is a script nobody reviews.  return key.replace(/%(?:lld|lf|@)/g, "\0");}/** * The catalogue entries no `Strings*.swift` says any more. * * Shape-tolerant in the same direction the add pass is. `"%@ MB so far"` and * `"%lld MB so far"` are ONE sentence whose interpolation changed type, and the * add pass deliberately does not mint the second key while the first is there — * so a prune on the exact key alone would delete the entry the add pass had * just declined to replace, and the sentence would leave the catalogue * altogether. An entry whose SHAPE a live sentence still has is kept. * * Pure: it is handed both key sets rather than reading either. */export function staleKeys(catalogueKeys, liveKeys) {  const live = new Set(liveKeys);  const liveShapes = new Set([...live].map(shape));  return [...catalogueKeys].filter((key) => !live.has(key) && !liveShapes.has(shape(key))).sort();}/** * One literal's shape WITHOUT typing it — what a sentence looks like once every * interpolation is blanked. * * The ten sentences this script refuses to key (`\(groupedFigure(count))` and * friends) are still said by a table, so a prune that only knew the keys it * could compute would read them as dead and delete entries the app renders from * today. Their shape is computable even when their specifier is not, and the * shape is what the prune already compares on, so it is enough to hold them. * * `keyFor` is reused with a type table that answers every identifier, which * gives `%@` throughout; `shape` then blanks those to the same marker a typed * key's would be. A guessed specifier never leaves this function. */export function looseShape(literal) {  return shape(keyFor(literal, { get: () => "String" }).key);}function main() {  const write = process.argv.includes("--write");  const pruning = process.argv.includes("--stale");  const catalogue = JSON.parse(readFileSync(CATALOGUE, "utf8"));  const have = new Set(Object.keys(catalogue.strings));  const haveShapes = new Set([...have].map(shape));  const live = new Set();  const missing = new Set();  const untyped = [];  for (const file of stringFiles()) {    const { found, untyped: bad } = sentencesIn(readFileSync(file, "utf8"));    for (const key of found) {      live.add(key);      if (have.has(key) || haveShapes.has(shape(key))) continue;      missing.add(key);    }    for (const b of bad) untyped.push({ file, ...b });  }  for (const b of untyped) {    console.warn(`untyped interpolation \\(${b.expr}) in "${b.literal}" — not added`);  }  console.log(`${have.size} entries, ${missing.size} sentences missing`);  // An untyped literal yields no key, so it is not in `live` — and a prune that  // read that absence as "nothing says this" would delete an entry a table  // still says. `looseShape` holds those ten sentences by shape instead, which  // is what the prune compares on anyway.  let stale = [];  if (pruning) {    stale = staleKeys(have, [...live, ...untyped.map((b) => looseShape(b.literal))]);    console.log(`${stale.length} entries no sentence says any more`);  }  if (!write) {    for (const key of [...missing].sort()) console.log(`  + ${key}`);    for (const key of stale) console.log(`  - ${key}`);    return;  }  if (missing.size === 0 && stale.length === 0) return;  for (const key of missing) {    catalogue.strings[key] = {      localizations: { en: { stringUnit: { state: "translated", value: key } } },    };  }  for (const key of stale) delete catalogue.strings[key];  const sorted = {};  for (const key of Object.keys(catalogue.strings).sort()) sorted[key] = catalogue.strings[key];  catalogue.strings = sorted;  // Xcode keeps the file ASCII (`\u2014`, never a raw em dash), so the write  // does too — otherwise every non-ASCII entry re-flows and a three-key change  // is a two-hundred-line diff that conflicts with every open lane.  const ascii = JSON.stringify(catalogue, null, 2).replace(/[^\x00-\x7f]/g, (c) =>    `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`,  );  writeFileSync(CATALOGUE, `${ascii}\n`);  console.log(`wrote ${Object.keys(sorted).length} entries`);}if (process.argv[1] && import.meta.url.endsWith(process.argv[1].split("/").pop())) main();