Coverage for sphinx_reports/Sphinx.py: 20%

115 statements  

« prev     ^ index     » next       coverage.py v7.11.1, created at 2025-11-07 22:13 +0000

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

2# _ _ _ # 

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

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

5# \__ \ |_) | | | | | | | |> <_____| | | __/ |_) | (_) | | | |_\__ \ # 

6# |___/ .__/|_| |_|_|_| |_/_/\_\ |_| \___| .__/ \___/|_| \__|___/ # 

7# |_| |_| # 

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

9# Authors: # 

10# Patrick Lehmann # 

11# # 

12# License: # 

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

14# Copyright 2023-2025 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""" 

32**Helper functions and derived classes from Sphinx.** 

33""" 

34from re import match as re_match 

35from typing import Optional as Nullable, Tuple, List 

36 

37from docutils import nodes 

38from sphinx.directives import ObjectDescription 

39from pyTooling.Decorators import export 

40from sphinx.util.logging import getLogger 

41 

42from sphinx_reports.Common import ReportExtensionError, LegendStyle 

43 

44 

45@export 

46def strip(option: str) -> str: 

47 return option.strip() 

48 

49 

50@export 

51def stripAndNormalize(option: str) -> str: 

52 return option.strip().lower() 

53 

54 

55@export 

56class BaseDirective(ObjectDescription): 

57 has_content: bool = False 

58 """ 

59 A boolean; ``True`` if content is allowed. 

60 

61 Client code must handle the case where content is required but not supplied (an empty content list will be supplied). 

62 """ 

63 

64 required_arguments = 0 

65 """Number of required directive arguments.""" 

66 

67 optional_arguments = 0 

68 """Number of optional arguments after the required arguments.""" 

69 

70 final_argument_whitespace = False 

71 """A boolean, indicating if the final argument may contain whitespace.""" 

72 

73 option_spec = {} 

74 """ 

75 Mapping of option names to validator functions. 

76 

77 A dictionary, mapping known option names to conversion functions such as :class:`int` or :class:`float` 

78 (default: {}, no options). Several conversion functions are defined in the ``directives/__init__.py`` module. 

79 

80 Option conversion functions take a single parameter, the option argument (a string or :class:`None`), validate it 

81 and/or convert it to the appropriate form. Conversion functions may raise :exc:`ValueError` and 

82 :exc:`TypeError` exceptions. 

