Coverage for trlcdoc/sphinx_links.py: 99%

75 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-28 14:00 +0000

1"""Sphinx extension resolving the relative links and images of Markdown pages against the project. 

2 

3A Markdown document is copied into the Sphinx source folder, so its relative 

4links and images would point into that folder instead of the project. This 

5extension resolves them against the location of the Markdown file in the project: 

6 

7- an image is taken from the project, Sphinx copies it into the site 

8- a link to a file of a site page links to that page 

9- a link to any other project file or folder links to the repository at the built commit 

10- without a repository, such a link is shown as text with a warning 

11 

12Links to targets which do not exist in the project are left to MyST, which reports them. 

13 

14The settings are provided by trlcdoc in the configuration value 'trlcdoc_links'. 

15 

16""" 

17 

18# trlcdoc - A utility for producing project documentation from TRLC and LOBSTER contents. 

19# Copyright (c) 2026 - 2026 Norbert Schulz github@schulznorbert.de 

20# 

21# This file is part of trlcdoc program. 

22# 

23# The trlcdoc program is free software: you can redistribute it and/or modify it under 

24# the terms of the GNU General Public License as published by the Free Software Foundation, 

25# either version 3 of the License, or (at your option) any later version. 

26# 

27# The trlcdoc program is distributed in the hope that it will be useful, but 

28# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 

29# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 

30# 

31# You should have received a copy of the GNU General Public License along with pyTRLCConverter. 

32# If not, see <https://www.gnu.org/licenses/>. 

33 

34# Imports ********************************************************************** 

35 

36import os 

37import posixpath 

38import re 

39from pathlib import Path 

40from typing import Any 

41from urllib.parse import quote 

42 

43from docutils import nodes 

44from sphinx import addnodes 

45from sphinx.application import Sphinx 

46from sphinx.transforms import SphinxTransform 

47from sphinx.transforms.post_transforms import SphinxPostTransform 

48from sphinx.util import logging 

49 

50# Variables ******************************************************************** 

51 

52LOGGER = logging.getLogger(__name__) 

53 

54# Name of the configuration value with the link settings written by trlcdoc. 

55CONFIG_NAME = "trlcdoc_links" 

56 

57# Matches URLs with a scheme, e.g. https:, mailto: or data:. 

58URL_SCHEME = re.compile(r"^[a-zA-Z][a-zA-Z0-9+.-]*:") 

59 

60# Classes ********************************************************************** 

61 

62 

63class MarkdownImages(SphinxTransform): 

64 # lobster-trace: SwRequirements.sw_req_markdown_links 

65 """Take the relative images of Markdown pages from the project, while the page is read.""" 

66 

67 default_priority = 400 

68 

69 def apply(self, **kwargs: Any) -> None: 

70 """Replace the image paths of a Markdown page by the paths of the project files. 

71 

72 Args: 

73 **kwargs (Any): Unused transform arguments. 

74 """ 

75 settings = self.config[CONFIG_NAME] 

76 source = settings.get("markdown_sources", {}).get(self.env.docname) 

77 if source is not None: 

78 page_dir = Path(self.env.srcdir) / posixpath.dirname(self.env.docname) 

79 for image in self.document.findall(nodes.image): 

80 project_path = _project_path(settings, source, image["uri"]) 

81 project_file = Path(settings["root"]) / project_path if project_path is not None else None 

82 if project_file is not None and project_file.is_file() and not (page_dir / image["uri"]).exists(): 

83 image["uri"] = Path(os.path.relpath(project_file, page_dir)).as_posix() 

84 

85 

86class MarkdownLinks(SphinxPostTransform): 

87 # lobster-trace: SwRequirements.sw_req_markdown_links 

88 """Resolve the relative links of Markdown pages, which MyST could not resolve in the Sphinx source folder.""" 

89 

90 # Before the MyST reference resolver (9), which resolves the page links and reports the unresolved links. 

91 default_priority = 8 

92 

93 def run(self, **kwargs: Any) -> None: 

94 """Replace the unresolved links to project files by page links, repository links or text. 

95 

96 Args: 

97 **kwargs (Any): Unused transform arguments. 

98 """ 

99 settings = self.config[CONFIG_NAME] 

100 source = settings.get("markdown_sources", {}).get(self.env.docname) 

101 if source is not None: 

102 for xref in list(self.document.findall(addnodes.pending_xref)): 

