frontend.py 44 KB

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