83 """ 

84 

85 directiveName: str 

86 

87 def _ParseBooleanOption(self, optionName: str, default: Nullable[bool] = None) -> bool: 

88 try: 

89 option = self.options[optionName] 

90 except KeyError as ex: 

91 if default is not None: 

92 return default 

93 else: 

94 raise ReportExtensionError(f"{self.directiveName}: Required option '{optionName}' not found for directive.") from ex 

95 

96 if option in ("yes", "true"): 

97 return True 

98 elif option in ("no", "false"): 

99 return False 

100 else: 

101 raise ReportExtensionError(f"{self.directiveName}::{optionName}: '{option}' not supported for a boolean value (yes/true, no/false).") 

102 

103 def _ParseStringOption(self, optionName: str, default: Nullable[str] = None, regexp: str = "\\w+") -> str: 

104 try: 

105 option: str = self.options[optionName] 

106 except KeyError as ex: 

107 if default is not None: 

108 return default 

109 else: 

110 raise ReportExtensionError(f"{self.directiveName}: Required option '{optionName}' not found for directive.") from ex 

111 

112 if re_match(regexp, option): 

113 return option 

114 else: 

115 raise ReportExtensionError(f"{self.directiveName}::{optionName}: '{option}' not an accepted value for regexp '{regexp}'.") 

116 

117 def _ParseLegendStyle(self, optionName: str, default: Nullable[LegendStyle] = None) -> LegendStyle: 

118 try: 

119 option: str = self.options[optionName] 

120 except KeyError as ex: 

121 if default is not None: 

122 return default 

123 else: 

124 raise ReportExtensionError(f"{self.directiveName}: Required option '{optionName}' not found for directive.") from ex 

125 

126 identifier = option.lower().replace("-", "_") 

127 

128 try: 

129 return LegendStyle[identifier] 

130 except KeyError as ex: 

131 raise ReportExtensionError(f"{self.directiveName}::{optionName}: Value '{option}' (transformed: '{identifier}') is not a valid member of 'LegendStyle'.") from ex 

132 

133 def _CreateSingleTableHeader(self, columns: List[Tuple[str, Nullable[int]]], identifier: str, classes: List[str]) -> nodes.tgroup: 

134 table = nodes.table("", identifier=identifier, classes=classes) 

135 table += (tableGroup := nodes.tgroup(cols=(len(columns)))) 

136 

137 # Setup column specifications 

138 for _, width in columns: 

139 tableGroup += nodes.colspec(colwidth=width) 

140 

141 tableGroup += (tableHeader := nodes.thead()) 

142 tableHeader += (headerRow := nodes.row()) 

143 

144 # Setup header row 

145 for columnTitle, _ in columns: 

146 headerRow += nodes.entry("", nodes.Text(columnTitle)) 

147 

148 return tableGroup 

149 

150 def _CreateDoubleRowTableHeader(self, columns: List[Tuple[str, Nullable[List[Tuple[str, int]]], Nullable[int]]], identifier: str, classes: List[str]) -> Tuple[nodes.table, nodes.tgroup]: 

151 columnCount = sum(len(groupColumn[1]) if groupColumn[1] is not None else 1 for groupColumn in columns) 

152 

153 # Create table with N columns 

154 table = nodes.table("", identifier=identifier, classes=classes) 

155 table += (tableGroup := nodes.tgroup(cols=columnCount)) 

156 

157 # Setup column specifications 

158 for _, more, width in columns: 

159 if more is None: 

160 tableGroup += nodes.colspec(colwidth=width) 

161 else: 

162 for _, width in more: 

163 tableGroup += nodes.colspec(colwidth=width) 

164 tableGroup += (tableHeader := nodes.thead()) 

165 tableHeader += (headerRow1 := nodes.row()) 

166 

167 # Setup primary header row 

168 for columnTitle, more, _ in columns: 

169 if more is None: 

170 headerRow1 += nodes.entry("", nodes.Text(columnTitle), morerows=1) 

171 else: 

172 headerRow1 += nodes.entry("", nodes.Text(columnTitle), morecols=(morecols := len(more) - 1)) 

173 for i in range(morecols): 

174 headerRow1 += None 

175 

176 # Setup secondary header row 

177 tableHeader += (headerRow2 := nodes.row()) 

178 for columnTitle, more, _ in columns: 

179 if more is None: 

180 headerRow2 += None 

181 else: 

182 for columnTitle, _ in more: 

183 headerRow2 += nodes.entry("", nodes.Text(columnTitle)) 

184 

185 return tableGroup 

186 

187 def _CreateRotatedTableHeader(self, columns: List[Tuple[str, Nullable[List[str]]]], identifier: str, classes: List[str]) -> nodes.tgroup: 

188 table = nodes.table("", identifier=identifier, classes=classes) 

189 table += (tableGroup := nodes.tgroup(cols=len(columns))) 

190 

191 # Setup column specifications 

192 for i, (_, width) in enumerate(columns): 

193 tableGroup += nodes.colspec(classes=[f"col-{i}"]) 

194 

195 tableGroup += (tableHeader := nodes.thead()) 

196 tableHeader += (headerRow := nodes.row()) 

197 

198 # Setup header row 

199 for columnTitle, classes in columns: 

200 span = nodes.inline("", text=columnTitle) 

201 div = nodes.container("", span) 

202 headerRow += nodes.entry("", div, classes=[] if classes is None else classes) 

203 

204 return tableGroup 

205 

206 def _internalError(self, container: nodes.container, location: str, message: str, exception: Exception) -> List[nodes.Node]: 

207 logger = getLogger(location) 

208 logger.error(f"{message}") 

209 logger.error(f" {exception.__class__.__name__}: {exception}") 

210 if exception.__cause__ is not None: 

211 logger.error(f" {exception.__cause__.__class__.__name__}: {exception.__cause__}") 

212 logger.exception(exception) 

213 

214 container += nodes.paragraph(text=message) 

215 

216 return [container]