A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

85 lines
3.4 KiB

  1. # Copyright (C) 2012-2023 Ben Kurtovic <ben.kurtovic@gmail.com>
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. # SOFTWARE.
  20. """
  21. This module contains accessory functions for other parts of the library. Parser
  22. users generally won't need stuff from here.
  23. """
  24. from __future__ import annotations
  25. __all__ = ["parse_anything"]
  26. import typing
  27. from typing import Any
  28. if typing.TYPE_CHECKING:
  29. from .wikicode import Wikicode
  30. def parse_anything(
  31. value: Any, context: int = 0, *, skip_style_tags: bool = False
  32. ) -> Wikicode:
  33. """Return a :class:`.Wikicode` for *value*, allowing multiple types.
  34. This differs from :meth:`.Parser.parse` in that we accept more than just a
  35. string to be parsed. Strings, bytes, integers (converted to strings),
  36. ``None``, existing :class:`.Node` or :class:`.Wikicode` objects, as well
  37. as an iterable of these types, are supported. This is used to parse input
  38. on-the-fly by various methods of :class:`.Wikicode` and others like
  39. :class:`.Template`, such as :meth:`wikicode.insert() <.Wikicode.insert>`
  40. or setting :meth:`template.name <.Template.name>`.
  41. Additional arguments are passed directly to :meth:`.Parser.parse`.
  42. """
  43. # pylint: disable=cyclic-import,import-outside-toplevel
  44. from .nodes import Node
  45. from .parser import Parser
  46. from .smart_list import SmartList
  47. from .wikicode import Wikicode
  48. if isinstance(value, Wikicode):
  49. return value
  50. if isinstance(value, Node):
  51. return Wikicode(SmartList([value]))
  52. if isinstance(value, str):
  53. return Parser().parse(value, context, skip_style_tags)
  54. if isinstance(value, bytes):
  55. return Parser().parse(value.decode("utf8"), context, skip_style_tags)
  56. if isinstance(value, int):
  57. return Parser().parse(str(value), context, skip_style_tags)
  58. if value is None:
  59. return Wikicode(SmartList())
  60. if hasattr(value, "read"):
  61. return parse_anything(value.read(), context, skip_style_tags=skip_style_tags)
  62. try:
  63. nodelist = SmartList()
  64. for item in value:
  65. nodelist += parse_anything(
  66. item, context, skip_style_tags=skip_style_tags
  67. ).nodes
  68. return Wikicode(nodelist)
  69. except TypeError as exc:
  70. error = (
  71. "Needs string, Node, Wikicode, file, int, None, or "
  72. "iterable of these, but got {0}: {1}"
  73. )
  74. raise ValueError(error.format(type(value).__name__, value)) from exc