2017-01-13 09:01:09 +01:00
|
|
|
import re
|
2017-01-15 15:08:47 +01:00
|
|
|
from os import walk
|
|
|
|
|
|
|
|
from src.markdown_converter import MarkdownConverter
|
|
|
|
|
2017-01-12 21:45:49 +01:00
|
|
|
|
2017-01-15 15:08:47 +01:00
|
|
|
@MarkdownConverter.Register
|
|
|
|
class MarkdownLinks():
|
2017-01-13 13:17:54 +01:00
|
|
|
# see http://pythex.org/
|
|
|
|
pattern = re.compile('(\[\[)(.*?)(\]\])')
|
2017-01-12 21:45:49 +01:00
|
|
|
|
|
|
|
def convert(self, text):
|
2017-01-13 09:01:09 +01:00
|
|
|
result = text
|
2017-01-13 12:59:45 +01:00
|
|
|
for regex_link in MarkdownLinks.pattern.findall(text):
|
2017-01-13 13:17:54 +01:00
|
|
|
origlink = ''.join(regex_link)
|
2017-01-13 09:01:09 +01:00
|
|
|
convertedlink = ""
|
2017-01-13 13:17:54 +01:00
|
|
|
if "http" in origlink or "www" in origlink:
|
2017-01-13 12:59:45 +01:00
|
|
|
convertedlink = self.convert_as_external_link(origlink)
|
2017-01-13 13:17:54 +01:00
|
|
|
elif ">" in origlink:
|
2017-01-13 12:59:45 +01:00
|
|
|
convertedlink = self.convert_as_interwiki_link(origlink)
|
2017-01-13 09:01:09 +01:00
|
|
|
else:
|
2017-01-13 12:59:45 +01:00
|
|
|
convertedlink = self.convert_as_internal_link(origlink)
|
|
|
|
result = result.replace(origlink, convertedlink)
|
2017-01-13 09:01:09 +01:00
|
|
|
return result
|
2017-01-12 21:45:49 +01:00
|
|
|
|
|
|
|
def parseUrl(self, text):
|
|
|
|
return text[2:text.index('|')]
|
|
|
|
|
|
|
|
def parseInternalUrl(self, text):
|
|
|
|
return text[2:len(text)-2].replace(":", "/")
|
|
|
|
|
|
|
|
def parseTitle(self, text):
|
2017-01-13 09:01:09 +01:00
|
|
|
return text[text.index('|') + 1: text.index(']]')]
|
2017-01-12 21:45:49 +01:00
|
|
|
|
|
|
|
def convert_as_interwiki_link(self, text):
|
|
|
|
interwiki_shortcode = text[2:text.index('>')]
|
|
|
|
self.assert_interwiki_is_known(interwiki_shortcode)
|
|
|
|
interwiki_urlpart = text[text.index('>') + 1 : len(text) - 2]
|
|
|
|
|
|
|
|
return """{{< %s %s >}}""" % (interwiki_shortcode, interwiki_urlpart)
|
|
|
|
|
|
|
|
def convert_as_internal_link(self, text):
|
|
|
|
if "|" not in text:
|
|
|
|
return """{{< relref "%s" >}}""" % (self.parseInternalUrl(text))
|
|
|
|
|
|
|
|
url = self.parseUrl(text).replace(":", "/")
|
|
|
|
title = self.parseTitle(text)
|
|
|
|
|
|
|
|
return """[%s]({{< relref "%s" >}})""" % (title, url)
|
|
|
|
|
|
|
|
def convert_as_external_link(self, text):
|
|
|
|
url = self.parseUrl(text)
|
|
|
|
title = self.parseTitle(text)
|
|
|
|
|
|
|
|
return "[" + title + "](" + url + ")"
|
|
|
|
|
|
|
|
def assert_interwiki_is_known(self, shortcode):
|
|
|
|
shortcodes = []
|
|
|
|
for (dirpath, dirnames, filenames) in walk("../layouts/shortcodes"):
|
|
|
|
shortcodes.extend(filenames)
|
|
|
|
break
|
|
|
|
if not shortcode in map(lambda x: x.replace(".html", ""), shortcodes):
|
|
|
|
raise ValueError("Unknown Interwiki code " + shortcode + " - please add a shortcode in the layouts dir!")
|