A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 

513 wiersze
22 KiB

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