0
# Core Utilities
1
2
Essential utilities, caching, and configuration management used throughout the sphinx-toolbox extension ecosystem. These foundational components provide common functionality shared across all extensions.
3
4
## Capabilities
5
6
### Utility Functions
7
8
Core utility functions for URL generation, validation, string processing, and common patterns used across extensions.
9
10
```python { .api }
11
def make_github_url(username: str, repository: str) -> RequestsURL:
12
"""
13
Create a GitHub URL from username and repository.
14
15
Args:
16
username: GitHub username or organization
17
repository: Repository name
18
19
Returns:
20
RequestsURL object for the GitHub repository
21
"""
22
23
def flag(argument: Any) -> bool:
24
"""
25
Validate flag options for Sphinx directives.
26
27
Args:
28
argument: Directive argument to validate
29
30
Returns:
31
Always True for flag directives
32
33
Raises:
34
ValueError: If argument is not None or empty string
35
"""
36
37
def get_first_matching(condition: Callable, iterable: Iterable, default: Any = None) -> Any:
38
"""
39
Return first item from iterable that matches condition.
40
41
Args:
42
condition: Function that returns True for matching items
43
iterable: Items to search through
44
default: Value to return if no match found
45
46
Returns:
47
First matching item or default value
48
"""
49
50
def escape_trailing__(string: str) -> str:
51
"""
52
Escape trailing underscores in strings for reStructuredText.
53
54
Args:
55
string: String that may have trailing underscores
56
57
Returns:
58
String with trailing underscores escaped
59
"""
60
61
def code_repr(obj: Any) -> str:
62
"""
63
Return object repr as reStructuredText inline code.
64
65
Args:
66
obj: Object to represent
67
68
Returns:
69
String formatted as RST inline code
70
"""
71
72
def sphinx_ext_metadata(version: str, parallel_read_safe: bool = True,
73
parallel_write_safe: bool = True) -> SphinxExtMetadata:
74
"""
75
Create SphinxExtMetadata dictionary.
76
77
Args:
78
version: Extension version
79
parallel_read_safe: Whether extension supports parallel reading
80
parallel_write_safe: Whether extension supports parallel writing
81
82
Returns:
83
SphinxExtMetadata dictionary
84
"""
85
```
86
87
### Logging and Warning Functions
88
89
Specialized logging functions for Sphinx extension development and debugging.
90
91
```python { .api }
92
def unknown_module_warning(documenter: Documenter) -> None:
93
"""
94
Log warning for unknown modules during autodoc processing.
95
96
Args:
97
documenter: Sphinx autodocumenter instance
98
"""
99
100
def filter_members_warning(member: Any, exception: Exception) -> None:
101
"""
102
Log warning when filtering autodoc members fails.
103
104
Args:
105
member: Member being filtered
106
exception: Exception that occurred during filtering
107
"""
108
```
109
110
### Parameter Parsing
111
112
Functions for parsing docstring parameters and processing documentation text.
113
114
```python { .api }
115
def parse_parameters(lines: List[str], tab_size: int = 8) -> List[Param]:
116
"""
117
Parse docstring parameters from text lines.
118
119
Args:
120
lines: Lines of docstring text to parse
121
tab_size: Tab size for indentation processing
122
123
Returns:
124
List of parsed parameter objects
125
"""
126
127
# Parameter type definition
128
class Param(TypedDict):
129
"""Represents a parsed docstring parameter."""
130
name: str
131
type: Optional[str]
132
description: str
133
```
134
135
### Type Checking Utilities
136
137
Utilities for type checking and object inspection.
138
139
```python { .api }
140
def is_namedtuple(obj: Any) -> bool:
141
"""
142
Check if object is a namedtuple.
143
144
Args:
145
obj: Object to check
146
147
Returns:
148
True if object is namedtuple, False otherwise
149
"""
150
151
def baseclass_is_private(obj: Type) -> bool:
152
"""
153
Check if base class should be considered private.
154
155
Args:
156
obj: Class type to check
157
158
Returns:
159
True if base class is private, False otherwise
160
"""
161
```
162
163
### Extension Management
164
165
Functions for managing Sphinx extensions and autodocumenters.
166
167
```python { .api }
168
def allow_subclass_add(app: Sphinx, *documenters: Type[Documenter]) -> None:
169
"""
170
Add autodocumenters only if their subclass doesn't already exist.
171
172
Args:
173
app: Sphinx application instance
174
*documenters: Documenter classes to add conditionally
175
"""
176
177
def metadata_add_version(func: SetupFunc) -> SetupFunc:
178
"""
179
Decorator that adds version metadata to setup function return.
180
181
Args:
182
func: Setup function to decorate
183
184
Returns:
185
Decorated setup function
186
"""
187
```
188
189
### Configuration Processing
190
191
Functions for processing Sphinx configuration and adding substitutions.
192
193
```python { .api }
194
def add_nbsp_substitution(config: sphinx.config.Config) -> None:
195
"""
196
Add non-breaking space substitution to configuration.
197
198
Args:
199
config: Sphinx configuration object
200
"""
201
202
def add_fallback_css_class(objtypes_css_fallbacks: Dict[str, str]) -> Callable:
203
"""
204
Register CSS class transform for object types.
205
206
Args:
207
objtypes_css_fallbacks: Mapping of object types to CSS classes
208
209
Returns:
210
Transform function for CSS class handling
211
"""
212
```
213
214
### Node Management
215
216
Utilities for managing Sphinx document nodes and purging outdated content.
217
218
```python { .api }
219
class Purger:
220
"""Class for purging redundant nodes from Sphinx build environment."""
221
222
def __init__(self) -> None: ...
223
224
def purge_nodes(self, app: Sphinx, env: BuildEnvironment, docname: str) -> None:
225
"""Remove nodes associated with a document."""
226
227
class NoMatchError(Exception):
228
"""Exception raised when no matching values are found."""
229
```
230
231
### HTTP Caching
232
233
HTTP caching functionality for external requests.
234
235
```python { .api }
236
# Global cache instance
237
cache: HTTPCache
238
239
class HTTPCache:
240
"""HTTP cache with automatic expiration."""
241
242
def get(self, url: str) -> requests.Response:
243
"""Get cached response or fetch from URL."""
244
245
def clear(self) -> None:
246
"""Clear all cached responses."""
247
```
248
249
### Configuration Management
250
251
Extended configuration classes with type annotations for sphinx-toolbox settings.
252
253
```python { .api }
254
class MissingOptionError(SphinxError):
255
"""Exception raised when a required configuration option is missing."""
256
257
class InvalidOptionError(SphinxError):
258
"""Exception raised when a configuration option has an invalid value."""
259
260
class ToolboxConfig(Config):
261
"""Extended Sphinx Config class with type annotations for all sphinx-toolbox configuration values."""
262
263
# GitHub integration
264
github_username: Optional[str]
265
github_repository: Optional[str]
266
267
# Asset handling
268
assets_dir: str
269
270
# Enhanced autodoc
271
all_typevars: bool
272
no_unbound_typevars: bool
273
274
# And many more typed configuration options...
275
276
def validate_config(app: Sphinx, config: ToolboxConfig) -> None:
277
"""
278
Validate sphinx-toolbox configuration values.
279
280
Args:
281
app: Sphinx application instance
282
config: Configuration object to validate
283
284
Raises:
285
MissingOptionError: When required options are missing
286
InvalidOptionError: When options have invalid values
287
"""
288
```
289
290
### Constants and Type Definitions
291
292
Important constants and type definitions used throughout the package.
293
294
```python { .api }
295
# GitHub integration
296
GITHUB_COM: RequestsURL
297
298
# Type definitions
299
OptionSpec = Dict[str, Callable[[str], Any]]
300
SetupFunc = Callable[[Sphinx], SphinxExtMetadata]
301
SphinxExtMetadata = TypedDict('SphinxExtMetadata', {
302
'version': str,
303
'parallel_read_safe': bool,
304
'parallel_write_safe': bool,
305
'env_version': int,
306
}, total=False)
307
308
# Regex patterns for parameter parsing
309
typed_param_regex: Pattern[str]
310
untyped_param_regex: Pattern[str]
311
typed_flag_regex: Pattern[str]
312
313
# Default option specifications
314
flag_default_option_spec: OptionSpec
315
shield_default_option_spec: OptionSpec
316
317
# Common validators
318
flag: Callable[[Any], bool]
319
positive_int: Callable[[str], int]
320
nonnegative_int: Callable[[str], int]
321
unchanged: Callable[[str], str]
322
```