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.
 
 
 
 

546 lines
24 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2013 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 deque
  24. from itertools import chain
  25. import re
  26. from .compat import py3k, range, str
  27. from .nodes import (Argument, Comment, ExternalLink, Heading, HTMLEntity,
  28. Node, Tag, Template, Text, Wikilink)
  29. from .string_mixin import StringMixIn
  30. from .utils import parse_anything
  31. __all__ = ["Wikicode"]
  32. FLAGS = re.IGNORECASE | re.DOTALL | re.UNICODE
  33. class Wikicode(StringMixIn):
  34. """A ``Wikicode`` is a container for nodes that operates like a string.
  35. Additionally, it contains methods that can be used to extract data from or
  36. modify the nodes, implemented in an interface similar to a list. For
  37. example, :py:meth:`index` can get the index of a node in the list, and
  38. :py:meth:`insert` can add a new node at that index. The :py:meth:`filter()
  39. <ifilter>` series of functions is very useful for extracting and iterating
  40. over, for example, all of the templates in the object.
  41. """
  42. def __init__(self, nodes):
  43. super(Wikicode, self).__init__()
  44. self._nodes = nodes
  45. def __unicode__(self):
  46. return "".join([str(node) for node in self.nodes])
  47. @staticmethod
  48. def _get_children(node, contexts=False, parent=None):
  49. """Iterate over all child :py:class:`.Node`\ s of a given *node*."""
  50. yield (parent, node) if contexts else node
  51. for code in node.__children__():
  52. for child in code.nodes:
  53. for result in Wikicode._get_children(child, contexts, code):
  54. yield result
  55. @staticmethod
  56. def _slice_replace(code, index, old, new):
  57. """Replace the string *old* with *new* across *index* in *code*."""
  58. nodes = [str(node) for node in code.get(index)]
  59. substring = "".join(nodes).replace(old, new)
  60. code.nodes[index] = parse_anything(substring).nodes
  61. def _do_strong_search(self, obj, recursive=True):
  62. """Search for the specific element *obj* within the node list.
  63. *obj* can be either a :py:class:`.Node` or a :py:class:`.Wikicode`
  64. object. If found, we return a tuple (*context*, *index*) where
  65. *context* is the :py:class:`.Wikicode` that contains *obj* and *index*
  66. is its index there, as a :py:class:`slice`. Note that if *recursive* is
  67. ``False``, *context* will always be ``self`` (since we only look for
  68. *obj* among immediate descendants), but if *recursive* is ``True``,
  69. then it could be any :py:class:`.Wikicode` contained by a node within
  70. ``self``. If *obj* is not found, :py:exc:`ValueError` is raised.
  71. """
  72. mkslice = lambda i: slice(i, i + 1)
  73. if isinstance(obj, Node):
  74. if not recursive:
  75. return self, mkslice(self.index(obj))
  76. for i, node in enumerate(self.nodes):
  77. for context, child in self._get_children(node, contexts=True):
  78. if obj is child:
  79. if not context:
  80. context = self
  81. return context, mkslice(context.index(child))
  82. else:
  83. context, ind = self._do_strong_search(obj.get(0), recursive)
  84. for i in range(1, len(obj.nodes)):
  85. if obj.get(i) is not context.get(ind.start + i):
  86. break
  87. else:
  88. return context, slice(ind.start, ind.start + len(obj.nodes))
  89. raise ValueError(obj)
  90. def _do_weak_search(self, obj, recursive):
  91. """Search for an element that looks like *obj* within the node list.
  92. This follows the same rules as :py:meth:`_do_strong_search` with some
  93. differences. *obj* is treated as a string that might represent any
  94. :py:class:`.Node`, :py:class:`.Wikicode`, or combination of the two
  95. present in the node list. Thus, matching is weak (using string
  96. comparisons) rather than strong (using ``is``). Because multiple nodes
  97. can match *obj*, the result is a list of tuples instead of just one
  98. (however, :py:exc:`ValueError` is still raised if nothing is found).
  99. Individual matches will never overlap.
  100. The tuples contain a new first element, *exact*, which is ``True`` if
  101. we were able to match *obj* exactly to one or more adjacent nodes, or
  102. ``False`` if we found *obj* inside a node or incompletely spanning
  103. multiple nodes.
  104. """
  105. obj = parse_anything(obj)
  106. if not obj or obj not in self:
  107. raise ValueError(obj)
  108. results = []
  109. contexts = [self]
  110. while contexts:
  111. context = contexts.pop()
  112. i = len(context.nodes) - 1
  113. while i >= 0:
  114. node = context.get(i)
  115. if obj.get(-1) == node:
  116. for j in range(-len(obj.nodes), -1):
  117. if obj.get(j) != context.get(i + j + 1):
  118. break
  119. else:
  120. i -= len(obj.nodes) - 1
  121. index = slice(i, i + len(obj.nodes))
  122. results.append((True, context, index))
  123. elif recursive and obj in node:
  124. contexts.extend(node.__children__())
  125. i -= 1
  126. if not results:
  127. if not recursive:
  128. raise ValueError(obj)
  129. results.append((False, self, slice(0, len(self.nodes))))
  130. return results
  131. def _get_tree(self, code, lines, marker, indent):
  132. """Build a tree to illustrate the way the Wikicode object was parsed.
  133. The method that builds the actual tree is ``__showtree__`` of ``Node``
  134. objects. *code* is the ``Wikicode`` object to build a tree for. *lines*
  135. is the list to append the tree to, which is returned at the end of the
  136. method. *marker* is some object to be used to indicate that the builder
  137. should continue on from the last line instead of starting a new one; it
  138. should be any object that can be tested for with ``is``. *indent* is
  139. the starting indentation.
  140. """
  141. def write(*args):
  142. """Write a new line following the proper indentation rules."""
  143. if lines and lines[-1] is marker: # Continue from the last line
  144. lines.pop() # Remove the marker
  145. last = lines.pop()
  146. lines.append(last + " ".join(args))
  147. else:
  148. lines.append(" " * 6 * indent + " ".join(args))
  149. get = lambda code: self._get_tree(code, lines, marker, indent + 1)
  150. mark = lambda: lines.append(marker)
  151. for node in code.nodes:
  152. node.__showtree__(write, get, mark)
  153. return lines
  154. @classmethod
  155. def _build_filter_methods(cls, **meths):
  156. """Given Node types, build the corresponding i?filter shortcuts.
  157. The should be given as keys storing the method's base name paired
  158. with values storing the corresponding :py:class:`~.Node` type. For
  159. example, the dict may contain the pair ``("templates", Template)``,
  160. which will produce the methods :py:meth:`ifilter_templates` and
  161. :py:meth:`filter_templates`, which are shortcuts for
  162. :py:meth:`ifilter(forcetype=Template) <ifilter>` and
  163. :py:meth:`filter(forcetype=Template) <filter>`, respectively. These
  164. shortcuts are added to the class itself, with an appropriate docstring.
  165. """
  166. doc = """Iterate over {0}.
  167. This is equivalent to :py:meth:`{1}` with *forcetype* set to
  168. :py:class:`~{2.__module__}.{2.__name__}`.
  169. """
  170. make_ifilter = lambda ftype: (lambda self, **kw:
  171. self.ifilter(forcetype=ftype, **kw))
  172. make_filter = lambda ftype: (lambda self, **kw:
  173. self.filter(forcetype=ftype, **kw))
  174. for name, ftype in (meths.items() if py3k else meths.iteritems()):
  175. ifilter = make_ifilter(ftype)
  176. filter = make_filter(ftype)
  177. ifilter.__doc__ = doc.format(name, "ifilter", ftype)
  178. filter.__doc__ = doc.format(name, "filter", ftype)
  179. setattr(cls, "ifilter_" + name, ifilter)
  180. setattr(cls, "filter_" + name, filter)
  181. @property
  182. def nodes(self):
  183. """A list of :py:class:`~.Node` objects.
  184. This is the internal data actually stored within a
  185. :py:class:`~.Wikicode` object.
  186. """
  187. return self._nodes
  188. @nodes.setter
  189. def nodes(self, value):
  190. if not isinstance(value, list):
  191. value = parse_anything(value).nodes
  192. self._nodes = value
  193. def get(self, index):
  194. """Return the *index*\ th node within the list of nodes."""
  195. return self.nodes[index]
  196. def set(self, index, value):
  197. """Set the ``Node`` at *index* to *value*.
  198. Raises :py:exc:`IndexError` if *index* is out of range, or
  199. :py:exc:`ValueError` if *value* cannot be coerced into one
  200. :py:class:`~.Node`. To insert multiple nodes at an index, use
  201. :py:meth:`get` with either :py:meth:`remove` and :py:meth:`insert` or
  202. :py:meth:`replace`.
  203. """
  204. nodes = parse_anything(value).nodes
  205. if len(nodes) > 1:
  206. raise ValueError("Cannot coerce multiple nodes into one index")
  207. if index >= len(self.nodes) or -1 * index > len(self.nodes):
  208. raise IndexError("List assignment index out of range")
  209. if nodes:
  210. self.nodes[index] = nodes[0]
  211. else:
  212. self.nodes.pop(index)
  213. def index(self, obj, recursive=False):
  214. """Return the index of *obj* in the list of nodes.
  215. Raises :py:exc:`ValueError` if *obj* is not found. If *recursive* is
  216. ``True``, we will look in all nodes of ours and their descendants, and
  217. return the index of our direct descendant node within *our* list of
  218. nodes. Otherwise, the lookup is done only on direct descendants.
  219. """
  220. strict = isinstance(obj, Node)
  221. equivalent = (lambda o, n: o is n) if strict else (lambda o, n: o == n)
  222. for i, node in enumerate(self.nodes):
  223. if recursive:
  224. for child in self._get_children(node):
  225. if equivalent(obj, child):
  226. return i
  227. elif equivalent(obj, node):
  228. return i
  229. raise ValueError(obj)
  230. def insert(self, index, value):
  231. """Insert *value* at *index* in the list of nodes.
  232. *value* can be anything parasable by :py:func:`.parse_anything`, which
  233. includes strings or other :py:class:`~.Wikicode` or :py:class:`~.Node`
  234. objects.
  235. """
  236. nodes = parse_anything(value).nodes
  237. for node in reversed(nodes):
  238. self.nodes.insert(index, node)
  239. def insert_before(self, obj, value, recursive=True):
  240. """Insert *value* immediately before *obj*.
  241. *obj* can be either a string, a :py:class:`~.Node`, or another
  242. :py:class:`~.Wikicode` object (as created by :py:meth:`get_sections`,
  243. for example). If *obj* is a string, we will operate on all instances
  244. of that string within the code, otherwise only on the specific instance
  245. given. *value* can be anything parasable by :py:func:`.parse_anything`.
  246. If *recursive* is ``True``, we will try to find *obj* within our child
  247. nodes even if it is not a direct descendant of this
  248. :py:class:`~.Wikicode` object. If *obj* is not found,
  249. :py:exc:`ValueError` is raised.
  250. """
  251. if isinstance(obj, (Node, Wikicode)):
  252. context, index = self._do_strong_search(obj, recursive)
  253. context.insert(index.start, value)
  254. else:
  255. for exact, context, index in self._do_weak_search(obj, recursive):
  256. if exact:
  257. context.insert(index.start, value)
  258. else:
  259. obj = str(obj)
  260. self._slice_replace(context, index, obj, str(value) + obj)
  261. def insert_after(self, obj, value, recursive=True):
  262. """Insert *value* immediately after *obj*.
  263. *obj* can be either a string, a :py:class:`~.Node`, or another
  264. :py:class:`~.Wikicode` object (as created by :py:meth:`get_sections`,
  265. for example). If *obj* is a string, we will operate on all instances
  266. of that string within the code, otherwise only on the specific instance
  267. given. *value* can be anything parasable by :py:func:`.parse_anything`.
  268. If *recursive* is ``True``, we will try to find *obj* within our child
  269. nodes even if it is not a direct descendant of this
  270. :py:class:`~.Wikicode` object. If *obj* is not found,
  271. :py:exc:`ValueError` is raised.
  272. """
  273. if isinstance(obj, (Node, Wikicode)):
  274. context, index = self._do_strong_search(obj, recursive)
  275. context.insert(index.stop, value)
  276. else:
  277. for exact, context, index in self._do_weak_search(obj, recursive):
  278. if exact:
  279. context.insert(index.stop, value)
  280. else:
  281. obj = str(obj)
  282. self._slice_replace(context, index, obj, obj + str(value))
  283. def replace(self, obj, value, recursive=True):
  284. """Replace *obj* with *value*.
  285. *obj* can be either a string, a :py:class:`~.Node`, or another
  286. :py:class:`~.Wikicode` object (as created by :py:meth:`get_sections`,
  287. for example). If *obj* is a string, we will operate on all instances
  288. of that string within the code, otherwise only on the specific instance
  289. given. *value* can be anything parasable by :py:func:`.parse_anything`.
  290. If *recursive* is ``True``, we will try to find *obj* within our child
  291. nodes even if it is not a direct descendant of this
  292. :py:class:`~.Wikicode` object. If *obj* is not found,
  293. :py:exc:`ValueError` is raised.
  294. """
  295. if isinstance(obj, (Node, Wikicode)):
  296. context, index = self._do_strong_search(obj, recursive)
  297. for i in range(index.start, index.stop):
  298. context.nodes.pop(index.start)
  299. context.insert(index.start, value)
  300. else:
  301. for exact, context, index in self._do_weak_search(obj, recursive):
  302. if exact:
  303. for i in range(index.start, index.stop):
  304. context.nodes.pop(index.start)
  305. context.insert(index.start, value)
  306. else:
  307. self._slice_replace(context, index, str(obj), str(value))
  308. def append(self, value):
  309. """Insert *value* at the end of the list of nodes.
  310. *value* can be anything parasable by :py:func:`.parse_anything`.
  311. """
  312. nodes = parse_anything(value).nodes
  313. for node in nodes:
  314. self.nodes.append(node)
  315. def remove(self, obj, recursive=True):
  316. """Remove *obj* from the list of nodes.
  317. *obj* can be either a string, a :py:class:`~.Node`, or another
  318. :py:class:`~.Wikicode` object (as created by :py:meth:`get_sections`,
  319. for example). If *obj* is a string, we will operate on all instances
  320. of that string within the code, otherwise only on the specific instance
  321. given. If *recursive* is ``True``, we will try to find *obj* within our
  322. child nodes even if it is not a direct descendant of this
  323. :py:class:`~.Wikicode` object. If *obj* is not found,
  324. :py:exc:`ValueError` is raised.
  325. """
  326. if isinstance(obj, (Node, Wikicode)):
  327. context, index = self._do_strong_search(obj, recursive)
  328. for i in range(index.start, index.stop):
  329. context.nodes.pop(index.start)
  330. else:
  331. for exact, context, index in self._do_weak_search(obj, recursive):
  332. if exact:
  333. for i in range(index.start, index.stop):
  334. context.nodes.pop(index.start)
  335. else:
  336. self._slice_replace(context, index, str(obj), "")
  337. def matches(self, other):
  338. """Do a loose equivalency test suitable for comparing page names.
  339. *other* can be any string-like object, including
  340. :py:class:`~.Wikicode`, or a tuple of these. This operation is
  341. symmetric; both sides are adjusted. Specifically, whitespace and markup
  342. is stripped and the first letter's case is normalized. Typical usage is
  343. ``if template.name.matches("stub"): ...``.
  344. """
  345. cmp = lambda a, b: (a[0].upper() + a[1:] == b[0].upper() + b[1:]
  346. if a and b else a == b)
  347. this = self.strip_code().strip()
  348. if isinstance(other, (tuple, list)):
  349. for obj in other:
  350. that = parse_anything(obj).strip_code().strip()
  351. if cmp(this, that):
  352. return True
  353. return False
  354. that = parse_anything(other).strip_code().strip()
  355. return cmp(this, that)
  356. def ifilter(self, recursive=True, matches=None, flags=FLAGS,
  357. forcetype=None):
  358. """Iterate over nodes in our list matching certain conditions.
  359. If *recursive* is ``True``, we will iterate over our children and all
  360. of their descendants, otherwise just our immediate children. If
  361. *forcetype* is given, only nodes that are instances of this type are
  362. yielded. *matches* can be used to further restrict the nodes, either as
  363. a function (taking a single :py:class:`.Node` and returning a boolean)
  364. or a regular expression (matched against the node's string
  365. representation with :py:func:`re.search`). If *matches* is a regex, the
  366. flags passed to :py:func:`re.search` are :py:const:`re.IGNORECASE`,
  367. :py:const:`re.DOTALL`, and :py:const:`re.UNICODE`, but custom flags can
  368. be specified by passing *flags*.
  369. """
  370. if matches and not callable(matches):
  371. pat, matches = matches, lambda obj: re.search(pat, str(obj), flags)
  372. if recursive:
  373. getter = self._get_children
  374. nodes = chain.from_iterable(getter(n) for n in self.nodes)
  375. else:
  376. nodes = self.nodes
  377. for node in nodes:
  378. if not forcetype or isinstance(node, forcetype):
  379. if not matches or matches(node):
  380. yield node
  381. def filter(self, recursive=True, matches=None, flags=FLAGS,
  382. forcetype=None):
  383. """Return a list of nodes within our list matching certain conditions.
  384. This is equivalent to calling :py:func:`list` on :py:meth:`ifilter`.
  385. """
  386. return list(self.ifilter(recursive, matches, flags, forcetype))
  387. def get_sections(self, levels=None, matches=None, flags=FLAGS, flat=False,
  388. include_lead=None, include_headings=True):
  389. """Return a list of sections within the page.
  390. Sections are returned as :py:class:`~.Wikicode` objects with a shared
  391. node list (implemented using :py:class:`~.SmartList`) so that changes
  392. to sections are reflected in the parent Wikicode object.
  393. Each section contains all of its subsections, unless *flat* is
  394. ``True``. If *levels* is given, it should be a iterable of integers;
  395. only sections whose heading levels are within it will be returned. If
  396. *matches* is given, it should be a regex to be matched against the
  397. titles of section headings; only sections whose headings match the
  398. regex will be included. *flags* can be used to override the default
  399. regex flags (see :py:meth:`ifilter`) if *matches* is used.
  400. If *include_lead* is ``True``, the first, lead section (without a
  401. heading) will be included in the list; ``False`` will not include it;
  402. the default will include it only if no specific *levels* were given. If
  403. *include_headings* is ``True``, the section's beginning
  404. :py:class:`~.Heading` object will be included; otherwise, this is
  405. skipped.
  406. """
  407. if matches:
  408. matches = r"^(=+?)\s*" + matches + r"\s*\1$"
  409. headings = self.filter_headings(recursive=False, matches=matches,
  410. flags=flags)
  411. if levels:
  412. headings = [head for head in headings if head.level in levels]
  413. sections = []
  414. if include_lead or not (include_lead is not None or matches or levels):
  415. iterator = self.ifilter_headings(recursive=False)
  416. try:
  417. first = self.index(next(iterator))
  418. sections.append(Wikicode(self.nodes[:first]))
  419. except StopIteration: # No headings in page
  420. sections.append(Wikicode(self.nodes[:]))
  421. for heading in headings:
  422. start = self.index(heading)
  423. i = start + 1
  424. if not include_headings:
  425. start += 1
  426. while i < len(self.nodes):
  427. node = self.nodes[i]
  428. if isinstance(node, Heading):
  429. if flat or node.level <= heading.level:
  430. break
  431. i += 1
  432. sections.append(Wikicode(self.nodes[start:i]))
  433. return sections
  434. def strip_code(self, normalize=True, collapse=True):
  435. """Return a rendered string without unprintable code such as templates.
  436. The way a node is stripped is handled by the
  437. :py:meth:`~.Node.__showtree__` method of :py:class:`~.Node` objects,
  438. which generally return a subset of their nodes or ``None``. For
  439. example, templates and tags are removed completely, links are stripped
  440. to just their display part, headings are stripped to just their title.
  441. If *normalize* is ``True``, various things may be done to strip code
  442. further, such as converting HTML entities like ``&Sigma;``, ``&#931;``,
  443. and ``&#x3a3;`` to ``Σ``. If *collapse* is ``True``, we will try to
  444. remove excess whitespace as well (three or more newlines are converted
  445. to two, for example).
  446. """
  447. nodes = []
  448. for node in self.nodes:
  449. stripped = node.__strip__(normalize, collapse)
  450. if stripped:
  451. nodes.append(str(stripped))
  452. if collapse:
  453. stripped = "".join(nodes).strip("\n")
  454. while "\n\n\n" in stripped:
  455. stripped = stripped.replace("\n\n\n", "\n\n")
  456. return stripped
  457. else:
  458. return "".join(nodes)
  459. def get_tree(self):
  460. """Return a hierarchical tree representation of the object.
  461. The representation is a string makes the most sense printed. It is
  462. built by calling :py:meth:`_get_tree` on the
  463. :py:class:`~.Wikicode` object and its children recursively. The end
  464. result may look something like the following::
  465. >>> text = "Lorem ipsum {{foo|bar|{{baz}}|spam=eggs}}"
  466. >>> print mwparserfromhell.parse(text).get_tree()
  467. Lorem ipsum
  468. {{
  469. foo
  470. | 1
  471. = bar
  472. | 2
  473. = {{
  474. baz
  475. }}
  476. | spam
  477. = eggs
  478. }}
  479. """
  480. marker = object() # Random object we can find with certainty in a list
  481. return "\n".join(self._get_tree(self, [], marker, 0))
  482. Wikicode._build_filter_methods(
  483. arguments=Argument, comments=Comment, external_links=ExternalLink,
  484. headings=Heading, html_entities=HTMLEntity, tags=Tag, templates=Template,
  485. text=Text, wikilinks=Wikilink)