wp_plugin_to_jekyll.py 1.95 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
import sys
import re


def alert_template(type: str, match: re.Match) -> str:
    return "{{% include alerts/{}.html content=\"{}\" %}}".format(type, match.group(1).replace('"', r'\"'))


# [leaflet-map height=300 width=500 lat=45.47991 lng=9.22693 zoom=16][leaflet-marker]
def leaflet_template(match: re.Match, marker: bool = True) -> str:
    string = match.group(0)
    params = {
        "height": int(re.search(r"height=(\d+)", string).group(1)),
        "width": int(re.search(r"width=(\d+)", string).group(1)),
        "lat": float(re.search(r"lat=(\d+\.\d+)", string).group(1)),
        "long": float(re.search(r"lng=(\d+\.\d+)", string).group(1)),
        "zoom": int(re.search(r"width=(\d+)", string).group(1)),
        "id": "wp-map-" + str(int(random.random() * 1000000)),
        "marker": str(marker).lower(),
        "class_": "wp-map"
    }

    return '{{% include leaflet.html id="{id}" class="{class_}" width="{width}" height="{height}" lat="{lat}" long="{' \
           'long}" zoom="{zoom}" marker="{marker}" %}}'.format(**params)


replacements = {
    re.compile(r"\[important\](.*?)\[/important\]"):
        lambda match: alert_template("important", match),

    re.compile(r"\[notice\](.*?)\[/notice\]"):
        lambda match: alert_template("notice", match),

    re.compile(r"\[warning\](.*?)\[/warning\]"):
        lambda match: alert_template("warning", match),

    re.compile(r"(\[leaflet-map .+\]\[leaflet-marker\])"):
        lambda match: leaflet_template(match, marker=True),

    re.compile(r"(\[leaflet-map .+\])"):
        lambda match: leaflet_template(match, marker=False)
}


def rewrite_file(filename: str):
    with open(filename) as f:
        content = f.read()

    for regex, repl in replacements.items():
        content = regex.sub(repl, content)

    with open(filename, "w") as f:
        f.write(content)


if __name__ == "__main__":
    for i in sys.argv[1:]:
        rewrite_file(i)