File: ext_github.py

package info (click to toggle)
streamlink 2.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 3,756 kB
  • sloc: python: 33,642; makefile: 137; sh: 87
file content (66 lines) | stat: -rw-r--r-- 2,059 bytes parent folder | download
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
"""Creates Github links from @user and #issue text.

Bascially a much simplified version of sphinxcontrib.issuetracker
with support for @user.
"""

import re

from docutils import nodes
from docutils.transforms import Transform

GITHUB_ISSUE_URL = "https://github.com/{0}/issues/{1}"
GITHUB_USER_URL = "https://github.com/{1}"


class GithubReferences(Transform):
    default_priority = 999

    def apply(self):
        config = self.document.settings.env.config
        issue_re = re.compile(config.github_issue_pattern)
        mention_re = re.compile(config.github_mention_pattern)

        self._replace_pattern(issue_re, GITHUB_ISSUE_URL)
        self._replace_pattern(mention_re, GITHUB_USER_URL)

    def _replace_pattern(self, pattern, url_format):
        project = self.document.settings.env.config.github_project

        for node in self.document.traverse(nodes.Text):
            parent = node.parent
            if isinstance(parent, (nodes.literal, nodes.FixedTextElement)):
                continue

            text = str(node)
            new_nodes = []
            last_ref_end = 0
            for match in pattern.finditer(text):
                head = text[last_ref_end:match.start()]
                if head:
                    new_nodes.append(nodes.Text(head))

                last_ref_end = match.end()
                ref = url_format.format(project, match.group(1))
                link = nodes.reference(
                    match.group(0),
                    match.group(0),
                    refuri=ref
                )
                new_nodes.append(link)

            if not new_nodes:
                continue

            tail = text[last_ref_end:]
            if tail:
                new_nodes.append(nodes.Text(tail))

            parent.replace(node, new_nodes)


def setup(app):
    app.add_config_value("github_project", None, "env")
    app.add_config_value("github_issue_pattern", r"#(\d+)", "env")
    app.add_config_value("github_mention_pattern", r"@(\w+)", "env")
    app.add_transform(GithubReferences)