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.
 
 
 
 

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