babel_extract.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """This module implements the :origin:`searxng_msg <babel.cfg>` extractor to
  3. extract messages from:
  4. - :origin:`searx/searxng.msg`
  5. The ``searxng.msg`` files are selected by Babel_, see Babel's configuration in
  6. :origin:`babel.cfg`::
  7. searxng_msg = searx.babel_extract.extract
  8. ...
  9. [searxng_msg: **/searxng.msg]
  10. A ``searxng.msg`` file is a python file that is *executed* by the
  11. :py:obj:`extract` function. Additional ``searxng.msg`` files can be added by:
  12. 1. Adding a ``searxng.msg`` file in one of the SearXNG python packages and
  13. 2. implement a method in :py:obj:`extract` that yields messages from this file.
  14. .. _Babel: https://babel.pocoo.org/en/latest/index.html
  15. """
  16. from os import path
  17. SEARXNG_MSG_FILE = "searxng.msg"
  18. _MSG_FILES = [path.join(path.dirname(__file__), SEARXNG_MSG_FILE)]
  19. def extract(
  20. # pylint: disable=unused-argument
  21. fileobj,
  22. keywords,
  23. comment_tags,
  24. options,
  25. ):
  26. """Extract messages from ``searxng.msg`` files by a custom extractor_.
  27. .. _extractor:
  28. https://babel.pocoo.org/en/latest/messages.html#writing-extraction-methods
  29. """
  30. if fileobj.name not in _MSG_FILES:
  31. raise RuntimeError("don't know how to extract messages from %s" % fileobj.name)
  32. namespace = {}
  33. exec(fileobj.read(), {}, namespace) # pylint: disable=exec-used
  34. for obj_name in namespace['__all__']:
  35. obj = namespace[obj_name]
  36. if isinstance(obj, list):
  37. for msg in obj:
  38. # (lineno, funcname, message, comments)
  39. yield 0, '_', msg, [f"{obj_name}"]
  40. elif isinstance(obj, dict):
  41. for k, msg in obj.items():
  42. yield 0, '_', msg, [f"{obj_name}['{k}']"]
  43. else:
  44. raise ValueError(f"{obj_name} should be list or dict")