Coverage for pyTooling/Documentation/Sphinx/__init__.py: 98%

73 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-10-03 23:02 +0000

1# ==================================================================================================================== # 

2# _____ _ _ ____ _ _ _ # 

3# _ __ _ |_ _|__ ___ | (_)_ __ __ _ | _ \ ___ ___ _ _ _ __ ___ ___ _ __ | |_ __ _| |_(_) ___ _ __ # 

4# | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` | | | | |/ _ \ / __| | | | '_ ` _ \ / _ \ '_ \| __/ _` | __| |/ _ \| '_ \ # 

5# | |_) | |_| || | (_) | (_) | | | | | | (_| |_| |_| | (_) | (__| |_| | | | | | | __/ | | | || (_| | |_| | (_) | | | |# 

6# | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)____/ \___/ \___|\__,_|_| |_| |_|\___|_| |_|\__\__,_|\__|_|\___/|_| |_|# 

7# |_| |___/ |___/ # 

8# ==================================================================================================================== # 

9# Authors: # 

10# Patrick Lehmann # 

11# # 

12# License: # 

13# ==================================================================================================================== # 

14# Copyright 2026-2026 Patrick Lehmann - Bötzingen, Germany # 

15# # 

16# Licensed under the Apache License, Version 2.0 (the "License"); # 

17# you may not use this file except in compliance with the License. # 

18# You may obtain a copy of the License at # 

19# # 

20# http://www.apache.org/licenses/LICENSE-2.0 # 

21# # 

22# Unless required by applicable law or agreed to in writing, software # 

23# distributed under the License is distributed on an "AS IS" BASIS, # 

24# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # 

25# See the License for the specific language governing permissions and # 

26# limitations under the License. # 

27# # 

28# SPDX-License-Identifier: Apache-2.0 # 

29# ==================================================================================================================== # 

30# 

31""" 

32A Sphinx extension providing the roles, nodes and directives shared by pyTooling and its sibling projects. 

33 

34Every project in the family used to carry its own :file:`doc/prolog.inc` - eighteen hand-copied files, 36 to 67 

35lines each, already drifted apart - declaring the same roles as **ReST source** that is re-parsed into every 

36document of every project. This extension declares them once: 

37 

38.. code-block:: Python 

39 

40 # doc/conf.py 

41 extensions = [ 

42 ..., 

43 "pyTooling.Documentation.Sphinx", 

44 ] 

45 

46.. rubric:: What it registers 

47 

48* the **style roles**, together with the stylesheet they need - so the styling is a CSS file instead of a 

49 ``raw:: html`` block smuggled into every page: 

50 

51 * ``:bolditalic:``, ``:underline:``, ``:strike:`` and ``:xlarge:`` - weight, decoration and size; 

52 * ``:red:``, ``:green:``, ``:blue:`` and ``:purple:`` - colour, each from a CSS custom property a project can 

53 redefine; 

54 * ``:deletion:`` and ``:addition:`` - the two a diff needs. 

55 

56* the **code role**: 

57 

58 * ``:pycode:`` - highlights inline Python. 

59 

60* the **directives**: 

61 

62 * :rst:dir:`condensed-class` - renders a class' public interface from its source; 

63 * :rst:dir:`dependency-table` - renders a project's dependencies from its requirements files, which 

64 :file:`conf.py` declares under ``pyTooling_Dependency_Requirements``; 

65 * :rst:dir:`xsd-graph` - draws an XML schema as a Graphviz graph. It sets up :mod:`sphinx.ext.graphviz` 

66 itself, and needs :mod:`xmlschema` only in a project that uses it. 

67 * :rst:dir:`shields` - renders a project's badges from shields.io, in rows, from the coordinates its options 

68 state: the GitHub repository, the PyPI package, the licenses, the workflow and the documentation's URL. 

69 

70* the **domain** ``gha`` - documents GitHub Actions workflows, taking an input's type, requirement and default from the 

71 workflow file; see :mod:`pyTooling.Documentation.Sphinx.GitHubActions`. 

72 

73Two classes aren't registered, because they are base-classes for a project's own directives: 

74:class:`~pyTooling.Documentation.Sphinx.Directives.BaseDirective` offers typed option access and table construction 

75over the untyped mapping and the hand-assembled node trees docutils presents, and 

76:class:`~pyTooling.Documentation.Sphinx.SchemaGraph.SchemaGraph` draws a schema file named as a directive's 

77argument, leaving only the reading of that schema to a derived class. 

78 

79.. attention:: 

80 

81 This package imports Sphinx and docutils, which :mod:`pyTooling` itself does not depend on. Install it as 

82 ``pyTooling[sphinx]``, or rely on Sphinx already being present - which it is, wherever a :file:`conf.py` is 

83 being executed. 

84 

85 ``pyTooling[sphinx]`` requires **Python 3.12 or newer**, because it requires Sphinx 9.1 and Sphinx 9.1 does. 

86 The rest of :mod:`pyTooling` still supports Python 3.11. 

87 

88:raises MissingDependencyError: If the 'sphinx' extra isn't installed. 

89 

90.. seealso:: 

91 

92 :mod:`pyTooling.Documentation` 

93 |rarr| The doc-string helpers, which need no Sphinx. 

94""" 

