|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +コミット構文 |
| 4 | +========================================= |
| 5 | +
|
| 6 | +コミットIDをリンクに変換する |
| 7 | +[commit REPOSITORY_NAME, commit-id0, commit-id-2...] |
| 8 | +
|
| 9 | + >>> text = "[commit REPOSITORY_NAME, 1234567, abcdefg]" |
| 10 | + >>> md = markdown.Markdown(['commit']) |
| 11 | + >>> print md.convert(text) |
| 12 | + <a href="https://github.com/REPOSITORY_NAME/commit/1234567">1234567</a> <a href="https://github.com/REPOSITORY_NAME/commit/abcdefg">abcdefg</a> |
| 13 | +""" |
| 14 | + |
| 15 | +import re |
| 16 | + |
| 17 | +from markdown.extensions import Extension |
| 18 | +from markdown.preprocessors import Preprocessor |
| 19 | + |
| 20 | + |
| 21 | +def replace_commit_line(line: str) -> str: |
| 22 | + new_line: str = line |
| 23 | + for m in re.finditer(r'\[commit (.*?)\]', line.strip()): |
| 24 | + c = m[1].split(", ") |
| 25 | + repo = c[0] |
| 26 | + links: list[str] = [] |
| 27 | + for id in c[1:]: |
| 28 | + id = id.strip() |
| 29 | + if len(id) == 0: |
| 30 | + continue |
| 31 | + links.append("<a href=\"https://github.com/{0}/commit/{1}\">{1}</a>".format(repo, id)) |
| 32 | + commits: str = " ".join(links) |
| 33 | + new_line = new_line.replace(m[0], commits) |
| 34 | + return new_line |
| 35 | + |
| 36 | +class CommitExtension(Extension): |
| 37 | + |
| 38 | + def extendMarkdown(self, md, md_globals): |
| 39 | + pre = CommitPreprocessor(md) |
| 40 | + |
| 41 | + md.registerExtension(self) |
| 42 | + md.preprocessors.add('commit', pre, ">normalize_whitespace") |
| 43 | + |
| 44 | + |
| 45 | +class CommitPreprocessor(Preprocessor): |
| 46 | + |
| 47 | + def __init__(self, md): |
| 48 | + Preprocessor.__init__(self, md) |
| 49 | + self._markdown = md |
| 50 | + |
| 51 | + def run(self, lines): |
| 52 | + new_lines = [] |
| 53 | + self._markdown._meta_result = {} |
| 54 | + |
| 55 | + for line in lines: |
| 56 | + new_line = replace_commit_line(line) |
| 57 | + new_lines.append(new_line) |
| 58 | + |
| 59 | + return new_lines |
| 60 | + |
| 61 | + |
| 62 | +def makeExtension(**kwargs): |
| 63 | + return CommitExtension(**kwargs) |
0 commit comments