-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkify_issues.py
79 lines (62 loc) · 2.29 KB
/
linkify_issues.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import re
import typing as t
from docutils import nodes
from sphinx.application import Sphinx
from sphinx.transforms import SphinxTransform
from docutils_compat import findall
DEFAULT_ISSUE_RE = r"#(?P<issue_id>\d+)"
"""Default pattern to search plain nodes for issues."""
class LinkifyIssues(SphinxTransform):
default_priority = 999
def apply(self) -> None:
config = self.document.settings.env.config
issue_re: re.Pattern[str] = (
re.compile(config.issue_re)
if isinstance(config.issue_re, str)
else config.issue_re
)
assert issue_re.groups == 1
def condition(node: nodes.Node) -> bool:
cond = (
isinstance(node, nodes.Text)
and len(re.findall(issue_re, node.astext())) > 0
) and not isinstance(
node.parent, (nodes.literal, nodes.FixedTextElement, nodes.reference)
)
return cond
for node in findall(self.document)(condition):
text = node.astext()
retnodes = []
pos = 0
for match in issue_re.finditer(text):
if match.start() > pos:
txt = text[pos : match.start()]
retnodes.append(nodes.Text(txt))
refnode = nodes.reference(
refuri=f"{config.issue_url_tpl}".format(**match.groupdict()),
internal=False,
classes=["issue"],
)
refnode += nodes.inline(match.group(0), match.group(0))
retnodes.append(refnode)
pos = match.end()
if pos < len(text):
retnodes.append(nodes.Text(text[pos:]))
node.parent.replace(node, retnodes)
class SetupDict(t.TypedDict):
version: str
parallel_read_safe: bool
parallel_write_safe: bool
def setup(app: Sphinx) -> SetupDict:
app.add_transform(LinkifyIssues)
app.add_config_value("issue_re", re.compile(DEFAULT_ISSUE_RE), "env")
app.add_config_value(
"issue_url_tpl", r"https://github.com/git-pull/gp-libs/issues/{issue_id}", "env"
)
return SetupDict(
{
"version": "0.1",
"parallel_read_safe": True,
"parallel_write_safe": True,
}
)