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.
 
 
 
 

151 lines
5.1 KiB

  1. #
  2. # Copyright (C) 2012-2019 Ben Kurtovic <ben.kurtovic@gmail.com>
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining a copy
  5. # of this software and associated documentation files (the "Software"), to deal
  6. # in the Software without restriction, including without limitation the rights
  7. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. # copies of the Software, and to permit persons to whom the Software is
  9. # furnished to do so, subject to the following conditions:
  10. #
  11. # The above copyright notice and this permission notice shall be included in
  12. # all copies or substantial portions of the Software.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. from ...string_mixin import StringMixIn
  22. from ...utils import parse_anything
  23. __all__ = ["Attribute"]
  24. class Attribute(StringMixIn):
  25. """Represents an attribute of an HTML tag.
  26. This is used by :class:`.Tag` objects. For example, the tag
  27. ``<ref name="foo">`` contains an Attribute whose name is ``"name"`` and
  28. whose value is ``"foo"``.
  29. """
  30. def __init__(self, name, value=None, quotes='"', pad_first=" ",
  31. pad_before_eq="", pad_after_eq=""):
  32. super().__init__()
  33. self.name = name
  34. self._quotes = None
  35. self.value = value
  36. self.quotes = quotes
  37. self.pad_first = pad_first
  38. self.pad_before_eq = pad_before_eq
  39. self.pad_after_eq = pad_after_eq
  40. def __unicode__(self):
  41. result = self.pad_first + str(self.name) + self.pad_before_eq
  42. if self.value is not None:
  43. result += "=" + self.pad_after_eq
  44. if self.quotes:
  45. return result + self.quotes + str(self.value) + self.quotes
  46. return result + str(self.value)
  47. return result
  48. @staticmethod
  49. def _value_needs_quotes(val):
  50. """Return valid quotes for the given value, or None if unneeded."""
  51. if not val:
  52. return None
  53. val = "".join(str(node) for node in val.filter_text(recursive=False))
  54. if not any(char.isspace() for char in val):
  55. return None
  56. if "'" in val and '"' not in val:
  57. return '"'
  58. if '"' in val and "'" not in val:
  59. return "'"
  60. return "\"'" # Either acceptable, " preferred over '
  61. def _set_padding(self, attr, value):
  62. """Setter for the value of a padding attribute."""
  63. if not value:
  64. setattr(self, attr, "")
  65. else:
  66. value = str(value)
  67. if not value.isspace():
  68. raise ValueError("padding must be entirely whitespace")
  69. setattr(self, attr, value)
  70. @staticmethod
  71. def coerce_quotes(quotes):
  72. """Coerce a quote type into an acceptable value, or raise an error."""
  73. orig, quotes = quotes, str(quotes) if quotes else None
  74. if quotes not in [None, '"', "'"]:
  75. raise ValueError("{!r} is not a valid quote type".format(orig))
  76. return quotes
  77. @property
  78. def name(self):
  79. """The name of the attribute as a :class:`.Wikicode` object."""
  80. return self._name
  81. @property
  82. def value(self):
  83. """The value of the attribute as a :class:`.Wikicode` object."""
  84. return self._value
  85. @property
  86. def quotes(self):
  87. """How to enclose the attribute value. ``"``, ``'``, or ``None``."""
  88. return self._quotes
  89. @property
  90. def pad_first(self):
  91. """Spacing to insert right before the attribute."""
  92. return self._pad_first
  93. @property
  94. def pad_before_eq(self):
  95. """Spacing to insert right before the equal sign."""
  96. return self._pad_before_eq
  97. @property
  98. def pad_after_eq(self):
  99. """Spacing to insert right after the equal sign."""
  100. return self._pad_after_eq
  101. @name.setter
  102. def name(self, value):
  103. self._name = parse_anything(value)
  104. @value.setter
  105. def value(self, newval):
  106. if newval is None:
  107. self._value = None
  108. else:
  109. code = parse_anything(newval)
  110. quotes = self._value_needs_quotes(code)
  111. if quotes and (not self.quotes or self.quotes not in quotes):
  112. self._quotes = quotes[0]
  113. self._value = code
  114. @quotes.setter
  115. def quotes(self, value):
  116. value = self.coerce_quotes(value)
  117. if not value and self._value_needs_quotes(self.value):
  118. raise ValueError("attribute value requires quotes")
  119. self._quotes = value
  120. @pad_first.setter
  121. def pad_first(self, value):
  122. self._set_padding("_pad_first", value)
  123. @pad_before_eq.setter
  124. def pad_before_eq(self, value):
  125. self._set_padding("_pad_before_eq", value)
  126. @pad_after_eq.setter
  127. def pad_after_eq(self, value):
  128. self._set_padding("_pad_after_eq", value)