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.
 
 
 
 

336 lines
13 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2015 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 collections import defaultdict
  24. import re
  25. from . import HTMLEntity, Node, Text
  26. from .extras import Parameter
  27. from ..compat import range, str
  28. from ..utils import parse_anything
  29. __all__ = ["Template"]
  30. FLAGS = re.DOTALL | re.UNICODE
  31. class Template(Node):
  32. """Represents a template in wikicode, like ``{{foo}}``."""
  33. def __init__(self, name, params=None):
  34. super(Template, self).__init__()
  35. self._name = name
  36. if params:
  37. self._params = params
  38. else:
  39. self._params = []
  40. def __unicode__(self):
  41. if self.params:
  42. params = "|".join([str(param) for param in self.params])
  43. return "{{" + str(self.name) + "|" + params + "}}"
  44. else:
  45. return "{{" + str(self.name) + "}}"
  46. def __children__(self):
  47. yield self.name
  48. for param in self.params:
  49. if param.showkey:
  50. yield param.name
  51. yield param.value
  52. def __showtree__(self, write, get, mark):
  53. write("{{")
  54. get(self.name)
  55. for param in self.params:
  56. write(" | ")
  57. mark()
  58. get(param.name)
  59. write(" = ")
  60. mark()
  61. get(param.value)
  62. write("}}")
  63. def _surface_escape(self, code, char):
  64. """Return *code* with *char* escaped as an HTML entity.
  65. The main use of this is to escape pipes (``|``) or equal signs (``=``)
  66. in parameter names or values so they are not mistaken for new
  67. parameters.
  68. """
  69. replacement = str(HTMLEntity(value=ord(char)))
  70. for node in code.filter_text(recursive=False):
  71. if char in node:
  72. code.replace(node, node.replace(char, replacement), False)
  73. def _select_theory(self, theories):
  74. """Return the most likely spacing convention given different options.
  75. Given a dictionary of convention options as keys and their occurrence
  76. as values, return the convention that occurs the most, or ``None`` if
  77. there is no clear preferred style.
  78. """
  79. if theories:
  80. values = tuple(theories.values())
  81. best = max(values)
  82. confidence = float(best) / sum(values)
  83. if confidence >= 0.75:
  84. return tuple(theories.keys())[values.index(best)]
  85. def _get_spacing_conventions(self, use_names):
  86. """Try to determine the whitespace conventions for parameters.
  87. This will examine the existing parameters and use
  88. :meth:`_select_theory` to determine if there are any preferred styles
  89. for how much whitespace to put before or after the value.
  90. """
  91. before_theories = defaultdict(lambda: 0)
  92. after_theories = defaultdict(lambda: 0)
  93. for param in self.params:
  94. if use_names:
  95. component = str(param.name)
  96. else:
  97. component = str(param.value)
  98. match = re.search(r"^(\s*).*?(\s*)$", component, FLAGS)
  99. before, after = match.group(1), match.group(2)
  100. before_theories[before] += 1
  101. after_theories[after] += 1
  102. before = self._select_theory(before_theories)
  103. after = self._select_theory(after_theories)
  104. return before, after
  105. def _blank_param_value(self, value):
  106. """Remove the content from *value* while keeping its whitespace.
  107. Replace *value*\ 's nodes with two text nodes, the first containing
  108. whitespace from before its content and the second containing whitespace
  109. from after its content.
  110. """
  111. match = re.search(r"^(\s*).*?(\s*)$", str(value), FLAGS)
  112. value.nodes = [Text(match.group(1)), Text(match.group(2))]
  113. def _fix_dependendent_params(self, i):
  114. """Unhide keys if necessary after removing the param at index *i*."""
  115. if not self.params[i].showkey:
  116. for param in self.params[i + 1:]:
  117. if not param.showkey:
  118. param.showkey = True
  119. def _remove_exact(self, needle, keep_field):
  120. """Remove a specific parameter, *needle*, from the template."""
  121. for i, param in enumerate(self.params):
  122. if param is needle:
  123. if keep_field:
  124. self._blank_param_value(param.value)
  125. else:
  126. self._fix_dependendent_params(i)
  127. self.params.pop(i)
  128. return
  129. raise ValueError(needle)
  130. def _should_remove(self, i, name):
  131. """Look ahead for a parameter with the same name, but hidden.
  132. If one exists, we should remove the given one rather than blanking it.
  133. """
  134. if self.params[i].showkey:
  135. following = self.params[i + 1:]
  136. better_matches = [after.name.strip() == name and not after.showkey
  137. for after in following]
  138. return any(better_matches)
  139. return False
  140. @property
  141. def name(self):
  142. """The name of the template, as a :class:`.Wikicode` object."""
  143. return self._name
  144. @property
  145. def params(self):
  146. """The list of parameters contained within the template."""
  147. return self._params
  148. @name.setter
  149. def name(self, value):
  150. self._name = parse_anything(value)
  151. def has(self, name, ignore_empty=False):
  152. """Return ``True`` if any parameter in the template is named *name*.
  153. With *ignore_empty*, ``False`` will be returned even if the template
  154. contains a parameter with the name *name*, if the parameter's value
  155. is empty. Note that a template may have multiple parameters with the
  156. same name, but only the last one is read by the MediaWiki parser.
  157. """
  158. name = str(name).strip()
  159. for param in self.params:
  160. if param.name.strip() == name:
  161. if ignore_empty and not param.value.strip():
  162. continue
  163. return True
  164. return False
  165. has_param = lambda self, name, ignore_empty=False: \
  166. self.has(name, ignore_empty)
  167. has_param.__doc__ = "Alias for :meth:`has`."
  168. def get(self, name):
  169. """Get the parameter whose name is *name*.
  170. The returned object is a :class:`.Parameter` instance. Raises
  171. :exc:`ValueError` if no parameter has this name. Since multiple
  172. parameters can have the same name, we'll return the last match, since
  173. the last parameter is the only one read by the MediaWiki parser.
  174. """
  175. name = str(name).strip()
  176. for param in reversed(self.params):
  177. if param.name.strip() == name:
  178. return param
  179. raise ValueError(name)
  180. def add(self, name, value, showkey=None, before=None,
  181. preserve_spacing=True):
  182. """Add a parameter to the template with a given *name* and *value*.
  183. *name* and *value* can be anything parsable by
  184. :func:`.utils.parse_anything`; pipes and equal signs are automatically
  185. escaped from *value* when appropriate.
  186. If *name* is already a parameter in the template, we'll replace its
  187. value.
  188. If *showkey* is given, this will determine whether or not to show the
  189. parameter's name (e.g., ``{{foo|bar}}``'s parameter has a name of
  190. ``"1"`` but it is hidden); otherwise, we'll make a safe and intelligent
  191. guess.
  192. If *before* is given (either a :class:`.Parameter` object or a name),
  193. then we will place the parameter immediately before this one.
  194. Otherwise, it will be added at the end. If *before* is a name and
  195. exists multiple times in the template, we will place it before the last
  196. occurrence. If *before* is not in the template, :exc:`ValueError` is
  197. raised. The argument is ignored if *name* is an existing parameter.
  198. If *preserve_spacing* is ``True``, we will try to preserve whitespace
  199. conventions around the parameter, whether it is new or we are updating
  200. an existing value. It is disabled for parameters with hidden keys,
  201. since MediaWiki doesn't strip whitespace in this case.
  202. """
  203. name, value = parse_anything(name), parse_anything(value)
  204. self._surface_escape(value, "|")
  205. if self.has(name):
  206. self.remove(name, keep_field=True)
  207. existing = self.get(name)
  208. if showkey is not None:
  209. existing.showkey = showkey
  210. if not existing.showkey:
  211. self._surface_escape(value, "=")
  212. nodes = existing.value.nodes
  213. if preserve_spacing and existing.showkey:
  214. for i in range(2): # Ignore empty text nodes
  215. if not nodes[i]:
  216. nodes[i] = None
  217. existing.value = parse_anything([nodes[0], value, nodes[1]])
  218. else:
  219. existing.value = value
  220. return existing
  221. if showkey is None:
  222. if Parameter.can_hide_key(name):
  223. int_name = int(str(name))
  224. int_keys = set()
  225. for param in self.params:
  226. if not param.showkey:
  227. int_keys.add(int(str(param.name)))
  228. expected = min(set(range(1, len(int_keys) + 2)) - int_keys)
  229. if expected == int_name:
  230. showkey = False
  231. else:
  232. showkey = True
  233. else:
  234. showkey = True
  235. if not showkey:
  236. self._surface_escape(value, "=")
  237. if preserve_spacing and showkey:
  238. before_n, after_n = self._get_spacing_conventions(use_names=True)
  239. before_v, after_v = self._get_spacing_conventions(use_names=False)
  240. name = parse_anything([before_n, name, after_n])
  241. value = parse_anything([before_v, value, after_v])
  242. param = Parameter(name, value, showkey)
  243. if before:
  244. if not isinstance(before, Parameter):
  245. before = self.get(before)
  246. self.params.insert(self.params.index(before), param)
  247. else:
  248. self.params.append(param)
  249. return param
  250. def remove(self, param, keep_field=False):
  251. """Remove a parameter from the template, identified by *param*.
  252. If *param* is a :class:`.Parameter` object, it will be matched exactly,
  253. otherwise it will be treated like the *name* argument to :meth:`has`
  254. and :meth:`get`.
  255. If *keep_field* is ``True``, we will keep the parameter's name, but
  256. blank its value. Otherwise, we will remove the parameter completely.
  257. When removing a parameter with a hidden name, subsequent parameters
  258. with hidden names will be made visible. For example, removing ``bar``
  259. from ``{{foo|bar|baz}}`` produces ``{{foo|2=baz}}`` because
  260. ``{{foo|baz}}`` is incorrect.
  261. If the parameter shows up multiple times in the template and *param* is
  262. not a :class:`.Parameter` object, we will remove all instances of it
  263. (and keep only one if *keep_field* is ``True`` - either the one with a
  264. hidden name, if it exists, or the first instance).
  265. """
  266. if isinstance(param, Parameter):
  267. return self._remove_exact(param, keep_field)
  268. name = str(param).strip()
  269. removed = False
  270. to_remove = []
  271. for i, param in enumerate(self.params):
  272. if param.name.strip() == name:
  273. if keep_field:
  274. if self._should_remove(i, name):
  275. to_remove.append(i)
  276. else:
  277. self._blank_param_value(param.value)
  278. keep_field = False
  279. else:
  280. self._fix_dependendent_params(i)
  281. to_remove.append(i)
  282. if not removed:
  283. removed = True
  284. if not removed:
  285. raise ValueError(name)
  286. for i in reversed(to_remove):
  287. self.params.pop(i)