extract.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. """
  2. babel.messages.extract
  3. ~~~~~~~~~~~~~~~~~~~~~~
  4. Basic infrastructure for extracting localizable messages from source files.
  5. This module defines an extensible system for collecting localizable message
  6. strings from a variety of sources. A native extractor for Python source
  7. files is builtin, extractors for other sources can be added using very
  8. simple plugins.
  9. The main entry points into the extraction functionality are the functions
  10. `extract_from_dir` and `extract_from_file`.
  11. :copyright: (c) 2013-2025 by the Babel Team.
  12. :license: BSD, see LICENSE for more details.
  13. """
  14. from __future__ import annotations
  15. import ast
  16. import io
  17. import os
  18. import sys
  19. import tokenize
  20. from collections.abc import (
  21. Callable,
  22. Collection,
  23. Generator,
  24. Iterable,
  25. Mapping,
  26. MutableSequence,
  27. )
  28. from functools import lru_cache
  29. from os.path import relpath
  30. from textwrap import dedent
  31. from tokenize import COMMENT, NAME, NL, OP, STRING, generate_tokens
  32. from typing import TYPE_CHECKING, Any, TypedDict
  33. from babel.messages._compat import find_entrypoints
  34. from babel.util import parse_encoding, parse_future_flags, pathmatch
  35. if TYPE_CHECKING:
  36. from typing import IO, Final, Protocol
  37. from _typeshed import SupportsItems, SupportsRead, SupportsReadline
  38. from typing_extensions import TypeAlias
  39. class _PyOptions(TypedDict, total=False):
  40. encoding: str
  41. class _JSOptions(TypedDict, total=False):
  42. encoding: str
  43. jsx: bool
  44. template_string: bool
  45. parse_template_string: bool
  46. class _FileObj(SupportsRead[bytes], SupportsReadline[bytes], Protocol):
  47. def seek(self, __offset: int, __whence: int = ...) -> int: ...
  48. def tell(self) -> int: ...
  49. _SimpleKeyword: TypeAlias = tuple[int | tuple[int, int] | tuple[int, str], ...] | None
  50. _Keyword: TypeAlias = dict[int | None, _SimpleKeyword] | _SimpleKeyword
  51. # 5-tuple of (filename, lineno, messages, comments, context)
  52. _FileExtractionResult: TypeAlias = tuple[str, int, str | tuple[str, ...], list[str], str | None]
  53. # 4-tuple of (lineno, message, comments, context)
  54. _ExtractionResult: TypeAlias = tuple[int, str | tuple[str, ...], list[str], str | None]
  55. # Required arguments: fileobj, keywords, comment_tags, options
  56. # Return value: Iterable of (lineno, message, comments, context)
  57. _CallableExtractionMethod: TypeAlias = Callable[
  58. [_FileObj | IO[bytes], Mapping[str, _Keyword], Collection[str], Mapping[str, Any]],
  59. Iterable[_ExtractionResult],
  60. ]
  61. _ExtractionMethod: TypeAlias = _CallableExtractionMethod | str
  62. GROUP_NAME: Final[str] = 'babel.extractors'
  63. DEFAULT_KEYWORDS: dict[str, _Keyword] = {
  64. '_': None,
  65. 'gettext': None,
  66. 'ngettext': (1, 2),
  67. 'ugettext': None,
  68. 'ungettext': (1, 2),
  69. 'dgettext': (2,),
  70. 'dngettext': (2, 3),
  71. 'N_': None,
  72. 'pgettext': ((1, 'c'), 2),
  73. 'npgettext': ((1, 'c'), 2, 3),
  74. }
  75. DEFAULT_MAPPING: list[tuple[str, str]] = [('**.py', 'python')]
  76. # New tokens in Python 3.12, or None on older versions
  77. FSTRING_START = getattr(tokenize, "FSTRING_START", None)
  78. FSTRING_MIDDLE = getattr(tokenize, "FSTRING_MIDDLE", None)
  79. FSTRING_END = getattr(tokenize, "FSTRING_END", None)
  80. def _strip_comment_tags(comments: MutableSequence[str], tags: Iterable[str]):
  81. """Helper function for `extract` that strips comment tags from strings
  82. in a list of comment lines. This functions operates in-place.
  83. """
  84. def _strip(line: str):
  85. for tag in tags:
  86. if line.startswith(tag):
  87. return line[len(tag):].strip()
  88. return line
  89. comments[:] = map(_strip, comments)
  90. def default_directory_filter(dirpath: str | os.PathLike[str]) -> bool:
  91. subdir = os.path.basename(dirpath)
  92. # Legacy default behavior: ignore dot and underscore directories
  93. return not (subdir.startswith('.') or subdir.startswith('_'))
  94. def extract_from_dir(
  95. dirname: str | os.PathLike[str] | None = None,
  96. method_map: Iterable[tuple[str, str]] = DEFAULT_MAPPING,
  97. options_map: SupportsItems[str, dict[str, Any]] | None = None,
  98. keywords: Mapping[str, _Keyword] = DEFAULT_KEYWORDS,
  99. comment_tags: Collection[str] = (),
  100. callback: Callable[[str, str, dict[str, Any]], object] | None = None,
  101. strip_comment_tags: bool = False,
  102. directory_filter: Callable[[str], bool] | None = None,
  103. ) -> Generator[_FileExtractionResult, None, None]:
  104. """Extract messages from any source files found in the given directory.
  105. This function generates tuples of the form ``(filename, lineno, message,
  106. comments, context)``.
  107. Which extraction method is used per file is determined by the `method_map`
  108. parameter, which maps extended glob patterns to extraction method names.
  109. For example, the following is the default mapping:
  110. >>> method_map = [
  111. ... ('**.py', 'python')
  112. ... ]
  113. This basically says that files with the filename extension ".py" at any
  114. level inside the directory should be processed by the "python" extraction
  115. method. Files that don't match any of the mapping patterns are ignored. See
  116. the documentation of the `pathmatch` function for details on the pattern
  117. syntax.
  118. The following extended mapping would also use the "genshi" extraction
  119. method on any file in "templates" subdirectory:
  120. >>> method_map = [
  121. ... ('**/templates/**.*', 'genshi'),
  122. ... ('**.py', 'python')
  123. ... ]
  124. The dictionary provided by the optional `options_map` parameter augments
  125. these mappings. It uses extended glob patterns as keys, and the values are
  126. dictionaries mapping options names to option values (both strings).
  127. The glob patterns of the `options_map` do not necessarily need to be the
  128. same as those used in the method mapping. For example, while all files in
  129. the ``templates`` folders in an application may be Genshi applications, the
  130. options for those files may differ based on extension:
  131. >>> options_map = {
  132. ... '**/templates/**.txt': {
  133. ... 'template_class': 'genshi.template:TextTemplate',
  134. ... 'encoding': 'latin-1'
  135. ... },
  136. ... '**/templates/**.html': {
  137. ... 'include_attrs': ''
  138. ... }
  139. ... }
  140. :param dirname: the path to the directory to extract messages from. If
  141. not given the current working directory is used.
  142. :param method_map: a list of ``(pattern, method)`` tuples that maps of
  143. extraction method names to extended glob patterns
  144. :param options_map: a dictionary of additional options (optional)
  145. :param keywords: a dictionary mapping keywords (i.e. names of functions
  146. that should be recognized as translation functions) to
  147. tuples that specify which of their arguments contain
  148. localizable strings
  149. :param comment_tags: a list of tags of translator comments to search for
  150. and include in the results
  151. :param callback: a function that is called for every file that message are
  152. extracted from, just before the extraction itself is
  153. performed; the function is passed the filename, the name
  154. of the extraction method and and the options dictionary as
  155. positional arguments, in that order
  156. :param strip_comment_tags: a flag that if set to `True` causes all comment
  157. tags to be removed from the collected comments.
  158. :param directory_filter: a callback to determine whether a directory should
  159. be recursed into. Receives the full directory path;
  160. should return True if the directory is valid.
  161. :see: `pathmatch`
  162. """
  163. if dirname is None:
  164. dirname = os.getcwd()
  165. if options_map is None:
  166. options_map = {}
  167. if directory_filter is None:
  168. directory_filter = default_directory_filter
  169. absname = os.path.abspath(dirname)
  170. for root, dirnames, filenames in os.walk(absname):
  171. dirnames[:] = [
  172. subdir for subdir in dirnames
  173. if directory_filter(os.path.join(root, subdir))
  174. ]
  175. dirnames.sort()
  176. filenames.sort()
  177. for filename in filenames:
  178. filepath = os.path.join(root, filename).replace(os.sep, '/')
  179. yield from check_and_call_extract_file(
  180. filepath,
  181. method_map,
  182. options_map,
  183. callback,
  184. keywords,
  185. comment_tags,
  186. strip_comment_tags,
  187. dirpath=absname,
  188. )
  189. def check_and_call_extract_file(
  190. filepath: str | os.PathLike[str],
  191. method_map: Iterable[tuple[str, str]],
  192. options_map: SupportsItems[str, dict[str, Any]],
  193. callback: Callable[[str, str, dict[str, Any]], object] | None,
  194. keywords: Mapping[str, _Keyword],
  195. comment_tags: Collection[str],
  196. strip_comment_tags: bool,
  197. dirpath: str | os.PathLike[str] | None = None,
  198. ) -> Generator[_FileExtractionResult, None, None]:
  199. """Checks if the given file matches an extraction method mapping, and if so, calls extract_from_file.
  200. Note that the extraction method mappings are based relative to dirpath.
  201. So, given an absolute path to a file `filepath`, we want to check using
  202. just the relative path from `dirpath` to `filepath`.
  203. Yields 5-tuples (filename, lineno, messages, comments, context).
  204. :param filepath: An absolute path to a file that exists.
  205. :param method_map: a list of ``(pattern, method)`` tuples that maps of
  206. extraction method names to extended glob patterns
  207. :param options_map: a dictionary of additional options (optional)
  208. :param callback: a function that is called for every file that message are
  209. extracted from, just before the extraction itself is
  210. performed; the function is passed the filename, the name
  211. of the extraction method and and the options dictionary as
  212. positional arguments, in that order
  213. :param keywords: a dictionary mapping keywords (i.e. names of functions
  214. that should be recognized as translation functions) to
  215. tuples that specify which of their arguments contain
  216. localizable strings
  217. :param comment_tags: a list of tags of translator comments to search for
  218. and include in the results
  219. :param strip_comment_tags: a flag that if set to `True` causes all comment
  220. tags to be removed from the collected comments.
  221. :param dirpath: the path to the directory to extract messages from.
  222. :return: iterable of 5-tuples (filename, lineno, messages, comments, context)
  223. :rtype: Iterable[tuple[str, int, str|tuple[str], list[str], str|None]
  224. """
  225. # filename is the relative path from dirpath to the actual file
  226. filename = relpath(filepath, dirpath)
  227. for pattern, method in method_map:
  228. if not pathmatch(pattern, filename):
  229. continue
  230. options = {}
  231. for opattern, odict in options_map.items():
  232. if pathmatch(opattern, filename):
  233. options = odict
  234. break
  235. if callback:
  236. callback(filename, method, options)
  237. for message_tuple in extract_from_file(
  238. method, filepath,
  239. keywords=keywords,
  240. comment_tags=comment_tags,
  241. options=options,
  242. strip_comment_tags=strip_comment_tags,
  243. ):
  244. yield (filename, *message_tuple)
  245. break
  246. def extract_from_file(
  247. method: _ExtractionMethod,
  248. filename: str | os.PathLike[str],
  249. keywords: Mapping[str, _Keyword] = DEFAULT_KEYWORDS,
  250. comment_tags: Collection[str] = (),
  251. options: Mapping[str, Any] | None = None,
  252. strip_comment_tags: bool = False,
  253. ) -> list[_ExtractionResult]:
  254. """Extract messages from a specific file.
  255. This function returns a list of tuples of the form ``(lineno, message, comments, context)``.
  256. :param filename: the path to the file to extract messages from
  257. :param method: a string specifying the extraction method (.e.g. "python")
  258. :param keywords: a dictionary mapping keywords (i.e. names of functions
  259. that should be recognized as translation functions) to
  260. tuples that specify which of their arguments contain
  261. localizable strings
  262. :param comment_tags: a list of translator tags to search for and include
  263. in the results
  264. :param strip_comment_tags: a flag that if set to `True` causes all comment
  265. tags to be removed from the collected comments.
  266. :param options: a dictionary of additional options (optional)
  267. :returns: list of tuples of the form ``(lineno, message, comments, context)``
  268. :rtype: list[tuple[int, str|tuple[str], list[str], str|None]
  269. """
  270. if method == 'ignore':
  271. return []
  272. with open(filename, 'rb') as fileobj:
  273. return list(extract(method, fileobj, keywords, comment_tags,
  274. options, strip_comment_tags))
  275. def _match_messages_against_spec(
  276. lineno: int,
  277. messages: list[str | None],
  278. comments: list[str],
  279. fileobj: _FileObj,
  280. spec: tuple[int | tuple[int, str], ...],
  281. ):
  282. translatable = []
  283. context = None
  284. # last_index is 1 based like the keyword spec
  285. last_index = len(messages)
  286. for index in spec:
  287. if isinstance(index, tuple): # (n, 'c')
  288. context = messages[index[0] - 1]
  289. continue
  290. if last_index < index:
  291. # Not enough arguments
  292. return
  293. message = messages[index - 1]
  294. if message is None:
  295. return
  296. translatable.append(message)
  297. # keyword spec indexes are 1 based, therefore '-1'
  298. if isinstance(spec[0], tuple):
  299. # context-aware *gettext method
  300. first_msg_index = spec[1] - 1
  301. else:
  302. first_msg_index = spec[0] - 1
  303. # An empty string msgid isn't valid, emit a warning
  304. if not messages[first_msg_index]:
  305. filename = (getattr(fileobj, "name", None) or "(unknown)")
  306. sys.stderr.write(
  307. f"{filename}:{lineno}: warning: Empty msgid. It is reserved by GNU gettext: gettext(\"\") "
  308. f"returns the header entry with meta information, not the empty string.\n",
  309. )
  310. return
  311. translatable = tuple(translatable)
  312. if len(translatable) == 1:
  313. translatable = translatable[0]
  314. return lineno, translatable, comments, context
  315. @lru_cache(maxsize=None)
  316. def _find_extractor(name: str):
  317. for ep_name, load in find_entrypoints(GROUP_NAME):
  318. if ep_name == name:
  319. return load()
  320. return None
  321. def extract(
  322. method: _ExtractionMethod,
  323. fileobj: _FileObj,
  324. keywords: Mapping[str, _Keyword] = DEFAULT_KEYWORDS,
  325. comment_tags: Collection[str] = (),
  326. options: Mapping[str, Any] | None = None,
  327. strip_comment_tags: bool = False,
  328. ) -> Generator[_ExtractionResult, None, None]:
  329. """Extract messages from the given file-like object using the specified
  330. extraction method.
  331. This function returns tuples of the form ``(lineno, message, comments, context)``.
  332. The implementation dispatches the actual extraction to plugins, based on the
  333. value of the ``method`` parameter.
  334. >>> source = b'''# foo module
  335. ... def run(argv):
  336. ... print(_('Hello, world!'))
  337. ... '''
  338. >>> from io import BytesIO
  339. >>> for message in extract('python', BytesIO(source)):
  340. ... print(message)
  341. (3, u'Hello, world!', [], None)
  342. :param method: an extraction method (a callable), or
  343. a string specifying the extraction method (.e.g. "python");
  344. if this is a simple name, the extraction function will be
  345. looked up by entry point; if it is an explicit reference
  346. to a function (of the form ``package.module:funcname`` or
  347. ``package.module.funcname``), the corresponding function
  348. will be imported and used
  349. :param fileobj: the file-like object the messages should be extracted from
  350. :param keywords: a dictionary mapping keywords (i.e. names of functions
  351. that should be recognized as translation functions) to
  352. tuples that specify which of their arguments contain
  353. localizable strings
  354. :param comment_tags: a list of translator tags to search for and include
  355. in the results
  356. :param options: a dictionary of additional options (optional)
  357. :param strip_comment_tags: a flag that if set to `True` causes all comment
  358. tags to be removed from the collected comments.
  359. :raise ValueError: if the extraction method is not registered
  360. :returns: iterable of tuples of the form ``(lineno, message, comments, context)``
  361. :rtype: Iterable[tuple[int, str|tuple[str], list[str], str|None]
  362. """
  363. if callable(method):
  364. func = method
  365. elif ':' in method or '.' in method:
  366. if ':' not in method:
  367. lastdot = method.rfind('.')
  368. module, attrname = method[:lastdot], method[lastdot + 1:]
  369. else:
  370. module, attrname = method.split(':', 1)
  371. func = getattr(__import__(module, {}, {}, [attrname]), attrname)
  372. else:
  373. func = _find_extractor(method)
  374. if func is None:
  375. # if no named entry point was found,
  376. # we resort to looking up a builtin extractor
  377. func = _BUILTIN_EXTRACTORS.get(method)
  378. if func is None:
  379. raise ValueError(f"Unknown extraction method {method!r}")
  380. results = func(fileobj, keywords.keys(), comment_tags,
  381. options=options or {})
  382. for lineno, funcname, messages, comments in results:
  383. if not isinstance(messages, (list, tuple)):
  384. messages = [messages]
  385. if not messages:
  386. continue
  387. specs = keywords[funcname] or None if funcname else None
  388. # {None: x} may be collapsed into x for backwards compatibility.
  389. if not isinstance(specs, dict):
  390. specs = {None: specs}
  391. if strip_comment_tags:
  392. _strip_comment_tags(comments, comment_tags)
  393. # None matches all arities.
  394. for arity in (None, len(messages)):
  395. try:
  396. spec = specs[arity]
  397. except KeyError:
  398. continue
  399. if spec is None:
  400. spec = (1,)
  401. result = _match_messages_against_spec(lineno, messages, comments, fileobj, spec)
  402. if result is not None:
  403. yield result
  404. def extract_nothing(
  405. fileobj: _FileObj,
  406. keywords: Mapping[str, _Keyword],
  407. comment_tags: Collection[str],
  408. options: Mapping[str, Any],
  409. ) -> list[_ExtractionResult]:
  410. """Pseudo extractor that does not actually extract anything, but simply
  411. returns an empty list.
  412. """
  413. return []
  414. def extract_python(
  415. fileobj: IO[bytes],
  416. keywords: Mapping[str, _Keyword],
  417. comment_tags: Collection[str],
  418. options: _PyOptions,
  419. ) -> Generator[_ExtractionResult, None, None]:
  420. """Extract messages from Python source code.
  421. It returns an iterator yielding tuples in the following form ``(lineno,
  422. funcname, message, comments)``.
  423. :param fileobj: the seekable, file-like object the messages should be
  424. extracted from
  425. :param keywords: a list of keywords (i.e. function names) that should be
  426. recognized as translation functions
  427. :param comment_tags: a list of translator tags to search for and include
  428. in the results
  429. :param options: a dictionary of additional options (optional)
  430. :rtype: ``iterator``
  431. """
  432. funcname = lineno = message_lineno = None
  433. call_stack = -1
  434. buf = []
  435. messages = []
  436. translator_comments = []
  437. in_def = in_translator_comments = False
  438. comment_tag = None
  439. encoding = parse_encoding(fileobj) or options.get('encoding', 'UTF-8')
  440. future_flags = parse_future_flags(fileobj, encoding)
  441. next_line = lambda: fileobj.readline().decode(encoding)
  442. tokens = generate_tokens(next_line)
  443. # Current prefix of a Python 3.12 (PEP 701) f-string, or None if we're not
  444. # currently parsing one.
  445. current_fstring_start = None
  446. for tok, value, (lineno, _), _, _ in tokens:
  447. if call_stack == -1 and tok == NAME and value in ('def', 'class'):
  448. in_def = True
  449. elif tok == OP and value == '(':
  450. if in_def:
  451. # Avoid false positives for declarations such as:
  452. # def gettext(arg='message'):
  453. in_def = False
  454. continue
  455. if funcname:
  456. call_stack += 1
  457. elif in_def and tok == OP and value == ':':
  458. # End of a class definition without parens
  459. in_def = False
  460. continue
  461. elif call_stack == -1 and tok == COMMENT:
  462. # Strip the comment token from the line
  463. value = value[1:].strip()
  464. if in_translator_comments and \
  465. translator_comments[-1][0] == lineno - 1:
  466. # We're already inside a translator comment, continue appending
  467. translator_comments.append((lineno, value))
  468. continue
  469. # If execution reaches this point, let's see if comment line
  470. # starts with one of the comment tags
  471. for comment_tag in comment_tags:
  472. if value.startswith(comment_tag):
  473. in_translator_comments = True
  474. translator_comments.append((lineno, value))
  475. break
  476. elif funcname and call_stack == 0:
  477. nested = (tok == NAME and value in keywords)
  478. if (tok == OP and value == ')') or nested:
  479. if buf:
  480. messages.append(''.join(buf))
  481. del buf[:]
  482. else:
  483. messages.append(None)
  484. messages = tuple(messages) if len(messages) > 1 else messages[0]
  485. # Comments don't apply unless they immediately
  486. # precede the message
  487. if translator_comments and \
  488. translator_comments[-1][0] < message_lineno - 1:
  489. translator_comments = []
  490. yield (message_lineno, funcname, messages,
  491. [comment[1] for comment in translator_comments])
  492. funcname = lineno = message_lineno = None
  493. call_stack = -1
  494. messages = []
  495. translator_comments = []
  496. in_translator_comments = False
  497. if nested:
  498. funcname = value
  499. elif tok == STRING:
  500. val = _parse_python_string(value, encoding, future_flags)
  501. if val is not None:
  502. if not message_lineno:
  503. message_lineno = lineno
  504. buf.append(val)
  505. # Python 3.12+, see https://peps.python.org/pep-0701/#new-tokens
  506. elif tok == FSTRING_START:
  507. current_fstring_start = value
  508. if not message_lineno:
  509. message_lineno = lineno
  510. elif tok == FSTRING_MIDDLE:
  511. if current_fstring_start is not None:
  512. current_fstring_start += value
  513. elif tok == FSTRING_END:
  514. if current_fstring_start is not None:
  515. fstring = current_fstring_start + value
  516. val = _parse_python_string(fstring, encoding, future_flags)
  517. if val is not None:
  518. buf.append(val)
  519. elif tok == OP and value == ',':
  520. if buf:
  521. messages.append(''.join(buf))
  522. del buf[:]
  523. else:
  524. messages.append(None)
  525. if translator_comments:
  526. # We have translator comments, and since we're on a
  527. # comma(,) user is allowed to break into a new line
  528. # Let's increase the last comment's lineno in order
  529. # for the comment to still be a valid one
  530. old_lineno, old_comment = translator_comments.pop()
  531. translator_comments.append((old_lineno + 1, old_comment))
  532. elif tok != NL and not message_lineno:
  533. message_lineno = lineno
  534. elif call_stack > 0 and tok == OP and value == ')':
  535. call_stack -= 1
  536. elif funcname and call_stack == -1:
  537. funcname = None
  538. elif tok == NAME and value in keywords:
  539. funcname = value
  540. if current_fstring_start is not None and tok not in {FSTRING_START, FSTRING_MIDDLE}:
  541. # In Python 3.12, tokens other than FSTRING_* mean the
  542. # f-string is dynamic, so we don't wan't to extract it.
  543. # And if it's FSTRING_END, we've already handled it above.
  544. # Let's forget that we're in an f-string.
  545. current_fstring_start = None
  546. def _parse_python_string(value: str, encoding: str, future_flags: int) -> str | None:
  547. # Unwrap quotes in a safe manner, maintaining the string's encoding
  548. # https://sourceforge.net/tracker/?func=detail&atid=355470&aid=617979&group_id=5470
  549. code = compile(
  550. f'# coding={str(encoding)}\n{value}',
  551. '<string>',
  552. 'eval',
  553. ast.PyCF_ONLY_AST | future_flags,
  554. )
  555. if isinstance(code, ast.Expression):
  556. body = code.body
  557. if isinstance(body, ast.Constant):
  558. return body.value
  559. if isinstance(body, ast.JoinedStr): # f-string
  560. if all(isinstance(node, ast.Constant) for node in body.values):
  561. return ''.join(node.value for node in body.values)
  562. # TODO: we could raise an error or warning when not all nodes are constants
  563. return None
  564. def extract_javascript(
  565. fileobj: _FileObj,
  566. keywords: Mapping[str, _Keyword],
  567. comment_tags: Collection[str],
  568. options: _JSOptions,
  569. lineno: int = 1,
  570. ) -> Generator[_ExtractionResult, None, None]:
  571. """Extract messages from JavaScript source code.
  572. :param fileobj: the seekable, file-like object the messages should be
  573. extracted from
  574. :param keywords: a list of keywords (i.e. function names) that should be
  575. recognized as translation functions
  576. :param comment_tags: a list of translator tags to search for and include
  577. in the results
  578. :param options: a dictionary of additional options (optional)
  579. Supported options are:
  580. * `jsx` -- set to false to disable JSX/E4X support.
  581. * `template_string` -- if `True`, supports gettext(`key`)
  582. * `parse_template_string` -- if `True` will parse the
  583. contents of javascript
  584. template strings.
  585. :param lineno: line number offset (for parsing embedded fragments)
  586. """
  587. from babel.messages.jslexer import Token, tokenize, unquote_string
  588. funcname = message_lineno = None
  589. messages = []
  590. last_argument = None
  591. translator_comments = []
  592. concatenate_next = False
  593. encoding = options.get('encoding', 'utf-8')
  594. last_token = None
  595. call_stack = -1
  596. dotted = any('.' in kw for kw in keywords)
  597. for token in tokenize(
  598. fileobj.read().decode(encoding),
  599. jsx=options.get("jsx", True),
  600. template_string=options.get("template_string", True),
  601. dotted=dotted,
  602. lineno=lineno,
  603. ):
  604. if ( # Turn keyword`foo` expressions into keyword("foo") calls:
  605. funcname and # have a keyword...
  606. (last_token and last_token.type == 'name') and # we've seen nothing after the keyword...
  607. token.type == 'template_string' # this is a template string
  608. ):
  609. message_lineno = token.lineno
  610. messages = [unquote_string(token.value)]
  611. call_stack = 0
  612. token = Token('operator', ')', token.lineno)
  613. if options.get('parse_template_string') and not funcname and token.type == 'template_string':
  614. yield from parse_template_string(token.value, keywords, comment_tags, options, token.lineno)
  615. elif token.type == 'operator' and token.value == '(':
  616. if funcname:
  617. message_lineno = token.lineno
  618. call_stack += 1
  619. elif call_stack == -1 and token.type == 'linecomment':
  620. value = token.value[2:].strip()
  621. if translator_comments and \
  622. translator_comments[-1][0] == token.lineno - 1:
  623. translator_comments.append((token.lineno, value))
  624. continue
  625. for comment_tag in comment_tags:
  626. if value.startswith(comment_tag):
  627. translator_comments.append((token.lineno, value.strip()))
  628. break
  629. elif token.type == 'multilinecomment':
  630. # only one multi-line comment may precede a translation
  631. translator_comments = []
  632. value = token.value[2:-2].strip()
  633. for comment_tag in comment_tags:
  634. if value.startswith(comment_tag):
  635. lines = value.splitlines()
  636. if lines:
  637. lines[0] = lines[0].strip()
  638. lines[1:] = dedent('\n'.join(lines[1:])).splitlines()
  639. for offset, line in enumerate(lines):
  640. translator_comments.append((token.lineno + offset,
  641. line))
  642. break
  643. elif funcname and call_stack == 0:
  644. if token.type == 'operator' and token.value == ')':
  645. if last_argument is not None:
  646. messages.append(last_argument)
  647. if len(messages) > 1:
  648. messages = tuple(messages)
  649. elif messages:
  650. messages = messages[0]
  651. else:
  652. messages = None
  653. # Comments don't apply unless they immediately precede the
  654. # message
  655. if translator_comments and \
  656. translator_comments[-1][0] < message_lineno - 1:
  657. translator_comments = []
  658. if messages is not None:
  659. yield (message_lineno, funcname, messages,
  660. [comment[1] for comment in translator_comments])
  661. funcname = message_lineno = last_argument = None
  662. concatenate_next = False
  663. translator_comments = []
  664. messages = []
  665. call_stack = -1
  666. elif token.type in ('string', 'template_string'):
  667. new_value = unquote_string(token.value)
  668. if concatenate_next:
  669. last_argument = (last_argument or '') + new_value
  670. concatenate_next = False
  671. else:
  672. last_argument = new_value
  673. elif token.type == 'operator':
  674. if token.value == ',':
  675. if last_argument is not None:
  676. messages.append(last_argument)
  677. last_argument = None
  678. else:
  679. messages.append(None)
  680. concatenate_next = False
  681. elif token.value == '+':
  682. concatenate_next = True
  683. elif call_stack > 0 and token.type == 'operator' \
  684. and token.value == ')':
  685. call_stack -= 1
  686. elif funcname and call_stack == -1:
  687. funcname = None
  688. elif call_stack == -1 and token.type == 'name' and \
  689. token.value in keywords and \
  690. (last_token is None or last_token.type != 'name' or
  691. last_token.value != 'function'):
  692. funcname = token.value
  693. last_token = token
  694. def parse_template_string(
  695. template_string: str,
  696. keywords: Mapping[str, _Keyword],
  697. comment_tags: Collection[str],
  698. options: _JSOptions,
  699. lineno: int = 1,
  700. ) -> Generator[_ExtractionResult, None, None]:
  701. """Parse JavaScript template string.
  702. :param template_string: the template string to be parsed
  703. :param keywords: a list of keywords (i.e. function names) that should be
  704. recognized as translation functions
  705. :param comment_tags: a list of translator tags to search for and include
  706. in the results
  707. :param options: a dictionary of additional options (optional)
  708. :param lineno: starting line number (optional)
  709. """
  710. from babel.messages.jslexer import line_re
  711. prev_character = None
  712. level = 0
  713. inside_str = False
  714. expression_contents = ''
  715. for character in template_string[1:-1]:
  716. if not inside_str and character in ('"', "'", '`'):
  717. inside_str = character
  718. elif inside_str == character and prev_character != r'\\':
  719. inside_str = False
  720. if level:
  721. expression_contents += character
  722. if not inside_str:
  723. if character == '{' and prev_character == '$':
  724. level += 1
  725. elif level and character == '}':
  726. level -= 1
  727. if level == 0 and expression_contents:
  728. expression_contents = expression_contents[0:-1]
  729. fake_file_obj = io.BytesIO(expression_contents.encode())
  730. yield from extract_javascript(fake_file_obj, keywords, comment_tags, options, lineno)
  731. lineno += len(line_re.findall(expression_contents))
  732. expression_contents = ''
  733. prev_character = character
  734. _BUILTIN_EXTRACTORS = {
  735. 'ignore': extract_nothing,
  736. 'python': extract_python,
  737. 'javascript': extract_javascript,
  738. }