Skip to content

Plugin Features Test

This page demonstrates the mkdocs-material plugins: admonitions, tabs, and API includes.

Admonitions (Callouts)

Admonitions provide visually distinct callout boxes for different types of information.

Information Note

This is a note admonition. Use it to provide helpful information to users.

Pro Tip

This is a tip admonition. Perfect for sharing best practices and helpful hints.

Important Warning

This is a warning admonition. Use it to highlight potential issues or important considerations.

Critical Alert

This is a danger admonition. Use it for critical information that users must be aware of.

Code Example

This is an example admonition with code:

from hands_scaphoid import Shell

with Shell() as shell:
    result = shell.run("echo 'Hello World'")
    print(result.stdout)

Summary

This is an abstract admonition for summarizing key points.

Additional Information

You can also use collapsible admonitions:

Click to expand

This content is hidden by default and can be expanded by clicking.

Frequently Asked Question

Q: How do I use the Shell context manager?

A: Simply import it and use it in a with statement as shown in the examples above.

Tabs

Tabs allow you to organize related content in a compact, navigable interface.

from hands_scaphoid import Shell

# Basic usage
with Shell() as shell:
    result = shell.run("ls -la")
    print(result.stdout)
from hands_scaphoid import Shell

# Windows PowerShell example
with Shell(shell="powershell") as shell:
    result = shell.run("Get-ChildItem")
    print(result.stdout)
from hands_scaphoid import Shell

# Windows Command Prompt example
with Shell(shell="cmd") as shell:
    result = shell.run("dir")
    print(result.stdout)
from hands_scaphoid import Shell

# WSL/Bash example
with Shell(shell="bash") as shell:
    result = shell.run("find . -name '*.py'")
    print(result.stdout)

Configuration Tabs

from hands_scaphoid import Shell

# Simple configuration
shell = Shell(
    shell="bash",
    timeout=30
)
from hands_scaphoid import Shell

# Advanced configuration with custom environment
shell = Shell(
    shell="bash",
    timeout=60,
    env={"PATH": "/custom/path"},
    cwd="/custom/working/directory"
)
from hands_scaphoid import Shell

# Windows-specific configuration
shell = Shell(
    shell="powershell",
    timeout=45,
    execution_policy="RemoteSigned"
)

API Documentation Includes

The mkdocstrings plugin automatically generates API documentation from docstrings.

Shell Class Example

A secure shell command executor with environment management.

This class provides a secure way to execute shell commands with features like: - Command allowlisting for security - Environment variable management - Docker container command execution - Working directory management

Functions

__init__(cwd=None, env=None, env_file='~/.env')

Initialize the Shell instance.

Parameters:

Name Type Description Default
cwd Optional[Union[str, PathLike]]

Working directory for command execution. Defaults to current directory.

None
env Optional[dict[str, str]]

Environment variables dictionary. Defaults to copy of os.environ.

None
env_file str

Path to environment file to load variables from.

'~/.env'

Raises:

Type Description
FileNotFoundError

If the specified working directory doesn't exist.

allow(command)

Allow a command to be executed.

Parameters:

Name Type Description Default
command Union[str, List[str]]

The command or lost of commands to allow (first word will be extracted).

required

Returns:

Type Description
bool

True if command was successfully allowed, False if command doesn't exist.

Raises:

Type Description
ValueError

If command is empty or invalid.

cd(path)

Change the current working directory.

Parameters:

Name Type Description Default
path str

Path to change to (relative or absolute).

required

Raises:

Type Description
NotADirectoryError

If the path is not a valid directory.

ValueError

If path is empty.

depends_on(names)

Check if Docker containers are running.

Parameters:

Name Type Description Default
names Union[str, List[str]]

Container name(s) to check.

required

Returns:

Type Description
bool

True if all containers are running.

Raises:

Type Description
SystemExit

If any container is not running.

RuntimeError

If docker command fails.

get_allowed_commands()

Get the list of currently allowed commands.

Returns:

Type Description
List[str]

List of allowed command names.

get_env_var(var_name)

Get the value of an environment variable.

Parameters:

Name Type Description Default
var_name str

Name of the environment variable.

required

Returns:

Type Description
Optional[str]

Value of the environment variable or None if not found.

Raises:

Type Description
ValueError

If var_name is empty.

is_command_allowed(command)

Check if a command is in the allow list.

Parameters:

Name Type Description Default
command str

Command name to check.

required

Returns:

Type Description
bool

True if command is allowed, False otherwise.

run(command_with_args, timeout=None, capture_output=True, text=True, check=True)

Execute a shell command with security checks.

Parameters:

Name Type Description Default
command_with_args str

The shell command to execute including arguments.

required
timeout Optional[int]

Maximum seconds to wait for command completion.

None
capture_output bool

Whether to capture stdout and stderr.

True
text bool

Whether to return output as text (str) or bytes.

True
check bool

Whether to raise exception on non-zero exit codes.

True

Returns:

Type Description
CompletedProcess

CompletedProcess object with execution results.

Raises:

Type Description
PermissionError

If the command is not in the allow list.

CalledProcessError

If check=True and command fails.

TimeoutExpired

If command times out.

ValueError

If command is empty or invalid.

