Debian Codegraph @

babel/messages/extract.py

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