šŸ“š Shell Class Documentation

Overview

The Shell class is an abstract base class (ABC) that provides a framework for executing shell commands with consistent logging, context management, and error handling. It implements the Template Method pattern for command execution and allows different shell implementations to define their own command formatting strategies.

Class: Shell

Inheritance

Constructor Parameters

Parameter Type Description Default
context Optional[SessionContext] Session context containing working directory and environment variables SessionContext()
logger Optional[Logger] Logger instance for recording operations NullLogger()
default_timeout float Default timeout for command execution in seconds 30.0

Attributes

Attribute Type Description
context SessionContext The session context for command execution
logger Logger Logger instance for recording operations
default_timeout float Default timeout value for command execution

Abstract Methods

_format_command(executable: str, args: list[str]) -> list[str]

Abstract method that must be implemented by child classes to define how the final command list should be formatted (Strategy pattern).

Parameters:

Returns:

Public Methods

__enter__() -> Shell

Context manager entry method. Logs the start of a shell session.

Returns:
Logging:

__exit__(exc_type, exc_val, exc_tb)

Context manager exit method. Logs session termination, including any errors that occurred.

Parameters:
Logging:
Note: Does not suppress exceptions (returns None)

run(command, timeout: Optional[float] = None) -> CommandResult

Template method that coordinates the command execution process.

Parameters:
Returns:
Process Flow:
  1. Lazy Binary Check: Verifies if the executable exists in PATH
  2. Command Formatting: Calls _format_command() to prepare the final command list
  3. Execution: Runs the command using subprocess.run() with:
  4. Result Processing: Creates and returns a CommandResult object
Exceptions:
Logging:

Usage Example

# Create a concrete shell implementation
class BashShell(Shell):
    def _format_command(self, executable: str, args: list[str]) -> list[str]:
        return [executable] + args

# Use the shell
with BashShell(logger=my_logger, default_timeout=60.0) as shell:
    result = shell.run(my_command, timeout=30.0)
    if result.is_success():
        print(f"Output: {result.standard_output}")
    

Design Patterns Used

1. Abstract Base Class

Provides a common interface for different shell implementations

2. Template Method

The run() method defines the skeleton of the command execution algorithm

3. Strategy Pattern

The _format_command() abstract method allows different shell implementations to define their own formatting strategies

Dependencies