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.
 
 
 
 

154 lines
5.2 KiB

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