Add script to convert WP plugin codes to Jekyll templates

parent 3ed393e6
#!/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)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment