| 1 |
"""Run babel for translations. |
| 2 |
|
| 3 |
Usage: |
| 4 |
|
| 5 |
babel_runner.py extract |
| 6 |
Extract messages from the source code and update the ".pot" template file. |
| 7 |
|
| 8 |
babel_runner.py update |
| 9 |
Update all language catalogues in "sphinx/locale/<language>/LC_MESSAGES" |
| 10 |
with the current messages in the template file. |
| 11 |
|
| 12 |
babel_runner.py compile |
| 13 |
Compile the ".po" catalogue files to ".mo" and ".js" files. |
| 14 |
""" |
| 15 |
|
| 16 |
from __future__ import annotations |
| 17 |
|
| 18 |
import json |
| 19 |
import logging |
| 20 |
import sys |
| 21 |
import tempfile |
| 22 |
from os import environ |
| 23 |
from pathlib import Path |
| 24 |
|
| 25 |
from babel.messages.catalog import Catalog |
| 26 |
from babel.messages.extract import ( |
| 27 |
DEFAULT_KEYWORDS, |
| 28 |
extract, |
| 29 |
extract_javascript, |
| 30 |
extract_python, |
| 31 |
) |
| 32 |
from babel.messages.mofile import write_mo |
| 33 |
from babel.messages.pofile import read_po, write_po |
| 34 |
from babel.util import pathmatch |
| 35 |
from jinja2.ext import babel_extract as extract_jinja2 |
| 36 |
|
| 37 |
IS_CI = 'CI' in environ |
| 38 |
ROOT = Path(__file__).resolve().parent.parent |
| 39 |
TEX_DELIMITERS = { |
| 40 |
'variable_start_string': '<%=', |
| 41 |
'variable_end_string': '%>', |
| 42 |
'block_start_string': '<%', |
| 43 |
'block_end_string': '%>', |
| 44 |
} |
| 45 |
METHOD_MAP = [ |
| 46 |
# Extraction from Python source files |
| 47 |
('**.py', extract_python), |
| 48 |
# Extraction from Jinja2 template files |
| 49 |
('**/templates/latex/**.tex.jinja', extract_jinja2), |
| 50 |
('**/templates/latex/**.tex_t', extract_jinja2), |
| 51 |
('**/templates/latex/**.sty.jinja', extract_jinja2), |
| 52 |
('**/templates/latex/**.sty_t', extract_jinja2), |
| 53 |
# Extraction from Jinja2 HTML templates |
| 54 |
('**/themes/**.html', extract_jinja2), |
| 55 |
# Extraction from Jinja2 XML templates |
| 56 |
('**/themes/**.xml', extract_jinja2), |
| 57 |
# Extraction from JavaScript files |
| 58 |
('**.js', extract_javascript), |
| 59 |
('**.js.jinja', extract_javascript), |
| 60 |
('**.js_t', extract_javascript), |
| 61 |
] |
| 62 |
OPTIONS_MAP = { |
| 63 |
# Extraction from Python source files |
| 64 |
'**.py': { |
| 65 |
'encoding': 'utf-8', |
| 66 |
}, |
| 67 |
# Extraction from Jinja2 template files |
| 68 |
'**/templates/latex/**.tex.jinja': TEX_DELIMITERS.copy(), |
| 69 |
'**/templates/latex/**.tex_t': TEX_DELIMITERS.copy(), |
| 70 |
'**/templates/latex/**.sty.jinja': TEX_DELIMITERS.copy(), |
| 71 |
'**/templates/latex/**.sty_t': TEX_DELIMITERS.copy(), |
| 72 |
# Extraction from Jinja2 HTML templates |
| 73 |
'**/themes/**.html': { |
| 74 |
'encoding': 'utf-8', |
| 75 |
'ignore_tags': 'script,style', |
| 76 |
'include_attrs': 'alt title summary', |
| 77 |
}, |
| 78 |
} |
| 79 |
KEYWORDS = {**DEFAULT_KEYWORDS, '_': None, '__': None} |
| 80 |
|
| 81 |
|
| 82 |
def run_extract() -> None: |
| 83 |
"""Message extraction function.""" |
| 84 |
log = _get_logger() |
| 85 |
|
| 86 |
with open('sphinx/__init__.py', encoding='utf-8') as f: |
| 87 |
lines = f.readlines() |
| 88 |
for line in lines: |
| 89 |
if line.startswith('__version__: Final = '): |
| 90 |
# remove prefix; strip whitespace; remove quotation marks |
| 91 |
sphinx_version = line[21:].strip()[1:-1] |
| 92 |
break |
| 93 |
|
| 94 |
catalogue = Catalog(project='Sphinx', version=sphinx_version, charset='utf-8') |
| 95 |
|
| 96 |
base = ROOT / 'sphinx' |
| 97 |
for filename in base.rglob('*'): |
| 98 |
relative_name = filename.relative_to(base) |
| 99 |
for pattern, method in METHOD_MAP: |
| 100 |
if not pathmatch(pattern, str(relative_name)): |
| 101 |
continue |
| 102 |
|
| 103 |
options = {} |
| 104 |
for opt_pattern, opt_dict in OPTIONS_MAP.items(): |
| 105 |
if pathmatch(opt_pattern, str(relative_name)): |
| 106 |
options = opt_dict |
| 107 |
with open(filename, 'rb') as fileobj: |
| 108 |
for lineno, message, comments, context in extract( |
| 109 |
method, # type: ignore[arg-type] |
| 110 |
fileobj, |
| 111 |
KEYWORDS, |
| 112 |
options=options, |
| 113 |
): |
| 114 |
catalogue.add( |
| 115 |
message, |
| 116 |
None, |
| 117 |
[(str(relative_name), lineno)], |
| 118 |
auto_comments=comments, |
| 119 |
context=context, |
| 120 |
) |
| 121 |
break |
| 122 |
|
| 123 |
output_file = ROOT / 'sphinx' / 'locale' / 'sphinx.pot' |
| 124 |
log.info('writing PO template file to %s', output_file.relative_to(ROOT)) |
| 125 |
with open(output_file, 'wb') as outfile: |
| 126 |
write_po(outfile, catalogue) |
| 127 |
|
| 128 |
|
| 129 |
def run_update() -> None: |
| 130 |
"""Catalog merging command.""" |
| 131 |
log = _get_logger() |
| 132 |
|
| 133 |
domain = 'sphinx' |
| 134 |
locale_dir = ROOT / 'sphinx' / 'locale' |
| 135 |
template_file = locale_dir / 'sphinx.pot' |
| 136 |
|
| 137 |
with open(template_file, encoding='utf-8') as infile: |
| 138 |
template = read_po(infile) |
| 139 |
|
| 140 |
for locale in locale_dir.iterdir(): |
| 141 |
filename = locale / 'LC_MESSAGES' / f'{domain}.po' |
| 142 |
if not filename.exists(): |
| 143 |
continue |
| 144 |
|
| 145 |
log.info( |
| 146 |
'updating catalogue %s based on %s', |
| 147 |
filename.relative_to(ROOT), |
| 148 |
template_file.relative_to(ROOT), |
| 149 |
) |
| 150 |
with open(filename, encoding='utf-8') as infile: |
| 151 |
catalogue = read_po(infile, locale=locale.name, domain=domain) |
| 152 |
|
| 153 |
catalogue.update(template) |
| 154 |
tmp_name = filename.parent / (tempfile.gettempprefix() + filename.name) |
| 155 |
try: |
| 156 |
with open(tmp_name, 'wb') as tmpfile: |
| 157 |
write_po(tmpfile, catalogue) |
| 158 |
except Exception: |
| 159 |
tmp_name.unlink() |
| 160 |
raise |
| 161 |
|
| 162 |
tmp_name.replace(filename) |
| 163 |
|
| 164 |
|
| 165 |
def run_compile() -> None: |
| 166 |
"""Catalogue compilation command. |
| 167 |
|
| 168 |
An extended command that writes all message strings that occur in |
| 169 |
JavaScript files to a JavaScript file along with the .mo file. |
| 170 |
|
| 171 |
Unfortunately, babel's setup command isn't built very extensible, so |
| 172 |
most of the run() code is duplicated here. |
| 173 |
""" |
| 174 |
log = _get_logger() |
| 175 |
|
| 176 |
directory = ROOT / 'sphinx' / 'locale' |
| 177 |
total_errors = {} |
| 178 |
|
| 179 |
for locale in directory.iterdir(): |
| 180 |
po_file = locale / 'LC_MESSAGES' / 'sphinx.po' |
| 181 |
if not po_file.exists(): |
| 182 |
continue |
| 183 |
|
| 184 |
with open(po_file, encoding='utf-8') as infile: |
| 185 |
catalogue = read_po(infile, locale=locale.name) |
| 186 |
|
| 187 |
if catalogue.fuzzy: |
| 188 |
log.info( |
| 189 |
'catalogue %s is marked as fuzzy, skipping', po_file.relative_to(ROOT) |
| 190 |
) |
| 191 |
continue |
| 192 |
|
| 193 |
locale_errors = 0 |
| 194 |
for message, errors in catalogue.check(): |
| 195 |
for error in errors: |
| 196 |
locale_errors += 1 |
| 197 |
log.error( |
| 198 |
'error: %s:%d: %s\nerror: in message string: %r', |
| 199 |
po_file.relative_to(ROOT), |
| 200 |
message.lineno, |
| 201 |
error, |
| 202 |
message.string, |
| 203 |
) |
| 204 |
|
| 205 |
if locale_errors: |
| 206 |
total_errors[locale.name] = locale_errors |
| 207 |
log.info( |
| 208 |
'%d errors encountered in %r locale, skipping', |
| 209 |
locale_errors, |
| 210 |
locale.name, |
| 211 |
) |
| 212 |
continue |
| 213 |
|
| 214 |
mo_file = locale / 'LC_MESSAGES' / 'sphinx.mo' |
| 215 |
log.info( |
| 216 |
'compiling catalogue %s to %s', |
| 217 |
po_file.relative_to(ROOT), |
| 218 |
mo_file.relative_to(ROOT), |
| 219 |
) |
| 220 |
with open(mo_file, 'wb') as outfile: |
| 221 |
write_mo(outfile, catalogue, use_fuzzy=False) |
| 222 |
|
| 223 |
js_file = locale / 'LC_MESSAGES' / 'sphinx.js' |
| 224 |
log.info( |
| 225 |
'writing JavaScript strings in catalogue %s to %s', |
| 226 |
po_file.relative_to(ROOT), |
| 227 |
js_file.relative_to(ROOT), |
| 228 |
) |
| 229 |
js_catalogue = {} |
| 230 |
for message in catalogue: |
| 231 |
if any( |
| 232 |
x[0].endswith(('.js', '.js.jinja', '.js_t', '.html')) |
| 233 |
for x in message.locations |
| 234 |
): |
| 235 |
msgid = message.id |
| 236 |
if isinstance(msgid, (list, tuple)): |
| 237 |
msgid = msgid[0] |
| 238 |
js_catalogue[msgid] = message.string |
| 239 |
|
| 240 |
obj = json.dumps( |
| 241 |
{ |
| 242 |
'messages': js_catalogue, |
| 243 |
'plural_expr': catalogue.plural_expr, |
| 244 |
'locale': str(catalogue.locale), |
| 245 |
}, |
| 246 |
sort_keys=True, |
| 247 |
indent=4, |
| 248 |
) |
| 249 |
with open(js_file, 'wb') as outfile: |
| 250 |
# to ensure lines end with ``\n`` rather than ``\r\n``: |
| 251 |
outfile.write(f'Documentation.addTranslations({obj});'.encode()) |
| 252 |
|
| 253 |
if total_errors: |
| 254 |
_write_pr_body_line('## Babel catalogue errors') |
| 255 |
_write_pr_body_line('') |
| 256 |
for locale_name, err_count in total_errors.items(): |
| 257 |
log.error( |
| 258 |
'error: %d errors encountered in %r locale.', err_count, locale_name |
| 259 |
) |
| 260 |
s = 's' if err_count != 1 else '' |
| 261 |
_write_pr_body_line(f'* {locale_name}: {err_count} error{s}') |
| 262 |
|
| 263 |
|
| 264 |
def _get_logger() -> logging.Logger: |
| 265 |
log = logging.getLogger('babel') |
| 266 |
log.setLevel(logging.INFO) |
| 267 |
handler = logging.StreamHandler() |
| 268 |
handler.setFormatter(logging.Formatter('%(message)s')) |
| 269 |
log.addHandler(handler) |
| 270 |
return log |
| 271 |
|
| 272 |
|
| 273 |
def _write_pr_body_line(message: str) -> None: |
| 274 |
if not IS_CI: |
| 275 |
return |
| 276 |
with open('babel_compile.txt', 'a', encoding='utf-8') as f: |
| 277 |
f.write(f'{message}\n') |
| 278 |
|
| 279 |
|
| 280 |
if __name__ == '__main__': |
| 281 |
try: |
| 282 |
action = sys.argv[1].lower() |
| 283 |
except IndexError: |
| 284 |
print(__doc__, file=sys.stderr) |
| 285 |
raise SystemExit(2) from None |
| 286 |
|
| 287 |
if action == 'extract': |
| 288 |
run_extract() |
| 289 |
elif action == 'update': |
| 290 |
run_update() |
| 291 |
elif action == 'compile': |
| 292 |
run_compile() |
| 293 |
elif action == 'all': |
| 294 |
run_extract() |
| 295 |
run_update() |
| 296 |
run_compile() |
| 297 |
else: |
| 298 |
msg = f"invalid action: '{action}'" |
| 299 |
raise ValueError(msg) |
| 300 |
raise SystemExit |