i18n_keys.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # Lists the translatable strings of the UI (string literals passed to tr() / TR_NOOP()) and
  2. # checks them against a translation table.
  3. # Usage: python3 tools/i18n_keys.py [resources/i18n/pt-BR.txt] [--missing] [--unused]
  4. # --missing print the keys with no translation, as lines ready to paste into the table
  5. # --unused print table entries no source uses (JUCE's own strings are expected here)
  6. import pathlib, re, sys
  7. root = pathlib.Path(__file__).resolve().parent.parent
  8. def unescape(s):
  9. out, i = [], 0
  10. while i < len(s):
  11. c = s[i]
  12. if c == "\\" and i + 1 < len(s):
  13. n = s[i + 1]
  14. out.append({"n": "\n", "t": "\t", '"': '"', "\\": "\\", "'": "'"}.get(n, n))
  15. i += 2
  16. else:
  17. out.append(c)
  18. i += 1
  19. return "".join(out)
  20. def escape(s):
  21. return s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n").replace("\t", "\\t")
  22. def source_keys():
  23. keys = {}
  24. call = re.compile(r'(?<![A-Za-z0-9_])(tr|trc|TR_NOOP)\s*\(\s*')
  25. literal = re.compile(r'"((?:[^"\\\n]|\\.)*)"\s*')
  26. for path in sorted(list((root / "src").rglob("*.cpp")) + list((root / "src").rglob("*.h")) + list((root / "src").rglob("*.inc"))):
  27. text = path.read_text(encoding="utf-8", errors="replace")
  28. text = "\n".join("" if l.strip().startswith("//") else l for l in text.split("\n"))
  29. for m in call.finditer(text):
  30. pos, parts = m.end(), []
  31. while True:
  32. lm = literal.match(text, pos)
  33. if not lm:
  34. break
  35. parts.append(lm.group(1))
  36. pos = lm.end()
  37. if parts:
  38. keys.setdefault(unescape("".join(parts)), str(path.relative_to(root)))
  39. return keys
  40. def table(path):
  41. entries = {}
  42. pair = re.compile(r'^"((?:[^"\\]|\\.)*)"\s*=\s*"((?:[^"\\]|\\.)*)"\s*$')
  43. for line in pathlib.Path(path).read_text(encoding="utf-8").split("\n"):
  44. m = pair.match(line.strip())
  45. if m:
  46. entries[unescape(m.group(1))] = unescape(m.group(2))
  47. return entries
  48. if __name__ == "__main__":
  49. args = [a for a in sys.argv[1:] if not a.startswith("--")]
  50. path = args[0] if args else root / "resources/i18n/pt-BR.txt"
  51. keys = source_keys()
  52. entries = table(path) if pathlib.Path(path).exists() else {}
  53. missing = [k for k in keys if not entries.get(k)]
  54. if "--missing" in sys.argv:
  55. last = None
  56. for k in missing:
  57. if keys[k] != last:
  58. print(f"\n# {keys[k]}")
  59. last = keys[k]
  60. print(f'"{escape(k)}" = ""')
  61. elif "--unused" in sys.argv:
  62. for k in entries:
  63. if k not in keys:
  64. print(f'"{escape(k)}"')
  65. else:
  66. print(f"{len(keys)} keys in the sources, {len(entries)} entries in {path}, {len(missing)} missing")