95from hashlib import md5 

96from pathlib import Path 

97from typing import Any 

98 

99from pyTooling.Common import __version__, readResourceFile 

100from pyTooling.Decorators import export 

101from pyTooling.Exceptions import MissingDependencyError 

102from pyTooling.Resources import Sphinx as SphinxResources 

103 

104try: 

105 from sphinx.application import Sphinx 

106except ImportError as ex: # pragma: no cover 

107 raise MissingDependencyError(dependency="sphinx", extra="sphinx") from ex 

108 

109from pyTooling.Documentation.Sphinx.CondensedClass import CondensedClass 

110from pyTooling.Documentation.Sphinx.DependencyTable import CONFIG_PREFIX, DependencyTable 

111from pyTooling.Documentation.Sphinx.DependencyTable import prepareEntrypoints, reportBuildTime 

112from pyTooling.Documentation.Sphinx.Directives import BaseDirective, SphinxExtensionError, strip 

113from pyTooling.Documentation.Sphinx.Directives import stripAndNormalize 

114from pyTooling.Documentation.Sphinx.GitHubActions import GitHubActionsDomain 

115from pyTooling.Documentation.Sphinx.GitHubActions.Graph import PipelineGraph, resolveLinks 

116from pyTooling.Documentation.Sphinx.GitHubActions.Reference import AutoInputs, Dependencies, Interface, ParameterTable 

117from pyTooling.Documentation.Sphinx.GitHubActions.Reference import YAMLExcerpt 

118from pyTooling.Documentation.Sphinx.GitHubActions.Reference import checkUndocumentedInputs 

119from pyTooling.Documentation.Sphinx.SchemaGraph import SchemaGraph 

120from pyTooling.Documentation.Sphinx.Roles import BREAK_ROLES, PYTHON_CODE_ROLE, STYLE_ROLES 

121from pyTooling.Documentation.Sphinx.Roles import breakRole, pythonCodeRole, styleRole 

122from pyTooling.Documentation.Sphinx.Shields import Shields 

123from pyTooling.Documentation.Sphinx.XSDSchemaGraph import XSDSchemaGraph 

124 

125 

126__all__ = ["STYLESHEET", "SUBSTITUTIONS"] 

127 

128#: Name of the stylesheet, in :mod:`pyTooling.Resources.Sphinx`. 

129STYLESHEET = "pyTooling.css" 

130 

131#: Substitutions that have to stay substitutions, because ``|br|`` is written as one in every project. 

132#: 

133#: ``|br|`` and ``|hr|`` delegate to the ``:br:`` and ``:hr:`` roles rather than writing HTML themselves, so they 

134#: reach every output format instead of only HTML - see :func:`~pyTooling.Documentation.Sphinx.Roles.breakRole`. 

135SUBSTITUTIONS = """ 

136.. |degree| unicode:: U+00B0 

137 :trim: 

138 

139.. |br| replace:: :br:`.` 

140 

141.. |hr| replace:: :hr:`.` 

142""" 

143 

144 

145@export 

146def installStylesheet(sphinx: Sphinx) -> None: 

147 """ 

148 Call-back for Sphinx' ``builder-inited`` event, writing the stylesheet into the build and linking it. 

149 

150 The file is named by the hash of its content, so a browser re-reads it when the styles change and re-uses it when 

151 they don't. Older copies are removed when the content changed. 

152 

153 :param sphinx: The Sphinx application. 

154 """ 

155 staticDirectory = (Path(sphinx.outdir) / "_pyTooling_static").resolve() 

