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.
 
 
 
 

477 lines
20 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012 Ben Kurtovic <ben.kurtovic@verizon.net>
  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. import re
  24. from .compat import maxsize, str
  25. from .nodes import Heading, Node, Tag, Template, Text, Wikilink
  26. from .string_mixin import StringMixIn
  27. from .utils import parse_anything
  28. __all__ = ["Wikicode"]
  29. FLAGS = re.IGNORECASE | re.DOTALL | re.UNICODE
  30. class Wikicode(StringMixIn):
  31. """A ``Wikicode`` is a container for nodes that operates like a string.
  32. Additionally, it contains methods that can be used to extract data from or
  33. modify the nodes, implemented in an interface similar to a list. For
  34. example, :py:meth:`index` can get the index of a node in the list, and
  35. :py:meth:`insert` can add a new node at that index. The :py:meth:`filter()
  36. <ifilter>` series of functions is very useful for extracting and iterating
  37. over, for example, all of the templates in the object.
  38. """
  39. def __init__(self, nodes):
  40. super(Wikicode, self).__init__()
  41. self._nodes = nodes
  42. def __unicode__(self):
  43. return "".join([str(node) for node in self.nodes])
  44. def _get_children(self, node):
  45. """Iterate over all descendants of a given *node*, including itself.
  46. This is implemented by the ``__iternodes__()`` generator of ``Node``
  47. classes, which by default yields itself and nothing more.
  48. """
  49. if node: #fixes bug on malformed wikitext from wikipedia dump
  50. for context, child in node.__iternodes__(self._get_all_nodes):
  51. yield child
  52. def _get_context(self, node, obj):
  53. """Return a ``Wikicode`` that contains *obj* in its descendants.
  54. The closest (shortest distance from *node*) suitable ``Wikicode`` will
  55. be returned, or ``None`` if the *obj* is the *node* itself.
  56. Raises ``ValueError`` if *obj* is not within *node*.
  57. """
  58. for context, child in node.__iternodes__(self._get_all_nodes):
  59. if child is obj:
  60. return context
  61. raise ValueError(obj)
  62. def _get_all_nodes(self, code):
  63. """Iterate over all of our descendant nodes.
  64. This is implemented by calling :py:meth:`_get_children` on every node
  65. in our node list (:py:attr:`self.nodes <nodes>`).
  66. """
  67. for node in code.nodes:
  68. for child in self._get_children(node):
  69. yield child
  70. def _is_equivalent(self, obj, node):
  71. """Return ``True`` if *obj* and *node* are equivalent, else ``False``.
  72. If *obj* is a ``Node``, the function will test whether they are the
  73. same object, otherwise it will compare them with ``==``.
  74. """
  75. if isinstance(obj, Node):
  76. if node is obj:
  77. return True
  78. else:
  79. if node == obj:
  80. return True
  81. return False
  82. def _contains(self, nodes, obj):
  83. """Return ``True`` if *obj* is inside of *nodes*, else ``False``.
  84. If *obj* is a ``Node``, we will only return ``True`` if *obj* is
  85. actually in the list (and not just a node that equals it). Otherwise,
  86. the test is simply ``obj in nodes``.
  87. """
  88. if isinstance(obj, Node):
  89. for node in nodes:
  90. if node is obj:
  91. return True
  92. return False
  93. return obj in nodes
  94. def _do_search(self, obj, recursive, callback, context, *args, **kwargs):
  95. """Look within *context* for *obj*, executing *callback* if found.
  96. If *recursive* is ``True``, we'll look within context and its
  97. descendants, otherwise we'll just execute callback. We raise
  98. :py:exc:`ValueError` if *obj* isn't in our node list or context. If
  99. found, *callback* is passed the context, the index of the node within
  100. the context, and whatever were passed as ``*args`` and ``**kwargs``.
  101. """
  102. if recursive:
  103. for i, node in enumerate(context.nodes):
  104. if self._is_equivalent(obj, node):
  105. return callback(context, i, *args, **kwargs)
  106. if self._contains(self._get_children(node), obj):
  107. context = self._get_context(node, obj)
  108. return self._do_search(obj, recursive, callback, context,
  109. *args, **kwargs)
  110. raise ValueError(obj)
  111. callback(context, self.index(obj, recursive=False), *args, **kwargs)
  112. def _get_tree(self, code, lines, marker, indent):
  113. """Build a tree to illustrate the way the Wikicode object was parsed.
  114. The method that builds the actual tree is ``__showtree__`` of ``Node``
  115. objects. *code* is the ``Wikicode`` object to build a tree for. *lines*
  116. is the list to append the tree to, which is returned at the end of the
  117. method. *marker* is some object to be used to indicate that the builder
  118. should continue on from the last line instead of starting a new one; it
  119. should be any object that can be tested for with ``is``. *indent* is
  120. the starting indentation.
  121. """
  122. def write(*args):
  123. """Write a new line following the proper indentation rules."""
  124. if lines and lines[-1] is marker: # Continue from the last line
  125. lines.pop() # Remove the marker
  126. last = lines.pop()
  127. lines.append(last + " ".join(args))
  128. else:
  129. lines.append(" " * 6 * indent + " ".join(args))
  130. get = lambda code: self._get_tree(code, lines, marker, indent + 1)
  131. mark = lambda: lines.append(marker)
  132. for node in code.nodes:
  133. node.__showtree__(write, get, mark)
  134. return lines
  135. @property
  136. def nodes(self):
  137. """A list of :py:class:`~.Node` objects.
  138. This is the internal data actually stored within a
  139. :py:class:`~.Wikicode` object.
  140. """
  141. return self._nodes
  142. @nodes.setter
  143. def nodes(self, value):
  144. self._nodes = value
  145. def get(self, index):
  146. """Return the *index*\ th node within the list of nodes."""
  147. return self.nodes[index]
  148. def set(self, index, value):
  149. """Set the ``Node`` at *index* to *value*.
  150. Raises :py:exc:`IndexError` if *index* is out of range, or
  151. :py:exc:`ValueError` if *value* cannot be coerced into one
  152. :py:class:`~.Node`. To insert multiple nodes at an index, use
  153. :py:meth:`get` with either :py:meth:`remove` and :py:meth:`insert` or
  154. :py:meth:`replace`.
  155. """
  156. nodes = parse_anything(value).nodes
  157. if len(nodes) > 1:
  158. raise ValueError("Cannot coerce multiple nodes into one index")
  159. if index >= len(self.nodes) or -1 * index > len(self.nodes):
  160. raise IndexError("List assignment index out of range")
  161. self.nodes.pop(index)
  162. if nodes:
  163. self.nodes[index] = nodes[0]
  164. def index(self, obj, recursive=False):
  165. """Return the index of *obj* in the list of nodes.
  166. Raises :py:exc:`ValueError` if *obj* is not found. If *recursive* is
  167. ``True``, we will look in all nodes of ours and their descendants, and
  168. return the index of our direct descendant node within *our* list of
  169. nodes. Otherwise, the lookup is done only on direct descendants.
  170. """
  171. if recursive:
  172. for i, node in enumerate(self.nodes):
  173. if self._contains(self._get_children(node), obj):
  174. return i
  175. raise ValueError(obj)
  176. for i, node in enumerate(self.nodes):
  177. if self._is_equivalent(obj, node):
  178. return i
  179. raise ValueError(obj)
  180. def insert(self, index, value):
  181. """Insert *value* at *index* in the list of nodes.
  182. *value* can be anything parasable by :py:func:`.parse_anything`, which
  183. includes strings or other :py:class:`~.Wikicode` or :py:class:`~.Node`
  184. objects.
  185. """
  186. nodes = parse_anything(value).nodes
  187. for node in reversed(nodes):
  188. self.nodes.insert(index, node)
  189. def insert_before(self, obj, value, recursive=True):
  190. """Insert *value* immediately before *obj* in the list of nodes.
  191. *obj* can be either a string or a :py:class:`~.Node`. *value* can be
  192. anything parasable by :py:func:`.parse_anything`. If *recursive* is
  193. ``True``, we will try to find *obj* within our child nodes even if it
  194. is not a direct descendant of this :py:class:`~.Wikicode` object. If
  195. *obj* is not in the node list, :py:exc:`ValueError` is raised.
  196. """
  197. callback = lambda self, i, value: self.insert(i, value)
  198. self._do_search(obj, recursive, callback, self, value)
  199. def insert_after(self, obj, value, recursive=True):
  200. """Insert *value* immediately after *obj* in the list of nodes.
  201. *obj* can be either a string or a :py:class:`~.Node`. *value* can be
  202. anything parasable by :py:func:`.parse_anything`. If *recursive* is
  203. ``True``, we will try to find *obj* within our child nodes even if it
  204. is not a direct descendant of this :py:class:`~.Wikicode` object. If
  205. *obj* is not in the node list, :py:exc:`ValueError` is raised.
  206. """
  207. callback = lambda self, i, value: self.insert(i + 1, value)
  208. self._do_search(obj, recursive, callback, self, value)
  209. def replace(self, obj, value, recursive=True):
  210. """Replace *obj* with *value* in the list of nodes.
  211. *obj* can be either a string or a :py:class:`~.Node`. *value* can be
  212. anything parasable by :py:func:`.parse_anything`. If *recursive* is
  213. ``True``, we will try to find *obj* within our child nodes even if it
  214. is not a direct descendant of this :py:class:`~.Wikicode` object. If
  215. *obj* is not in the node list, :py:exc:`ValueError` is raised.
  216. """
  217. def callback(self, i, value):
  218. self.nodes.pop(i)
  219. self.insert(i, value)
  220. self._do_search(obj, recursive, callback, self, value)
  221. def append(self, value):
  222. """Insert *value* at the end of the list of nodes.
  223. *value* can be anything parasable by :py:func:`.parse_anything`.
  224. """
  225. nodes = parse_anything(value).nodes
  226. for node in nodes:
  227. self.nodes.append(node)
  228. def remove(self, obj, recursive=True):
  229. """Remove *obj* from the list of nodes.
  230. *obj* can be either a string or a :py:class:`~.Node`. If *recursive* is
  231. ``True``, we will try to find *obj* within our child nodes even if it
  232. is not a direct descendant of this :py:class:`~.Wikicode` object. If
  233. *obj* is not in the node list, :py:exc:`ValueError` is raised.
  234. """
  235. callback = lambda self, i: self.nodes.pop(i)
  236. self._do_search(obj, recursive, callback, self)
  237. def ifilter(self, recursive=False, matches=None, flags=FLAGS,
  238. forcetype=None):
  239. """Iterate over nodes in our list matching certain conditions.
  240. If *recursive* is ``True``, we will iterate over our children and all
  241. descendants of our children, otherwise just our immediate children. If
  242. *matches* is given, we will only yield the nodes that match the given
  243. regular expression (with :py:func:`re.search`). The default flags used
  244. are :py:const:`re.IGNORECASE`, :py:const:`re.DOTALL`, and
  245. :py:const:`re.UNICODE`, but custom flags can be specified by passing
  246. *flags*. If *forcetype* is given, only nodes that are instances of this
  247. type are yielded.
  248. """
  249. if recursive:
  250. nodes = self._get_all_nodes(self)
  251. else:
  252. nodes = self.nodes
  253. for node in nodes:
  254. if not forcetype or isinstance(node, forcetype):
  255. if not matches or re.search(matches, str(node), flags):
  256. yield node
  257. def ifilter_links(self, recursive=False, matches=None, flags=FLAGS):
  258. """Iterate over wikilink nodes.
  259. This is equivalent to :py:meth:`ifilter` with *forcetype* set to
  260. :py:class:`~.Wikilink`.
  261. """
  262. return self.ifilter(recursive, matches, flags, forcetype=Wikilink)
  263. def ifilter_templates(self, recursive=False, matches=None, flags=FLAGS):
  264. """Iterate over template nodes.
  265. This is equivalent to :py:meth:`ifilter` with *forcetype* set to
  266. :py:class:`~.Template`.
  267. """
  268. return self.filter(recursive, matches, flags, forcetype=Template)
  269. def ifilter_text(self, recursive=False, matches=None, flags=FLAGS):
  270. """Iterate over text nodes.
  271. This is equivalent to :py:meth:`ifilter` with *forcetype* set to
  272. :py:class:`~.nodes.Text`.
  273. """
  274. return self.filter(recursive, matches, flags, forcetype=Text)
  275. def ifilter_tags(self, recursive=False, matches=None, flags=FLAGS):
  276. """Iterate over tag nodes.
  277. This is equivalent to :py:meth:`ifilter` with *forcetype* set to
  278. :py:class:`~.Tag`.
  279. """
  280. return self.ifilter(recursive, matches, flags, forcetype=Tag)
  281. def filter(self, recursive=False, matches=None, flags=FLAGS,
  282. forcetype=None):
  283. """Return a list of nodes within our list matching certain conditions.
  284. This is equivalent to calling :py:func:`list` on :py:meth:`ifilter`.
  285. """
  286. return list(self.ifilter(recursive, matches, flags, forcetype))
  287. def filter_links(self, recursive=False, matches=None, flags=FLAGS):
  288. """Return a list of wikilink nodes.
  289. This is equivalent to calling :py:func:`list` on
  290. :py:meth:`ifilter_links`.
  291. """
  292. return list(self.ifilter_links(recursive, matches, flags))
  293. def filter_templates(self, recursive=False, matches=None, flags=FLAGS):
  294. """Return a list of template nodes.
  295. This is equivalent to calling :py:func:`list` on
  296. :py:meth:`ifilter_templates`.
  297. """
  298. return list(self.ifilter_templates(recursive, matches, flags))
  299. def filter_text(self, recursive=False, matches=None, flags=FLAGS):
  300. """Return a list of text nodes.
  301. This is equivalent to calling :py:func:`list` on
  302. :py:meth:`ifilter_text`.
  303. """
  304. return list(self.ifilter_text(recursive, matches, flags))
  305. def filter_tags(self, recursive=False, matches=None, flags=FLAGS):
  306. """Return a list of tag nodes.
  307. This is equivalent to calling :py:func:`list` on
  308. :py:meth:`ifilter_tags`.
  309. """
  310. return list(self.ifilter_tags(recursive, matches, flags))
  311. def get_sections(self, flat=True, matches=None, levels=None, flags=FLAGS,
  312. include_headings=True):
  313. """Return a list of sections within the page.
  314. Sections are returned as :py:class:`~.Wikicode` objects with a shared
  315. node list (implemented using :py:class:`~.SmartList`) so that changes
  316. to sections are reflected in the parent Wikicode object.
  317. With *flat* as ``True``, each returned section contains all of its
  318. subsections within the :py:class:`~.Wikicode`; otherwise, the returned
  319. sections contain only the section up to the next heading, regardless of
  320. its size. If *matches* is given, it should be a regex to be matched
  321. against the titles of section headings; only sections whose headings
  322. match the regex will be included. If *levels* is given, it should be a
  323. iterable of integers; only sections whose heading levels are within it
  324. will be returned. If *include_headings* is ``True``, the section's
  325. beginning :py:class:`~.Heading` object will be included in returned
  326. :py:class:`~.Wikicode` objects; otherwise, this is skipped.
  327. """
  328. if matches:
  329. matches = r"^(=+?)\s*" + matches + r"\s*\1$"
  330. headings = self.filter(recursive=True, matches=matches, flags=flags,
  331. forcetype=Heading)
  332. if levels:
  333. headings = [head for head in headings if head.level in levels]
  334. sections = []
  335. buffers = [(maxsize, 0)]
  336. i = 0
  337. while i < len(self.nodes):
  338. if self.nodes[i] in headings:
  339. this = self.nodes[i].level
  340. for (level, start) in buffers:
  341. if not flat or this <= level:
  342. buffers.remove((level, start))
  343. sections.append(Wikicode(self.nodes[start:i]))
  344. buffers.append((this, i))
  345. if not include_headings:
  346. i += 1
  347. i += 1
  348. for (level, start) in buffers:
  349. if start != i:
  350. sections.append(Wikicode(self.nodes[start:i]))
  351. return sections
  352. def strip_code(self, normalize=True, collapse=True):
  353. """Return a rendered string without unprintable code such as templates.
  354. The way a node is stripped is handled by the
  355. :py:meth:`~.Node.__showtree__` method of :py:class:`~.Node` objects,
  356. which generally return a subset of their nodes or ``None``. For
  357. example, templates and tags are removed completely, links are stripped
  358. to just their display part, headings are stripped to just their title.
  359. If *normalize* is ``True``, various things may be done to strip code
  360. further, such as converting HTML entities like ``&Sigma;``, ``&#931;``,
  361. and ``&#x3a3;`` to ``Σ``. If *collapse* is ``True``, we will try to
  362. remove excess whitespace as well (three or more newlines are converted
  363. to two, for example).
  364. """
  365. nodes = []
  366. for node in self.nodes:
  367. stripped = node.__strip__(normalize, collapse)
  368. if stripped:
  369. nodes.append(str(stripped))
  370. if collapse:
  371. stripped = "".join(nodes).strip("\n")
  372. while "\n\n\n" in stripped:
  373. stripped = stripped.replace("\n\n\n", "\n\n")
  374. return stripped
  375. else:
  376. return "".join(nodes)
  377. def get_tree(self):
  378. """Return a hierarchical tree representation of the object.
  379. The representation is a string makes the most sense printed. It is
  380. built by calling :py:meth:`_get_tree` on the
  381. :py:class:`~.Wikicode` object and its children recursively. The end
  382. result may look something like the following::
  383. >>> text = "Lorem ipsum {{foo|bar|{{baz}}|spam=eggs}}"
  384. >>> print mwparserfromhell.parse(text).get_tree()
  385. Lorem ipsum
  386. {{
  387. foo
  388. | 1
  389. = bar
  390. | 2
  391. = {{
  392. baz
  393. }}
  394. | spam
  395. = eggs
  396. }}
  397. """
  398. marker = object() # Random object we can find with certainty in a list
  399. return "\n".join(self._get_tree(self, [], marker, 0))