matplotlib

Форк
0
167 строк · 5.2 Кб
1
"""
2
Define text roles for GitHub.
3

4
* ghissue - Issue
5
* ghpull - Pull Request
6
* ghuser - User
7

8
Adapted from bitbucket example here:
9
https://bitbucket.org/birkenfeld/sphinx-contrib/src/tip/bitbucket/sphinxcontrib/bitbucket.py
10

11
Authors
12
-------
13

14
* Doug Hellmann
15
* Min RK
16
"""
17
#
18
# Original Copyright (c) 2010 Doug Hellmann.  All rights reserved.
19
#
20

21
from docutils import nodes, utils
22
from docutils.parsers.rst.roles import set_classes
23

24

25
def make_link_node(rawtext, app, type, slug, options):
26
    """
27
    Create a link to a github resource.
28

29
    :param rawtext: Text being replaced with link node.
30
    :param app: Sphinx application context
31
    :param type: Link type (issues, changeset, etc.)
32
    :param slug: ID of the thing to link to
33
    :param options: Options dictionary passed to role func.
34
    """
35

36
    try:
37
        base = app.config.github_project_url
38
        if not base:
39
            raise AttributeError
40
        if not base.endswith('/'):
41
            base += '/'
42
    except AttributeError as err:
43
        raise ValueError(
44
            f'github_project_url configuration value is not set '
45
            f'({err})') from err
46

47
    ref = base + type + '/' + slug + '/'
48
    set_classes(options)
49
    prefix = "#"
50
    if type == 'pull':
51
        prefix = "PR " + prefix
52
    node = nodes.reference(rawtext, prefix + utils.unescape(slug), refuri=ref,
53
                           **options)
54
    return node
55

56

57
def ghissue_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
58
    """
59
    Link to a GitHub issue.
60

61
    Returns 2 part tuple containing list of nodes to insert into the
62
    document and a list of system messages.  Both are allowed to be
63
    empty.
64

65
    :param name: The role name used in the document.
66
    :param rawtext: The entire markup snippet, with role.
67
    :param text: The text marked with the role.
68
    :param lineno: The line number where rawtext appears in the input.
69
    :param inliner: The inliner instance that called us.
70
    :param options: Directive options for customization.
71
    :param content: The directive content for customization.
72
    """
73

74
    try:
75
        issue_num = int(text)
76
        if issue_num <= 0:
77
            raise ValueError
78
    except ValueError:
79
        msg = inliner.reporter.error(
80
            'GitHub issue number must be a number greater than or equal to 1; '
81
            '"%s" is invalid.' % text, line=lineno)
82
        prb = inliner.problematic(rawtext, rawtext, msg)
83
        return [prb], [msg]
84
    app = inliner.document.settings.env.app
85
    if 'pull' in name.lower():
86
        category = 'pull'
87
    elif 'issue' in name.lower():
88
        category = 'issues'
89
    else:
90
        msg = inliner.reporter.error(
91
            'GitHub roles include "ghpull" and "ghissue", '
92
            '"%s" is invalid.' % name, line=lineno)
93
        prb = inliner.problematic(rawtext, rawtext, msg)
94
        return [prb], [msg]
95
    node = make_link_node(rawtext, app, category, str(issue_num), options)
96
    return [node], []
97

98

99
def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
100
    """
101
    Link to a GitHub user.
102

103
    Returns 2 part tuple containing list of nodes to insert into the
104
    document and a list of system messages.  Both are allowed to be
105
    empty.
106

107
    :param name: The role name used in the document.
108
    :param rawtext: The entire markup snippet, with role.
109
    :param text: The text marked with the role.
110
    :param lineno: The line number where rawtext appears in the input.
111
    :param inliner: The inliner instance that called us.
112
    :param options: Directive options for customization.
113
    :param content: The directive content for customization.
114
    """
115
    ref = 'https://www.github.com/' + text
116
    node = nodes.reference(rawtext, text, refuri=ref, **options)
117
    return [node], []
118

119

120
def ghcommit_role(
121
        name, rawtext, text, lineno, inliner, options={}, content=[]):
122
    """
123
    Link to a GitHub commit.
124

125
    Returns 2 part tuple containing list of nodes to insert into the
126
    document and a list of system messages.  Both are allowed to be
127
    empty.
128

129
    :param name: The role name used in the document.
130
    :param rawtext: The entire markup snippet, with role.
131
    :param text: The text marked with the role.
132
    :param lineno: The line number where rawtext appears in the input.
133
    :param inliner: The inliner instance that called us.
134
    :param options: Directive options for customization.
135
    :param content: The directive content for customization.
136
    """
137
    app = inliner.document.settings.env.app
138
    try:
139
        base = app.config.github_project_url
140
        if not base:
141
            raise AttributeError
142
        if not base.endswith('/'):
143
            base += '/'
144
    except AttributeError as err:
145
        raise ValueError(
146
            f'github_project_url configuration value is not set '
147
            f'({err})') from err
148

149
    ref = base + text
150
    node = nodes.reference(rawtext, text[:6], refuri=ref, **options)
151
    return [node], []
152

153

154
def setup(app):
155
    """
156
    Install the plugin.
157

158
    :param app: Sphinx application context.
159
    """
160
    app.add_role('ghissue', ghissue_role)
161
    app.add_role('ghpull', ghissue_role)
162
    app.add_role('ghuser', ghuser_role)
163
    app.add_role('ghcommit', ghcommit_role)
164
    app.add_config_value('github_project_url', None, 'env')
165

166
    metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
167
    return metadata
168

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.