Coverage for sphinx_reports/Sphinx.py: 21%

100 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-20 22:14 +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 _CreateTableHeader(self, columns: List[Tuple[str, Nullable[List[Tuple[str, int]]], Nullable[int]]], identifier: str, classes: List[str]) -> Tuple[nodes.table, nodes.tgroup]: 

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

135 

136 hasSecondHeaderRow = False 

137 columnCount = 0 

138 for groupColumn in columns: 

139 if groupColumn[1] is not None: 

140 columnCount += len(groupColumn[1]) 

141 hasSecondHeaderRow = True 

142 else: 

143 columnCount += 1 

144 

145 tableGroup = nodes.tgroup(cols=columnCount) 

146 table += tableGroup 

147 

148 # Setup column specifications 

149 for _, more, width in columns: 

150 if more is None: 

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

152 else: 

153 for _, width in more: 

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

155 

156 # Setup primary header row 

157 headerRow = nodes.row() 

158 for columnTitle, more, _ in columns: 

159 if more is None: 

160 headerRow += nodes.entry("", nodes.paragraph(text=columnTitle), morerows=1) 

161 else: 

162 morecols = len(more) - 1 

163 headerRow += nodes.entry("", nodes.paragraph(text=columnTitle), morecols=morecols) 

164 for i in range(morecols): 

165 headerRow += None 

166 

167 tableHeader = nodes.thead("", headerRow) 

168 tableGroup += tableHeader 

169 

170 # If present, setup secondary header row 

171 if hasSecondHeaderRow: 

172 tableRow = nodes.row() 

173 for columnTitle, more, _ in columns: 

174 if more is None: 

175 tableRow += None 

176 else: 

177 for columnTitle, _ in more: 

178 tableRow += nodes.entry("", nodes.paragraph(text=columnTitle)) 

179 

180 tableHeader += tableRow 

181 

182 return table, tableGroup 

183 

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

185 logger = getLogger(location) 

186 logger.error(f"{message}\n {exception}") 

187 

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

189 

190 return [container]