Coverage for sphinx_reports/Sphinx.py: 20%

97 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-05-09 22:12 +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().lower() 

48 

49 

50@export 

51class BaseDirective(ObjectDescription): 

52 has_content: bool = False 

53 """ 

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

55 

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

57 """ 

58 

59 required_arguments = 0 

60 """Number of required directive arguments.""" 

61 

62 optional_arguments = 0 

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

64 

65 final_argument_whitespace = False 

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

67 

68 option_spec = {} 

69 """ 

70 Mapping of option names to validator functions. 

71 

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

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

74 

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

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

77 :exc:`TypeError` exceptions. 

78 """ 

79 

80 directiveName: str 

81 

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

83 try: 

84 option = self.options[optionName] 

85 except KeyError as ex: 

86 if default is not None: 

87 return default 

88 else: 

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

90 

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

92 return True 

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

94 return False 

95 else: 

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

97 

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

99 try: 

100 option: str = self.options[optionName] 

101 except KeyError as ex: 

102 if default is not None: 

103 return default 

104 else: 

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

106 

107 if re_match(regexp, option): 

108 return option 

109 else: 

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

111 

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

113 try: 

114 option: str = self.options[optionName] 

115 except KeyError as ex: 

116 if default is not None: 

117 return default 

118 else: 

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

120 

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

122 

123 try: 

124 return LegendStyle[identifier] 

125 except KeyError as ex: 

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

127 

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

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

130 

131 hasSecondHeaderRow = False 

132 columnCount = 0 

133 for groupColumn in columns: 

134 if groupColumn[1] is not None: 

135 columnCount += len(groupColumn[1]) 

136 hasSecondHeaderRow = True 

137 else: 

138 columnCount += 1 

139 

140 tableGroup = nodes.tgroup(cols=columnCount) 

141 table += tableGroup 

142 

143 # Setup column specifications 

144 for _, more, width in columns: 

145 if more is None: 

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

147 else: 

148 for _, width in more: 

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

150 

151 # Setup primary header row 

152 headerRow = nodes.row() 

153 for columnTitle, more, _ in columns: 

154 if more is None: 

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

156 else: 

157 morecols = len(more) - 1 

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

159 for i in range(morecols): 

160 headerRow += None 

161 

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

163 tableGroup += tableHeader 

164 

165 # If present, setup secondary header row 

166 if hasSecondHeaderRow: 

167 tableRow = nodes.row() 

168 for columnTitle, more, _ in columns: 

169 if more is None: 

170 tableRow += None 

171 else: 

172 for columnTitle, _ in more: 

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

174 

175 tableHeader += tableRow 

176 

177 return table, tableGroup 

178 

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

180 logger = getLogger(location) 

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

182 

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

184 

185 return [container]