CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-sphinx-autobuild

Rebuild Sphinx documentation on changes, with hot reloading in the browser.

Overview
Eval results
Files

build.mddocs/

Build Management

The build management system controls the Sphinx documentation build process with support for pre/post-build commands, error handling, and integration with the file watching system.

Capabilities

Builder Class

The main class responsible for executing Sphinx builds when files change.

class Builder:
    def __init__(
        self, 
        sphinx_args, 
        *, 
        url_host, 
        pre_build_commands, 
        post_build_commands
    ):
        """
        Initialize builder with Sphinx arguments and command hooks.
        
        Parameters:
        - sphinx_args: list[str] - Arguments to pass to sphinx-build
        - url_host: str - Host:port string for server URL display
        - pre_build_commands: list[list[str]] - Commands to run before build
        - post_build_commands: list[list[str]] - Commands to run after successful build
        """
    
    def __call__(self, *, changed_paths):
        """
        Execute build process when files change.
        
        Parameters:
        - changed_paths: Sequence[Path] - Paths of files that changed (triggers rebuild)
        
        Returns:
        - None
        
        Side Effects:
        - Runs pre-build commands
        - Executes sphinx-build with configured arguments  
        - Runs post-build commands (only if build succeeds)
        - Prints status messages and server URL
        - Handles build errors gracefully
        """

Build Process Flow

The build process follows a specific sequence:

  1. Change Detection: Display changed file paths (up to 5 files shown)
  2. Pre-build Commands: Execute all configured pre-build commands in order
  3. Sphinx Build: Run sphinx-build with provided arguments
  4. Post-build Commands: Execute post-build commands only if build succeeds
  5. Status Display: Show server URL for user convenience

Usage Example:

from sphinx_autobuild.build import Builder
from pathlib import Path

# Initialize builder
builder = Builder(
    sphinx_args=['-b', 'html', 'docs', '_build/html'],
    url_host='127.0.0.1:8000',
    pre_build_commands=[['echo', 'Starting build']],
    post_build_commands=[['echo', 'Build complete']]
)

# Trigger build
changed_files = [Path('docs/index.rst'), Path('docs/api.rst')]
builder(changed_paths=changed_files)

Command Execution

Handles pre-build and post-build command execution with error management.

def _run_commands(self, commands, log_context):
    """
    Execute a list of commands in sequence.
    
    Parameters:
    - commands: list[list[str]] - List of commands to execute
    - log_context: str - Context string for logging ('pre-build' or 'post-build')
    
    Returns:
    - int - Return code (0 for success, non-zero for failure)
    
    Error Handling:
    - Prints error message and traceback on command failure
    - Returns early on first command failure
    - Server continues running even after command failures
    """

Sphinx Integration

Integrates with different versions of Sphinx, handling version-specific argument formats.

Sphinx Version Compatibility:

  • Sphinx ≥7.2.3: Uses python -m sphinx build command format
  • Sphinx <7.2.3: Uses python -m sphinx command format

Build Arguments: The builder accepts all standard sphinx-build arguments:

# Common Sphinx arguments
sphinx_args = [
    '-b', 'html',           # Builder type
    '-E',                   # Don't use saved environment
    '-a',                   # Write all files
    '-v',                   # Verbose output
    '-W',                   # Turn warnings into errors
    '-d', '_build/doctrees', # Doctree directory
    'docs',                 # Source directory  
    '_build/html'           # Output directory
]

Usage Examples

Basic Build Management

from sphinx_autobuild.build import Builder

# Simple builder with no extra commands
builder = Builder(
    sphinx_args=['docs', '_build/html'],
    url_host='localhost:8000',
    pre_build_commands=[],
    post_build_commands=[]
)

# Trigger rebuild
builder(changed_paths=[])

Advanced Build Configuration

from sphinx_autobuild.build import Builder
import shlex

# Complex builder with multiple commands
pre_build = [
    ['python', 'scripts/generate_api.py'],
    ['python', '-c', 'print("API docs generated")']
]

post_build = [
    ['python', 'scripts/validate_links.py'],
    shlex.split('find _build -name "*.html" -exec echo "Generated: {}" \\;')
]

builder = Builder(
    sphinx_args=['-b', 'html', '-E', '-v', 'docs', '_build/html'],
    url_host='192.168.1.100:8080',
    pre_build_commands=pre_build,
    post_build_commands=post_build
)

Integration with File Watcher

from sphinx_autobuild.build import Builder
from sphinx_autobuild.server import RebuildServer
from sphinx_autobuild.filter import IgnoreFilter
from pathlib import Path

# Create builder
builder = Builder(
    sphinx_args=['docs', '_build/html'],
    url_host='127.0.0.1:8000',
    pre_build_commands=[],
    post_build_commands=[]
)

# Create file watcher that uses builder as callback
watch_dirs = [Path('docs')]
ignore_filter = IgnoreFilter([], [])
server = RebuildServer(watch_dirs, ignore_filter, builder)

Error Handling

Build Failures

When Sphinx build fails:

  • Error message with exit code is displayed
  • Server continues serving existing content
  • User is advised to fix errors or stop server
  • Pre-build command failures prevent Sphinx execution
  • Post-build commands only run after successful builds

Command Failures

Pre/post-build command failures:

  • Error details and traceback are printed
  • Descriptive error messages with context
  • Server continues operating
  • Subsequent commands in the list are skipped

Common Error Scenarios

# Command not found
pre_build_commands = [['nonexistent-command', 'arg']]
# Output: "Pre-build command exited with exit code: 127"

# Sphinx syntax error
# Output: "Sphinx exited with exit code: 2"
# Server continues serving stale content

# Permission denied
post_build_commands = [['chmod', '000', '/protected/file']]  
# Output: "Post-build command exited with exit code: 1"

Performance Considerations

  • Incremental Builds: Sphinx's incremental building is preserved
  • Command Caching: No caching of command results - each change triggers full command sequence
  • File Path Limiting: Only first 5 changed paths are displayed to avoid spam
  • Process Isolation: Commands run in separate processes for stability

Install with Tessl CLI

npx tessl i tessl/pypi-sphinx-autobuild

docs

build.md

cli.md

filtering.md

index.md

middleware.md

server.md

utils.md

tile.json