extract.py 36 KB

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