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.
 
 
 
 

150 lines
5.1 KiB

  1. # Copyright (C) 2012-2020 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. from ...string_mixin import StringMixIn
  21. from ...utils import parse_anything
  22. __all__ = ["Attribute"]
  23. class Attribute(StringMixIn):
  24. """Represents an attribute of an HTML tag.
  25. This is used by :class:`.Tag` objects. For example, the tag
  26. ``<ref name="foo">`` contains an Attribute whose name is ``"name"`` and
  27. whose value is ``"foo"``.
  28. """
  29. def __init__(self, name, value=None, quotes='"', pad_first=" ",
  30. pad_before_eq="", pad_after_eq=""):
  31. super().__init__()
  32. self.name = name
  33. self._quotes = None
  34. self.value = value
  35. self.quotes = quotes
  36. self.pad_first = pad_first
  37. self.pad_before_eq = pad_before_eq
  38. self.pad_after_eq = pad_after_eq
  39. def __str__(self):
  40. result = self.pad_first + str(self.name) + self.pad_before_eq
  41. if self.value is not None:
  42. result += "=" + self.pad_after_eq
  43. if self.quotes:
  44. return result + self.quotes + str(self.value) + self.quotes
  45. return result + str(self.value)
  46. return result
  47. @staticmethod
  48. def _value_needs_quotes(val):
  49. """Return valid quotes for the given value, or None if unneeded."""
  50. if not val:
  51. return None
  52. val = "".join(str(node) for node in val.filter_text(recursive=False))
  53. if not any(char.isspace() for char in val):
  54. return None
  55. if "'" in val and '"' not in val:
  56. return '"'
  57. if '"' in val and "'" not in val:
  58. return "'"
  59. return "\"'" # Either acceptable, " preferred over '
  60. def _set_padding(self, attr, value):
  61. """Setter for the value of a padding attribute."""
  62. if not value:
  63. setattr(self, attr, "")
  64. else:
  65. value = str(value)
  66. if not value.isspace():
  67. raise ValueError("padding must be entirely whitespace")
  68. setattr(self, attr, value)
  69. @staticmethod
  70. def coerce_quotes(quotes):
  71. """Coerce a quote type into an acceptable value, or raise an error."""
  72. orig, quotes = quotes, str(quotes) if quotes else None
  73. if quotes not in [None, '"', "'"]:
  74. raise ValueError("{!r} is not a valid quote type".format(orig))
  75. return quotes
  76. @property
  77. def name(self):
  78. """The name of the attribute as a :class:`.Wikicode` object."""
  79. return self._name
  80. @property
  81. def value(self):
  82. """The value of the attribute as a :class:`.Wikicode` object."""
  83. return self._value
  84. @property
  85. def quotes(self):
  86. """How to enclose the attribute value. ``"``, ``'``, or ``None``."""
  87. return self._quotes
  88. @property
  89. def pad_first(self):
  90. """Spacing to insert right before the attribute."""
  91. return self._pad_first
  92. @property
  93. def pad_before_eq(self):
  94. """Spacing to insert right before the equal sign."""
  95. return self._pad_before_eq
  96. @property
  97. def pad_after_eq(self):
  98. """Spacing to insert right after the equal sign."""
  99. return self._pad_after_eq
  100. @name.setter
  101. def name(self, value):
  102. self._name = parse_anything(value)
  103. @value.setter
  104. def value(self, newval):
  105. if newval is None:
  106. self._value = None
  107. else:
  108. code = parse_anything(newval)
  109. quotes = self._value_needs_quotes(code)
  110. if quotes and (not self.quotes or self.quotes not in quotes):
  111. self._quotes = quotes[0]
  112. self._value = code
  113. @quotes.setter
  114. def quotes(self, value):
  115. value = self.coerce_quotes(value)
  116. if not value and self._value_needs_quotes(self.value):
  117. raise ValueError("attribute value requires quotes")
  118. self._quotes = value
  119. @pad_first.setter
  120. def pad_first(self, value):
  121. self._set_padding("_pad_first", value)
  122. @pad_before_eq.setter
  123. def pad_before_eq(self, value):
  124. self._set_padding("_pad_before_eq", value)
  125. @pad_after_eq.setter
  126. def pad_after_eq(self, value):
  127. self._set_padding("_pad_after_eq", value)