]> ToastFreeware Gitweb - philipp/winterrodeln/wrpylib.git/blob - wrpylib/lib_sledrun_wikitext_to_json.py
Move some functions to lib_sledrun_wikitext_to_json.py
[philipp/winterrodeln/wrpylib.git] / wrpylib / lib_sledrun_wikitext_to_json.py
1 from itertools import takewhile, dropwhile
2 from typing import Optional, Any
3
4 from mwparserfromhell.nodes import Template, Text, Tag, Wikilink, ExternalLink
5 from mwparserfromhell.wikicode import Wikicode
6
7
8 def optional_set(haystack: dict, key: str, value: Optional[Any]):
9     """Sets the key to value in haystack only if value is not None"""
10     if value is not None:
11         haystack[key] = value
12
13
14 def wikilink_to_json(value: Wikilink) -> dict:
15     wl = {'title': str(value.title)}
16     if value.text is not None:
17         wl['text'] = str(value.text)
18     return wl
19
20
21 def external_link_to_json(value: ExternalLink) -> dict:
22     link = {'url': str(value.url)}
23     if value.title is not None:
24         link['text'] = str(value.title)
25     return link
26
27
28 def template_to_json(value: Template) -> dict:
29     parameter = []
30     for p in value.params:
31         parameter.append({'value': str(p)})
32     return {
33         'name': str(value.name),
34         'parameter': parameter
35     }
36
37
38 def get_sledrun_description(sledrun: Wikicode) -> Optional[str]:
39     """Get description from sledrun"""
40     for v in sledrun.get_sections(levels=[2], matches='Allgemeines', include_headings=False):
41         dw = dropwhile(lambda n: isinstance(n, Template) or (isinstance(n, Text) and not str(n).strip()), v.nodes)
42         tw = takewhile(lambda n: not (isinstance(n, Tag) and str(n) == '*'), dw)
43         result = str(Wikicode(tw)).strip()
44         if result:
45             return result