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. # Copyright (C) 2012-2020 Ben Kurtovic <ben.kurtovic@gmail.com>
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. # SOFTWARE.
  20. from collections import defaultdict
  21. import re
  22. from ._base import Node
  23. from .html_entity import HTMLEntity
  24. from .text import Text
  25. from .extras import Parameter
  26. from ..utils import parse_anything
  27. __all__ = ["Template"]
  28. FLAGS = re.DOTALL | re.UNICODE
  29. # Used to allow None as a valid fallback value
  30. _UNSET = object()
  31. class Template(Node):
  32. """Represents a template in wikicode, like ``{{foo}}``."""
  33. def __init__(self, name, params=None):
  34. super().__init__()
  35. self.name = name
  36. if params:
  37. self._params = params
  38. else:
  39. self._params = []
  40. def __str__(self):
  41. if self.params:
  42. params = "|".join([str(param) for param in self.params])
  43. return "{{" + str(self.name) + "|" + params + "}}"
  44. return "{{" + str(self.name) + "}}"
  45. def __children__(self):
  46. yield self.name
  47. for param in self.params:
  48. if param.showkey:
  49. yield param.name
  50. yield param.value
  51. def __strip__(self, **kwargs):
  52. if kwargs.get("keep_template_params"):
  53. parts = [param.value.strip_code(**kwargs) for param in self.params]
  54. return " ".join(part for part in parts if part)
  55. return None
  56. def __showtree__(self, write, get, mark):
  57. write("{{")
  58. get(self.name)
  59. for param in self.params:
  60. write(" | ")
  61. mark()
  62. get(param.name)
  63. write(" = ")
  64. mark()
  65. get(param.value)
  66. write("}}")
  67. @staticmethod
  68. def _surface_escape(code, char):
  69. """Return *code* with *char* escaped as an HTML entity.
  70. The main use of this is to escape pipes (``|``) or equal signs (``=``)
  71. in parameter names or values so they are not mistaken for new
  72. parameters.
  73. """
  74. replacement = str(HTMLEntity(value=ord(char)))
  75. for node in code.filter_text(recursive=False):
  76. if char in node:
  77. code.replace(node, node.replace(char, replacement), False)
  78. @staticmethod
  79. def _select_theory(theories):
  80. """Return the most likely spacing convention given different options.
  81. Given a dictionary of convention options as keys and their occurrence
  82. as values, return the convention that occurs the most, or ``None`` if
  83. there is no clear preferred style.
  84. """
  85. if theories:
  86. values = tuple(theories.values())
  87. best = max(values)
  88. confidence = float(best) / sum(values)
  89. if confidence > 0.5:
  90. return tuple(theories.keys())[values.index(best)]
  91. return None
  92. @staticmethod
  93. def _blank_param_value(value):
  94. """Remove the content from *value* while keeping its whitespace.
  95. Replace *value*\\ 's nodes with two text nodes, the first containing
  96. whitespace from before its content and the second containing whitespace
  97. from after its content.
  98. """
  99. sval = str(value)
  100. if sval.isspace():
  101. before, after = "", sval
  102. else:
  103. match = re.search(r"^(\s*).*?(\s*)$", sval, FLAGS)
  104. before, after = match.group(1), match.group(2)
  105. value.nodes = [Text(before), Text(after)]
  106. def _get_spacing_conventions(self, use_names):
  107. """Try to determine the whitespace conventions for parameters.
  108. This will examine the existing parameters and use
  109. :meth:`_select_theory` to determine if there are any preferred styles
  110. for how much whitespace to put before or after the value.
  111. """
  112. before_theories = defaultdict(lambda: 0)
  113. after_theories = defaultdict(lambda: 0)
  114. for param in self.params:
  115. if not param.showkey:
  116. continue
  117. if use_names:
  118. component = str(param.name)
  119. else:
  120. component = str(param.value)
  121. match = re.search(r"^(\s*).*?(\s*)$", component, FLAGS)
  122. before, after = match.group(1), match.group(2)
  123. if not use_names and component.isspace() and "\n" in before:
  124. # If the value is empty, we expect newlines in the whitespace
  125. # to be after the content, not before it:
  126. before, after = before.split("\n", 1)
  127. after = "\n" + after
  128. before_theories[before] += 1
  129. after_theories[after] += 1
  130. before = self._select_theory(before_theories)
  131. after = self._select_theory(after_theories)
  132. return before, after
  133. def _fix_dependendent_params(self, i):
  134. """Unhide keys if necessary after removing the param at index *i*."""
  135. if not self.params[i].showkey:
  136. for param in self.params[i + 1 :]:
  137. if not param.showkey:
  138. param.showkey = True
  139. def _remove_exact(self, needle, keep_field):
  140. """Remove a specific parameter, *needle*, from the template."""
  141. for i, param in enumerate(self.params):
  142. if param is needle:
  143. if keep_field:
  144. self._blank_param_value(param.value)
  145. else:
  146. self._fix_dependendent_params(i)
  147. self.params.pop(i)
  148. return
  149. raise ValueError(needle)
  150. def _should_remove(self, i, name):
  151. """Look ahead for a parameter with the same name, but hidden.
  152. If one exists, we should remove the given one rather than blanking it.
  153. """
  154. if self.params[i].showkey:
  155. following = self.params[i + 1 :]
  156. better_matches = [
  157. after.name.strip() == name and not after.showkey for after in following
  158. ]
  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, preserve_spacing=True):
  207. """Add a parameter to the template with a given *name* and *value*.
  208. *name* and *value* can be anything parsable by
  209. :func:`.utils.parse_anything`; pipes and equal signs are automatically
  210. escaped from *value* when appropriate.
  211. If *name* is already a parameter in the template, we'll replace its
  212. value.
  213. If *showkey* is given, this will determine whether or not to show the
  214. parameter's name (e.g., ``{{foo|bar}}``'s parameter has a name of
  215. ``"1"`` but it is hidden); otherwise, we'll make a safe and intelligent
  216. guess.
  217. If *before* is given (either a :class:`.Parameter` object or a name),
  218. then we will place the parameter immediately before this one.
  219. Otherwise, it will be added at the end. If *before* is a name and
  220. exists multiple times in the template, we will place it before the last
  221. occurrence. If *before* is not in the template, :exc:`ValueError` is
  222. raised. The argument is ignored if *name* is an existing parameter.
  223. If *preserve_spacing* is ``True``, we will try to preserve whitespace
  224. conventions around the parameter, whether it is new or we are updating
  225. an existing value. It is disabled for parameters with hidden keys,
  226. since MediaWiki doesn't strip whitespace in this case.
  227. """
  228. name, value = parse_anything(name), parse_anything(value)
  229. self._surface_escape(value, "|")
  230. if self.has(name):
  231. self.remove(name, keep_field=True)
  232. existing = self.get(name)
  233. if showkey is not None:
  234. existing.showkey = showkey
  235. if not existing.showkey:
  236. self._surface_escape(value, "=")
  237. nodes = existing.value.nodes
  238. if preserve_spacing and existing.showkey:
  239. for i in range(2): # Ignore empty text nodes
  240. if not nodes[i]:
  241. nodes[i] = None
  242. existing.value = parse_anything([nodes[0], value, nodes[1]])
  243. else:
  244. existing.value = value
  245. return existing
  246. if showkey is None:
  247. if Parameter.can_hide_key(name):
  248. int_name = int(str(name))
  249. int_keys = set()
  250. for param in self.params:
  251. if not param.showkey:
  252. int_keys.add(int(str(param.name)))
  253. expected = min(set(range(1, len(int_keys) + 2)) - int_keys)
  254. if expected == int_name:
  255. showkey = False
  256. else:
  257. showkey = True
  258. else:
  259. showkey = True
  260. if not showkey:
  261. self._surface_escape(value, "=")
  262. if preserve_spacing and showkey:
  263. before_n, after_n = self._get_spacing_conventions(use_names=True)
  264. before_v, after_v = self._get_spacing_conventions(use_names=False)
  265. name = parse_anything([before_n, name, after_n])
  266. value = parse_anything([before_v, value, after_v])
  267. param = Parameter(name, value, showkey)
  268. if before:
  269. if not isinstance(before, Parameter):
  270. before = self.get(before)
  271. self.params.insert(self.params.index(before), param)
  272. else:
  273. self.params.append(param)
  274. return param
  275. def __setitem__(self, name, value):
  276. return self.add(name, value)
  277. def remove(self, param, keep_field=False):
  278. """Remove a parameter from the template, identified by *param*.
  279. If *param* is a :class:`.Parameter` object, it will be matched exactly,
  280. otherwise it will be treated like the *name* argument to :meth:`has`
  281. and :meth:`get`.
  282. If *keep_field* is ``True``, we will keep the parameter's name, but
  283. blank its value. Otherwise, we will remove the parameter completely.
  284. When removing a parameter with a hidden name, subsequent parameters
  285. with hidden names will be made visible. For example, removing ``bar``
  286. from ``{{foo|bar|baz}}`` produces ``{{foo|2=baz}}`` because
  287. ``{{foo|baz}}`` is incorrect.
  288. If the parameter shows up multiple times in the template and *param* is
  289. not a :class:`.Parameter` object, we will remove all instances of it
  290. (and keep only one if *keep_field* is ``True`` - either the one with a
  291. hidden name, if it exists, or the first instance).
  292. """
  293. if isinstance(param, Parameter):
  294. self._remove_exact(param, keep_field)
  295. return
  296. name = str(param).strip()
  297. removed = False
  298. to_remove = []
  299. for i, par in enumerate(self.params):
  300. if par.name.strip() == name:
  301. if keep_field:
  302. if self._should_remove(i, name):
  303. to_remove.append(i)
  304. else:
  305. self._blank_param_value(par.value)
  306. keep_field = False
  307. else:
  308. self._fix_dependendent_params(i)
  309. to_remove.append(i)
  310. if not removed:
  311. removed = True
  312. if not removed:
  313. raise ValueError(name)
  314. for i in reversed(to_remove):
  315. self.params.pop(i)
  316. def __delitem__(self, param):
  317. return self.remove(param)