xref: /aosp_15_r20/external/pigweed/pw_docgen/py/pw_docgen/sphinx/bug.py (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1# Copyright 2024 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14"""Custom role for creating bug links."""
15
16from docutils import nodes
17from docutils.parsers.rst import roles
18
19from sphinx.application import Sphinx
20
21
22def bug_role(
23    role,  # pylint: disable=unused-argument
24    rawtext,
25    text,
26    lineno,
27    inliner,
28    options=None,
29    content=None,  # pylint: disable=unused-argument
30):
31    options = roles.normalized_role_options(options)
32    try:
33        bug = int(nodes.unescape(text))
34        if bug < 1:
35            raise ValueError
36    except ValueError:
37        msg = inliner.reporter.error(
38            'Bug number must be a number greater than or equal to 1; '
39            '"%s" is invalid.' % text,
40            line=lineno,
41        )
42        prb = inliner.problematic(rawtext, rawtext, msg)
43        return [prb], [msg]
44
45    ref = 'https://pwbug.dev/{:d}'.format(bug)
46    node = nodes.reference(rawtext, 'b/{:d}'.format(bug), refuri=ref, **options)
47    return [node], []
48
49
50def setup(app: Sphinx) -> dict[str, bool]:
51    app.add_role('bug', bug_role)
52    return {
53        'parallel_read_safe': True,
54        'parallel_write_safe': True,
55    }
56