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.
 
 
 
 

369 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. # Used to allow None as a valid fallback value
  29. _UNSET = object()
  30. class Template(Node):
  31. """Represents a template in wikicode, like ``{{foo}}``."""
  32. def __init__(self, name, params=None):
  33. super().__init__()
  34. self.name = name
  35. if params:
  36. self._params = params
  37. else:
  38. self._params = []
  39. def __unicode__(self):
  40. if self.params:
  41. params = "|".join([str(param) for param in self.params])
  42. return "{{" + str(self.name) + "|" + params + "}}"
  43. else:
  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. @staticmethod
  92. def _blank_param_value(value):
  93. """Remove the content from *value* while keeping its whitespace.
  94. Replace *value*\\ 's nodes with two text nodes, the first containing
  95. whitespace from before its content and the second containing whitespace
  96. from after its content.
  97. """
  98. sval = str(value)
  99. if sval.isspace():
  100. before, after = "", sval
  101. else:
  102. match = re.search(r"^(\s*).*?(\s*)$", sval, FLAGS)
  103. before, after = match.group(1), match.group(2)
  104. value.nodes = [Text(before), Text(after)]
  105. def _get_spacing_conventions(self, use_names):
  106. """Try to determine the whitespace conventions for parameters.
  107. This will examine the existing parameters and use
  108. :meth:`_select_theory` to determine if there are any preferred styles
  109. for how much whitespace to put before or after the value.
  110. """
  111. before_theories = defaultdict(lambda: 0)
  112. after_theories = defaultdict(lambda: 0)
  113. for param in self.params:
  114. if not param.showkey:
  115. continue
  116. if use_names:
  117. component = str(param.name)
  118. else:
  119. component = str(param.value)
  120. match = re.search(r"^(\s*).*?(\s*)$", component, FLAGS)
  121. before, after = match.group(1), match.group(2)
  122. if not use_names and component.isspace() and "\n" in before:
  123. # If the value is empty, we expect newlines in the whitespace
  124. # to be after the content, not before it:
  125. before, after = before.split("\n", 1)
  126. after = "\n" + after
  127. before_theories[before] += 1
  128. after_theories[after] += 1
  129. before = self._select_theory(before_theories)
  130. after = self._select_theory(after_theories)
  131. return before, after
  132. def _fix_dependendent_params(self, i):
  133. """Unhide keys if necessary after removing the param at index *i*."""
  134. if not self.params[i].showkey:
  135. for param in self.params[i + 1:]:
  136. if not param.showkey:
  137. param.showkey = True
  138. def _remove_exact(self, needle, keep_field):
  139. """Remove a specific parameter, *needle*, from the template."""
  140. for i, param in enumerate(self.params):
  141. if param is needle:
  142. if keep_field:
  143. self._blank_param_value(param.value)
  144. else:
  145. self._fix_dependendent_params(i)
  146. self.params.pop(i)
  147. return
  148. raise ValueError(needle)
  149. def _should_remove(self, i, name):
  150. """Look ahead for a parameter with the same name, but hidden.
  151. If one exists, we should remove the given one rather than blanking it.
  152. """
  153. if self.params[i].showkey:
  154. following = self.params[i + 1:]
  155. better_matches = [after.name.strip() == name and not after.showkey
  156. for after in following]
  157. return any(better_matches)
  158. return False
  159. @property
  160. def name(self):
  161. """The name of the template, as a :class:`.Wikicode` object."""
  162. return self._name
  163. @property
  164. def params(self):
  165. """The list of parameters contained within the template."""
  166. return self._params
  167. @name.setter
  168. def name(self, value):
  169. self._name = parse_anything(value)
  170. def has(self, name, ignore_empty=False):
  171. """Return ``True`` if any parameter in the template is named *name*.
  172. With *ignore_empty*, ``False`` will be returned even if the template
  173. contains a parameter with the name *name*, if the parameter's value
  174. is empty. Note that a template may have multiple parameters with the
  175. same name, but only the last one is read by the MediaWiki parser.
  176. """
  177. name = str(name).strip()
  178. for param in self.params:
  179. if param.name.strip() == name:
  180. if ignore_empty and not param.value.strip():
  181. continue
  182. return True
  183. return False
  184. def has_param(self, name, ignore_empty=False):
  185. """Alias for :meth:`has`."""
  186. return self.has(name, ignore_empty)
  187. def get(self, name, default=_UNSET):
  188. """Get the parameter whose name is *name*.
  189. The returned object is a :class:`.Parameter` instance. Raises
  190. :exc:`ValueError` if no parameter has this name. If *default* is set,
  191. returns that instead. Since multiple parameters can have the same name,
  192. we'll return the last match, since the last parameter is the only one
  193. read by the MediaWiki parser.
  194. """
  195. name = str(name).strip()
  196. for param in reversed(self.params):
  197. if param.name.strip() == name:
  198. return param
  199. if default is _UNSET:
  200. raise ValueError(name)
  201. else:
  202. return default
  203. def __getitem__(self, name):
  204. return self.get(name)
  205. def add(self, name, value, showkey=None, before=None,
  206. 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. return self._remove_exact(param, keep_field)
  295. name = str(param).strip()
  296. removed = False
  297. to_remove = []
  298. for i, param in enumerate(self.params):
  299. if param.name.strip() == name:
  300. if keep_field:
  301. if self._should_remove(i, name):
  302. to_remove.append(i)
  303. else:
  304. self._blank_param_value(param.value)
  305. keep_field = False
  306. else:
  307. self._fix_dependendent_params(i)
  308. to_remove.append(i)
  309. if not removed:
  310. removed = True
  311. if not removed:
  312. raise ValueError(name)
  313. for i in reversed(to_remove):
  314. self.params.pop(i)
  315. def __delitem__(self, param):
  316. return self.remove(param)