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
« 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
37from docutils import nodes
38from sphinx.directives import ObjectDescription
39from pyTooling.Decorators import export
40from sphinx.util.logging import getLogger
42from sphinx_reports.Common import ReportExtensionError, LegendStyle
45@export
46def strip(option: str) -> str:
47 return option.strip()
50@export
51def stripAndNormalize(option: str) -> str:
52 return option.strip().lower()
55@export
56class BaseDirective(ObjectDescription):
57 has_content: bool = False
58 """
59 A boolean; ``True`` if content is allowed.
61 Client code must handle the case where content is required but not supplied (an empty content list will be supplied).
62 """
64 required_arguments = 0
65 """Number of required directive arguments."""
67 optional_arguments = 0
68 """Number of optional arguments after the required arguments."""
70 final_argument_whitespace = False
71 """A boolean, indicating if the final argument may contain whitespace."""
73 option_spec = {}
74 """
75 Mapping of option names to validator functions.
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.
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 """
85 directiveName: str
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
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).")
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
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}'.")
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
126 identifier = option.lower().replace("-", "_")
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
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))))
137 # Setup column specifications
138 for _, width in columns:
139 tableGroup += nodes.colspec(colwidth=width)
141 tableGroup += (tableHeader := nodes.thead())
142 tableHeader += (headerRow := nodes.row())
144 # Setup header row
145 for columnTitle, _ in columns:
146 headerRow += nodes.entry("", nodes.Text(columnTitle))
148 return tableGroup
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)
153 # Create table with N columns
154 table = nodes.table("", identifier=identifier, classes=classes)
155 table += (tableGroup := nodes.tgroup(cols=columnCount))
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())
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
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))
185 return tableGroup
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)))
191 # Setup column specifications
192 for i, (_, width) in enumerate(columns):
193 tableGroup += nodes.colspec(classes=[f"col-{i}"])
195 tableGroup += (tableHeader := nodes.thead())
196 tableHeader += (headerRow := nodes.row())
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)
204 return tableGroup
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)
214 container += nodes.paragraph(text=message)
216 return [container]