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.
 
 
 
 

371 lines
14 KiB

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