156 staticDirectory.mkdir(exist_ok=True) 

157 sphinx.config.html_static_path.append(str(staticDirectory)) 

158 

159 content = readResourceFile(SphinxResources, STYLESHEET) 

160 digest = md5(content.encode("utf-8")).hexdigest() # nosec B324 - a cache-busting name, not a signature 

161 stylesheet = staticDirectory / f"pyTooling.{digest}.css" 

162 sphinx.add_css_file(stylesheet.name) 

163 

164 if not stylesheet.exists(): 

165 # Only this package's own copies - the directory is on 'html_static_path', so another extension may 

166 # have written its stylesheet beside ours. 

167 for outdated in staticDirectory.glob("pyTooling.*.css"): 167 ↛ 168line 167 didn't jump to line 168 because the loop on line 167 never started

168 outdated.unlink() 

169 

170 stylesheet.write_text(content, encoding="utf-8") 

171 

172 

173@export 

174def extendProlog(sphinx: Sphinx, config: Any) -> None: 

175 """ 

176 Call-back for Sphinx' ``config-inited`` event, appending the shared substitutions to ``rst_prolog``. 

177 

178 A role can be registered; a **substitution** cannot - ``|br|`` is substitution syntax, and every project writes 

179 it that way already. Appending them here is what lets a project delete them from its own prolog without changing 

180 a single document. 

181 

182 :param sphinx: The Sphinx application. 

183 :param config: The configuration, after :file:`conf.py` was read. 

184 """ 

185 config.rst_prolog = (config.rst_prolog or "") + SUBSTITUTIONS 

186 

187 

188@export 

189def setup(sphinx: Sphinx) -> dict[str, Any]: 

190 """ 

191 Register the roles, the node and the directives with Sphinx. 

192 

193 :param sphinx: The Sphinx application to register with. 

194 :returns: The extension's metadata. 

195 """ 

196 for roleName in STYLE_ROLES: 

197 sphinx.add_role(roleName, styleRole) 

198 

199 for roleName in BREAK_ROLES: 

200 sphinx.add_role(roleName, breakRole) 

201 

202 sphinx.add_role(PYTHON_CODE_ROLE, pythonCodeRole) 

203 

204 sphinx.add_directive("condensed-class", CondensedClass) 

205 sphinx.add_directive("dependency-table", DependencyTable) 

206 sphinx.add_directive("xsd-graph", XSDSchemaGraph) 

207 sphinx.add_directive("shields", Shields) 

208 

209 sphinx.add_domain(GitHubActionsDomain) 

210 sphinx.add_directive_to_domain("gha", "pipeline-graph", PipelineGraph) 

211 sphinx.add_directive_to_domain("gha", "parameter-table", ParameterTable) 

212 sphinx.add_directive_to_domain("gha", "interface", Interface) 

213 sphinx.add_directive_to_domain("gha", "dependencies", Dependencies) 

214 sphinx.add_directive_to_domain("gha", "yaml", YAMLExcerpt) 

215 sphinx.add_directive_to_domain("gha", "autoinputs", AutoInputs) 

216 

217 sphinx.setup_extension("sphinx.ext.graphviz") 

218 

219 for configName, (default, rebuild, types) in DependencyTable.configValues.items(): 

220 sphinx.add_config_value(f"{CONFIG_PREFIX}_{configName}", default, rebuild, types) 

221 

222 for configName, (default, rebuild, types) in GitHubActionsDomain.configValues.items(): 

223 sphinx.add_config_value(f"{GitHubActionsDomain.name}_{configName}", default, rebuild, types) 

224 

225 sphinx.connect("config-inited", extendProlog) 

226 # after the configuration values above are registered, and before any document is read - a requirements file 

227 # that doesn't exist should end the build here rather than in the middle of a page 

228 sphinx.connect("config-inited", prepareEntrypoints) 

229 sphinx.connect("build-finished", reportBuildTime) 

230 sphinx.connect("doctree-read", checkUndocumentedInputs) 

231 sphinx.connect("doctree-resolved", resolveLinks) 

232 sphinx.connect("builder-inited", installStylesheet) 

233 

234 # The extension's version is the package's - it ships with pyTooling and is released with it, so a second 

235 # number to keep in step would only ever disagree. 

236 return {"version": __version__, "parallel_read_safe": True, "parallel_write_safe": True}