Box of handy tools for Sphinx providing comprehensive extensions and enhancements for documentation generation.
Essential utilities, caching, and configuration management used throughout the sphinx-toolbox extension ecosystem. These foundational components provide common functionality shared across all extensions.
Core utility functions for URL generation, validation, string processing, and common patterns used across extensions.
def make_github_url(username: str, repository: str) -> RequestsURL:
"""
Create a GitHub URL from username and repository.
Args:
username: GitHub username or organization
repository: Repository name
Returns:
RequestsURL object for the GitHub repository
"""
def flag(argument: Any) -> bool:
"""
Validate flag options for Sphinx directives.
Args:
argument: Directive argument to validate
Returns:
Always True for flag directives
Raises:
ValueError: If argument is not None or empty string
"""
def get_first_matching(condition: Callable, iterable: Iterable, default: Any = None) -> Any:
"""
Return first item from iterable that matches condition.
Args:
condition: Function that returns True for matching items
iterable: Items to search through
default: Value to return if no match found
Returns:
First matching item or default value
"""
def escape_trailing__(string: str) -> str:
"""
Escape trailing underscores in strings for reStructuredText.
Args:
string: String that may have trailing underscores
Returns:
String with trailing underscores escaped
"""
def code_repr(obj: Any) -> str:
"""
Return object repr as reStructuredText inline code.
Args:
obj: Object to represent
Returns:
String formatted as RST inline code
"""
def sphinx_ext_metadata(version: str, parallel_read_safe: bool = True,
parallel_write_safe: bool = True) -> SphinxExtMetadata:
"""
Create SphinxExtMetadata dictionary.
Args:
version: Extension version
parallel_read_safe: Whether extension supports parallel reading
parallel_write_safe: Whether extension supports parallel writing
Returns:
SphinxExtMetadata dictionary
"""Specialized logging functions for Sphinx extension development and debugging.
def unknown_module_warning(documenter: Documenter) -> None:
"""
Log warning for unknown modules during autodoc processing.
Args:
documenter: Sphinx autodocumenter instance
"""
def filter_members_warning(member: Any, exception: Exception) -> None:
"""
Log warning when filtering autodoc members fails.
Args:
member: Member being filtered
exception: Exception that occurred during filtering
"""Functions for parsing docstring parameters and processing documentation text.
def parse_parameters(lines: List[str], tab_size: int = 8) -> List[Param]:
"""
Parse docstring parameters from text lines.
Args:
lines: Lines of docstring text to parse
tab_size: Tab size for indentation processing
Returns:
List of parsed parameter objects
"""
# Parameter type definition
class Param(TypedDict):
"""Represents a parsed docstring parameter."""
name: str
type: Optional[str]
description: strUtilities for type checking and object inspection.
def is_namedtuple(obj: Any) -> bool:
"""
Check if object is a namedtuple.
Args:
obj: Object to check
Returns:
True if object is namedtuple, False otherwise
"""
def baseclass_is_private(obj: Type) -> bool:
"""
Check if base class should be considered private.
Args:
obj: Class type to check
Returns:
True if base class is private, False otherwise
"""Functions for managing Sphinx extensions and autodocumenters.
def allow_subclass_add(app: Sphinx, *documenters: Type[Documenter]) -> None:
"""
Add autodocumenters only if their subclass doesn't already exist.
Args:
app: Sphinx application instance
*documenters: Documenter classes to add conditionally
"""
def metadata_add_version(func: SetupFunc) -> SetupFunc:
"""
Decorator that adds version metadata to setup function return.
Args:
func: Setup function to decorate
Returns:
Decorated setup function
"""Functions for processing Sphinx configuration and adding substitutions.
def add_nbsp_substitution(config: sphinx.config.Config) -> None:
"""
Add non-breaking space substitution to configuration.
Args:
config: Sphinx configuration object
"""
def add_fallback_css_class(objtypes_css_fallbacks: Dict[str, str]) -> Callable:
"""
Register CSS class transform for object types.
Args:
objtypes_css_fallbacks: Mapping of object types to CSS classes
Returns:
Transform function for CSS class handling
"""Utilities for managing Sphinx document nodes and purging outdated content.
class Purger:
"""Class for purging redundant nodes from Sphinx build environment."""
def __init__(self) -> None: ...
def purge_nodes(self, app: Sphinx, env: BuildEnvironment, docname: str) -> None:
"""Remove nodes associated with a document."""
class NoMatchError(Exception):
"""Exception raised when no matching values are found."""HTTP caching functionality for external requests.
# Global cache instance
cache: HTTPCache
class HTTPCache:
"""HTTP cache with automatic expiration."""
def get(self, url: str) -> requests.Response:
"""Get cached response or fetch from URL."""
def clear(self) -> None:
"""Clear all cached responses."""Extended configuration classes with type annotations for sphinx-toolbox settings.
class MissingOptionError(SphinxError):
"""Exception raised when a required configuration option is missing."""
class InvalidOptionError(SphinxError):
"""Exception raised when a configuration option has an invalid value."""
class ToolboxConfig(Config):
"""Extended Sphinx Config class with type annotations for all sphinx-toolbox configuration values."""
# GitHub integration
github_username: Optional[str]
github_repository: Optional[str]
# Asset handling
assets_dir: str
# Enhanced autodoc
all_typevars: bool
no_unbound_typevars: bool
# And many more typed configuration options...
def validate_config(app: Sphinx, config: ToolboxConfig) -> None:
"""
Validate sphinx-toolbox configuration values.
Args:
app: Sphinx application instance
config: Configuration object to validate
Raises:
MissingOptionError: When required options are missing
InvalidOptionError: When options have invalid values
"""Important constants and type definitions used throughout the package.
# GitHub integration
GITHUB_COM: RequestsURL
# Type definitions
OptionSpec = Dict[str, Callable[[str], Any]]
SetupFunc = Callable[[Sphinx], SphinxExtMetadata]
SphinxExtMetadata = TypedDict('SphinxExtMetadata', {
'version': str,
'parallel_read_safe': bool,
'parallel_write_safe': bool,
'env_version': int,
}, total=False)
# Regex patterns for parameter parsing
typed_param_regex: Pattern[str]
untyped_param_regex: Pattern[str]
typed_flag_regex: Pattern[str]
# Default option specifications
flag_default_option_spec: OptionSpec
shield_default_option_spec: OptionSpec
# Common validators
flag: Callable[[Any], bool]
positive_int: Callable[[str], int]
nonnegative_int: Callable[[str], int]
unchanged: Callable[[str], str]Install with Tessl CLI
npx tessl i tessl/pypi-sphinx-toolbox