build_messages.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. #!/usr/bin/env python3
  2. """
  3. Merge all .po files from translations/<lang>/sources/ into
  4. translations/<lang>/LC_MESSAGES/messages.po and compile them with pybabel.
  5. Usage:
  6. python tools/build_messages.py [--lang en] [--no-compile]
  7. """
  8. import argparse
  9. import re
  10. import subprocess
  11. import sys
  12. from datetime import datetime, timezone
  13. from pathlib import Path
  14. # ---------------------------------------------------------------------------
  15. # PO entry dataclass
  16. # ---------------------------------------------------------------------------
  17. class PoEntry:
  18. """Holds one PO message entry."""
  19. def __init__(self):
  20. self.comments: list[str] = [] # # … and #: … and #, …
  21. self.msgid: list[str] = [] # one or more lines
  22. self.msgid_plural: list[str] = []
  23. self.msgstr: list[str] = [] # singular or msgstr[0], [1] …
  24. self.msgstr_plural: dict[int, list[str]] = {}
  25. self.obsolete: bool = False
  26. @property
  27. def key(self) -> str:
  28. return "".join(self.msgid)
  29. def is_empty_header(self) -> bool:
  30. return self.key == ""
  31. def render(self) -> str:
  32. lines = []
  33. for c in self.comments:
  34. lines.append(c)
  35. if self.msgid_plural:
  36. lines.append(_render_field("msgid", self.msgid))
  37. lines.append(_render_field("msgid_plural", self.msgid_plural))
  38. for idx in sorted(self.msgstr_plural):
  39. lines.append(_render_field(f"msgstr[{idx}]", self.msgstr_plural[idx]))
  40. else:
  41. lines.append(_render_field("msgid", self.msgid))
  42. lines.append(_render_field("msgstr", self.msgstr))
  43. return "\n".join(lines)
  44. def _render_field(name: str, parts: list[str]) -> str:
  45. if len(parts) == 1:
  46. return f"{name} {parts[0]}"
  47. # multiline
  48. return f'{name} ""\n' + "\n".join(parts)
  49. # ---------------------------------------------------------------------------
  50. # Simple PO parser
  51. # ---------------------------------------------------------------------------
  52. def parse_po_entries(text: str) -> list[PoEntry]:
  53. """Return all non-header entries from a PO file text."""
  54. entries: list[PoEntry] = []
  55. current = PoEntry()
  56. state = "idle" # idle | comments | msgid | msgid_plural | msgstr | msgstr_plural
  57. def flush():
  58. nonlocal current
  59. if current.msgid or current.comments:
  60. entries.append(current)
  61. current = PoEntry()
  62. for raw_line in text.splitlines():
  63. line = raw_line.rstrip()
  64. # Obsolete entries – preserve but mark
  65. if line.startswith("#~"):
  66. if state not in ("idle", "comments"):
  67. flush()
  68. state = "idle"
  69. current.comments.append(line)
  70. current.obsolete = True
  71. state = "comments"
  72. continue
  73. # Blank line → flush entry
  74. if line == "":
  75. if state != "idle":
  76. flush()
  77. state = "idle"
  78. continue
  79. # Comment / reference / flag lines
  80. if line.startswith("#"):
  81. if state not in ("idle", "comments"):
  82. flush()
  83. state = "idle"
  84. current.comments.append(line)
  85. state = "comments"
  86. continue
  87. # Continuation string
  88. if line.startswith('"'):
  89. if state == "msgid":
  90. current.msgid.append(line)
  91. elif state == "msgid_plural":
  92. current.msgid_plural.append(line)
  93. elif state == "msgstr":
  94. current.msgstr.append(line)
  95. elif state == "msgstr_plural":
  96. current.msgstr_plural[_last_plural_idx(current)].append(line)
  97. continue
  98. # Keywords
  99. if line.startswith("msgid_plural "):
  100. value = line[len("msgid_plural ") :]
  101. current.msgid_plural = [value]
  102. state = "msgid_plural"
  103. continue
  104. if line.startswith("msgid "):
  105. value = line[len("msgid ") :]
  106. current.msgid = [value]
  107. state = "msgid"
  108. continue
  109. m = re.match(r"^msgstr\[(\d+)\] (.+)$", line)
  110. if m:
  111. idx = int(m.group(1))
  112. current.msgstr_plural[idx] = [m.group(2)]
  113. state = "msgstr_plural"
  114. continue
  115. if line.startswith("msgstr "):
  116. value = line[len("msgstr ") :]
  117. current.msgstr = [value]
  118. state = "msgstr"
  119. continue
  120. # Flush last entry
  121. if state != "idle":
  122. flush()
  123. return entries
  124. def _last_plural_idx(entry: PoEntry) -> int:
  125. return max(entry.msgstr_plural.keys()) if entry.msgstr_plural else 0
  126. # ---------------------------------------------------------------------------
  127. # Merge logic
  128. # ---------------------------------------------------------------------------
  129. PO_HEADER = """\
  130. # English translations for SquidStats.
  131. # Edit the files under sources/ and then run:
  132. # python tools/build_messages.py
  133. #
  134. msgid ""
  135. msgstr ""
  136. "Project-Id-Version: SquidStats\\n"
  137. "Report-Msgid-Bugs-To: \\n"
  138. "POT-Creation-Date: {now}\\n"
  139. "PO-Revision-Date: {now}\\n"
  140. "Last-Translator: \\n"
  141. "Language: {lang}\\n"
  142. "Language-Team: {lang} <LL@li.org>\\n"
  143. "Plural-Forms: nplurals=2; plural=(n != 1);\\n"
  144. "MIME-Version: 1.0\\n"
  145. "Content-Type: text/plain; charset=utf-8\\n"
  146. "Content-Transfer-Encoding: 8bit\\n"
  147. "Generated-By: build_messages.py\\n"
  148. """
  149. def merge_sources(sources_dir: Path) -> list[PoEntry]:
  150. """Read all .po files in sources_dir (sorted) and merge entries."""
  151. po_files = sorted(sources_dir.glob("*.po"))
  152. if not po_files:
  153. print(f" [!] No .po files found in {sources_dir}", file=sys.stderr)
  154. return []
  155. seen: dict[str, PoEntry] = {} # msgid → entry (deduplication)
  156. for po_file in po_files:
  157. print(f" Reading {po_file.name}")
  158. text = po_file.read_text(encoding="utf-8")
  159. for entry in parse_po_entries(text):
  160. if entry.is_empty_header():
  161. continue
  162. if entry.key not in seen:
  163. seen[entry.key] = entry
  164. # If duplicate, merge location comments
  165. else:
  166. existing = seen[entry.key]
  167. new_refs = [c for c in entry.comments if c.startswith("#:")]
  168. for ref in new_refs:
  169. if ref not in existing.comments:
  170. existing.comments.append(ref)
  171. return list(seen.values())
  172. def write_messages_po(output_path: Path, entries: list[PoEntry], lang: str) -> None:
  173. now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M%z")
  174. header = PO_HEADER.format(now=now, lang=lang)
  175. regular = [e for e in entries if not e.obsolete]
  176. obsolete = [e for e in entries if e.obsolete]
  177. blocks = [header]
  178. for entry in regular:
  179. blocks.append(entry.render())
  180. if obsolete:
  181. for entry in obsolete:
  182. blocks.append(entry.render())
  183. output_path.write_text("\n\n".join(blocks) + "\n", encoding="utf-8")
  184. print(
  185. f" Written → {output_path} ({len(regular)} entries, {len(obsolete)} obsolete)"
  186. )
  187. def compile_po(translations_dir: Path) -> bool:
  188. cmd = [
  189. sys.executable,
  190. "-m",
  191. "babel.messages.frontend",
  192. "compile",
  193. "-d",
  194. str(translations_dir),
  195. ]
  196. # Try the pybabel CLI as fallback
  197. pybabel_cmd = ["pybabel", "compile", "-d", str(translations_dir)]
  198. print(f"\n Running: pybabel compile -d {translations_dir}")
  199. try:
  200. result = subprocess.run( # noqa: S603
  201. pybabel_cmd,
  202. capture_output=True,
  203. text=True,
  204. shell=False,
  205. )
  206. if result.returncode == 0:
  207. print(result.stdout or " Compilation successful.")
  208. return True
  209. # Fallback to module invocation
  210. result2 = subprocess.run( # noqa: S603
  211. cmd,
  212. capture_output=True,
  213. text=True,
  214. shell=False,
  215. )
  216. if result2.returncode == 0:
  217. print(result2.stdout or " Compilation successful.")
  218. return True
  219. print(
  220. f" [ERROR] pybabel compile failed:\n{result.stderr}\n{result2.stderr}",
  221. file=sys.stderr,
  222. )
  223. return False
  224. except FileNotFoundError:
  225. result = subprocess.run( # noqa: S603
  226. cmd,
  227. capture_output=True,
  228. text=True,
  229. shell=False,
  230. )
  231. if result.returncode == 0:
  232. print(result.stdout or " Compilation successful.")
  233. return True
  234. print(f" [ERROR] {result.stderr}", file=sys.stderr)
  235. return False
  236. # ---------------------------------------------------------------------------
  237. # Main
  238. # ---------------------------------------------------------------------------
  239. def main():
  240. parser = argparse.ArgumentParser(
  241. description="Merge sources/*.po → messages.po and compile."
  242. )
  243. parser.add_argument("--lang", default="en", help="Language code (default: en)")
  244. parser.add_argument(
  245. "--no-compile", action="store_true", help="Skip pybabel compile step"
  246. )
  247. args = parser.parse_args()
  248. # Resolve paths relative to the project root (one level up from tools/)
  249. script_dir = Path(__file__).resolve().parent
  250. project_root = script_dir.parent
  251. translations_dir = project_root / "translations"
  252. lang_dir = translations_dir / args.lang
  253. sources_dir = lang_dir / "sources"
  254. output_path = lang_dir / "LC_MESSAGES" / "messages.po"
  255. print(f"\n=== Building messages.po for language: {args.lang} ===")
  256. print(f" Sources : {sources_dir}")
  257. print(f" Output : {output_path}\n")
  258. if not sources_dir.exists():
  259. print(f"[ERROR] Sources directory not found: {sources_dir}", file=sys.stderr)
  260. sys.exit(1)
  261. entries = merge_sources(sources_dir)
  262. if not entries:
  263. print("[ERROR] No entries found. Aborting.", file=sys.stderr)
  264. sys.exit(1)
  265. write_messages_po(output_path, entries, args.lang)
  266. if not args.no_compile:
  267. ok = compile_po(translations_dir)
  268. if not ok:
  269. sys.exit(1)
  270. print("\nDone.")
  271. if __name__ == "__main__":
  272. main()