1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
|
# ==================================================================================================================== #
# _ _ _ #
# ___ _ __ | |__ (_)_ __ __ __ _ __ ___ _ __ ___ _ __| |_ ___ #
# / __| '_ \| '_ \| | '_ \\ \/ /____| '__/ _ \ '_ \ / _ \| '__| __/ __| #
# \__ \ |_) | | | | | | | |> <_____| | | __/ |_) | (_) | | | |_\__ \ #
# |___/ .__/|_| |_|_|_| |_/_/\_\ |_| \___| .__/ \___/|_| \__|___/ #
# |_| |_| #
# ==================================================================================================================== #
# Authors: #
# Patrick Lehmann #
# #
# License: #
# ==================================================================================================================== #
# Copyright 2023-2024 Patrick Lehmann - Bötzingen, Germany #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
# #
# SPDX-License-Identifier: Apache-2.0 #
# ==================================================================================================================== #
#
"""
**Helper functions and derived classes from Sphinx.**
"""
from re import match as re_match
from typing import Optional as Nullable, Tuple, List
from docutils import nodes
from sphinx.directives import ObjectDescription
from pyTooling.Decorators import export
from sphinx.util.logging import getLogger
from sphinx_reports.Common import ReportExtensionError, LegendStyle
@export
def strip(option: str) -> str:
return option.strip().lower()
@export
class BaseDirective(ObjectDescription):
has_content: bool = False
"""
A boolean; ``True`` if content is allowed.
Client code must handle the case where content is required but not supplied (an empty content list will be supplied).
"""
required_arguments = 0
"""Number of required directive arguments."""
optional_arguments = 0
"""Number of optional arguments after the required arguments."""
final_argument_whitespace = False
"""A boolean, indicating if the final argument may contain whitespace."""
option_spec = {}
"""
Mapping of option names to validator functions.
A dictionary, mapping known option names to conversion functions such as :class:`int` or :class:`float`
(default: {}, no options). Several conversion functions are defined in the ``directives/__init__.py`` module.
Option conversion functions take a single parameter, the option argument (a string or :class:`None`), validate it
and/or convert it to the appropriate form. Conversion functions may raise :exc:`ValueError` and
:exc:`TypeError` exceptions.
"""
directiveName: str
def _ParseBooleanOption(self, optionName: str, default: Nullable[bool] = None) -> bool:
try:
option = self.options[optionName]
except KeyError as ex:
if default is not None:
return default
else:
raise ReportExtensionError(f"{self.directiveName}: Required option '{optionName}' not found for directive.") from ex
if option in ("yes", "true"):
return True
elif option in ("no", "false"):
return False
else:
raise ReportExtensionError(f"{self.directiveName}::{optionName}: '{option}' not supported for a boolean value (yes/true, no/false).")
def _ParseStringOption(self, optionName: str, default: Nullable[str] = None, regexp: str = "\\w+") -> str:
try:
option: str = self.options[optionName]
except KeyError as ex:
if default is not None:
return default
else:
raise ReportExtensionError(f"{self.directiveName}: Required option '{optionName}' not found for directive.") from ex
if re_match(regexp, option):
return option
else:
raise ReportExtensionError(f"{self.directiveName}::{optionName}: '{option}' not an accepted value for regexp '{regexp}'.")
def _ParseLegendStyle(self, optionName: str, default: Nullable[LegendStyle] = None) -> LegendStyle:
try:
option: str = self.options[optionName]
except KeyError as ex:
if default is not None:
return default
else:
raise ReportExtensionError(f"{self.directiveName}: Required option '{optionName}' not found for directive.") from ex
identifier = option.lower().replace("-", "_")
try:
return LegendStyle[identifier]
except KeyError as ex:
raise ReportExtensionError(f"{self.directiveName}::{optionName}: Value '{option}' (transformed: '{identifier}') is not a valid member of 'LegendStyle'.") from ex
def _CreateTableHeader(self, columns: List[Tuple[str, Nullable[List[Tuple[str, int]]], Nullable[int]]], identifier: str, classes: List[str]) -> Tuple[nodes.table, nodes.tgroup]:
table = nodes.table("", identifier=identifier, classes=classes)
hasSecondHeaderRow = False
columnCount = 0
for groupColumn in columns:
if groupColumn[1] is not None:
columnCount += len(groupColumn[1])
hasSecondHeaderRow = True
else:
columnCount += 1
tableGroup = nodes.tgroup(cols=columnCount)
table += tableGroup
# Setup column specifications
for _, more, width in columns:
if more is None:
tableGroup += nodes.colspec(colwidth=width)
else:
for _, width in more:
tableGroup += nodes.colspec(colwidth=width)
# Setup primary header row
headerRow = nodes.row()
for columnTitle, more, _ in columns:
if more is None:
headerRow += nodes.entry("", nodes.paragraph(text=columnTitle), morerows=1)
else:
morecols = len(more) - 1
headerRow += nodes.entry("", nodes.paragraph(text=columnTitle), morecols=morecols)
for i in range(morecols):
headerRow += None
tableHeader = nodes.thead("", headerRow)
tableGroup += tableHeader
# If present, setup secondary header row
if hasSecondHeaderRow:
tableRow = nodes.row()
for columnTitle, more, _ in columns:
if more is None:
tableRow += None
else:
for columnTitle, _ in more:
tableRow += nodes.entry("", nodes.paragraph(text=columnTitle))
tableHeader += tableRow
return table, tableGroup
def _internalError(self, container: nodes.container, location: str, message: str, exception: Exception) -> List[nodes.Node]:
logger = getLogger(location)
logger.error(f"{message}\n {exception}")
container += nodes.paragraph(text=message)
return [container]
|