|
4 | 4 |
|
5 | 5 | import argparse |
6 | 6 | import ast |
| 7 | +import json |
7 | 8 | import subprocess |
8 | 9 | import tomllib |
9 | 10 | from pathlib import Path |
10 | 11 |
|
| 12 | +from babel.messages.mofile import read_mo |
| 13 | +from babel.messages.pofile import read_po |
11 | 14 | from hatchling.builders.hooks.plugin.interface import BuildHookInterface |
12 | 15 |
|
13 | 16 | # Global variables used by pybabel below (paths relative to PROJECT_DIR) |
@@ -107,6 +110,43 @@ def compile_catalogs(locale: str) -> None: |
107 | 110 | cmd.extend(["-l", locale]) |
108 | 111 | subprocess.run(cmd, cwd=PROJECT_DIR, check=True) |
109 | 112 |
|
| 113 | + locale_dirs = PROJECT_DIR / LOCALES_DIR |
| 114 | + catalogs = ( |
| 115 | + [locale_dirs / locale / "LC_MESSAGES" / f"{DOMAIN}.po"] |
| 116 | + if locale |
| 117 | + else sorted(locale_dirs.glob(f"*/LC_MESSAGES/{DOMAIN}.po")) |
| 118 | + ) |
| 119 | + for pofile in catalogs: |
| 120 | + compile_js_catalog(pofile) |
| 121 | + |
| 122 | + |
| 123 | +def compile_js_catalog(pofile: Path) -> None: |
| 124 | + """Export translated singular JavaScript messages from the compiled catalog.""" |
| 125 | + mofile = pofile.with_suffix(".mo") |
| 126 | + jsfile = pofile.with_suffix(".js") |
| 127 | + if not mofile.exists(): |
| 128 | + jsfile.unlink(missing_ok=True) |
| 129 | + return |
| 130 | + with pofile.open("rb") as f: |
| 131 | + source = read_po(f) |
| 132 | + with mofile.open("rb") as f: |
| 133 | + compiled = read_mo(f) |
| 134 | + messages = {} |
| 135 | + for message in source: |
| 136 | + if not isinstance(message.id, str): |
| 137 | + continue |
| 138 | + if not any(filename.endswith(".js") for filename, _ in message.locations): |
| 139 | + continue |
| 140 | + translation = compiled.get(message.id) |
| 141 | + if translation is not None and translation.string: |
| 142 | + messages[message.id] = translation.string |
| 143 | + jsfile.write_text( |
| 144 | + "Object.assign(Documentation.TRANSLATIONS, " |
| 145 | + + json.dumps(messages, ensure_ascii=True, sort_keys=True) |
| 146 | + + ");\n", |
| 147 | + encoding="utf-8", |
| 148 | + ) |
| 149 | + |
110 | 150 |
|
111 | 151 | class CustomBuildHook(BuildHookInterface): |
112 | 152 | def initialize(self, version: str, build_data: dict[str, object]) -> None: |
|
0 commit comments