From: Vladimír Vondruš Date: Tue, 4 Jul 2017 09:22:01 +0000 (+0200) Subject: plugins: reST roles for linking to GitHub articles. X-Git-Url: https://www.chiark.greenend.org.uk/ucgi/~cjwatson/git?a=commitdiff_plain;h=3412979c545604f26e31fde4d2a528ebb673038e;p=blog.git plugins: reST roles for linking to GitHub articles. --- diff --git a/pelican-plugins/m/__init__.py b/pelican-plugins/m/__init__.py new file mode 100644 index 00000000..4ab2dca8 --- /dev/null +++ b/pelican-plugins/m/__init__.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python + +from docutils import utils +import re + +link_regexp = re.compile(r'(?P.*) <(?P<link>.+)>') + +def parse_link(text): + link = utils.unescape(text) + m = link_regexp.match(link) + if m: return m.group('title', 'link') + return None, link diff --git a/pelican-plugins/m/gh.py b/pelican-plugins/m/gh.py new file mode 100644 index 00000000..9db3bccd --- /dev/null +++ b/pelican-plugins/m/gh.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python + +from . import parse_link +from docutils import nodes +from docutils.parsers import rst + +def gh_internal(account, ref, title, link): + base_url = "https://github.com/{}/{}/{}/{}" + if '#' in ref: + project, _, issue = ref.partition('#') + url = base_url.format(account, project, "issues", issue) + if not title: title = link + elif '@' in ref: + project, _, commit = ref.partition('@') + url = base_url.format(account, project, "commit", commit) + if not title: title = link + elif '$' in ref: + project, _, branch = ref.partition('$') + url = base_url.format(account, project, "tree", branch) + if not title: title = url + elif '^' in ref: + project, _, branch = ref.partition('^') + url = base_url.format(account, project, "releases/tag", branch) + if not title: title = url + else: + url = "https://github.com/{}/{}".format(account, ref) + if not title: title = url + + return title, url + +def gh(name, rawtext, text, lineno, inliner, options={}, content=[]): + title, link = parse_link(text) + account, _, ref = link.partition('/') + if not ref: + url = "https://github.com/{}".format(account) + if not title: title = "@{}".format(account) + else: + title, url = gh_internal(account, ref, title, link) + + node = nodes.reference(rawtext, title, refuri=url, **options) + return [node], [] + +def register(): + rst.roles.register_local_role('gh', gh)