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.
 
 
 
 

118 lines
4.5 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012 Ben Kurtovic <ben.kurtovic@verizon.net>
  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. import re
  23. from mwparserfromhell.nodes import HTMLEntity, Node, Text
  24. from mwparserfromhell.nodes.extras import Parameter
  25. from mwparserfromhell.utils import parse_anything
  26. __all__ = ["Template"]
  27. class Template(Node):
  28. def __init__(self, name, params=None):
  29. self._name = name
  30. if params:
  31. self._params = params
  32. else:
  33. self._params = []
  34. def __unicode__(self):
  35. if self.params:
  36. params = u"|".join([unicode(param) for param in self.params])
  37. return "{{" + unicode(self.name) + "|" + params + "}}"
  38. else:
  39. return "{{" + unicode(self.name) + "}}"
  40. def _surface_escape(self, code, char):
  41. replacement = HTMLEntity(value=ord(char))
  42. for node in code.filter_text(recursive=False):
  43. if char in node:
  44. code.replace(node, node.replace(char, replacement))
  45. def _blank_param_value(self, value):
  46. match = re.search("^(\s*).*?(\s*)$", value, re.DOTALL|re.UNICODE)
  47. value.nodes = [Text(match.group(1)), Text(match.group(2))]
  48. @property
  49. def name(self):
  50. return self._name
  51. @property
  52. def params(self):
  53. return self._params
  54. def has_param(self, name, ignore_empty=True):
  55. name = name.strip() if isinstance(name, basestring) else unicode(name)
  56. for param in self.params:
  57. if param.name.strip() == name:
  58. if ignore_empty and not param.value.strip():
  59. continue
  60. return True
  61. return False
  62. def get(self, name):
  63. name = name.strip() if isinstance(name, basestring) else unicode(name)
  64. for param in self.params:
  65. if param.name.strip() == name:
  66. return param
  67. raise ValueError(name)
  68. def add(self, name, value, showkey=None):
  69. name, value = parse_anything(name), parse_anything(value)
  70. self._surface_escape(value, "|")
  71. if self.has_param(name):
  72. self.remove(name, keep_field=True)
  73. existing = self.get(name)
  74. if showkey is None: # Infer showkey from current value
  75. showkey = existing.showkey
  76. if not showkey:
  77. self._surface_escape(value, "=")
  78. nodes = existing.value.nodes
  79. existing.value = parse_anything([nodes[0], value, nodes[1]])
  80. return existing
  81. if showkey is None:
  82. try:
  83. int(name)
  84. showkey = True
  85. except ValueError:
  86. showkey = False
  87. if not showkey:
  88. self._surface_escape(value, "=")
  89. param = Parameter(name, value, showkey) # CONFORM TO FORMATTING CONVENTIONS?
  90. self.params.append(param)
  91. return param
  92. def remove(self, name, keep_field=False, force_no_field=False):
  93. name = name.strip() if isinstance(name, basestring) else unicode(name)
  94. for i, param in enumerate(self.params):
  95. if param.name.strip() == name:
  96. if keep_field:
  97. return self._blank_param_value(param.value)
  98. dependent = [not after.showkey for after in self.params[i+1:]]
  99. if any(dependent) and not param.showkey and not force_no_field:
  100. return self._blank_param_value(param.value)
  101. return self.params.remove(param)
  102. raise ValueError(name)