#!/usr/bin/env python3 """Every key used in the code must exist in every catalogue. A UI that is half translated is worse than one that is not translated at all: the operator cannot tell a missing string from a deliberate one. This walks the sources for sp_t()/sp_td() keys and compares them with share/locale/*.msg. """ import pathlib import re import sys ROOT = pathlib.Path(__file__).resolve().parent.parent KEY = re.compile(r'sp_td?\(\s*"([^"]+)"') def used_keys(): keys = set() sources = list(ROOT.glob("src/**/*.c")) sources += list(ROOT.glob("plugins/*/*.c")) for path in sources: keys.update(KEY.findall(path.read_text(encoding="utf-8", errors="replace"))) return keys def catalogue(path): out = {} for line in path.read_text(encoding="utf-8").splitlines(): line = line.strip() if not line or line.startswith("#") or "=" not in line: continue k, v = line.split("=", 1) out[k.strip()] = v.strip() return out # Anything drawn on the screen must come from a catalogue. These are the calls # that put text into a curses window; a literal there is a string the operator # can never translate. DRAW = re.compile(r'\b(mvwaddstr|mvwaddnstr|mvwprintw|waddstr|wprintw|winsstr)\s*\(') LITERAL_ARG = re.compile(r',\s*"([^"\\]*(?:\\.[^"\\]*)*)"') def hardcoded(): bad = [] for path in ROOT.glob("src/**/*.c"): for no, line in enumerate(path.read_text(encoding="utf-8", errors="replace").splitlines(), 1): if not DRAW.search(line) or "sp_t" in line: continue m = LITERAL_ARG.search(line) if m is not None: bad.append(f"{path.name}:{no}: {m.group(1)!r}") return bad # A catalogue text is data, never a format: a "%" in a translation that reaches # printf as the format is read as a conversion (undefined behaviour, and clang's # -Wformat-security says so). sp_t()/sp_td() may be an argument, never the # format itself. PRINTF = re.compile(r'\b(snprintf|vsnprintf|sp_buf_printf|fprintf|printf|' r'sprintf|syslog)\s*\(') # which argument is the format, per callee FMT_ARG = {"snprintf": 2, "vsnprintf": 2, "sp_buf_printf": 1, "fprintf": 1, "printf": 0, "sprintf": 1, "syslog": 1} def top_level_args(text, start): """The arguments of the call whose '(' is at text[start], split at depth 1.""" args, depth, i, cur = [], 1, start + 1, start + 1 quote = None while i < len(text): c = text[i] if quote is not None: if c == "\\": i += 2 continue if c == quote: quote = None elif c in "\"'": quote = c elif c == "(": depth += 1 elif c == ")": depth -= 1 if depth == 0: args.append(text[cur:i]) return args elif c == "," and depth == 1: args.append(text[cur:i]) cur = i + 1 i += 1 return args def catalogue_as_format(): """A catalogue text may be a format only when arguments follow it. With no argument behind it, a '%' that creeps into a translation (or into an English entry written by hand) is read as a conversion: clang's -Wformat-security names exactly this call shape. """ bad = [] for path in ROOT.glob("src/**/*.c"): text = path.read_text(encoding="utf-8", errors="replace") for m in PRINTF.finditer(text): args = top_level_args(text, m.end() - 1) want = FMT_ARG.get(m.group(1), 1) if len(args) <= want: continue fmt = args[want].strip() if not (fmt.startswith("sp_t(") or fmt.startswith("sp_td(")): continue if len(args) > want + 1: continue # arguments follow: the conversions are meant line = text.count("\n", 0, m.start()) + 1 bad.append(f"{path.name}:{line}: {m.group(1)}(...) takes a " f"catalogue text as its format, with no argument " f"behind it") return bad # Roles are keys too: add_entry() takes an identifier, the label comes from the # catalogue. An unknown identifier would ship as untranslated text. ROLE_CALL = re.compile(r'add_entry\(\s*&?[A-Za-z_>.-]*\s*,\s*"([a-z_]+)"') ALLOWED_ROLES = {"you", "agent", "thinking", "tool", "observation", "error", "shell", "splinter", "diff"} def unknown_roles(): bad = [] for path in ROOT.glob("src/**/*.c"): for no, line in enumerate(path.read_text(encoding="utf-8", errors="replace").splitlines(), 1): for role in ROLE_CALL.findall(line): if role not in ALLOWED_ROLES: bad.append(f"{path.name}:{no}: role {role!r} has no label") return bad def main(): used = used_keys() # role. is built by role_label(), never written literally used.add("role.you"); used.add("role.agent"); used.add("role.thinking") used.add("role.tool"); used.add("role.observation"); used.add("role.error") used.add("role.shell"); used.add("role.splinter"); used.add("role.diff") bad = 0 cats = sorted(ROOT.glob("share/locale/*.msg")) if not cats: print("check_i18n: no catalogues in share/locale", file=sys.stderr) return 1 for path in cats: cat = catalogue(path) missing = sorted(k for k in used if k not in cat) if missing: bad = 1 print(f"{path.name}: missing {len(missing)} key(s): " + ", ".join(missing), file=sys.stderr) # the English catalogue is the reference: everything in it must be used en = catalogue(ROOT / "share/locale/en.msg") # keys built at run time from a name: interview.q., widget. dynamic = ("interview.q.", "interview.h.", "widget.") unused = sorted(k for k in en if k not in used and not k.startswith(dynamic)) if unused: print("en.msg: keys nothing uses: " + ", ".join(unused), file=sys.stderr) roles = unknown_roles() if roles: bad = 1 print("unknown role identifiers:", file=sys.stderr) for item in roles: print(" " + item, file=sys.stderr) lit = hardcoded() if lit: bad = 1 print("hardcoded text on screen (use sp_t/sp_td):", file=sys.stderr) for item in lit: print(" " + item, file=sys.stderr) fmt = catalogue_as_format() if fmt: bad = 1 print("catalogue text used as a printf format:", file=sys.stderr) for item in fmt: print(" " + item, file=sys.stderr) if bad == 0: print(f"check_i18n: ok ({len(used)} keys in {len(cats)} catalogues)") return bad if __name__ == "__main__": sys.exit(main())