A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

357 行
14 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2017 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 __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. @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 = [after.name.strip() == name and not after.showkey
  157. for after in following]
  158. return any(better_matches)
  159. return False
  160. @property
  161. def name(self):
  162. """The name of the template, as a :class:`.Wikicode` object."""
  163. return self._name
  164. @property
  165. def params(self):
  166. """The list of parameters contained within the template."""
  167. return self._params
  168. @name.setter
  169. def name(self, value):
  170. self._name = parse_anything(value)
  171. def has(self, name, ignore_empty=False):
  172. """Return ``True`` if any parameter in the template is named *name*.
  173. With *ignore_empty*, ``False`` will be returned even if the template
  174. contains a parameter with the name *name*, if the parameter's value
  175. is empty. Note that a template may have multiple parameters with the
  176. same name, but only the last one is read by the MediaWiki parser.
  177. """
  178. name = str(name).strip()
  179. for param in self.params:
  180. if param.name.strip() == name:
  181. if ignore_empty and not param.value.strip():
  182. continue
  183. return True
  184. return False
  185. has_param = lambda self, name, ignore_empty=False: \
  186. self.has(name, ignore_empty)
  187. has_param.__doc__ = "Alias for :meth:`has`."
  188. def get(self, name):
  189. """Get the parameter whose name is *name*.
  190. The returned object is a :class:`.Parameter` instance. Raises
  191. :exc:`ValueError` if no parameter has this name. Since multiple
  192. parameters can have the same name, we'll return the last match, since
  193. the last parameter is the only one 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. raise ValueError(name)
  200. def add(self, name, value, showkey=None, before=None,
  201. preserve_spacing=True):
  202. """Add a parameter to the template with a given *name* and *value*.
  203. *name* and *value* can be anything parsable by
  204. :func:`.utils.parse_anything`; pipes and equal signs are automatically
  205. escaped from *value* when appropriate.
  206. If *name* is already a parameter in the template, we'll replace its
  207. value.
  208. If *showkey* is given, this will determine whether or not to show the
  209. parameter's name (e.g., ``{{foo|bar}}``'s parameter has a name of
  210. ``"1"`` but it is hidden); otherwise, we'll make a safe and intelligent
  211. guess.
  212. If *before* is given (either a :class:`.Parameter` object or a name),
  213. then we will place the parameter immediately before this one.
  214. Otherwise, it will be added at the end. If *before* is a name and
  215. exists multiple times in the template, we will place it before the last
  216. occurrence. If *before* is not in the template, :exc:`ValueError` is
  217. raised. The argument is ignored if *name* is an existing parameter.
  218. If *preserve_spacing* is ``True``, we will try to preserve whitespace
  219. conventions around the parameter, whether it is new or we are updating
  220. an existing value. It is disabled for parameters with hidden keys,
  221. since MediaWiki doesn't strip whitespace in this case.
  222. """
  223. name, value = parse_anything(name), parse_anything(value)
  224. self._surface_escape(value, "|")
  225. if self.has(name):
  226. self.remove(name, keep_field=True)
  227. existing = self.get(name)
  228. if showkey is not None:
  229. existing.showkey = showkey
  230. if not existing.showkey:
  231. self._surface_escape(value, "=")
  232. nodes = existing.value.nodes
  233. if preserve_spacing and existing.showkey:
  234. for i in range(2): # Ignore empty text nodes
  235. if not nodes[i]:
  236. nodes[i] = None
  237. existing.value = parse_anything([nodes[0], value, nodes[1]])
  238. else:
  239. existing.value = value
  240. return existing
  241. if showkey is None:
  242. if Parameter.can_hide_key(name):
  243. int_name = int(str(name))
  244. int_keys = set()
  245. for param in self.params:
  246. if not param.showkey:
  247. int_keys.add(int(str(param.name)))
  248. expected = min(set(range(1, len(int_keys) + 2)) - int_keys)
  249. if expected == int_name:
  250. showkey = False
  251. else:
  252. showkey = True
  253. else:
  254. showkey = True
  255. if not showkey:
  256. self._surface_escape(value, "=")
  257. if preserve_spacing and showkey:
  258. before_n, after_n = self._get_spacing_conventions(use_names=True)
  259. before_v, after_v = self._get_spacing_conventions(use_names=False)
  260. name = parse_anything([before_n, name, after_n])
  261. value = parse_anything([before_v, value, after_v])
  262. param = Parameter(name, value, showkey)
  263. if before:
  264. if not isinstance(before, Parameter):
  265. before = self.get(before)
  266. self.params.insert(self.params.index(before), param)
  267. else:
  268. self.params.append(param)
  269. return param
  270. def remove(self, param, keep_field=False):
  271. """Remove a parameter from the template, identified by *param*.
  272. If *param* is a :class:`.Parameter` object, it will be matched exactly,
  273. otherwise it will be treated like the *name* argument to :meth:`has`
  274. and :meth:`get`.
  275. If *keep_field* is ``True``, we will keep the parameter's name, but
  276. blank its value. Otherwise, we will remove the parameter completely.
  277. When removing a parameter with a hidden name, subsequent parameters
  278. with hidden names will be made visible. For example, removing ``bar``
  279. from ``{{foo|bar|baz}}`` produces ``{{foo|2=baz}}`` because
  280. ``{{foo|baz}}`` is incorrect.
  281. If the parameter shows up multiple times in the template and *param* is
  282. not a :class:`.Parameter` object, we will remove all instances of it
  283. (and keep only one if *keep_field* is ``True`` - either the one with a
  284. hidden name, if it exists, or the first instance).
  285. """
  286. if isinstance(param, Parameter):
  287. return self._remove_exact(param, keep_field)
  288. name = str(param).strip()
  289. removed = False
  290. to_remove = []
  291. for i, param in enumerate(self.params):
  292. if param.name.strip() == name:
  293. if keep_field:
  294. if self._should_remove(i, name):
  295. to_remove.append(i)
  296. else:
  297. self._blank_param_value(param.value)
  298. keep_field = False
  299. else:
  300. self._fix_dependendent_params(i)
  301. to_remove.append(i)
  302. if not removed:
  303. removed = True
  304. if not removed:
  305. raise ValueError(name)
  306. for i in reversed(to_remove):
  307. self.params.pop(i)