103 if xref.get("reftype") == "myst" and xref.get("refdomain") is None: 

104 self._resolve(settings, source, xref) 

105 

106 def _resolve(self, settings: dict[str, Any], source: str, xref: addnodes.pending_xref) -> None: 

107 """Replace a link to a project file or folder, leave other links to MyST. 

108 

109 Args: 

110 settings (dict[str, Any]): The link settings. 

111 source (str): The Markdown file of the page, relative to the project root. 

112 xref (addnodes.pending_xref): The unresolved link. 

113 """ 

114 target, _, anchor = xref["reftarget"].partition("#") 

115 project_path = _project_path(settings, source, target) 

116 if project_path is not None and (Path(settings["root"]) / project_path).exists(): 

117 path = project_path.as_posix() 

118 page = settings.get("pages", {}).get(path) 

119 if page is not None: 

120 # A document link as MyST creates it for found documents, resolved by the MyST resolver. 

121 xref["refdomain"] = "doc" 

122 xref["reftarget"] = page 

123 xref["reftargetid"] = anchor or None 

124 elif settings.get("repository") and settings.get("commit"): 

125 kind = "tree" if (Path(settings["root"]) / project_path).is_dir() else "blob" 

126 fragment = f"#{anchor}" if anchor else "" 

127 repository_path = posixpath.normpath(posixpath.join(settings.get("repository_path", "."), path)) 

128 uri = f"{settings['repository']}/{kind}/{settings['commit']}/{quote(repository_path)}{fragment}" 

129 xref.replace_self(nodes.reference("", "", *_link_content(xref, target), internal=False, refuri=uri)) 

130 else: 

131 LOGGER.warning( 

132 "Link to project file '%s' shown as text, no repository for the link.", 

133 path, 

134 location=xref, 

135 type="trlcdoc", 

136 subtype="link", 

137 ) 

138 xref.replace_self(nodes.inline("", "", *_link_content(xref, target))) 

139 

140 

141# Functions ******************************************************************** 

142 

143 

144def _link_content(xref: addnodes.pending_xref, target: str) -> list[nodes.Node]: 

145 # lobster-trace: SwRequirements.sw_req_markdown_links 

146 """Get the content of a link without the MyST cross-reference wrapper. 

147 

148 Args: 

149 xref (addnodes.pending_xref): The link. 

150 target (str): The link target, the content of a link without text. 

151 

152 Returns: 

153 list[nodes.Node]: The link text nodes. 

154 """ 

155 content: list[nodes.Node] = [nodes.literal(target, target)] 

156 if xref.astext(): 

157 content = [] 

158 for child in xref.children: 

159 if isinstance(child, nodes.inline) and "xref" in child["classes"]: 

160 content.extend(child.children) 

161 else: 

162 content.append(child) 

163 return content 

164 

165 

166def _project_path(settings: dict[str, Any], source: str, target: str) -> Path | None: 

167 # lobster-trace: SwRequirements.sw_req_markdown_links 

168 """Resolve a relative link target of a Markdown file against its location in the project. 

169 

170 Args: 

171 settings (dict[str, Any]): The link settings. 

172 source (str): The Markdown file, relative to the project root. 

173 target (str): The link target, relative to the Markdown file. 

174 

175 Returns: 

176 Path | None: The target relative to the project root, or None for URLs, absolute 

177 paths and targets outside of the project. 

178 """ 

179 result = None 

180 if target and not target.startswith("/") and URL_SCHEME.match(target) is None: 

181 path = posixpath.normpath(posixpath.join(posixpath.dirname(source), target)) 

182 if path != ".." and not path.startswith("../") and settings.get("root"): 

183 result = Path(path) 

184 return result 

185 

186 

187def setup(app: Sphinx) -> dict[str, Any]: 

188 # lobster-trace: SwRequirements.sw_req_markdown_links 

189 """Register the configuration value and the transforms. 

190 

191 Args: 

192 app (Sphinx): The Sphinx application. 

193 

194 Returns: 

195 dict[str, Any]: The extension metadata. 

196 """ 

197 app.add_config_value(CONFIG_NAME, {}, "env") 

198 app.add_transform(MarkdownImages) 

199 app.add_post_transform(MarkdownLinks) 

200 return {"parallel_read_safe": True, "parallel_write_safe": True} 

201 

202 

203# Main *************************************************************************