Debian Codegraph @

src/pydata_sphinx_theme/short_link.py

raw
1 """A custom Transform object to shorten github and gitlab links."""
2
3 from typing import ClassVar
4 from urllib.parse import ParseResult, urlparse, urlunparse
5
6 from docutils import nodes
7 from sphinx.transforms.post_transforms import SphinxPostTransform
8 from sphinx.util.nodes import NodeMatcher
9
10 from .utils import traverse_or_findall
11
12
13 class ShortenLinkTransform(SphinxPostTransform):
14 """
15 Shorten link when they are coming from github or gitlab and add an extra class to
16 the tag for further styling.
17
18 Before:
19 .. code-block:: html
20
21 <a class="reference external"
22 href="https://github.com/2i2c-org/infrastructure/issues/1329">
23 https://github.com/2i2c-org/infrastructure/issues/1329
24 </a>
25
26 After:
27 .. code-block:: html
28
29 <a class="reference external github"
30 href="https://github.com/2i2c-org/infrastructure/issues/1329">
31 2i2c-org/infrastructure#1329
32 </a>
33 """
34
35 default_priority = 400
36 formats = ("html",)
37 supported_platform: ClassVar[dict[str, str]] = {
38 "github.com": "github",
39 "gitlab.com": "gitlab",
40 }
41 platform = None
42
43 def run(self, **kwargs):
44 """Run the Transform object."""
45 matcher = NodeMatcher(nodes.reference)
46 # TODO: just use "findall" once docutils min version >=0.18.1
47 for node in traverse_or_findall(self.document, matcher):
48 uri = node.attributes.get("refuri")
49 text = next(iter(node.children), None)
50 # only act if the uri and text are the same
51 # if not the user has already customized the display of the link
52 if uri is not None and text is not None and text == uri:
53 uri = urlparse(uri)
54 # only do something if the platform is identified
55 self.platform = self.supported_platform.get(uri.netloc)
56 if self.platform is not None:
57 node.attributes["classes"].append(self.platform)
58 node.children[0] = nodes.Text(self.parse_url(uri))
59
60 def parse_url(self, uri: ParseResult) -> str:
61 """Parse the content of the url with respect to the selected platform.
62
63 Args:
64 uri: the link to the platform content
65
66 Returns:
67 the reformated url title
68 """
69 path = uri.path
70 if path == "":
71 # plain url passed, return platform only
72 return self.platform
73
74 # if the path is not empty it contains a leading "/", which we don't want to
75 # include in the parsed content
76 path = path.lstrip("/")
77
78 # check the platform name and read the information accordingly
79 # as "<organisation>/<repository>#<element number>"
80 # or "<group>/<subgroup 1>/…/<subgroup N>/<repository>#<element number>"
81 if self.platform == "github":
82 # split the url content
83 parts = path.split("/")
84
85 if parts[0] == "orgs" and "/projects" in path:
86 # We have a projects board link
87 # ref: `orgs/{org}/projects/{project-id}`
88 text = f"{parts[1]}/projects#{parts[3]}"
89 else:
90 # We have an issues, PRs, or repository link
91 if len(parts) > 0:
92 text = parts[0] # organisation
93 if len(parts) > 1:
94 text += f"/{parts[1]}" # repository
95 if len(parts) > 2:
96 if parts[2] in ["issues", "pull", "discussions"]:
97 text += f"#{parts[-1]}" # element number
98
99 elif self.platform == "gitlab":
100 # cp. https://docs.gitlab.com/ee/user/markdown.html#gitlab-specific-references
101 if "/-/" in path and any(
102 map(uri.path.__contains__, ["issues", "merge_requests"])
103 ):
104 group_and_subgroups, parts, *_ = path.split("/-/")
105 parts = parts.rstrip("/")
106 if "/" not in parts:
107 text = f"{group_and_subgroups}/{parts}"
108 else:
109 parts = parts.split("/")
110 url_type, element_number, *_ = parts
111 if not element_number:
112 text = group_and_subgroups
113 elif url_type == "issues":
114 text = f"{group_and_subgroups}#{element_number}"
115 elif url_type == "merge_requests":
116 text = f"{group_and_subgroups}!{element_number}"
117 else:
118 # display the whole uri (after "gitlab.com/") including parameters
119 # for example "<group>/<subgroup1>/<subgroup2>/<repository>"
120 text = uri._replace(netloc="", scheme="") # remove platform
121 text = urlunparse(text)[1:] # combine to string and strip leading "/"
122
123 return text