run_in(container_name, command_with_args, timeout=None, capture_output=True, text=True, check=True)

Execute a command inside a Docker container.

Parameters:

Name Type Description Default
container_name str

Name of the Docker container.

required
command_with_args list[str] | str

Command to execute inside the container.

required
timeout Optional[int]

Maximum seconds to wait for command completion.

None
capture_output bool

Whether to capture stdout and stderr.

True
text bool

Whether to return output as text (str) or bytes.

True
check bool

Whether to raise exception on non-zero exit codes.

True

Returns:

Type Description
CompletedProcess

CompletedProcess object with execution results.

Raises:

Type Description
PermissionError

If docker command is not allowed.

CalledProcessError

If check=True and command fails.

ValueError

If container_name or command is empty.

set_env_var(var_name, value)

Set an environment variable.

Parameters:

Name Type Description Default
var_name str

Name of the environment variable.

required
value str

Value to set.

required

Raises:

Type Description
ValueError

If var_name is empty.

sleep(seconds)

Sleep for the specified number of seconds.

Parameters:

Name Type Description Default
seconds Union[int, float]

Number of seconds to sleep.

required

Raises:

Type Description
ValueError

If seconds is negative.

ShellContext Class

hands_scaphoid.ShellContext(cwd=None, env=None, env_file='~/.env')

Context manager that provides global shell functions.

This context manager creates a Shell instance and exposes its methods as global functions for convenient script-like usage. The functions are automatically cleaned up when exiting the context.

Parameters:

Name Type Description Default
cwd Optional[Union[str, Path]]

Working directory for command execution.

None
env Optional[dict[str, str]]

Environment variables dictionary.

None
env_file str

Path to environment file to load variables from.

'~/.env'

Yields:

Name Type Description
Shell ShellExecutable

The Shell instance for advanced usage.

Example

with ShellContext() as shell: allow("ls") allow("echo") result = run("ls -la") cd("/tmp") run("echo 'Hello World'")

Source code in src/hands_scaphoid/contexts/ShellContext.py
@context_manager
def ShellContext(
    cwd: Optional[Union[str, Path]] = None,
    env: Optional[dict[str, str]] = None,
    env_file: str = "~/.env",
) -> Generator[Shell, None, None]:
    """
    Context manager that provides global shell functions.

    This context manager creates a Shell instance and exposes its methods
    as global functions for convenient script-like usage. The functions
    are automatically cleaned up when exiting the context.

    Args:
        cwd: Working directory for command execution.
        env: Environment variables dictionary.
        env_file: Path to environment file to load variables from.

    Yields:
        Shell: The Shell instance for advanced usage.

    Example:
        with ShellContext() as shell:
            allow("ls")
            allow("echo")
            result = run("ls -la")
            cd("/tmp")
            run("echo 'Hello World'")
    """
    ctx = Shell(cwd, env, env_file)

    # Store original functions if they exist
    original_functions = {}
    function_names = ["cd", "run", "run_in", "sleep", "allow", "depends_on"]

    for func_name in function_names:
        if hasattr(builtins, func_name):
            original_functions[func_name] = getattr(builtins, func_name)

    # Set global functions
    builtins.cd = ctx.cd
    builtins.run = ctx.run
    builtins.run_in = ctx.run_in
    builtins.sleep = ctx.sleep
    builtins.allow = ctx.allow
    builtins.depends_on = ctx.depends_on

    try:
        yield ctx
    finally:
        # Restore original functions or delete if they didn't exist
        for func_name in function_names:
            if func_name in original_functions:
                setattr(builtins, func_name, original_functions[func_name])
            elif hasattr(builtins, func_name):
                delattr(builtins, func_name)

File Operations

TODO: add file operations example

Combined Example

Here's an example that combines all three features:

Complete Workflow Example

First, install and import the necessary components:

from hands_scaphoid import Shell, ShellContext
import os
# Create a shell context
with Shell() as shell:
    # Run a simple command
    result = shell.run("echo 'Hello from shell!'")

    if result.success:
        print(f"Output: {result.stdout}")
    else:
        print(f"Error: {result.stderr}")
# Advanced usage with error handling
try:
    with Shell(timeout=30) as shell:
        # Multiple commands
        commands = [
            "pwd",
            "ls -la",
            "echo 'Processing complete'"
        ]

        for cmd in commands:
            result = shell.run(cmd)
            if not result.success:
                raise RuntimeError(f"Command failed: {cmd}")

except TimeoutError:
    print("Operation timed out")
except RuntimeError as e:
    print(f"Command execution failed: {e}")

Error Handling

Always implement proper error handling when working with shell commands, especially in production environments.

Performance

For multiple related commands, consider using a single shell context to avoid the overhead of creating multiple shell instances.

Testing the Plugins

To verify that all plugins are working correctly:

  1. Admonitions: Check that the callout boxes above render with proper styling and icons
  2. Tabs: Verify that the tabbed content switches properly when clicking different tabs
  3. API Includes: Confirm that the API documentation is automatically generated and displayed with proper formatting

All Features Working

If you can see properly formatted admonitions, functional tabs, and auto-generated API documentation, then all mkdocs-material plugins are configured correctly!