Skip to content

ShellContext API Reference

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)