0
# Configuration and Roles
1
2
Configuration value documentation, cross-referencing roles, and specialized formatting features. These extensions provide tools for documenting configuration options and creating rich cross-references within documentation.
3
4
## Capabilities
5
6
### Configuration Value Documentation
7
8
Specialized directive and role for documenting configuration values with proper formatting and cross-referencing.
9
10
```python { .api }
11
class ConfigurationValue(SphinxDirective):
12
"""Directive for documenting configuration values."""
13
14
has_content = True
15
required_arguments = 1 # configuration value name
16
optional_arguments = 0
17
final_argument_whitespace = False
18
19
option_spec = {
20
'type': directives.unchanged,
21
'default': directives.unchanged,
22
'required': directives.flag,
23
'versionadded': directives.unchanged,
24
'versionchanged': directives.unchanged,
25
'deprecated': directives.unchanged,
26
}
27
28
def run(self) -> List[Node]:
29
"""Create configuration value documentation."""
30
31
def register_confval(app: Sphinx, name: str, type_: type, default: Any = None) -> None:
32
"""
33
Register configuration value with Sphinx.
34
35
Args:
36
app: Sphinx application instance
37
name: Configuration value name
38
type_: Expected type for the value
39
default: Default value if not specified
40
"""
41
42
def confval_role(name: str, rawtext: str, text: str, lineno: int,
43
inliner: Inliner, options: Dict[str, Any] = {},
44
content: List[str] = []) -> Tuple[List[Node], List[system_message]]:
45
"""
46
Role for cross-referencing configuration values.
47
48
Args:
49
name: Role name ('confval')
50
rawtext: Raw role text
51
text: Configuration value name to reference
52
lineno: Line number in document
53
inliner: Sphinx inliner
54
options: Role options
55
content: Role content
56
57
Returns:
58
Tuple of confval reference nodes and any error messages
59
"""
60
```
61
62
Usage:
63
64
```rst
65
.. confval:: my_config_option
66
:type: str
67
:default: "default_value"
68
:versionadded: 1.2.0
69
70
This configuration option controls the behavior of...
71
72
Valid values are:
73
74
* ``"auto"`` - Automatic detection
75
* ``"manual"`` - Manual configuration
76
* ``"disabled"`` - Disable feature
77
78
Configuration can be referenced with :confval:`my_config_option`.
79
```
80
81
### Asset and File Roles
82
83
Roles for linking to various types of assets and files with enhanced handling.
84
85
```python { .api }
86
def asset_role(name: str, rawtext: str, text: str, lineno: int,
87
inliner: Inliner, options: Dict[str, Any] = {},
88
content: List[str] = []) -> Tuple[List[Node], List[system_message]]:
89
"""
90
Role for linking to assets that open in browser instead of downloading.
91
92
Args:
93
name: Role name ('asset')
94
rawtext: Raw role text
95
text: Asset path or URL
96
lineno: Line number in document
97
inliner: Sphinx inliner
98
options: Role options
99
content: Role content
100
101
Returns:
102
Tuple of asset link nodes and any error messages
103
"""
104
105
def source_role(name: str, rawtext: str, text: str, lineno: int,
106
inliner: Inliner, options: Dict[str, Any] = {},
107
content: List[str] = []) -> Tuple[List[Node], List[system_message]]:
108
"""
109
Role for linking to source files on GitHub or in documentation.
110
111
Args:
112
name: Role name ('source')
113
rawtext: Raw role text
114
text: File path
115
lineno: Line number in document
116
inliner: Sphinx inliner
117
options: Role options
118
content: Role content
119
120
Returns:
121
Tuple of source link nodes and any error messages
122
"""
123
```
124
125
Usage:
126
127
```rst
128
:asset:`documents/manual.pdf`
129
:asset:`https://example.com/image.png`
130
:source:`src/module/__init__.py`
131
:source:`sphinx_toolbox/utils.py`
132
```
133
134
### Wikipedia Integration
135
136
Role for creating links to Wikipedia articles with language support.
137
138
```python { .api }
139
def make_wikipedia_link(title: str, lang: str = "en",
140
display_text: Optional[str] = None) -> str:
141
"""
142
Create Wikipedia link URL.
143
144
Args:
145
title: Wikipedia article title
146
lang: Language code (default: "en")
147
display_text: Optional display text override
148
149
Returns:
150
Wikipedia article URL
151
"""
152
153
def wikipedia_role(name: str, rawtext: str, text: str, lineno: int,
154
inliner: Inliner, options: Dict[str, Any] = {},
155
content: List[str] = []) -> Tuple[List[Node], List[system_message]]:
156
"""
157
Role for linking to Wikipedia articles.
158
159
Args:
160
name: Role name ('wikipedia')
161
rawtext: Raw role text
162
text: Article title, optionally with lang prefix
163
lineno: Line number in document
164
inliner: Sphinx inliner
165
options: Role options
166
content: Role content
167
168
Returns:
169
Tuple of Wikipedia link nodes and any error messages
170
"""
171
```
172
173
Configuration:
174
175
```python
176
# Wikipedia language setting
177
wikipedia_lang = "en" # Default language for Wikipedia links
178
```
179
180
Usage:
181
182
```rst
183
:wikipedia:`Python (programming language)`
184
:wikipedia:`fr:Python (programming language)` (French Wikipedia)
185
:wikipedia:`Machine learning`
186
```
187
188
### Decorator Cross-References
189
190
Enhanced cross-referencing for Python decorators.
191
192
```python { .api }
193
class PyDecoXRefRole(XRefRole):
194
"""Cross-reference role for Python decorators."""
195
196
def process_link(self, env: BuildEnvironment, refnode: Element,
197
has_explicit_title: bool, title: str,
198
target: str) -> Tuple[str, str]:
199
"""
200
Process decorator cross-reference link.
201
202
Args:
203
env: Build environment
204
refnode: Reference node
205
has_explicit_title: Whether explicit title was provided
206
title: Link title
207
target: Link target
208
209
Returns:
210
Tuple of processed title and target
211
"""
212
213
def setup_decorator_xref(app: Sphinx) -> None:
214
"""Set up decorator cross-reference support."""
215
```
216
217
Usage:
218
219
```rst
220
:deco:`property`
221
:deco:`classmethod`
222
:deco:`staticmethod`
223
:deco:`my_custom_decorator`
224
```
225
226
### Flake8 Code Documentation
227
228
Special directive for documenting Flake8 error codes and warnings.
229
230
```python { .api }
231
class Flake8CodesDirective(SphinxDirective):
232
"""Directive for documenting Flake8 error codes."""
233
234
has_content = True
235
required_arguments = 0
236
optional_arguments = 1 # optional codes file path
237
238
option_spec = {
239
'codes': directives.unchanged,
240
'format': directives.unchanged,
241
}
242
243
def run(self) -> List[Node]:
244
"""Generate Flake8 codes documentation."""
245
246
def parse_flake8_codes(codes_content: str) -> List[Dict[str, str]]:
247
"""
248
Parse Flake8 codes from content.
249
250
Args:
251
codes_content: Content containing Flake8 codes
252
253
Returns:
254
List of parsed code dictionaries
255
"""
256
```
257
258
Usage:
259
260
```rst
261
.. flake8-codes::
262
:codes: flake8_codes.txt
263
:format: table
264
265
.. flake8-codes::
266
267
E101: Indentation contains mixed spaces and tabs
268
E111: Indentation is not a multiple of four
269
W291: Trailing whitespace
270
```
271
272
### Pre-commit Hook Integration
273
274
Utilities for documenting and integrating with pre-commit hooks.
275
276
```python { .api }
277
def setup_precommit_integration(app: Sphinx) -> None:
278
"""Set up pre-commit hook integration."""
279
280
class PreCommitDirective(SphinxDirective):
281
"""Directive for documenting pre-commit hooks."""
282
283
has_content = True
284
285
def run(self) -> List[Node]:
286
"""Document pre-commit hook configuration."""
287
```
288
289
### Version Change Documentation
290
291
Enhanced support for documenting version changes and deprecations.
292
293
```python { .api }
294
class VersionChange(SphinxDirective):
295
"""Enhanced version change documentation."""
296
297
option_spec = {
298
'version': directives.unchanged,
299
'reason': directives.unchanged,
300
}
301
302
def run(self) -> List[Node]:
303
"""Create version change documentation."""
304
```
305
306
Usage:
307
308
```rst
309
.. versionchange:: 2.0.0
310
:reason: API redesign
311
312
The ``old_function`` was replaced with ``new_function``.
313
314
.. deprecated:: 1.5.0
315
:reason: Security concerns
316
317
Use ``secure_function`` instead.
318
```
319
320
### Testing Utilities
321
322
Testing support for Sphinx extensions and documentation.
323
324
```python { .api }
325
def run_setup(app: Sphinx) -> None:
326
"""Run extension setup for testing."""
327
328
def check_html_regression(test_output: str, expected_output: str) -> None:
329
"""
330
Check HTML output against expected results.
331
332
Args:
333
test_output: Generated HTML output
334
expected_output: Expected HTML output
335
336
Raises:
337
AssertionError: If outputs don't match
338
"""
339
340
def make_test_app(**kwargs) -> Sphinx:
341
"""Create Sphinx application for testing."""
342
343
class SphinxTestCase:
344
"""Base class for Sphinx extension testing."""
345
346
def setup_app(self, **kwargs) -> Sphinx:
347
"""Set up test Sphinx application."""
348
349
def build_docs(self, builder: str = 'html') -> None:
350
"""Build documentation for testing."""
351
352
def get_output(self, filename: str) -> str:
353
"""Get built output content."""
354
```
355
356
### Configuration Management
357
358
Comprehensive configuration value definitions and validation.
359
360
```python { .api }
361
# Configuration values added by various extensions
362
CONFIGURATION_VALUES = {
363
# GitHub integration
364
'github_username': (None, 'env', [str, type(None)]),
365
'github_repository': (None, 'env', [str, type(None)]),
366
367
# Asset handling
368
'assets_dir': ('_assets', 'html', [str]),
369
370
# Wikipedia
371
'wikipedia_lang': ('en', 'env', [str]),
372
373
# Source links
374
'source_link_target': ('github', 'env', [str]),
375
376
# Enhanced autodoc
377
'all_typevars': (False, 'env', [bool]),
378
'no_unbound_typevars': (False, 'env', [bool]),
379
380
# And many more...
381
}
382
383
def validate_all_config(app: Sphinx, config: Config) -> None:
384
"""Validate all sphinx-toolbox configuration values."""
385
```
386
387
### Role Registration
388
389
Centralized role registration for all sphinx-toolbox roles.
390
391
```python { .api }
392
def register_all_roles(app: Sphinx) -> None:
393
"""Register all sphinx-toolbox roles with Sphinx."""
394
395
ROLE_REGISTRY = {
396
'asset': asset_role,
397
'source': source_role,
398
'wikipedia': wikipedia_role,
399
'confval': confval_role,
400
'deco': PyDecoXRefRole,
401
# Additional roles from other extensions
402
'issue': 'sphinx_toolbox.issues.issue_role',
403
'pull': 'sphinx_toolbox.issues.pull_role',
404
}
405
```
406
407
### Error Handling
408
409
Comprehensive error handling for configuration and role processing.
410
411
```python { .api }
412
class ConfigurationError(SphinxError):
413
"""Base exception for configuration errors."""
414
415
class RoleProcessingError(SphinxError):
416
"""Raised when role processing fails."""
417
418
class CrossReferenceError(SphinxError):
419
"""Raised when cross-reference resolution fails."""
420
```