frontend.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321
  1. """
  2. babel.messages.frontend
  3. ~~~~~~~~~~~~~~~~~~~~~~~
  4. Frontends for the message extraction functionality.
  5. :copyright: (c) 2013-2026 by the Babel Team.
  6. :license: BSD, see LICENSE for more details.
  7. """
  8. from __future__ import annotations
  9. import datetime
  10. import fnmatch
  11. import logging
  12. import optparse
  13. import os
  14. import pathlib
  15. import re
  16. import shutil
  17. import sys
  18. import tempfile
  19. import warnings
  20. from configparser import RawConfigParser
  21. from io import StringIO
  22. from typing import Any, BinaryIO, Iterable, Literal
  23. from babel import Locale, localedata
  24. from babel import __version__ as VERSION
  25. from babel.core import UnknownLocaleError
  26. from babel.messages.catalog import DEFAULT_HEADER, Catalog
  27. from babel.messages.extract import (
  28. DEFAULT_KEYWORDS,
  29. DEFAULT_MAPPING,
  30. check_and_call_extract_file,
  31. extract_from_dir,
  32. )
  33. from babel.messages.mofile import write_mo
  34. from babel.messages.pofile import read_po, write_po
  35. from babel.util import LOCALTZ
  36. log = logging.getLogger('babel')
  37. class BaseError(Exception):
  38. pass
  39. class OptionError(BaseError):
  40. pass
  41. class SetupError(BaseError):
  42. pass
  43. class ConfigurationError(BaseError):
  44. """
  45. Raised for errors in configuration files.
  46. """
  47. def listify_value(arg, split=None):
  48. """
  49. Make a list out of an argument.
  50. Values from `distutils` argument parsing are always single strings;
  51. values from `optparse` parsing may be lists of strings that may need
  52. to be further split.
  53. No matter the input, this function returns a flat list of whitespace-trimmed
  54. strings, with `None` values filtered out.
  55. >>> listify_value("foo bar")
  56. ['foo', 'bar']
  57. >>> listify_value(["foo bar"])
  58. ['foo', 'bar']
  59. >>> listify_value([["foo"], "bar"])
  60. ['foo', 'bar']
  61. >>> listify_value([["foo"], ["bar", None, "foo"]])
  62. ['foo', 'bar', 'foo']
  63. >>> listify_value("foo, bar, quux", ",")
  64. ['foo', 'bar', 'quux']
  65. :param arg: A string or a list of strings
  66. :param split: The argument to pass to `str.split()`.
  67. :return:
  68. """
  69. out = []
  70. if not isinstance(arg, (list, tuple)):
  71. arg = [arg]
  72. for val in arg:
  73. if val is None:
  74. continue
  75. if isinstance(val, (list, tuple)):
  76. out.extend(listify_value(val, split=split))
  77. continue
  78. out.extend(s.strip() for s in str(val).split(split))
  79. assert all(isinstance(val, str) for val in out)
  80. return out
  81. class CommandMixin:
  82. # This class is a small shim between Distutils commands and
  83. # optparse option parsing in the frontend command line.
  84. #: Option name to be input as `args` on the script command line.
  85. as_args = None
  86. #: Options which allow multiple values.
  87. #: This is used by the `optparse` transmogrification code.
  88. multiple_value_options = ()
  89. #: Options which are booleans.
  90. #: This is used by the `optparse` transmogrification code.
  91. # (This is actually used by distutils code too, but is never
  92. # declared in the base class.)
  93. boolean_options = ()
  94. #: Option aliases, to retain standalone command compatibility.
  95. #: Distutils does not support option aliases, but optparse does.
  96. #: This maps the distutils argument name to an iterable of aliases
  97. #: that are usable with optparse.
  98. option_aliases = {}
  99. #: Choices for options that needed to be restricted to specific
  100. #: list of choices.
  101. option_choices = {}
  102. #: Log object. To allow replacement in the script command line runner.
  103. log = log
  104. def __init__(self, dist=None):
  105. # A less strict version of distutils' `__init__`.
  106. self.distribution = dist
  107. self.initialize_options()
  108. self._dry_run = None
  109. self.verbose = False
  110. self.force = None
  111. self.help = 0
  112. self.finalized = 0
  113. def initialize_options(self):
  114. pass
  115. def ensure_finalized(self):
  116. if not self.finalized:
  117. self.finalize_options()
  118. self.finalized = 1
  119. def finalize_options(self):
  120. raise RuntimeError(
  121. f"abstract method -- subclass {self.__class__} must override",
  122. )
  123. class CompileCatalog(CommandMixin):
  124. description = 'compile message catalogs to binary MO files'
  125. user_options = [
  126. ('domain=', 'D',
  127. "domains of PO files (space separated list, default 'messages')"),
  128. ('directory=', 'd',
  129. 'path to base directory containing the catalogs'),
  130. ('input-file=', 'i',
  131. 'name of the input file'),
  132. ('output-file=', 'o',
  133. "name of the output file (default "
  134. "'<output_dir>/<locale>/LC_MESSAGES/<domain>.mo')"),
  135. ('locale=', 'l',
  136. 'locale of the catalog to compile'),
  137. ('use-fuzzy', 'f',
  138. 'also include fuzzy translations'),
  139. ('statistics', None,
  140. 'print statistics about translations'),
  141. ] # fmt: skip
  142. boolean_options = ['use-fuzzy', 'statistics']
  143. def initialize_options(self):
  144. self.domain = 'messages'
  145. self.directory = None
  146. self.input_file = None
  147. self.output_file = None
  148. self.locale = None
  149. self.use_fuzzy = False
  150. self.statistics = False
  151. def finalize_options(self):
  152. self.domain = listify_value(self.domain)
  153. if not self.input_file and not self.directory:
  154. raise OptionError('you must specify either the input file or the base directory')
  155. if not self.output_file and not self.directory:
  156. raise OptionError('you must specify either the output file or the base directory')
  157. def run(self):
  158. n_errors = 0
  159. for domain in self.domain:
  160. for errors in self._run_domain(domain).values():
  161. n_errors += len(errors)
  162. if n_errors:
  163. self.log.error('%d errors encountered.', n_errors)
  164. return 1 if n_errors else 0
  165. def _get_po_mo_triples(self, domain: str):
  166. if not self.input_file:
  167. dir_path = pathlib.Path(self.directory)
  168. if self.locale:
  169. lc_messages_path = dir_path / self.locale / "LC_MESSAGES"
  170. po_file = lc_messages_path / f"{domain}.po"
  171. yield self.locale, po_file, po_file.with_suffix(".mo")
  172. else:
  173. for locale_path in dir_path.iterdir():
  174. po_file = locale_path / "LC_MESSAGES" / f"{domain}.po"
  175. if po_file.exists():
  176. yield locale_path.name, po_file, po_file.with_suffix(".mo")
  177. else:
  178. po_file = pathlib.Path(self.input_file)
  179. if self.output_file:
  180. mo_file = pathlib.Path(self.output_file)
  181. else:
  182. mo_file = (
  183. pathlib.Path(self.directory) / self.locale / "LC_MESSAGES" / f"{domain}.mo"
  184. )
  185. yield self.locale, po_file, mo_file
  186. def _run_domain(self, domain):
  187. locale_po_mo_triples = list(self._get_po_mo_triples(domain))
  188. if not locale_po_mo_triples:
  189. raise OptionError(f'no message catalogs found for domain {domain!r}')
  190. catalogs_and_errors = {}
  191. for locale, po_file, mo_file in locale_po_mo_triples:
  192. with open(po_file, 'rb') as infile:
  193. catalog = read_po(infile, locale)
  194. if self.statistics:
  195. translated = 0
  196. for message in list(catalog)[1:]:
  197. if message.string:
  198. translated += 1
  199. percentage = 0
  200. if len(catalog):
  201. percentage = translated * 100 // len(catalog)
  202. self.log.info(
  203. '%d of %d messages (%d%%) translated in %s',
  204. translated,
  205. len(catalog),
  206. percentage,
  207. po_file,
  208. )
  209. if catalog.fuzzy and not self.use_fuzzy:
  210. self.log.info('catalog %s is marked as fuzzy, skipping', po_file)
  211. continue
  212. catalogs_and_errors[catalog] = catalog_errors = list(catalog.check())
  213. for message, errors in catalog_errors:
  214. for error in errors:
  215. self.log.error('error: %s:%d: %s', po_file, message.lineno, error)
  216. self.log.info('compiling catalog %s to %s', po_file, mo_file)
  217. with open(mo_file, 'wb') as outfile:
  218. write_mo(outfile, catalog, use_fuzzy=self.use_fuzzy)
  219. return catalogs_and_errors
  220. def _make_directory_filter(ignore_patterns):
  221. """
  222. Build a directory_filter function based on a list of ignore patterns.
  223. """
  224. def cli_directory_filter(dirname):
  225. basename = os.path.basename(dirname)
  226. return not any(
  227. fnmatch.fnmatch(basename, ignore_pattern) for ignore_pattern in ignore_patterns
  228. )
  229. return cli_directory_filter
  230. class ExtractMessages(CommandMixin):
  231. description = 'extract localizable strings from the project code'
  232. user_options = [
  233. ('charset=', None,
  234. 'charset to use in the output file (default "utf-8")'),
  235. ('keywords=', 'k',
  236. 'space-separated list of keywords to look for in addition to the '
  237. 'defaults (may be repeated multiple times)'),
  238. ('no-default-keywords', None,
  239. 'do not include the default keywords'),
  240. ('mapping-file=', 'F',
  241. 'path to the mapping configuration file'),
  242. ('no-location', None,
  243. 'do not include location comments with filename and line number'),
  244. ('add-location=', None,
  245. 'location lines format. If it is not given or "full", it generates '
  246. 'the lines with both file name and line number. If it is "file", '
  247. 'the line number part is omitted. If it is "never", it completely '
  248. 'suppresses the lines (same as --no-location).'),
  249. ('omit-header', None,
  250. 'do not include msgid "" entry in header'),
  251. ('output-file=', 'o',
  252. 'name of the output file'),
  253. ('width=', 'w',
  254. 'set output line width (default 76)'),
  255. ('no-wrap', None,
  256. 'do not break long message lines, longer than the output line width, '
  257. 'into several lines'),
  258. ('sort-output', None,
  259. 'generate sorted output (default False)'),
  260. ('sort-by-file', None,
  261. 'sort output by file location (default False)'),
  262. ('msgid-bugs-address=', None,
  263. 'set report address for msgid'),
  264. ('copyright-holder=', None,
  265. 'set copyright holder in output'),
  266. ('project=', None,
  267. 'set project name in output'),
  268. ('version=', None,
  269. 'set project version in output'),
  270. ('add-comments=', 'c',
  271. 'place comment block with TAG (or those preceding keyword lines) in '
  272. 'output file. Separate multiple TAGs with commas(,)'), # TODO: Support repetition of this argument
  273. ('strip-comments', 's',
  274. 'strip the comment TAGs from the comments.'),
  275. ('input-paths=', None,
  276. 'files or directories that should be scanned for messages. Separate multiple '
  277. 'files or directories with commas(,)'), # TODO: Support repetition of this argument
  278. ('input-dirs=', None, # TODO (3.x): Remove me.
  279. 'alias for input-paths (does allow files as well as directories).'),
  280. ('ignore-dirs=', None,
  281. 'Patterns for directories to ignore when scanning for messages. '
  282. 'Separate multiple patterns with spaces (default ".* ._")'),
  283. ('header-comment=', None,
  284. 'header comment for the catalog'),
  285. ('last-translator=', None,
  286. 'set the name and email of the last translator in output'),
  287. ] # fmt: skip
  288. boolean_options = [
  289. 'no-default-keywords',
  290. 'no-location',
  291. 'omit-header',
  292. 'no-wrap',
  293. 'sort-output',
  294. 'sort-by-file',
  295. 'strip-comments',
  296. ]
  297. as_args = 'input-paths'
  298. multiple_value_options = (
  299. 'add-comments',
  300. 'keywords',
  301. 'ignore-dirs',
  302. )
  303. option_aliases = {
  304. 'keywords': ('--keyword',),
  305. 'mapping-file': ('--mapping',),
  306. 'output-file': ('--output',),
  307. 'strip-comments': ('--strip-comment-tags',),
  308. 'last-translator': ('--last-translator',),
  309. }
  310. option_choices = {
  311. 'add-location': ('full', 'file', 'never'),
  312. }
  313. def initialize_options(self):
  314. self.charset = 'utf-8'
  315. self.keywords = None
  316. self.no_default_keywords = False
  317. self.mapping_file = None
  318. self.no_location = False
  319. self.add_location = None
  320. self.omit_header = False
  321. self.output_file = None
  322. self.input_dirs = None
  323. self.input_paths = None
  324. self.width = None
  325. self.no_wrap = False
  326. self.sort_output = False
  327. self.sort_by_file = False
  328. self.msgid_bugs_address = None
  329. self.copyright_holder = None
  330. self.project = None
  331. self.version = None
  332. self.add_comments = None
  333. self.strip_comments = False
  334. self.include_lineno = True
  335. self.ignore_dirs = None
  336. self.header_comment = None
  337. self.last_translator = None
  338. def finalize_options(self):
  339. if self.input_dirs:
  340. if not self.input_paths:
  341. self.input_paths = self.input_dirs
  342. else:
  343. raise OptionError(
  344. 'input-dirs and input-paths are mutually exclusive',
  345. )
  346. keywords = {} if self.no_default_keywords else DEFAULT_KEYWORDS.copy()
  347. keywords.update(parse_keywords(listify_value(self.keywords)))
  348. self.keywords = keywords
  349. if not self.keywords:
  350. raise OptionError(
  351. 'you must specify new keywords if you disable the default ones',
  352. )
  353. if not self.output_file:
  354. raise OptionError('no output file specified')
  355. if self.no_wrap and self.width:
  356. raise OptionError(
  357. "'--no-wrap' and '--width' are mutually exclusive",
  358. )
  359. if not self.no_wrap and not self.width:
  360. self.width = 76
  361. elif self.width is not None:
  362. self.width = int(self.width)
  363. if self.sort_output and self.sort_by_file:
  364. raise OptionError(
  365. "'--sort-output' and '--sort-by-file' are mutually exclusive",
  366. )
  367. if self.input_paths:
  368. if isinstance(self.input_paths, str):
  369. self.input_paths = re.split(r',\s*', self.input_paths)
  370. elif self.distribution is not None:
  371. self.input_paths = list(
  372. {k.split('.', 1)[0] for k in (self.distribution.packages or ())},
  373. )
  374. else:
  375. self.input_paths = []
  376. if not self.input_paths:
  377. raise OptionError("no input files or directories specified")
  378. for path in self.input_paths:
  379. if not os.path.exists(path):
  380. raise OptionError(f"Input path: {path} does not exist")
  381. self.add_comments = listify_value(self.add_comments or (), ",")
  382. if self.distribution:
  383. if not self.project:
  384. self.project = self.distribution.get_name()
  385. if not self.version:
  386. self.version = self.distribution.get_version()
  387. if self.add_location == 'never':
  388. self.no_location = True
  389. elif self.add_location == 'file':
  390. self.include_lineno = False
  391. ignore_dirs = listify_value(self.ignore_dirs)
  392. if ignore_dirs:
  393. self.directory_filter = _make_directory_filter(ignore_dirs)
  394. else:
  395. self.directory_filter = None
  396. def _build_callback(self, path: str):
  397. def callback(filename: str, method: str, options: dict):
  398. if method == 'ignore':
  399. return
  400. # If we explicitly provide a full filepath, just use that.
  401. # Otherwise, path will be the directory path and filename
  402. # is the relative path from that dir to the file.
  403. # So we can join those to get the full filepath.
  404. if os.path.isfile(path):
  405. filepath = path
  406. else:
  407. filepath = os.path.normpath(os.path.join(path, filename))
  408. optstr = ''
  409. if options:
  410. opt_values = ", ".join(f'{k}="{v}"' for k, v in options.items())
  411. optstr = f" ({opt_values})"
  412. self.log.info('extracting messages from %s%s', filepath, optstr)
  413. return callback
  414. def run(self):
  415. mappings = self._get_mappings()
  416. with open(self.output_file, 'wb') as outfile:
  417. catalog = Catalog(
  418. project=self.project,
  419. version=self.version,
  420. msgid_bugs_address=self.msgid_bugs_address,
  421. copyright_holder=self.copyright_holder,
  422. charset=self.charset,
  423. header_comment=(self.header_comment or DEFAULT_HEADER),
  424. last_translator=self.last_translator,
  425. )
  426. for path, method_map, options_map in mappings:
  427. callback = self._build_callback(path)
  428. if os.path.isfile(path):
  429. current_dir = os.getcwd()
  430. extracted = check_and_call_extract_file(
  431. path,
  432. method_map,
  433. options_map,
  434. callback=callback,
  435. comment_tags=self.add_comments,
  436. dirpath=current_dir,
  437. keywords=self.keywords,
  438. strip_comment_tags=self.strip_comments,
  439. )
  440. else:
  441. extracted = extract_from_dir(
  442. path,
  443. method_map,
  444. options_map,
  445. callback=callback,
  446. comment_tags=self.add_comments,
  447. directory_filter=self.directory_filter,
  448. keywords=self.keywords,
  449. strip_comment_tags=self.strip_comments,
  450. )
  451. for filename, lineno, message, comments, context in extracted:
  452. if os.path.isfile(path):
  453. filepath = filename # already normalized
  454. else:
  455. filepath = os.path.normpath(os.path.join(path, filename))
  456. catalog.add(
  457. message,
  458. None,
  459. [(filepath, lineno)],
  460. auto_comments=comments,
  461. context=context,
  462. )
  463. self.log.info('writing PO template file to %s', self.output_file)
  464. write_po(
  465. outfile,
  466. catalog,
  467. include_lineno=self.include_lineno,
  468. no_location=self.no_location,
  469. omit_header=self.omit_header,
  470. sort_by_file=self.sort_by_file,
  471. sort_output=self.sort_output,
  472. width=self.width,
  473. )
  474. def _get_mappings(self):
  475. mappings = []
  476. if self.mapping_file:
  477. if self.mapping_file.endswith(".toml"):
  478. with open(self.mapping_file, "rb") as fileobj:
  479. file_style = (
  480. "pyproject.toml"
  481. if os.path.basename(self.mapping_file) == "pyproject.toml"
  482. else "standalone"
  483. )
  484. method_map, options_map = _parse_mapping_toml(
  485. fileobj,
  486. filename=self.mapping_file,
  487. style=file_style,
  488. )
  489. else:
  490. with open(self.mapping_file) as fileobj:
  491. method_map, options_map = parse_mapping_cfg(
  492. fileobj,
  493. filename=self.mapping_file,
  494. )
  495. for path in self.input_paths:
  496. mappings.append((path, method_map, options_map))
  497. elif getattr(self.distribution, 'message_extractors', None):
  498. message_extractors = self.distribution.message_extractors
  499. for path, mapping in message_extractors.items():
  500. if isinstance(mapping, str):
  501. method_map, options_map = parse_mapping_cfg(StringIO(mapping))
  502. else:
  503. method_map, options_map = [], {}
  504. for pattern, method, options in mapping:
  505. method_map.append((pattern, method))
  506. options_map[pattern] = _parse_string_options(options or {})
  507. mappings.append((path, method_map, options_map))
  508. else:
  509. for path in self.input_paths:
  510. mappings.append((path, DEFAULT_MAPPING, {}))
  511. return mappings
  512. def _init_catalog(*, input_file, output_file, locale: Locale, width: int) -> None:
  513. with open(input_file, 'rb') as infile:
  514. # Although reading from the catalog template, read_po must be fed
  515. # the locale in order to correctly calculate plurals
  516. catalog = read_po(infile, locale=locale)
  517. catalog.locale = locale
  518. catalog.revision_date = datetime.datetime.now(LOCALTZ)
  519. catalog.fuzzy = False
  520. if dirname := os.path.dirname(output_file):
  521. os.makedirs(dirname, exist_ok=True)
  522. with open(output_file, 'wb') as outfile:
  523. write_po(outfile, catalog, width=width)
  524. class InitCatalog(CommandMixin):
  525. description = 'create a new catalog based on a POT file'
  526. user_options = [
  527. ('domain=', 'D',
  528. "domain of PO file (default 'messages')"),
  529. ('input-file=', 'i',
  530. 'name of the input file'),
  531. ('output-dir=', 'd',
  532. 'path to output directory'),
  533. ('output-file=', 'o',
  534. "name of the output file (default "
  535. "'<output_dir>/<locale>/LC_MESSAGES/<domain>.po')"),
  536. ('locale=', 'l',
  537. 'locale for the new localized catalog'),
  538. ('width=', 'w',
  539. 'set output line width (default 76)'),
  540. ('no-wrap', None,
  541. 'do not break long message lines, longer than the output line width, '
  542. 'into several lines'),
  543. ] # fmt: skip
  544. boolean_options = ['no-wrap']
  545. def initialize_options(self):
  546. self.output_dir = None
  547. self.output_file = None
  548. self.input_file = None
  549. self.locale = None
  550. self.domain = 'messages'
  551. self.no_wrap = False
  552. self.width = None
  553. def finalize_options(self):
  554. if not self.input_file:
  555. raise OptionError('you must specify the input file')
  556. if not self.locale:
  557. raise OptionError('you must provide a locale for the new catalog')
  558. try:
  559. self._locale = Locale.parse(self.locale)
  560. except UnknownLocaleError as e:
  561. raise OptionError(e) from e
  562. if not self.output_file and not self.output_dir:
  563. raise OptionError('you must specify the output directory')
  564. if not self.output_file:
  565. lc_messages_path = pathlib.Path(self.output_dir) / self.locale / "LC_MESSAGES"
  566. self.output_file = str(lc_messages_path / f"{self.domain}.po")
  567. if self.no_wrap and self.width:
  568. raise OptionError("'--no-wrap' and '--width' are mutually exclusive")
  569. if not self.no_wrap and not self.width:
  570. self.width = 76
  571. elif self.width is not None:
  572. self.width = int(self.width)
  573. def run(self):
  574. self.log.info(
  575. 'creating catalog %s based on %s',
  576. self.output_file,
  577. self.input_file,
  578. )
  579. _init_catalog(
  580. input_file=self.input_file,
  581. output_file=self.output_file,
  582. locale=self._locale,
  583. width=self.width,
  584. )
  585. class UpdateCatalog(CommandMixin):
  586. description = 'update message catalogs from a POT file'
  587. user_options = [
  588. ('domain=', 'D',
  589. "domain of PO file (default 'messages')"),
  590. ('input-file=', 'i',
  591. 'name of the input file'),
  592. ('output-dir=', 'd',
  593. 'path to base directory containing the catalogs'),
  594. ('output-file=', 'o',
  595. "name of the output file (default "
  596. "'<output_dir>/<locale>/LC_MESSAGES/<domain>.po')"),
  597. ('omit-header', None,
  598. "do not include msgid "" entry in header"),
  599. ('locale=', 'l',
  600. 'locale of the catalog to compile'),
  601. ('width=', 'w',
  602. 'set output line width (default 76)'),
  603. ('no-wrap', None,
  604. 'do not break long message lines, longer than the output line width, '
  605. 'into several lines'),
  606. ('ignore-obsolete=', None,
  607. 'whether to omit obsolete messages from the output'),
  608. ('init-missing=', None,
  609. 'if any output files are missing, initialize them first'),
  610. ('no-fuzzy-matching', 'N',
  611. 'do not use fuzzy matching'),
  612. ('update-header-comment', None,
  613. 'update target header comment'),
  614. ('previous', None,
  615. 'keep previous msgids of translated messages'),
  616. ('check=', None,
  617. 'don\'t update the catalog, just return the status. Return code 0 '
  618. 'means nothing would change. Return code 1 means that the catalog '
  619. 'would be updated'),
  620. ('ignore-pot-creation-date=', None,
  621. 'ignore changes to POT-Creation-Date when updating or checking'),
  622. ] # fmt: skip
  623. boolean_options = [
  624. 'omit-header',
  625. 'no-wrap',
  626. 'ignore-obsolete',
  627. 'init-missing',
  628. 'no-fuzzy-matching',
  629. 'previous',
  630. 'update-header-comment',
  631. 'check',
  632. 'ignore-pot-creation-date',
  633. ]
  634. def initialize_options(self):
  635. self.domain = 'messages'
  636. self.input_file = None
  637. self.output_dir = None
  638. self.output_file = None
  639. self.omit_header = False
  640. self.locale = None
  641. self.width = None
  642. self.no_wrap = False
  643. self.ignore_obsolete = False
  644. self.init_missing = False
  645. self.no_fuzzy_matching = False
  646. self.update_header_comment = False
  647. self.previous = False
  648. self.check = False
  649. self.ignore_pot_creation_date = False
  650. def finalize_options(self):
  651. if not self.input_file:
  652. raise OptionError('you must specify the input file')
  653. if not self.output_file and not self.output_dir:
  654. raise OptionError('you must specify the output file or directory')
  655. if self.output_file and not self.locale:
  656. raise OptionError('you must specify the locale')
  657. if self.init_missing:
  658. if not self.locale:
  659. raise OptionError(
  660. 'you must specify the locale for the init-missing option to work',
  661. )
  662. try:
  663. self._locale = Locale.parse(self.locale)
  664. except UnknownLocaleError as e:
  665. raise OptionError(e) from e
  666. else:
  667. self._locale = None
  668. if self.no_wrap and self.width:
  669. raise OptionError("'--no-wrap' and '--width' are mutually exclusive")
  670. if not self.no_wrap and not self.width:
  671. self.width = 76
  672. elif self.width is not None:
  673. self.width = int(self.width)
  674. if self.no_fuzzy_matching and self.previous:
  675. self.previous = False
  676. def _get_locale_po_file_tuples(self):
  677. if not self.output_file:
  678. output_path = pathlib.Path(self.output_dir)
  679. if self.locale:
  680. lc_messages_path = output_path / self.locale / "LC_MESSAGES"
  681. yield self.locale, str(lc_messages_path / f"{self.domain}.po")
  682. else:
  683. for locale_path in output_path.iterdir():
  684. po_file = locale_path / "LC_MESSAGES" / f"{self.domain}.po"
  685. if po_file.exists():
  686. yield locale_path.stem, po_file
  687. else:
  688. yield self.locale, self.output_file
  689. def run(self):
  690. domain = self.domain
  691. if not domain:
  692. domain = os.path.splitext(os.path.basename(self.input_file))[0]
  693. check_status = {}
  694. locale_po_file_tuples = list(self._get_locale_po_file_tuples())
  695. if not locale_po_file_tuples:
  696. raise OptionError(f'no message catalogs found for domain {domain!r}')
  697. with open(self.input_file, 'rb') as infile:
  698. template = read_po(infile)
  699. for locale, filename in locale_po_file_tuples:
  700. if self.init_missing and not os.path.exists(filename):
  701. if self.check:
  702. check_status[filename] = False
  703. continue
  704. self.log.info(
  705. 'creating catalog %s based on %s',
  706. filename,
  707. self.input_file,
  708. )
  709. _init_catalog(
  710. input_file=self.input_file,
  711. output_file=filename,
  712. locale=self._locale,
  713. width=self.width,
  714. )
  715. self.log.info('updating catalog %s based on %s', filename, self.input_file)
  716. with open(filename, 'rb') as infile:
  717. catalog = read_po(infile, locale=locale, domain=domain)
  718. catalog.update(
  719. template,
  720. no_fuzzy_matching=self.no_fuzzy_matching,
  721. update_header_comment=self.update_header_comment,
  722. update_creation_date=not self.ignore_pot_creation_date,
  723. )
  724. tmpname = os.path.join(
  725. os.path.dirname(filename),
  726. tempfile.gettempprefix() + os.path.basename(filename),
  727. )
  728. try:
  729. with open(tmpname, 'wb') as tmpfile:
  730. write_po(
  731. tmpfile,
  732. catalog,
  733. ignore_obsolete=self.ignore_obsolete,
  734. include_previous=self.previous,
  735. omit_header=self.omit_header,
  736. width=self.width,
  737. )
  738. except Exception:
  739. os.remove(tmpname)
  740. raise
  741. if self.check:
  742. with open(filename, "rb") as origfile:
  743. original_catalog = read_po(origfile)
  744. with open(tmpname, "rb") as newfile:
  745. updated_catalog = read_po(newfile)
  746. updated_catalog.revision_date = original_catalog.revision_date
  747. check_status[filename] = updated_catalog.is_identical(original_catalog)
  748. os.remove(tmpname)
  749. continue
  750. try:
  751. os.rename(tmpname, filename)
  752. except OSError:
  753. # We're probably on Windows, which doesn't support atomic
  754. # renames, at least not through Python
  755. # If the error is in fact due to a permissions problem, that
  756. # same error is going to be raised from one of the following
  757. # operations
  758. os.remove(filename)
  759. shutil.copy(tmpname, filename)
  760. os.remove(tmpname)
  761. if self.check:
  762. for filename, up_to_date in check_status.items():
  763. if up_to_date:
  764. self.log.info('Catalog %s is up to date.', filename)
  765. else:
  766. self.log.warning('Catalog %s is out of date.', filename)
  767. if not all(check_status.values()):
  768. raise BaseError("Some catalogs are out of date.")
  769. else:
  770. self.log.info("All the catalogs are up-to-date.")
  771. return
  772. class CommandLineInterface:
  773. """Command-line interface.
  774. This class provides a simple command-line interface to the message
  775. extraction and PO file generation functionality.
  776. """
  777. usage = '%%prog %s [options] %s'
  778. version = f'%prog {VERSION}'
  779. commands = {
  780. 'compile': 'compile message catalogs to MO files',
  781. 'extract': 'extract messages from source files and generate a POT file',
  782. 'init': 'create new message catalogs from a POT file',
  783. 'update': 'update existing message catalogs from a POT file',
  784. }
  785. command_classes = {
  786. 'compile': CompileCatalog,
  787. 'extract': ExtractMessages,
  788. 'init': InitCatalog,
  789. 'update': UpdateCatalog,
  790. }
  791. log = None # Replaced on instance level
  792. def run(self, argv=None):
  793. """Main entry point of the command-line interface.
  794. :param argv: list of arguments passed on the command-line
  795. """
  796. if argv is None:
  797. argv = sys.argv
  798. self.parser = optparse.OptionParser(
  799. usage=self.usage % ('command', '[args]'),
  800. version=self.version,
  801. )
  802. self.parser.disable_interspersed_args()
  803. self.parser.print_help = self._help
  804. self.parser.add_option(
  805. "--list-locales",
  806. dest="list_locales",
  807. action="store_true",
  808. help="print all known locales and exit",
  809. )
  810. self.parser.add_option(
  811. "-v",
  812. "--verbose",
  813. action="store_const",
  814. dest="loglevel",
  815. const=logging.DEBUG,
  816. help="print as much as possible",
  817. )
  818. self.parser.add_option(
  819. "-q",
  820. "--quiet",
  821. action="store_const",
  822. dest="loglevel",
  823. const=logging.ERROR,
  824. help="print as little as possible",
  825. )
  826. self.parser.set_defaults(list_locales=False, loglevel=logging.INFO)
  827. options, args = self.parser.parse_args(argv[1:])
  828. self._configure_logging(options.loglevel)
  829. if options.list_locales:
  830. identifiers = localedata.locale_identifiers()
  831. id_width = max(len(identifier) for identifier in identifiers) + 1
  832. for identifier in sorted(identifiers):
  833. locale = Locale.parse(identifier)
  834. print(f"{identifier:<{id_width}} {locale.english_name}")
  835. return 0
  836. if not args:
  837. self.parser.error(
  838. "no valid command or option passed. "
  839. "Try the -h/--help option for more information.",
  840. )
  841. cmdname = args[0]
  842. if cmdname not in self.commands:
  843. self.parser.error(f'unknown command "{cmdname}"')
  844. cmdinst = self._configure_command(cmdname, args[1:])
  845. return cmdinst.run()
  846. def _configure_logging(self, loglevel):
  847. self.log = log
  848. self.log.setLevel(loglevel)
  849. # Don't add a new handler for every instance initialization (#227), this
  850. # would cause duplicated output when the CommandLineInterface as an
  851. # normal Python class.
  852. if self.log.handlers:
  853. handler = self.log.handlers[0]
  854. else:
  855. handler = logging.StreamHandler()
  856. self.log.addHandler(handler)
  857. handler.setLevel(loglevel)
  858. formatter = logging.Formatter('%(message)s')
  859. handler.setFormatter(formatter)
  860. def _help(self):
  861. print(self.parser.format_help())
  862. print("commands:")
  863. cmd_width = max(8, max(len(command) for command in self.commands) + 1)
  864. for name, description in sorted(self.commands.items()):
  865. print(f" {name:<{cmd_width}} {description}")
  866. def _configure_command(self, cmdname, argv):
  867. """
  868. :type cmdname: str
  869. :type argv: list[str]
  870. """
  871. cmdclass = self.command_classes[cmdname]
  872. cmdinst = cmdclass()
  873. if self.log:
  874. cmdinst.log = self.log # Use our logger, not distutils'.
  875. assert isinstance(cmdinst, CommandMixin)
  876. cmdinst.initialize_options()
  877. parser = optparse.OptionParser(
  878. usage=self.usage % (cmdname, ''),
  879. description=self.commands[cmdname],
  880. )
  881. as_args: str | None = getattr(cmdclass, "as_args", None)
  882. for long, short, help in cmdclass.user_options:
  883. name = long.strip("=")
  884. default = getattr(cmdinst, name.replace("-", "_"))
  885. strs = [f"--{name}"]
  886. if short:
  887. strs.append(f"-{short}")
  888. strs.extend(cmdclass.option_aliases.get(name, ()))
  889. choices = cmdclass.option_choices.get(name, None)
  890. if name == as_args:
  891. parser.usage += f"<{name}>"
  892. elif name in cmdclass.boolean_options:
  893. parser.add_option(*strs, action="store_true", help=help)
  894. elif name in cmdclass.multiple_value_options:
  895. parser.add_option(*strs, action="append", help=help, choices=choices)
  896. else:
  897. parser.add_option(*strs, help=help, default=default, choices=choices)
  898. options, args = parser.parse_args(argv)
  899. if as_args:
  900. setattr(options, as_args.replace('-', '_'), args)
  901. for key, value in vars(options).items():
  902. setattr(cmdinst, key, value)
  903. try:
  904. cmdinst.ensure_finalized()
  905. except OptionError as err:
  906. parser.error(str(err))
  907. return cmdinst
  908. def main():
  909. return CommandLineInterface().run(sys.argv)
  910. def parse_mapping(fileobj, filename=None):
  911. warnings.warn(
  912. "parse_mapping is deprecated, use parse_mapping_cfg instead",
  913. DeprecationWarning,
  914. stacklevel=2,
  915. )
  916. return parse_mapping_cfg(fileobj, filename)
  917. def parse_mapping_cfg(fileobj, filename=None):
  918. """Parse an extraction method mapping from a file-like object.
  919. :param fileobj: a readable file-like object containing the configuration
  920. text to parse
  921. :param filename: the name of the file being parsed, for error messages
  922. """
  923. extractors = {}
  924. method_map = []
  925. options_map = {}
  926. parser = RawConfigParser()
  927. parser.read_file(fileobj, filename)
  928. for section in parser.sections():
  929. if section == 'extractors':
  930. extractors = dict(parser.items(section))
  931. else:
  932. method, pattern = (part.strip() for part in section.split(':', 1))
  933. method_map.append((pattern, method))
  934. options_map[pattern] = _parse_string_options(dict(parser.items(section)))
  935. if extractors:
  936. for idx, (pattern, method) in enumerate(method_map):
  937. if method in extractors:
  938. method = extractors[method]
  939. method_map[idx] = (pattern, method)
  940. return method_map, options_map
  941. def _parse_string_options(options: dict[str, str]) -> dict[str, Any]:
  942. """
  943. Parse string-formatted options from a mapping configuration.
  944. The `keywords` and `add_comments` options are parsed into a canonical
  945. internal format, so they can be merged with global keywords/comment tags
  946. during extraction.
  947. """
  948. options: dict[str, Any] = options.copy()
  949. if keywords_val := options.pop("keywords", None):
  950. options['keywords'] = parse_keywords(listify_value(keywords_val))
  951. if comments_val := options.pop("add_comments", None):
  952. options['add_comments'] = listify_value(comments_val)
  953. return options
  954. def _parse_config_object(config: dict, *, filename="(unknown)"):
  955. extractors = {}
  956. method_map = []
  957. options_map = {}
  958. extractors_read = config.get("extractors", {})
  959. if not isinstance(extractors_read, dict):
  960. raise ConfigurationError(
  961. f"{filename}: extractors: Expected a dictionary, got {type(extractors_read)!r}",
  962. )
  963. for method, callable_spec in extractors_read.items():
  964. if not isinstance(method, str):
  965. # Impossible via TOML, but could happen with a custom object.
  966. raise ConfigurationError(
  967. f"{filename}: extractors: Extraction method must be a string, got {method!r}",
  968. )
  969. if not isinstance(callable_spec, str):
  970. raise ConfigurationError(
  971. f"{filename}: extractors: Callable specification must be a string, got {callable_spec!r}",
  972. )
  973. extractors[method] = callable_spec
  974. if "mapping" in config:
  975. raise ConfigurationError(
  976. f"{filename}: 'mapping' is not a valid key, did you mean 'mappings'?",
  977. )
  978. mappings_read = config.get("mappings", [])
  979. if not isinstance(mappings_read, list):
  980. raise ConfigurationError(
  981. f"{filename}: mappings: Expected a list, got {type(mappings_read)!r}",
  982. )
  983. for idx, entry in enumerate(mappings_read):
  984. if not isinstance(entry, dict):
  985. raise ConfigurationError(
  986. f"{filename}: mappings[{idx}]: Expected a dictionary, got {type(entry)!r}",
  987. )
  988. entry = entry.copy()
  989. method = entry.pop("method", None)
  990. if not isinstance(method, str):
  991. raise ConfigurationError(
  992. f"{filename}: mappings[{idx}]: 'method' must be a string, got {method!r}",
  993. )
  994. method = extractors.get(method, method) # Map the extractor name to the callable now
  995. pattern = entry.pop("pattern", None)
  996. if not isinstance(pattern, (list, str)):
  997. raise ConfigurationError(
  998. f"{filename}: mappings[{idx}]: 'pattern' must be a list or a string, got {pattern!r}",
  999. )
  1000. if not isinstance(pattern, list):
  1001. pattern = [pattern]
  1002. if keywords_val := entry.pop("keywords", None):
  1003. if isinstance(keywords_val, str):
  1004. entry["keywords"] = parse_keywords(listify_value(keywords_val))
  1005. elif isinstance(keywords_val, list):
  1006. entry["keywords"] = parse_keywords(keywords_val)
  1007. else:
  1008. raise ConfigurationError(
  1009. f"{filename}: mappings[{idx}]: 'keywords' must be a string or list, got {keywords_val!r}",
  1010. )
  1011. if comments_val := entry.pop("add_comments", None):
  1012. if isinstance(comments_val, str):
  1013. entry["add_comments"] = [comments_val]
  1014. elif isinstance(comments_val, list):
  1015. entry["add_comments"] = comments_val
  1016. else:
  1017. raise ConfigurationError(
  1018. f"{filename}: mappings[{idx}]: 'add_comments' must be a string or list, got {comments_val!r}",
  1019. )
  1020. for pat in pattern:
  1021. if not isinstance(pat, str):
  1022. raise ConfigurationError(
  1023. f"{filename}: mappings[{idx}]: 'pattern' elements must be strings, got {pat!r}",
  1024. )
  1025. method_map.append((pat, method))
  1026. options_map[pat] = entry
  1027. return method_map, options_map
  1028. def _parse_mapping_toml(
  1029. fileobj: BinaryIO,
  1030. filename: str = "(unknown)",
  1031. style: Literal["standalone", "pyproject.toml"] = "standalone",
  1032. ):
  1033. """Parse an extraction method mapping from a binary file-like object.
  1034. .. warning: As of this version of Babel, this is a private API subject to changes.
  1035. :param fileobj: a readable binary file-like object containing the configuration TOML to parse
  1036. :param filename: the name of the file being parsed, for error messages
  1037. :param style: whether the file is in the style of a `pyproject.toml` file, i.e. whether to look for `tool.babel`.
  1038. """
  1039. try:
  1040. import tomllib
  1041. except ImportError:
  1042. try:
  1043. import tomli as tomllib
  1044. except ImportError as ie: # pragma: no cover
  1045. raise ImportError("tomli or tomllib is required to parse TOML files") from ie
  1046. try:
  1047. parsed_data = tomllib.load(fileobj)
  1048. except tomllib.TOMLDecodeError as e:
  1049. raise ConfigurationError(f"{filename}: Error parsing TOML file: {e}") from e
  1050. if style == "pyproject.toml":
  1051. try:
  1052. babel_data = parsed_data["tool"]["babel"]
  1053. except (TypeError, KeyError) as e:
  1054. raise ConfigurationError(
  1055. f"{filename}: No 'tool.babel' section found in file",
  1056. ) from e
  1057. elif style == "standalone":
  1058. babel_data = parsed_data
  1059. if "babel" in babel_data:
  1060. raise ConfigurationError(
  1061. f"{filename}: 'babel' should not be present in a stand-alone configuration file",
  1062. )
  1063. else: # pragma: no cover
  1064. raise ValueError(f"Unknown TOML style {style!r}")
  1065. return _parse_config_object(babel_data, filename=filename)
  1066. def _parse_spec(s: str) -> tuple[int | None, tuple[int | tuple[int, str], ...]]:
  1067. inds = []
  1068. number = None
  1069. for x in s.split(','):
  1070. if x[-1] == 't':
  1071. number = int(x[:-1])
  1072. elif x[-1] == 'c':
  1073. inds.append((int(x[:-1]), 'c'))
  1074. else:
  1075. inds.append(int(x))
  1076. return number, tuple(inds)
  1077. def parse_keywords(strings: Iterable[str] = ()):
  1078. """Parse keywords specifications from the given list of strings.
  1079. >>> import pprint
  1080. >>> keywords = ['_', 'dgettext:2', 'dngettext:2,3', 'pgettext:1c,2',
  1081. ... 'polymorphic:1', 'polymorphic:2,2t', 'polymorphic:3c,3t']
  1082. >>> pprint.pprint(parse_keywords(keywords))
  1083. {'_': None,
  1084. 'dgettext': (2,),
  1085. 'dngettext': (2, 3),
  1086. 'pgettext': ((1, 'c'), 2),
  1087. 'polymorphic': {None: (1,), 2: (2,), 3: ((3, 'c'),)}}
  1088. The input keywords are in GNU Gettext style; see :doc:`cmdline` for details.
  1089. The output is a dictionary mapping keyword names to a dictionary of specifications.
  1090. Keys in this dictionary are numbers of arguments, where ``None`` means that all numbers
  1091. of arguments are matched, and a number means only calls with that number of arguments
  1092. are matched (which happens when using the "t" specifier). However, as a special
  1093. case for backwards compatibility, if the dictionary of specifications would
  1094. be ``{None: x}``, i.e., there is only one specification and it matches all argument
  1095. counts, then it is collapsed into just ``x``.
  1096. A specification is either a tuple or None. If a tuple, each element can be either a number
  1097. ``n``, meaning that the nth argument should be extracted as a message, or the tuple
  1098. ``(n, 'c')``, meaning that the nth argument should be extracted as context for the
  1099. messages. A ``None`` specification is equivalent to ``(1,)``, extracting the first
  1100. argument.
  1101. """
  1102. keywords = {}
  1103. for string in strings:
  1104. if ':' in string:
  1105. funcname, spec_str = string.split(':')
  1106. number, spec = _parse_spec(spec_str)
  1107. else:
  1108. funcname = string
  1109. number = None
  1110. spec = None
  1111. keywords.setdefault(funcname, {})[number] = spec
  1112. # For best backwards compatibility, collapse {None: x} into x.
  1113. for k, v in keywords.items():
  1114. if set(v) == {None}:
  1115. keywords[k] = v[None]
  1116. return keywords
  1117. def __getattr__(name: str):
  1118. # Re-exports for backwards compatibility;
  1119. # `setuptools_frontend` is the canonical import location.
  1120. if name in {
  1121. 'check_message_extractors',
  1122. 'compile_catalog',
  1123. 'extract_messages',
  1124. 'init_catalog',
  1125. 'update_catalog',
  1126. }:
  1127. from babel.messages import setuptools_frontend
  1128. return getattr(setuptools_frontend, name)
  1129. raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
  1130. if __name__ == '__main__':
  1131. main()