Skip to content

os_commands

Class info

Re-exported classes

Class Module Description
Base64EncodeCommand anyenv.os_commands.base Base class for base64 encode commands.
CommandBatch anyenv.os_commands.batch Batch multiple commands into a single shell call.
CommandResult anyenv.os_commands.models Base command result model.
CopyPathCommand anyenv.os_commands.base Base class for copy path commands.
CreateDirectoryCommand anyenv.os_commands.base Base class for create directory commands.
CreateDirectoryResult anyenv.os_commands.models Result for directory creation commands.
DirectoryEntry anyenv.os_commands.models Directory entry model for detailed listings.
EnvVarCommand anyenv.os_commands.base Base class for environment variable commands.
ExistsCommand anyenv.os_commands.base Base class for exists commands.
ExistsResult anyenv.os_commands.models Result for existence check commands.
FileInfo anyenv.os_commands.models File information model.
FileInfoCommand anyenv.os_commands.base Base class for file info commands.
FindCommand anyenv.os_commands.base Base class for recursive find commands.
IsDirectoryCommand anyenv.os_commands.base Base class for is directory commands.
IsFileCommand anyenv.os_commands.base Base class for is file commands.
ListDirectoryCommand anyenv.os_commands.base Base class for list directory commands.
MacOSBase64EncodeCommand anyenv.os_commands.base64_encode macOS base64 encode command implementation.
MacOSCommandProvider anyenv.os_commands.providers macOS command provider using BSD tools.
MacOSCopyPathCommand anyenv.os_commands.copy_path macOS copy path command implementation.
MacOSCreateDirectoryCommand anyenv.os_commands.create_directory macOS create directory command implementation.
MacOSEnvVarCommand anyenv.os_commands.env_var macOS environment variable command implementation.
MacOSExistsCommand anyenv.os_commands.exists macOS exists command implementation.
MacOSFileInfoCommand anyenv.os_commands.file_info macOS file info command implementation using ls -la.
MacOSFindCommand anyenv.os_commands.find macOS find command implementation (BSD find).
MacOSIsDirectoryCommand anyenv.os_commands.is_directory macOS is directory command implementation.
MacOSIsFileCommand anyenv.os_commands.is_file macOS is file command implementation.
MacOSListDirectoryCommand anyenv.os_commands.list_directory macOS list directory command implementation.
MacOSPwdCommand anyenv.os_commands.pwd macOS pwd command implementation.
MacOSRemovePathCommand anyenv.os_commands.remove_path macOS remove path command implementation.
MacOSWhichCommand anyenv.os_commands.which macOS which command implementation.
OSCommandProvider anyenv.os_commands.providers Base class for OS-specific command providers using command classes.
PwdCommand anyenv.os_commands.base Base class for pwd (print working directory) commands.
RemovePathCommand anyenv.os_commands.base Base class for remove path commands.
RemovePathResult anyenv.os_commands.models Result for path removal commands.
UnixBase64EncodeCommand anyenv.os_commands.base64_encode Unix/Linux base64 encode command implementation.
UnixCommandProvider anyenv.os_commands.providers Unix/Linux command provider using GNU/POSIX tools.
UnixCopyPathCommand anyenv.os_commands.copy_path Unix/Linux copy path command implementation.
UnixCreateDirectoryCommand anyenv.os_commands.create_directory Unix/Linux create directory command implementation.
UnixEnvVarCommand anyenv.os_commands.env_var Unix/Linux environment variable command implementation.
UnixExistsCommand anyenv.os_commands.exists Unix/Linux exists command implementation.
UnixFileInfoCommand anyenv.os_commands.file_info Unix/Linux file info command implementation using ls -la.
UnixFindCommand anyenv.os_commands.find Unix/Linux find command implementation.
UnixIsDirectoryCommand anyenv.os_commands.is_directory Unix/Linux is directory command implementation.
UnixIsFileCommand anyenv.os_commands.is_file Unix/Linux is file command implementation.
UnixListDirectoryCommand anyenv.os_commands.list_directory Unix/Linux list directory command implementation.
UnixPwdCommand anyenv.os_commands.pwd Unix/Linux pwd command implementation.
UnixRemovePathCommand anyenv.os_commands.remove_path Unix/Linux remove path command implementation.
UnixWhichCommand anyenv.os_commands.which Unix/Linux which command implementation.
WhichCommand anyenv.os_commands.base Base class for which/where commands to locate executables.
WindowsBase64EncodeCommand anyenv.os_commands.base64_encode Windows base64 encode command implementation using PowerShell.
WindowsCommandProvider anyenv.os_commands.providers Windows command provider using PowerShell and CMD.
WindowsCopyPathCommand anyenv.os_commands.copy_path Windows copy path command implementation.
WindowsCreateDirectoryCommand anyenv.os_commands.create_directory Windows create directory command implementation.
WindowsEnvVarCommand anyenv.os_commands.env_var Windows environment variable command implementation.
WindowsExistsCommand anyenv.os_commands.exists Windows exists command implementation.
WindowsFileInfoCommand anyenv.os_commands.file_info Windows file info command implementation.
WindowsFindCommand anyenv.os_commands.find Windows find command implementation using PowerShell.
WindowsIsDirectoryCommand anyenv.os_commands.is_directory Windows is directory command implementation.
WindowsIsFileCommand anyenv.os_commands.is_file Windows is file command implementation.
WindowsListDirectoryCommand anyenv.os_commands.list_directory Windows list directory command implementation.
WindowsPwdCommand anyenv.os_commands.pwd Windows pwd command implementation.
WindowsRemovePathCommand anyenv.os_commands.remove_path Windows remove path command implementation.
WindowsWhichCommand anyenv.os_commands.which Windows where command implementation.

🛈 DocStrings

OS-specific terminal command abstractions for cross-platform filesystem operations.

This package provides a clean abstraction layer for executing OS-specific terminal commands across Unix/Linux, macOS, and Windows platforms. Commands are grouped by OS and individual command types for better organization and maintainability.

Base64EncodeCommand

Bases: ABC

Base class for base64 encode commands.

Source code in src/anyenv/os_commands/base.py
class Base64EncodeCommand(ABC):
    """Base class for base64 encode commands."""

    @abstractmethod
    def create_command(self, path: str) -> str:
        """Generate base64 encode command."""

    @abstractmethod
    def parse_command(self, output: str) -> bytes:
        """Parse base64 output and return decoded bytes."""

create_command abstractmethod

create_command(path: str) -> str

Generate base64 encode command.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def create_command(self, path: str) -> str:
    """Generate base64 encode command."""

parse_command abstractmethod

parse_command(output: str) -> bytes

Parse base64 output and return decoded bytes.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def parse_command(self, output: str) -> bytes:
    """Parse base64 output and return decoded bytes."""

CommandBatch dataclass

Batch multiple commands into a single shell call.

This class allows you to combine multiple OS commands into a single shell invocation, reducing round-trips when commands are executed over a protocol (SSH, containers, etc.).

Example

provider = get_os_command_provider() which_cmd = provider.get_command("which") exists_cmd = provider.get_command("exists")

batch = CommandBatch() batch.add(which_cmd, "python") batch.add(which_cmd, "node") batch.add(exists_cmd, "/tmp/test.txt")

Execute single combined command

combined = batch.create_batch_command() result = subprocess.run(combined, shell=True, capture_output=True, text=True)

Parse back to individual results

python_path, node_path, exists = batch.parse_batch_output(result.stdout)

Source code in src/anyenv/os_commands/batch.py
@dataclass
class CommandBatch:
    """Batch multiple commands into a single shell call.

    This class allows you to combine multiple OS commands into a single
    shell invocation, reducing round-trips when commands are executed
    over a protocol (SSH, containers, etc.).

    Example:
        >>> provider = get_os_command_provider()
        >>> which_cmd = provider.get_command("which")
        >>> exists_cmd = provider.get_command("exists")
        >>>
        >>> batch = CommandBatch()
        >>> batch.add(which_cmd, "python")
        >>> batch.add(which_cmd, "node")
        >>> batch.add(exists_cmd, "/tmp/test.txt")
        >>>
        >>> # Execute single combined command
        >>> combined = batch.create_batch_command()
        >>> result = subprocess.run(combined, shell=True, capture_output=True, text=True)
        >>>
        >>> # Parse back to individual results
        >>> python_path, node_path, exists = batch.parse_batch_output(result.stdout)
    """

    platform: Literal["unix", "windows"] = field(default_factory=lambda: _detect_platform())
    _commands: list[PendingCommand] = field(default_factory=list)

    def add(self, command: CommandProtocol, *args: Any, **kwargs: Any) -> CommandBatch:
        """Add a command with its arguments to the batch.

        Args:
            command: The command instance (e.g., WhichCommand, ExistsCommand)
            *args: Positional arguments to pass to create_command
            **kwargs: Keyword arguments to pass to create_command

        Returns:
            Self for method chaining
        """
        cmd_str = command.create_command(*args, **kwargs)
        self._commands.append(PendingCommand(cmd_str, command, args, kwargs))
        return self

    def create_batch_command(self) -> str:
        """Generate the combined shell command string.

        Returns:
            A single shell command that executes all batched commands
            and captures their individual outputs and exit codes.
        """
        if not self._commands:
            return ""

        if self.platform == "windows":
            return self._create_windows_batch()
        return self._create_unix_batch()

    def _create_unix_batch(self) -> str:
        """Generate Unix/macOS batch command."""
        # Wrap each command to capture its exit code
        # Using subshell to isolate each command
        parts = [f'({c.command_str}; echo "{EXIT_MARKER}$?{END_MARKER}")' for c in self._commands]
        return f'; echo "{DELIMITER}"; '.join(parts)

    def _create_windows_batch(self) -> str:
        """Generate Windows PowerShell batch command."""
        parts = []
        for cmd in self._commands:
            # Extract the actual command from powershell -c "..." wrapper if present
            # Unwrap PowerShell commands; the batch re-wraps them as one script.
            inner_cmd = powershell_script(cmd.command_str) or cmd.command_str

            # Build PowerShell script block that captures exit code
            # Use try/catch to handle command failures gracefully
            parts.append(
                f"try {{ {inner_cmd} }} catch {{ }}; "
                f"Write-Host '{EXIT_MARKER}' -NoNewline; "
                f"Write-Host $LASTEXITCODE -NoNewline; "
                f"Write-Host '{END_MARKER}'"
            )

        # Join with delimiter output between commands
        delimiter_cmd = f"Write-Host '{DELIMITER}'"
        script = f"; {delimiter_cmd}; ".join(parts)
        return powershell(script)

    def parse_batch_output(self, output: str) -> list[Any]:
        """Parse the combined output back to individual command results.

        Args:
            output: The raw output from executing the batch command

        Returns:
            List of parsed results, one per command in the batch,
            in the same order they were added.
        """
        if not self._commands:
            return []

        results = []
        segments = output.split(DELIMITER)

        for i, segment in enumerate(segments):
            if i >= len(self._commands):
                break

            pending = self._commands[i]

            # Extract exit code from segment
            cmd_output, exit_code = self._extract_exit_code(segment)

            # Call the command's parser with appropriate arguments
            result = self._parse_command_output(pending, cmd_output, exit_code)
            results.append(result)

        return results

    def _extract_exit_code(self, segment: str) -> tuple[str, int]:
        """Extract the exit code from a command output segment.

        Args:
            segment: Raw output segment including exit code marker

        Returns:
            Tuple of (cleaned output, exit code)
        """
        if EXIT_MARKER in segment:
            parts = segment.rsplit(EXIT_MARKER, 1)
            cmd_output = parts[0]
            # Extract exit code, removing the end marker
            exit_str = parts[1].split(END_MARKER)[0].strip()
            try:
                exit_code = int(exit_str)
            except ValueError:
                exit_code = 0
        else:
            cmd_output = segment
            exit_code = 0

        return cmd_output.strip(), exit_code

    def _parse_command_output(self, pending: PendingCommand, output: str, exit_code: int) -> Any:
        """Parse a single command's output using its parser.

        Handles the different parse_command signatures by inspecting
        what arguments the parser expects.

        Args:
            pending: The pending command with its original args
            output: The command's output
            exit_code: The command's exit code

        Returns:
            The parsed result from the command's parser
        """
        # Most parsers take (output, exit_code) or (output, some_original_arg)
        # We need to handle both cases

        # Try the standard (output, exit_code) signature first
        # Commands like WhichCommand, ExistsCommand, etc.
        try:
            # Check if the parse_command expects the original args
            # FileInfoCommand.parse_command(output, path) needs the path
            # ListDirectoryCommand.parse_command(output, path) needs the path
            import inspect

            sig = inspect.signature(pending.command.parse_command)
            params = list(sig.parameters.keys())

            # If second param is 'exit_code', pass exit_code
            # Otherwise, pass the first positional arg from create_command
            if len(params) >= 2:  # noqa: PLR2004
                second_param = params[1]
                if second_param == "exit_code":
                    return pending.command.parse_command(output, exit_code)
                if pending.args:
                    # Pass the first arg (usually 'path')
                    return pending.command.parse_command(output, pending.args[0])

            # Fallback: just pass output
            return pending.command.parse_command(output)

        except Exception:  # noqa: BLE001
            # Last resort fallback
            return pending.command.parse_command(output, exit_code)

    def clear(self) -> None:
        """Clear all pending commands from the batch."""
        self._commands.clear()

    def __len__(self) -> int:
        """Return the number of pending commands."""
        return len(self._commands)

__len__

__len__() -> int

Return the number of pending commands.

Source code in src/anyenv/os_commands/batch.py
def __len__(self) -> int:
    """Return the number of pending commands."""
    return len(self._commands)

add

add(command: CommandProtocol, *args: Any, **kwargs: Any) -> CommandBatch

Add a command with its arguments to the batch.

Parameters:

Name Type Description Default
command CommandProtocol

The command instance (e.g., WhichCommand, ExistsCommand)

required
*args Any

Positional arguments to pass to create_command

()
**kwargs Any

Keyword arguments to pass to create_command

{}

Returns:

Type Description
CommandBatch

Self for method chaining

Source code in src/anyenv/os_commands/batch.py
def add(self, command: CommandProtocol, *args: Any, **kwargs: Any) -> CommandBatch:
    """Add a command with its arguments to the batch.

    Args:
        command: The command instance (e.g., WhichCommand, ExistsCommand)
        *args: Positional arguments to pass to create_command
        **kwargs: Keyword arguments to pass to create_command

    Returns:
        Self for method chaining
    """
    cmd_str = command.create_command(*args, **kwargs)
    self._commands.append(PendingCommand(cmd_str, command, args, kwargs))
    return self

clear

clear() -> None

Clear all pending commands from the batch.

Source code in src/anyenv/os_commands/batch.py
def clear(self) -> None:
    """Clear all pending commands from the batch."""
    self._commands.clear()

create_batch_command

create_batch_command() -> str

Generate the combined shell command string.

Returns:

Type Description
str

A single shell command that executes all batched commands

str

and captures their individual outputs and exit codes.

Source code in src/anyenv/os_commands/batch.py
def create_batch_command(self) -> str:
    """Generate the combined shell command string.

    Returns:
        A single shell command that executes all batched commands
        and captures their individual outputs and exit codes.
    """
    if not self._commands:
        return ""

    if self.platform == "windows":
        return self._create_windows_batch()
    return self._create_unix_batch()

parse_batch_output

parse_batch_output(output: str) -> list[Any]

Parse the combined output back to individual command results.

Parameters:

Name Type Description Default
output str

The raw output from executing the batch command

required

Returns:

Type Description
list[Any]

List of parsed results, one per command in the batch,

list[Any]

in the same order they were added.

Source code in src/anyenv/os_commands/batch.py
def parse_batch_output(self, output: str) -> list[Any]:
    """Parse the combined output back to individual command results.

    Args:
        output: The raw output from executing the batch command

    Returns:
        List of parsed results, one per command in the batch,
        in the same order they were added.
    """
    if not self._commands:
        return []

    results = []
    segments = output.split(DELIMITER)

    for i, segment in enumerate(segments):
        if i >= len(self._commands):
            break

        pending = self._commands[i]

        # Extract exit code from segment
        cmd_output, exit_code = self._extract_exit_code(segment)

        # Call the command's parser with appropriate arguments
        result = self._parse_command_output(pending, cmd_output, exit_code)
        results.append(result)

    return results

CommandResult dataclass

Base command result model.

Source code in src/anyenv/os_commands/models.py
@dataclass
class CommandResult:
    """Base command result model."""

    success: bool
    exit_code: int = 0
    output: str = ""
    error: str = ""

CopyPathCommand

Bases: ABC

Base class for copy path commands.

Source code in src/anyenv/os_commands/base.py
class CopyPathCommand(ABC):
    """Base class for copy path commands."""

    @abstractmethod
    def create_command(self, source: str, destination: str, recursive: bool = False) -> str:
        """Generate copy command.

        Args:
            source: Source path to copy from
            destination: Destination path to copy to
            recursive: Whether to copy directories recursively
        """

    @abstractmethod
    def parse_command(self, output: str, exit_code: int = 0) -> bool:
        """Parse copy result.

        Returns:
            True if copy was successful, False otherwise
        """

create_command abstractmethod

create_command(source: str, destination: str, recursive: bool = False) -> str

Generate copy command.

Parameters:

Name Type Description Default
source str

Source path to copy from

required
destination str

Destination path to copy to

required
recursive bool

Whether to copy directories recursively

False
Source code in src/anyenv/os_commands/base.py
@abstractmethod
def create_command(self, source: str, destination: str, recursive: bool = False) -> str:
    """Generate copy command.

    Args:
        source: Source path to copy from
        destination: Destination path to copy to
        recursive: Whether to copy directories recursively
    """

parse_command abstractmethod

parse_command(output: str, exit_code: int = 0) -> bool

Parse copy result.

Returns:

Type Description
bool

True if copy was successful, False otherwise

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def parse_command(self, output: str, exit_code: int = 0) -> bool:
    """Parse copy result.

    Returns:
        True if copy was successful, False otherwise
    """

CreateDirectoryCommand

Bases: ABC

Base class for create directory commands.

Source code in src/anyenv/os_commands/base.py
class CreateDirectoryCommand(ABC):
    """Base class for create directory commands."""

    @abstractmethod
    def create_command(self, path: str, parents: bool = True) -> str:
        """Generate directory creation command."""

    @abstractmethod
    def parse_command(self, output: str, exit_code: int = 0) -> bool:
        """Parse directory creation result."""

create_command abstractmethod

create_command(path: str, parents: bool = True) -> str

Generate directory creation command.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def create_command(self, path: str, parents: bool = True) -> str:
    """Generate directory creation command."""

parse_command abstractmethod

parse_command(output: str, exit_code: int = 0) -> bool

Parse directory creation result.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def parse_command(self, output: str, exit_code: int = 0) -> bool:
    """Parse directory creation result."""

CreateDirectoryResult dataclass

Result for directory creation commands.

Source code in src/anyenv/os_commands/models.py
@dataclass
class CreateDirectoryResult:
    """Result for directory creation commands."""

    success: bool
    path: str
    created: bool = True

DirectoryEntry dataclass

Directory entry model for detailed listings.

Source code in src/anyenv/os_commands/models.py
@dataclass
class DirectoryEntry:
    """Directory entry model for detailed listings."""

    name: str
    path: str
    type: Literal["file", "directory", "link"]
    size: int
    timestamp: str | None = None
    permissions: str | None = None

EnvVarCommand

Bases: ABC

Base class for environment variable commands.

Source code in src/anyenv/os_commands/base.py
class EnvVarCommand(ABC):
    """Base class for environment variable commands."""

    @abstractmethod
    def create_command(self, name: str) -> str:
        """Generate command to get environment variable value."""

    @abstractmethod
    def parse_command(self, output: str, exit_code: int = 0) -> str | None:
        """Parse output and return variable value or None if not set."""

create_command abstractmethod

create_command(name: str) -> str

Generate command to get environment variable value.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def create_command(self, name: str) -> str:
    """Generate command to get environment variable value."""

parse_command abstractmethod

parse_command(output: str, exit_code: int = 0) -> str | None

Parse output and return variable value or None if not set.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def parse_command(self, output: str, exit_code: int = 0) -> str | None:
    """Parse output and return variable value or None if not set."""

ExistsCommand

Bases: ABC

Base class for exists commands.

Source code in src/anyenv/os_commands/base.py
class ExistsCommand(ABC):
    """Base class for exists commands."""

    @abstractmethod
    def create_command(self, path: str) -> str:
        """Generate exists test command."""

    @abstractmethod
    def parse_command(self, output: str, exit_code: int = 0) -> bool:
        """Parse exists test result."""

create_command abstractmethod

create_command(path: str) -> str

Generate exists test command.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def create_command(self, path: str) -> str:
    """Generate exists test command."""

parse_command abstractmethod

parse_command(output: str, exit_code: int = 0) -> bool

Parse exists test result.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def parse_command(self, output: str, exit_code: int = 0) -> bool:
    """Parse exists test result."""

ExistsResult dataclass

Result for existence check commands.

Source code in src/anyenv/os_commands/models.py
@dataclass
class ExistsResult:
    """Result for existence check commands."""

    exists: bool
    path: str

FileInfo dataclass

File information model.

Source code in src/anyenv/os_commands/models.py
@dataclass
class FileInfo:
    """File information model."""

    name: str
    path: str
    type: Literal["file", "directory", "link"]
    size: int
    mtime: int | None = None
    timestamp: str | None = None
    permissions: str | None = None

FileInfoCommand

Bases: ABC

Base class for file info commands.

Source code in src/anyenv/os_commands/base.py
class FileInfoCommand(ABC):
    """Base class for file info commands."""

    @abstractmethod
    def create_command(self, path: str) -> str:
        """Generate file info command."""

    @abstractmethod
    def parse_command(self, output: str, path: str) -> FileInfo:
        """Parse file info output."""

create_command abstractmethod

create_command(path: str) -> str

Generate file info command.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def create_command(self, path: str) -> str:
    """Generate file info command."""

parse_command abstractmethod

parse_command(output: str, path: str) -> FileInfo

Parse file info output.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def parse_command(self, output: str, path: str) -> FileInfo:
    """Parse file info output."""

FindCommand

Bases: ABC

Base class for recursive find commands.

Used for efficiently finding files/directories recursively in a single command, rather than walking the tree with multiple list operations.

Source code in src/anyenv/os_commands/base.py
class FindCommand(ABC):
    """Base class for recursive find commands.

    Used for efficiently finding files/directories recursively in a single
    command, rather than walking the tree with multiple list operations.
    """

    @abstractmethod
    def create_command(
        self,
        path: str,
        pattern: str | None = None,
        maxdepth: int | None = None,
        file_type: Literal["file", "directory", "all"] = "all",
        with_stats: bool = True,
    ) -> str:
        """Generate recursive find command.

        Args:
            path: Directory to search in
            pattern: Glob pattern for name matching (e.g., "*.py")
            maxdepth: Maximum directory depth to descend (None for unlimited)
            file_type: Filter by type - files only, directories only, or all
            with_stats: Include file stats (size, mtime, type, permissions)
        """

    @abstractmethod
    def parse_command(self, output: str, base_path: str = "") -> list[DirectoryEntry]:
        """Parse find output into DirectoryEntry objects.

        Args:
            output: Raw command output
            base_path: Base path used in the find command

        Returns:
            List of DirectoryEntry objects for found items
        """

create_command abstractmethod

create_command(
    path: str,
    pattern: str | None = None,
    maxdepth: int | None = None,
    file_type: Literal["file", "directory", "all"] = "all",
    with_stats: bool = True,
) -> str

Generate recursive find command.

Parameters:

Name Type Description Default
path str

Directory to search in

required
pattern str | None

Glob pattern for name matching (e.g., "*.py")

None
maxdepth int | None

Maximum directory depth to descend (None for unlimited)

None
file_type Literal['file', 'directory', 'all']

Filter by type - files only, directories only, or all

'all'
with_stats bool

Include file stats (size, mtime, type, permissions)

True
Source code in src/anyenv/os_commands/base.py
@abstractmethod
def create_command(
    self,
    path: str,
    pattern: str | None = None,
    maxdepth: int | None = None,
    file_type: Literal["file", "directory", "all"] = "all",
    with_stats: bool = True,
) -> str:
    """Generate recursive find command.

    Args:
        path: Directory to search in
        pattern: Glob pattern for name matching (e.g., "*.py")
        maxdepth: Maximum directory depth to descend (None for unlimited)
        file_type: Filter by type - files only, directories only, or all
        with_stats: Include file stats (size, mtime, type, permissions)
    """

parse_command abstractmethod

parse_command(output: str, base_path: str = '') -> list[DirectoryEntry]

Parse find output into DirectoryEntry objects.

Parameters:

Name Type Description Default
output str

Raw command output

required
base_path str

Base path used in the find command

''

Returns:

Type Description
list[DirectoryEntry]

List of DirectoryEntry objects for found items

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def parse_command(self, output: str, base_path: str = "") -> list[DirectoryEntry]:
    """Parse find output into DirectoryEntry objects.

    Args:
        output: Raw command output
        base_path: Base path used in the find command

    Returns:
        List of DirectoryEntry objects for found items
    """

IsDirectoryCommand

Bases: ABC

Base class for is directory commands.

Source code in src/anyenv/os_commands/base.py
class IsDirectoryCommand(ABC):
    """Base class for is directory commands."""

    @abstractmethod
    def create_command(self, path: str) -> str:
        """Generate directory test command."""

    @abstractmethod
    def parse_command(self, output: str, exit_code: int = 0) -> bool:
        """Parse directory test result."""

create_command abstractmethod

create_command(path: str) -> str

Generate directory test command.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def create_command(self, path: str) -> str:
    """Generate directory test command."""

parse_command abstractmethod

parse_command(output: str, exit_code: int = 0) -> bool

Parse directory test result.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def parse_command(self, output: str, exit_code: int = 0) -> bool:
    """Parse directory test result."""

IsFileCommand

Bases: ABC

Base class for is file commands.

Source code in src/anyenv/os_commands/base.py
class IsFileCommand(ABC):
    """Base class for is file commands."""

    @abstractmethod
    def create_command(self, path: str) -> str:
        """Generate file test command."""

    @abstractmethod
    def parse_command(self, output: str, exit_code: int = 0) -> bool:
        """Parse file test result."""

create_command abstractmethod

create_command(path: str) -> str

Generate file test command.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def create_command(self, path: str) -> str:
    """Generate file test command."""

parse_command abstractmethod

parse_command(output: str, exit_code: int = 0) -> bool

Parse file test result.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def parse_command(self, output: str, exit_code: int = 0) -> bool:
    """Parse file test result."""

ListDirectoryCommand

Bases: ABC

Base class for list directory commands.

Source code in src/anyenv/os_commands/base.py
class ListDirectoryCommand(ABC):
    """Base class for list directory commands."""

    @abstractmethod
    def create_command(self, path: str = "") -> str:
        """Generate directory listing command."""

    @abstractmethod
    def parse_command(self, output: str, path: str = "") -> list[DirectoryEntry]:
        """Parse directory listing output."""

create_command abstractmethod

create_command(path: str = '') -> str

Generate directory listing command.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def create_command(self, path: str = "") -> str:
    """Generate directory listing command."""

parse_command abstractmethod

parse_command(output: str, path: str = '') -> list[DirectoryEntry]

Parse directory listing output.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def parse_command(self, output: str, path: str = "") -> list[DirectoryEntry]:
    """Parse directory listing output."""

MacOSBase64EncodeCommand

Bases: Base64EncodeCommand

macOS base64 encode command implementation.

Source code in src/anyenv/os_commands/base64_encode.py
class MacOSBase64EncodeCommand(Base64EncodeCommand):
    """macOS base64 encode command implementation."""

    def create_command(self, path: str) -> str:
        """Generate macOS base64 command.

        Args:
            path: Path to file to encode

        Returns:
            The base64 command string
        """
        # macOS base64 uses -i for input file
        return f"base64 -i {sh_path(path)}"

    def parse_command(self, output: str) -> bytes:
        """Parse macOS base64 output.

        Args:
            output: Raw base64 encoded output

        Returns:
            Decoded bytes
        """
        cleaned = output.replace("\n", "").replace("\r", "").strip()
        return base64.b64decode(cleaned)

create_command

create_command(path: str) -> str

Generate macOS base64 command.

Parameters:

Name Type Description Default
path str

Path to file to encode

required

Returns:

Type Description
str

The base64 command string

Source code in src/anyenv/os_commands/base64_encode.py
def create_command(self, path: str) -> str:
    """Generate macOS base64 command.

    Args:
        path: Path to file to encode

    Returns:
        The base64 command string
    """
    # macOS base64 uses -i for input file
    return f"base64 -i {sh_path(path)}"

parse_command

parse_command(output: str) -> bytes

Parse macOS base64 output.

Parameters:

Name Type Description Default
output str

Raw base64 encoded output

required

Returns:

Type Description
bytes

Decoded bytes

Source code in src/anyenv/os_commands/base64_encode.py
def parse_command(self, output: str) -> bytes:
    """Parse macOS base64 output.

    Args:
        output: Raw base64 encoded output

    Returns:
        Decoded bytes
    """
    cleaned = output.replace("\n", "").replace("\r", "").strip()
    return base64.b64decode(cleaned)

MacOSCommandProvider

Bases: OSCommandProvider

macOS command provider using BSD tools.

Source code in src/anyenv/os_commands/providers.py
class MacOSCommandProvider(OSCommandProvider):
    """macOS command provider using BSD tools."""

    def __init__(self) -> None:
        """Initialize macOS command provider with macOS command instances."""
        super().__init__()
        self.commands = {
            "list_directory": MacOSListDirectoryCommand(),
            "file_info": MacOSFileInfoCommand(),
            "exists": MacOSExistsCommand(),
            "is_file": MacOSIsFileCommand(),
            "is_directory": MacOSIsDirectoryCommand(),
            "create_directory": MacOSCreateDirectoryCommand(),
            "remove_path": MacOSRemovePathCommand(),
            "copy_path": MacOSCopyPathCommand(),
            "base64_encode": MacOSBase64EncodeCommand(),
            "which": MacOSWhichCommand(),
            "pwd": MacOSPwdCommand(),
            "env_var": MacOSEnvVarCommand(),
            "find": MacOSFindCommand(),
        }

__init__

__init__() -> None

Initialize macOS command provider with macOS command instances.

Source code in src/anyenv/os_commands/providers.py
def __init__(self) -> None:
    """Initialize macOS command provider with macOS command instances."""
    super().__init__()
    self.commands = {
        "list_directory": MacOSListDirectoryCommand(),
        "file_info": MacOSFileInfoCommand(),
        "exists": MacOSExistsCommand(),
        "is_file": MacOSIsFileCommand(),
        "is_directory": MacOSIsDirectoryCommand(),
        "create_directory": MacOSCreateDirectoryCommand(),
        "remove_path": MacOSRemovePathCommand(),
        "copy_path": MacOSCopyPathCommand(),
        "base64_encode": MacOSBase64EncodeCommand(),
        "which": MacOSWhichCommand(),
        "pwd": MacOSPwdCommand(),
        "env_var": MacOSEnvVarCommand(),
        "find": MacOSFindCommand(),
    }

MacOSCopyPathCommand

Bases: CopyPathCommand

macOS copy path command implementation.

Source code in src/anyenv/os_commands/copy_path.py
class MacOSCopyPathCommand(CopyPathCommand):
    """macOS copy path command implementation."""

    def create_command(self, source: str, destination: str, recursive: bool = False) -> str:
        """Generate cp command (same as Unix).

        Args:
            source: Source path to copy from
            destination: Destination path to copy to
            recursive: Whether to copy directories recursively

        Returns:
            The cp command string
        """
        if recursive:
            return f"cp -r {sh_path(source)} {sh_path(destination)}"
        return f"cp {sh_path(source)} {sh_path(destination)}"

    def parse_command(self, output: str, exit_code: int = 0) -> bool:
        """Parse cp result based on exit code (same as Unix).

        Args:
            output: Raw command output (ignored)
            exit_code: Command exit code

        Returns:
            True if copy was successful, False otherwise
        """
        return exit_code == 0

create_command

create_command(source: str, destination: str, recursive: bool = False) -> str

Generate cp command (same as Unix).

Parameters:

Name Type Description Default
source str

Source path to copy from

required
destination str

Destination path to copy to

required
recursive bool

Whether to copy directories recursively

False

Returns:

Type Description
str

The cp command string

Source code in src/anyenv/os_commands/copy_path.py
def create_command(self, source: str, destination: str, recursive: bool = False) -> str:
    """Generate cp command (same as Unix).

    Args:
        source: Source path to copy from
        destination: Destination path to copy to
        recursive: Whether to copy directories recursively

    Returns:
        The cp command string
    """
    if recursive:
        return f"cp -r {sh_path(source)} {sh_path(destination)}"
    return f"cp {sh_path(source)} {sh_path(destination)}"

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse cp result based on exit code (same as Unix).

Parameters:

Name Type Description Default
output str

Raw command output (ignored)

required
exit_code int

Command exit code

0

Returns:

Type Description
bool

True if copy was successful, False otherwise

Source code in src/anyenv/os_commands/copy_path.py
def parse_command(self, output: str, exit_code: int = 0) -> bool:
    """Parse cp result based on exit code (same as Unix).

    Args:
        output: Raw command output (ignored)
        exit_code: Command exit code

    Returns:
        True if copy was successful, False otherwise
    """
    return exit_code == 0

MacOSCreateDirectoryCommand

Bases: CreateDirectoryCommand

macOS create directory command implementation.

Source code in src/anyenv/os_commands/create_directory.py
class MacOSCreateDirectoryCommand(CreateDirectoryCommand):
    """macOS create directory command implementation."""

    def create_command(self, path: str, parents: bool = True) -> str:
        """Generate mkdir command (same as Unix).

        Args:
            path: Directory path to create
            parents: Whether to create parent directories

        Returns:
            The mkdir command string
        """
        return f"mkdir -p {sh_path(path)}" if parents else f"mkdir {sh_path(path)}"

    def parse_command(
        self,
        output: str,
        exit_code: int = 0,
    ) -> bool:
        """Parse mkdir result based on exit code (same as Unix).

        Args:
            output: Raw command output (ignored)
            exit_code: Command exit code

        Returns:
            True if directory was created successfully, False otherwise
        """
        return exit_code == 0

create_command

create_command(path: str, parents: bool = True) -> str

Generate mkdir command (same as Unix).

Parameters:

Name Type Description Default
path str

Directory path to create

required
parents bool

Whether to create parent directories

True

Returns:

Type Description
str

The mkdir command string

Source code in src/anyenv/os_commands/create_directory.py
def create_command(self, path: str, parents: bool = True) -> str:
    """Generate mkdir command (same as Unix).

    Args:
        path: Directory path to create
        parents: Whether to create parent directories

    Returns:
        The mkdir command string
    """
    return f"mkdir -p {sh_path(path)}" if parents else f"mkdir {sh_path(path)}"

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse mkdir result based on exit code (same as Unix).

Parameters:

Name Type Description Default
output str

Raw command output (ignored)

required
exit_code int

Command exit code

0

Returns:

Type Description
bool

True if directory was created successfully, False otherwise

Source code in src/anyenv/os_commands/create_directory.py
def parse_command(
    self,
    output: str,
    exit_code: int = 0,
) -> bool:
    """Parse mkdir result based on exit code (same as Unix).

    Args:
        output: Raw command output (ignored)
        exit_code: Command exit code

    Returns:
        True if directory was created successfully, False otherwise
    """
    return exit_code == 0

MacOSEnvVarCommand

Bases: EnvVarCommand

macOS environment variable command implementation.

Source code in src/anyenv/os_commands/env_var.py
class MacOSEnvVarCommand(EnvVarCommand):
    """macOS environment variable command implementation."""

    def create_command(self, name: str) -> str:
        """Generate printenv command (same as Unix).

        Args:
            name: Name of environment variable

        Returns:
            The printenv command string
        """
        return f"printenv {sh_quote(name)}"

    def parse_command(self, output: str, exit_code: int = 0) -> str | None:
        """Parse printenv result (same as Unix).

        Args:
            output: Raw command output
            exit_code: Command exit code

        Returns:
            Variable value or None if not set
        """
        if exit_code != 0:
            return None
        return output.rstrip("\n") if output else None

create_command

create_command(name: str) -> str

Generate printenv command (same as Unix).

Parameters:

Name Type Description Default
name str

Name of environment variable

required

Returns:

Type Description
str

The printenv command string

Source code in src/anyenv/os_commands/env_var.py
def create_command(self, name: str) -> str:
    """Generate printenv command (same as Unix).

    Args:
        name: Name of environment variable

    Returns:
        The printenv command string
    """
    return f"printenv {sh_quote(name)}"

parse_command

parse_command(output: str, exit_code: int = 0) -> str | None

Parse printenv result (same as Unix).

Parameters:

Name Type Description Default
output str

Raw command output

required
exit_code int

Command exit code

0

Returns:

Type Description
str | None

Variable value or None if not set

Source code in src/anyenv/os_commands/env_var.py
def parse_command(self, output: str, exit_code: int = 0) -> str | None:
    """Parse printenv result (same as Unix).

    Args:
        output: Raw command output
        exit_code: Command exit code

    Returns:
        Variable value or None if not set
    """
    if exit_code != 0:
        return None
    return output.rstrip("\n") if output else None

MacOSExistsCommand

Bases: ExistsCommand

macOS exists command implementation.

Source code in src/anyenv/os_commands/exists.py
class MacOSExistsCommand(ExistsCommand):
    """macOS exists command implementation."""

    def create_command(self, path: str) -> str:
        """Generate test -e command (same as Unix).

        Args:
            path: Path to test for existence

        Returns:
            The test command string
        """
        return f"test -e {sh_path(path)}"

    def parse_command(
        self,
        output: str,
        exit_code: int = 0,
    ) -> bool:
        """Parse test result based on exit code (same as Unix).

        Args:
            output: Raw command output (ignored)
            exit_code: Command exit code

        Returns:
            True if path exists, False otherwise
        """
        return exit_code == 0

create_command

create_command(path: str) -> str

Generate test -e command (same as Unix).

Parameters:

Name Type Description Default
path str

Path to test for existence

required

Returns:

Type Description
str

The test command string

Source code in src/anyenv/os_commands/exists.py
def create_command(self, path: str) -> str:
    """Generate test -e command (same as Unix).

    Args:
        path: Path to test for existence

    Returns:
        The test command string
    """
    return f"test -e {sh_path(path)}"

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse test result based on exit code (same as Unix).

Parameters:

Name Type Description Default
output str

Raw command output (ignored)

required
exit_code int

Command exit code

0

Returns:

Type Description
bool

True if path exists, False otherwise

Source code in src/anyenv/os_commands/exists.py
def parse_command(
    self,
    output: str,
    exit_code: int = 0,
) -> bool:
    """Parse test result based on exit code (same as Unix).

    Args:
        output: Raw command output (ignored)
        exit_code: Command exit code

    Returns:
        True if path exists, False otherwise
    """
    return exit_code == 0

MacOSFileInfoCommand

Bases: FileInfoCommand

macOS file info command implementation using ls -la.

Source code in src/anyenv/os_commands/file_info.py
class MacOSFileInfoCommand(FileInfoCommand):
    """macOS file info command implementation using ls -la."""

    def create_command(self, path: str) -> str:
        """Generate ls -la command for file info.

        Uses ls -la instead of stat to avoid shell expansion issues with
        format specifiers.

        Args:
            path: Path to get information about

        Returns:
            The ls command string
        """
        return f"ls -lad {sh_path(path)}"

    def parse_command(self, output: str, path: str) -> FileInfo:
        """Parse ls -la output for a single file/directory.

        BSD ls output format is same as Unix.

        Args:
            output: Raw ls -la command output
            path: Original path requested

        Returns:
            FileInfo object with parsed information
        """
        # BSD ls output format is same as Unix
        unix_cmd = UnixFileInfoCommand()
        return unix_cmd.parse_command(output, path)

create_command

create_command(path: str) -> str

Generate ls -la command for file info.

Uses ls -la instead of stat to avoid shell expansion issues with format specifiers.

Parameters:

Name Type Description Default
path str

Path to get information about

required

Returns:

Type Description
str

The ls command string

Source code in src/anyenv/os_commands/file_info.py
def create_command(self, path: str) -> str:
    """Generate ls -la command for file info.

    Uses ls -la instead of stat to avoid shell expansion issues with
    format specifiers.

    Args:
        path: Path to get information about

    Returns:
        The ls command string
    """
    return f"ls -lad {sh_path(path)}"

parse_command

parse_command(output: str, path: str) -> FileInfo

Parse ls -la output for a single file/directory.

BSD ls output format is same as Unix.

Parameters:

Name Type Description Default
output str

Raw ls -la command output

required
path str

Original path requested

required

Returns:

Type Description
FileInfo

FileInfo object with parsed information

Source code in src/anyenv/os_commands/file_info.py
def parse_command(self, output: str, path: str) -> FileInfo:
    """Parse ls -la output for a single file/directory.

    BSD ls output format is same as Unix.

    Args:
        output: Raw ls -la command output
        path: Original path requested

    Returns:
        FileInfo object with parsed information
    """
    # BSD ls output format is same as Unix
    unix_cmd = UnixFileInfoCommand()
    return unix_cmd.parse_command(output, path)

MacOSFindCommand

Bases: FindCommand

macOS find command implementation (BSD find).

Source code in src/anyenv/os_commands/find.py
class MacOSFindCommand(FindCommand):
    """macOS find command implementation (BSD find)."""

    def create_command(
        self,
        path: str,
        pattern: str | None = None,
        maxdepth: int | None = None,
        file_type: Literal["file", "directory", "all"] = "all",
        with_stats: bool = True,
    ) -> str:
        """Generate macOS find command.

        BSD find doesn't support -printf, so we use -exec stat for file stats.

        Args:
            path: Directory to search in
            pattern: Glob pattern for name matching (e.g., "*.py")
            maxdepth: Maximum directory depth to descend
            file_type: Filter by type - files only, directories only, or all
            with_stats: Include file stats (uses -exec stat, slower than GNU -printf)

        Returns:
            The find command string
        """
        parts = ["find", sh_path(path)]

        if maxdepth is not None:
            parts.append(f"-maxdepth {int(maxdepth)}")

        if file_type == "file":
            parts.append("-type f")
        elif file_type == "directory":
            parts.append("-type d")

        if pattern:
            parts.append(f"-name {sh_quote(pattern)}")

        if with_stats:
            # BSD stat format: path\tsize\tmtime\ttype\tpermissions
            # %N = path, %z = size, %m = mtime (unix timestamp)
            # %HT = type (Regular File, Directory, etc.), %Sp = permissions
            # Single quotes protect the format string from shell interpretation
            parts.append(r"-exec stat -f '%N\t%z\t%m\t%HT\t%Sp' {} \;")

        return " ".join(parts)

    def parse_command(self, output: str, base_path: str = "") -> list[DirectoryEntry]:
        """Parse macOS find output.

        Handles both plain path output and stat-formatted output with stats.

        Args:
            output: Raw find command output
            base_path: Base path used in the find command

        Returns:
            List of DirectoryEntry objects
        """
        lines = output.strip().split("\n")
        if not lines or (len(lines) == 1 and not lines[0]):
            return []

        entries: list[DirectoryEntry] = []
        for line in lines:
            line = line.strip()
            if not line:
                continue

            # Check if this is stat-formatted output (contains tabs)
            if "\t" in line:
                parts = line.rsplit("\t", 4)
                if len(parts) == 5:  # noqa: PLR2004
                    path_str, size_str, timestamp_str, type_str, permissions = parts

                    # Map BSD stat type string to our type
                    if "Directory" in type_str:
                        entry_type: Literal["file", "directory", "link"] = "directory"
                    elif "Link" in type_str:
                        entry_type = "link"
                    else:
                        entry_type = "file"

                    try:
                        size = int(size_str)
                    except ValueError:
                        size = 0

                    name = path_str.rsplit("/", 1)[-1] if "/" in path_str else path_str

                    if name in (".", ".."):
                        continue

                    entries.append(
                        DirectoryEntry(
                            name=name,
                            path=path_str,
                            type=entry_type,
                            size=size,
                            timestamp=timestamp_str,
                            permissions=permissions,
                        )
                    )
                    continue

            # Fallback: plain path output
            name = line.rsplit("/", 1)[-1] if "/" in line else line

            if name in (".", ".."):
                continue

            entries.append(
                DirectoryEntry(
                    name=name,
                    path=line,
                    type="file",
                    size=0,
                    timestamp=None,
                    permissions=None,
                )
            )

        return entries

create_command

create_command(
    path: str,
    pattern: str | None = None,
    maxdepth: int | None = None,
    file_type: Literal["file", "directory", "all"] = "all",
    with_stats: bool = True,
) -> str

Generate macOS find command.

BSD find doesn't support -printf, so we use -exec stat for file stats.

Parameters:

Name Type Description Default
path str

Directory to search in

required
pattern str | None

Glob pattern for name matching (e.g., "*.py")

None
maxdepth int | None

Maximum directory depth to descend

None
file_type Literal['file', 'directory', 'all']

Filter by type - files only, directories only, or all

'all'
with_stats bool

Include file stats (uses -exec stat, slower than GNU -printf)

True

Returns:

Type Description
str

The find command string

Source code in src/anyenv/os_commands/find.py
def create_command(
    self,
    path: str,
    pattern: str | None = None,
    maxdepth: int | None = None,
    file_type: Literal["file", "directory", "all"] = "all",
    with_stats: bool = True,
) -> str:
    """Generate macOS find command.

    BSD find doesn't support -printf, so we use -exec stat for file stats.

    Args:
        path: Directory to search in
        pattern: Glob pattern for name matching (e.g., "*.py")
        maxdepth: Maximum directory depth to descend
        file_type: Filter by type - files only, directories only, or all
        with_stats: Include file stats (uses -exec stat, slower than GNU -printf)

    Returns:
        The find command string
    """
    parts = ["find", sh_path(path)]

    if maxdepth is not None:
        parts.append(f"-maxdepth {int(maxdepth)}")

    if file_type == "file":
        parts.append("-type f")
    elif file_type == "directory":
        parts.append("-type d")

    if pattern:
        parts.append(f"-name {sh_quote(pattern)}")

    if with_stats:
        # BSD stat format: path\tsize\tmtime\ttype\tpermissions
        # %N = path, %z = size, %m = mtime (unix timestamp)
        # %HT = type (Regular File, Directory, etc.), %Sp = permissions
        # Single quotes protect the format string from shell interpretation
        parts.append(r"-exec stat -f '%N\t%z\t%m\t%HT\t%Sp' {} \;")

    return " ".join(parts)

parse_command

parse_command(output: str, base_path: str = '') -> list[DirectoryEntry]

Parse macOS find output.

Handles both plain path output and stat-formatted output with stats.

Parameters:

Name Type Description Default
output str

Raw find command output

required
base_path str

Base path used in the find command

''

Returns:

Type Description
list[DirectoryEntry]

List of DirectoryEntry objects

Source code in src/anyenv/os_commands/find.py
def parse_command(self, output: str, base_path: str = "") -> list[DirectoryEntry]:
    """Parse macOS find output.

    Handles both plain path output and stat-formatted output with stats.

    Args:
        output: Raw find command output
        base_path: Base path used in the find command

    Returns:
        List of DirectoryEntry objects
    """
    lines = output.strip().split("\n")
    if not lines or (len(lines) == 1 and not lines[0]):
        return []

    entries: list[DirectoryEntry] = []
    for line in lines:
        line = line.strip()
        if not line:
            continue

        # Check if this is stat-formatted output (contains tabs)
        if "\t" in line:
            parts = line.rsplit("\t", 4)
            if len(parts) == 5:  # noqa: PLR2004
                path_str, size_str, timestamp_str, type_str, permissions = parts

                # Map BSD stat type string to our type
                if "Directory" in type_str:
                    entry_type: Literal["file", "directory", "link"] = "directory"
                elif "Link" in type_str:
                    entry_type = "link"
                else:
                    entry_type = "file"

                try:
                    size = int(size_str)
                except ValueError:
                    size = 0

                name = path_str.rsplit("/", 1)[-1] if "/" in path_str else path_str

                if name in (".", ".."):
                    continue

                entries.append(
                    DirectoryEntry(
                        name=name,
                        path=path_str,
                        type=entry_type,
                        size=size,
                        timestamp=timestamp_str,
                        permissions=permissions,
                    )
                )
                continue

        # Fallback: plain path output
        name = line.rsplit("/", 1)[-1] if "/" in line else line

        if name in (".", ".."):
            continue

        entries.append(
            DirectoryEntry(
                name=name,
                path=line,
                type="file",
                size=0,
                timestamp=None,
                permissions=None,
            )
        )

    return entries

MacOSIsDirectoryCommand

Bases: IsDirectoryCommand

macOS is directory command implementation.

Source code in src/anyenv/os_commands/is_directory.py
class MacOSIsDirectoryCommand(IsDirectoryCommand):
    """macOS is directory command implementation."""

    def create_command(self, path: str) -> str:
        """Generate test -d command (same as Unix).

        Args:
            path: Path to test if it's a directory

        Returns:
            The test command string
        """
        return f"test -d {sh_path(path)}"

    def parse_command(
        self,
        output: str,
        exit_code: int = 0,
    ) -> bool:
        """Parse test -d result based on exit code (same as Unix).

        Args:
            output: Raw command output (ignored)
            exit_code: Command exit code

        Returns:
            True if path is a directory, False otherwise
        """
        return exit_code == 0

create_command

create_command(path: str) -> str

Generate test -d command (same as Unix).

Parameters:

Name Type Description Default
path str

Path to test if it's a directory

required

Returns:

Type Description
str

The test command string

Source code in src/anyenv/os_commands/is_directory.py
def create_command(self, path: str) -> str:
    """Generate test -d command (same as Unix).

    Args:
        path: Path to test if it's a directory

    Returns:
        The test command string
    """
    return f"test -d {sh_path(path)}"

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse test -d result based on exit code (same as Unix).

Parameters:

Name Type Description Default
output str

Raw command output (ignored)

required
exit_code int

Command exit code

0

Returns:

Type Description
bool

True if path is a directory, False otherwise

Source code in src/anyenv/os_commands/is_directory.py
def parse_command(
    self,
    output: str,
    exit_code: int = 0,
) -> bool:
    """Parse test -d result based on exit code (same as Unix).

    Args:
        output: Raw command output (ignored)
        exit_code: Command exit code

    Returns:
        True if path is a directory, False otherwise
    """
    return exit_code == 0

MacOSIsFileCommand

Bases: IsFileCommand

macOS is file command implementation.

Source code in src/anyenv/os_commands/is_file.py
class MacOSIsFileCommand(IsFileCommand):
    """macOS is file command implementation."""

    def create_command(self, path: str) -> str:
        """Generate test -f command (same as Unix).

        Args:
            path: Path to test if it's a file

        Returns:
            The test command string
        """
        return f"test -f {sh_path(path)}"

    def parse_command(
        self,
        output: str,
        exit_code: int = 0,
    ) -> bool:
        """Parse test -f result based on exit code (same as Unix).

        Args:
            output: Raw command output (ignored)
            exit_code: Command exit code

        Returns:
            True if path is a file, False otherwise
        """
        return exit_code == 0

create_command

create_command(path: str) -> str

Generate test -f command (same as Unix).

Parameters:

Name Type Description Default
path str

Path to test if it's a file

required

Returns:

Type Description
str

The test command string

Source code in src/anyenv/os_commands/is_file.py
def create_command(self, path: str) -> str:
    """Generate test -f command (same as Unix).

    Args:
        path: Path to test if it's a file

    Returns:
        The test command string
    """
    return f"test -f {sh_path(path)}"

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse test -f result based on exit code (same as Unix).

Parameters:

Name Type Description Default
output str

Raw command output (ignored)

required
exit_code int

Command exit code

0

Returns:

Type Description
bool

True if path is a file, False otherwise

Source code in src/anyenv/os_commands/is_file.py
def parse_command(
    self,
    output: str,
    exit_code: int = 0,
) -> bool:
    """Parse test -f result based on exit code (same as Unix).

    Args:
        output: Raw command output (ignored)
        exit_code: Command exit code

    Returns:
        True if path is a file, False otherwise
    """
    return exit_code == 0

MacOSListDirectoryCommand

Bases: ListDirectoryCommand

macOS list directory command implementation.

Source code in src/anyenv/os_commands/list_directory.py
class MacOSListDirectoryCommand(ListDirectoryCommand):
    """macOS list directory command implementation."""

    def create_command(self, path: str = "") -> str:
        """Generate BSD ls command (no --time-style support).

        Args:
            path: Directory path to list

        Returns:
            The ls command string
        """
        cmd = "ls -la"
        return f"{cmd} {sh_path(path)}" if path else cmd

    def parse_command(
        self,
        output: str,
        path: str = "",
    ) -> list[DirectoryEntry]:
        """Parse BSD ls output (same as Unix).

        Args:
            output: Raw ls command output
            path: Base directory path

        Returns:
            List of DirectoryEntry objects
        """
        # BSD ls output format is same as Unix, just different timestamp format
        unix_cmd = UnixListDirectoryCommand()
        return unix_cmd.parse_command(output, path=path)

create_command

create_command(path: str = '') -> str

Generate BSD ls command (no --time-style support).

Parameters:

Name Type Description Default
path str

Directory path to list

''

Returns:

Type Description
str

The ls command string

Source code in src/anyenv/os_commands/list_directory.py
def create_command(self, path: str = "") -> str:
    """Generate BSD ls command (no --time-style support).

    Args:
        path: Directory path to list

    Returns:
        The ls command string
    """
    cmd = "ls -la"
    return f"{cmd} {sh_path(path)}" if path else cmd

parse_command

parse_command(output: str, path: str = '') -> list[DirectoryEntry]

Parse BSD ls output (same as Unix).

Parameters:

Name Type Description Default
output str

Raw ls command output

required
path str

Base directory path

''

Returns:

Type Description
list[DirectoryEntry]

List of DirectoryEntry objects

Source code in src/anyenv/os_commands/list_directory.py
def parse_command(
    self,
    output: str,
    path: str = "",
) -> list[DirectoryEntry]:
    """Parse BSD ls output (same as Unix).

    Args:
        output: Raw ls command output
        path: Base directory path

    Returns:
        List of DirectoryEntry objects
    """
    # BSD ls output format is same as Unix, just different timestamp format
    unix_cmd = UnixListDirectoryCommand()
    return unix_cmd.parse_command(output, path=path)

MacOSPwdCommand

Bases: PwdCommand

macOS pwd command implementation.

Source code in src/anyenv/os_commands/pwd.py
class MacOSPwdCommand(PwdCommand):
    """macOS pwd command implementation."""

    def create_command(self) -> str:
        """Generate pwd command (same as Unix).

        Returns:
            The pwd command string
        """
        return "pwd"

    def parse_command(self, output: str, exit_code: int = 0) -> str | None:
        """Parse pwd result (same as Unix).

        Args:
            output: Raw command output
            exit_code: Command exit code

        Returns:
            Current working directory or None on failure
        """
        if exit_code != 0:
            return None
        path = output.strip()
        return path if path else None

create_command

create_command() -> str

Generate pwd command (same as Unix).

Returns:

Type Description
str

The pwd command string

Source code in src/anyenv/os_commands/pwd.py
def create_command(self) -> str:
    """Generate pwd command (same as Unix).

    Returns:
        The pwd command string
    """
    return "pwd"

parse_command

parse_command(output: str, exit_code: int = 0) -> str | None

Parse pwd result (same as Unix).

Parameters:

Name Type Description Default
output str

Raw command output

required
exit_code int

Command exit code

0

Returns:

Type Description
str | None

Current working directory or None on failure

Source code in src/anyenv/os_commands/pwd.py
def parse_command(self, output: str, exit_code: int = 0) -> str | None:
    """Parse pwd result (same as Unix).

    Args:
        output: Raw command output
        exit_code: Command exit code

    Returns:
        Current working directory or None on failure
    """
    if exit_code != 0:
        return None
    path = output.strip()
    return path if path else None

MacOSRemovePathCommand

Bases: RemovePathCommand

macOS remove path command implementation.

Source code in src/anyenv/os_commands/remove_path.py
class MacOSRemovePathCommand(RemovePathCommand):
    """macOS remove path command implementation."""

    def create_command(self, path: str, recursive: bool = False) -> str:
        """Generate rm command (same as Unix).

        Args:
            path: Path to remove
            recursive: Whether to remove directories recursively

        Returns:
            The rm command string
        """
        return f"rm -rf {sh_path(path)}" if recursive else f"rm {sh_path(path)}"

    def parse_command(
        self,
        output: str,
        exit_code: int = 0,
    ) -> bool:
        """Parse rm result based on exit code (same as Unix).

        Args:
            output: Raw command output (ignored)
            exit_code: Command exit code

        Returns:
            True if path was removed successfully, False otherwise
        """
        return exit_code == 0

create_command

create_command(path: str, recursive: bool = False) -> str

Generate rm command (same as Unix).

Parameters:

Name Type Description Default
path str

Path to remove

required
recursive bool

Whether to remove directories recursively

False

Returns:

Type Description
str

The rm command string

Source code in src/anyenv/os_commands/remove_path.py
def create_command(self, path: str, recursive: bool = False) -> str:
    """Generate rm command (same as Unix).

    Args:
        path: Path to remove
        recursive: Whether to remove directories recursively

    Returns:
        The rm command string
    """
    return f"rm -rf {sh_path(path)}" if recursive else f"rm {sh_path(path)}"

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse rm result based on exit code (same as Unix).

Parameters:

Name Type Description Default
output str

Raw command output (ignored)

required
exit_code int

Command exit code

0

Returns:

Type Description
bool

True if path was removed successfully, False otherwise

Source code in src/anyenv/os_commands/remove_path.py
def parse_command(
    self,
    output: str,
    exit_code: int = 0,
) -> bool:
    """Parse rm result based on exit code (same as Unix).

    Args:
        output: Raw command output (ignored)
        exit_code: Command exit code

    Returns:
        True if path was removed successfully, False otherwise
    """
    return exit_code == 0

MacOSWhichCommand

Bases: WhichCommand

macOS which command implementation.

Source code in src/anyenv/os_commands/which.py
class MacOSWhichCommand(WhichCommand):
    """macOS which command implementation."""

    def create_command(self, executable: str) -> str:
        """Generate which command (same as Unix).

        Args:
            executable: Name of executable to find

        Returns:
            The which command string
        """
        return f"which {sh_quote(executable)}"

    def parse_command(self, output: str, exit_code: int = 0) -> str | None:
        """Parse which result (same as Unix).

        Args:
            output: Raw command output
            exit_code: Command exit code

        Returns:
            Path to executable or None if not found
        """
        if exit_code != 0:
            return None
        path = output.strip()
        return path if path else None

create_command

create_command(executable: str) -> str

Generate which command (same as Unix).

Parameters:

Name Type Description Default
executable str

Name of executable to find

required

Returns:

Type Description
str

The which command string

Source code in src/anyenv/os_commands/which.py
def create_command(self, executable: str) -> str:
    """Generate which command (same as Unix).

    Args:
        executable: Name of executable to find

    Returns:
        The which command string
    """
    return f"which {sh_quote(executable)}"

parse_command

parse_command(output: str, exit_code: int = 0) -> str | None

Parse which result (same as Unix).

Parameters:

Name Type Description Default
output str

Raw command output

required
exit_code int

Command exit code

0

Returns:

Type Description
str | None

Path to executable or None if not found

Source code in src/anyenv/os_commands/which.py
def parse_command(self, output: str, exit_code: int = 0) -> str | None:
    """Parse which result (same as Unix).

    Args:
        output: Raw command output
        exit_code: Command exit code

    Returns:
        Path to executable or None if not found
    """
    if exit_code != 0:
        return None
    path = output.strip()
    return path if path else None

OSCommandProvider

Base class for OS-specific command providers using command classes.

Source code in src/anyenv/os_commands/providers.py
class OSCommandProvider:
    """Base class for OS-specific command providers using command classes."""

    def __init__(self) -> None:
        """Initialize the command provider with command instances."""
        self.commands: dict[
            str,
            ListDirectoryCommand
            | FileInfoCommand
            | ExistsCommand
            | IsFileCommand
            | IsDirectoryCommand
            | CreateDirectoryCommand
            | RemovePathCommand
            | CopyPathCommand
            | Base64EncodeCommand
            | WhichCommand
            | PwdCommand
            | EnvVarCommand
            | FindCommand,
        ] = {}

    @overload
    def get_command(self, command_type: Literal["list_directory"]) -> ListDirectoryCommand: ...

    @overload
    def get_command(self, command_type: Literal["file_info"]) -> FileInfoCommand: ...

    @overload
    def get_command(self, command_type: Literal["exists"]) -> ExistsCommand: ...

    @overload
    def get_command(self, command_type: Literal["is_file"]) -> IsFileCommand: ...

    @overload
    def get_command(self, command_type: Literal["is_directory"]) -> IsDirectoryCommand: ...

    @overload
    def get_command(self, command_type: Literal["create_directory"]) -> CreateDirectoryCommand: ...

    @overload
    def get_command(self, command_type: Literal["remove_path"]) -> RemovePathCommand: ...

    @overload
    def get_command(self, command_type: Literal["copy_path"]) -> CopyPathCommand: ...

    @overload
    def get_command(self, command_type: Literal["base64_encode"]) -> Base64EncodeCommand: ...

    @overload
    def get_command(self, command_type: Literal["which"]) -> WhichCommand: ...

    @overload
    def get_command(self, command_type: Literal["pwd"]) -> PwdCommand: ...

    @overload
    def get_command(self, command_type: Literal["env_var"]) -> EnvVarCommand: ...

    @overload
    def get_command(self, command_type: Literal["find"]) -> FindCommand: ...

    def get_command(
        self, command_type: CommandType
    ) -> (
        ListDirectoryCommand
        | FileInfoCommand
        | ExistsCommand
        | IsFileCommand
        | IsDirectoryCommand
        | CreateDirectoryCommand
        | RemovePathCommand
        | CopyPathCommand
        | Base64EncodeCommand
        | WhichCommand
        | PwdCommand
        | EnvVarCommand
        | FindCommand
    ):
        """Get command instance by type."""
        return self.commands[command_type]

__init__

__init__() -> None

Initialize the command provider with command instances.

Source code in src/anyenv/os_commands/providers.py
def __init__(self) -> None:
    """Initialize the command provider with command instances."""
    self.commands: dict[
        str,
        ListDirectoryCommand
        | FileInfoCommand
        | ExistsCommand
        | IsFileCommand
        | IsDirectoryCommand
        | CreateDirectoryCommand
        | RemovePathCommand
        | CopyPathCommand
        | Base64EncodeCommand
        | WhichCommand
        | PwdCommand
        | EnvVarCommand
        | FindCommand,
    ] = {}

get_command

get_command(command_type: Literal['list_directory']) -> ListDirectoryCommand
get_command(command_type: Literal['file_info']) -> FileInfoCommand
get_command(command_type: Literal['exists']) -> ExistsCommand
get_command(command_type: Literal['is_file']) -> IsFileCommand
get_command(command_type: Literal['is_directory']) -> IsDirectoryCommand
get_command(command_type: Literal['create_directory']) -> CreateDirectoryCommand
get_command(command_type: Literal['remove_path']) -> RemovePathCommand
get_command(command_type: Literal['copy_path']) -> CopyPathCommand
get_command(command_type: Literal['base64_encode']) -> Base64EncodeCommand
get_command(command_type: Literal['which']) -> WhichCommand
get_command(command_type: Literal['pwd']) -> PwdCommand
get_command(command_type: Literal['env_var']) -> EnvVarCommand
get_command(command_type: Literal['find']) -> FindCommand

Get command instance by type.

Source code in src/anyenv/os_commands/providers.py
def get_command(
    self, command_type: CommandType
) -> (
    ListDirectoryCommand
    | FileInfoCommand
    | ExistsCommand
    | IsFileCommand
    | IsDirectoryCommand
    | CreateDirectoryCommand
    | RemovePathCommand
    | CopyPathCommand
    | Base64EncodeCommand
    | WhichCommand
    | PwdCommand
    | EnvVarCommand
    | FindCommand
):
    """Get command instance by type."""
    return self.commands[command_type]

PwdCommand

Bases: ABC

Base class for pwd (print working directory) commands.

Source code in src/anyenv/os_commands/base.py
class PwdCommand(ABC):
    """Base class for pwd (print working directory) commands."""

    @abstractmethod
    def create_command(self) -> str:
        """Generate command to get current working directory."""

    @abstractmethod
    def parse_command(self, output: str, exit_code: int = 0) -> str | None:
        """Parse output and return current directory or None on failure."""

create_command abstractmethod

create_command() -> str

Generate command to get current working directory.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def create_command(self) -> str:
    """Generate command to get current working directory."""

parse_command abstractmethod

parse_command(output: str, exit_code: int = 0) -> str | None

Parse output and return current directory or None on failure.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def parse_command(self, output: str, exit_code: int = 0) -> str | None:
    """Parse output and return current directory or None on failure."""

RemovePathCommand

Bases: ABC

Base class for remove path commands.

Source code in src/anyenv/os_commands/base.py
class RemovePathCommand(ABC):
    """Base class for remove path commands."""

    @abstractmethod
    def create_command(self, path: str, recursive: bool = False) -> str:
        """Generate removal command."""

    @abstractmethod
    def parse_command(self, output: str, exit_code: int = 0) -> bool:
        """Parse removal result."""

create_command abstractmethod

create_command(path: str, recursive: bool = False) -> str

Generate removal command.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def create_command(self, path: str, recursive: bool = False) -> str:
    """Generate removal command."""

parse_command abstractmethod

parse_command(output: str, exit_code: int = 0) -> bool

Parse removal result.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def parse_command(self, output: str, exit_code: int = 0) -> bool:
    """Parse removal result."""

RemovePathResult dataclass

Result for path removal commands.

Source code in src/anyenv/os_commands/models.py
@dataclass
class RemovePathResult:
    """Result for path removal commands."""

    success: bool
    path: str
    removed: bool = True

UnixBase64EncodeCommand

Bases: Base64EncodeCommand

Unix/Linux base64 encode command implementation.

Source code in src/anyenv/os_commands/base64_encode.py
class UnixBase64EncodeCommand(Base64EncodeCommand):
    """Unix/Linux base64 encode command implementation."""

    def create_command(self, path: str) -> str:
        """Generate Unix base64 command.

        Args:
            path: Path to file to encode

        Returns:
            The base64 command string
        """
        return f"base64 {sh_path(path)}"

    def parse_command(self, output: str) -> bytes:
        """Parse Unix base64 output.

        Args:
            output: Raw base64 encoded output

        Returns:
            Decoded bytes
        """
        # Remove any whitespace/newlines that base64 command may add
        cleaned = output.replace("\n", "").replace("\r", "").strip()
        return base64.b64decode(cleaned)

create_command

create_command(path: str) -> str

Generate Unix base64 command.

Parameters:

Name Type Description Default
path str

Path to file to encode

required

Returns:

Type Description
str

The base64 command string

Source code in src/anyenv/os_commands/base64_encode.py
def create_command(self, path: str) -> str:
    """Generate Unix base64 command.

    Args:
        path: Path to file to encode

    Returns:
        The base64 command string
    """
    return f"base64 {sh_path(path)}"

parse_command

parse_command(output: str) -> bytes

Parse Unix base64 output.

Parameters:

Name Type Description Default
output str

Raw base64 encoded output

required

Returns:

Type Description
bytes

Decoded bytes

Source code in src/anyenv/os_commands/base64_encode.py
def parse_command(self, output: str) -> bytes:
    """Parse Unix base64 output.

    Args:
        output: Raw base64 encoded output

    Returns:
        Decoded bytes
    """
    # Remove any whitespace/newlines that base64 command may add
    cleaned = output.replace("\n", "").replace("\r", "").strip()
    return base64.b64decode(cleaned)

UnixCommandProvider

Bases: OSCommandProvider

Unix/Linux command provider using GNU/POSIX tools.

Source code in src/anyenv/os_commands/providers.py
class UnixCommandProvider(OSCommandProvider):
    """Unix/Linux command provider using GNU/POSIX tools."""

    def __init__(self) -> None:
        """Initialize Unix command provider with Unix command instances."""
        super().__init__()
        self.commands = {
            "list_directory": UnixListDirectoryCommand(),
            "file_info": UnixFileInfoCommand(),
            "exists": UnixExistsCommand(),
            "is_file": UnixIsFileCommand(),
            "is_directory": UnixIsDirectoryCommand(),
            "create_directory": UnixCreateDirectoryCommand(),
            "remove_path": UnixRemovePathCommand(),
            "copy_path": UnixCopyPathCommand(),
            "base64_encode": UnixBase64EncodeCommand(),
            "which": UnixWhichCommand(),
            "pwd": UnixPwdCommand(),
            "env_var": UnixEnvVarCommand(),
            "find": UnixFindCommand(),
        }

__init__

__init__() -> None

Initialize Unix command provider with Unix command instances.

Source code in src/anyenv/os_commands/providers.py
def __init__(self) -> None:
    """Initialize Unix command provider with Unix command instances."""
    super().__init__()
    self.commands = {
        "list_directory": UnixListDirectoryCommand(),
        "file_info": UnixFileInfoCommand(),
        "exists": UnixExistsCommand(),
        "is_file": UnixIsFileCommand(),
        "is_directory": UnixIsDirectoryCommand(),
        "create_directory": UnixCreateDirectoryCommand(),
        "remove_path": UnixRemovePathCommand(),
        "copy_path": UnixCopyPathCommand(),
        "base64_encode": UnixBase64EncodeCommand(),
        "which": UnixWhichCommand(),
        "pwd": UnixPwdCommand(),
        "env_var": UnixEnvVarCommand(),
        "find": UnixFindCommand(),
    }

UnixCopyPathCommand

Bases: CopyPathCommand

Unix/Linux copy path command implementation.

Source code in src/anyenv/os_commands/copy_path.py
class UnixCopyPathCommand(CopyPathCommand):
    """Unix/Linux copy path command implementation."""

    def create_command(self, source: str, destination: str, recursive: bool = False) -> str:
        """Generate Unix cp command.

        Args:
            source: Source path to copy from
            destination: Destination path to copy to
            recursive: Whether to copy directories recursively

        Returns:
            The cp command string
        """
        if recursive:
            return f"cp -r {sh_path(source)} {sh_path(destination)}"
        return f"cp {sh_path(source)} {sh_path(destination)}"

    def parse_command(self, output: str, exit_code: int = 0) -> bool:
        """Parse Unix cp result based on exit code.

        Args:
            output: Raw command output (ignored)
            exit_code: Command exit code

        Returns:
            True if copy was successful, False otherwise
        """
        return exit_code == 0

create_command

create_command(source: str, destination: str, recursive: bool = False) -> str

Generate Unix cp command.

Parameters:

Name Type Description Default
source str

Source path to copy from

required
destination str

Destination path to copy to

required
recursive bool

Whether to copy directories recursively

False

Returns:

Type Description
str

The cp command string

Source code in src/anyenv/os_commands/copy_path.py
def create_command(self, source: str, destination: str, recursive: bool = False) -> str:
    """Generate Unix cp command.

    Args:
        source: Source path to copy from
        destination: Destination path to copy to
        recursive: Whether to copy directories recursively

    Returns:
        The cp command string
    """
    if recursive:
        return f"cp -r {sh_path(source)} {sh_path(destination)}"
    return f"cp {sh_path(source)} {sh_path(destination)}"

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse Unix cp result based on exit code.

Parameters:

Name Type Description Default
output str

Raw command output (ignored)

required
exit_code int

Command exit code

0

Returns:

Type Description
bool

True if copy was successful, False otherwise

Source code in src/anyenv/os_commands/copy_path.py
def parse_command(self, output: str, exit_code: int = 0) -> bool:
    """Parse Unix cp result based on exit code.

    Args:
        output: Raw command output (ignored)
        exit_code: Command exit code

    Returns:
        True if copy was successful, False otherwise
    """
    return exit_code == 0

UnixCreateDirectoryCommand

Bases: CreateDirectoryCommand

Unix/Linux create directory command implementation.

Source code in src/anyenv/os_commands/create_directory.py
class UnixCreateDirectoryCommand(CreateDirectoryCommand):
    """Unix/Linux create directory command implementation."""

    def create_command(self, path: str, parents: bool = True) -> str:
        """Generate Unix mkdir command.

        Args:
            path: Directory path to create
            parents: Whether to create parent directories

        Returns:
            The mkdir command string
        """
        return f"mkdir -p {sh_path(path)}" if parents else f"mkdir {sh_path(path)}"

    def parse_command(
        self,
        output: str,
        exit_code: int = 0,
    ) -> bool:
        """Parse Unix mkdir result based on exit code.

        Args:
            output: Raw command output (ignored)
            exit_code: Command exit code

        Returns:
            True if directory was created successfully, False otherwise
        """
        return exit_code == 0

create_command

create_command(path: str, parents: bool = True) -> str

Generate Unix mkdir command.

Parameters:

Name Type Description Default
path str

Directory path to create

required
parents bool

Whether to create parent directories

True

Returns:

Type Description
str

The mkdir command string

Source code in src/anyenv/os_commands/create_directory.py
def create_command(self, path: str, parents: bool = True) -> str:
    """Generate Unix mkdir command.

    Args:
        path: Directory path to create
        parents: Whether to create parent directories

    Returns:
        The mkdir command string
    """
    return f"mkdir -p {sh_path(path)}" if parents else f"mkdir {sh_path(path)}"

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse Unix mkdir result based on exit code.

Parameters:

Name Type Description Default
output str

Raw command output (ignored)

required
exit_code int

Command exit code

0

Returns:

Type Description
bool

True if directory was created successfully, False otherwise

Source code in src/anyenv/os_commands/create_directory.py
def parse_command(
    self,
    output: str,
    exit_code: int = 0,
) -> bool:
    """Parse Unix mkdir result based on exit code.

    Args:
        output: Raw command output (ignored)
        exit_code: Command exit code

    Returns:
        True if directory was created successfully, False otherwise
    """
    return exit_code == 0

UnixEnvVarCommand

Bases: EnvVarCommand

Unix/Linux environment variable command implementation.

Source code in src/anyenv/os_commands/env_var.py
class UnixEnvVarCommand(EnvVarCommand):
    """Unix/Linux environment variable command implementation."""

    def create_command(self, name: str) -> str:
        """Generate Unix printenv command.

        Args:
            name: Name of environment variable

        Returns:
            The printenv command string
        """
        return f"printenv {sh_quote(name)}"

    def parse_command(self, output: str, exit_code: int = 0) -> str | None:
        """Parse Unix printenv result.

        Args:
            output: Raw command output
            exit_code: Command exit code

        Returns:
            Variable value or None if not set
        """
        if exit_code != 0:
            return None
        # printenv includes trailing newline
        return output.rstrip("\n") if output else None

create_command

create_command(name: str) -> str

Generate Unix printenv command.

Parameters:

Name Type Description Default
name str

Name of environment variable

required

Returns:

Type Description
str

The printenv command string

Source code in src/anyenv/os_commands/env_var.py
def create_command(self, name: str) -> str:
    """Generate Unix printenv command.

    Args:
        name: Name of environment variable

    Returns:
        The printenv command string
    """
    return f"printenv {sh_quote(name)}"

parse_command

parse_command(output: str, exit_code: int = 0) -> str | None

Parse Unix printenv result.

Parameters:

Name Type Description Default
output str

Raw command output

required
exit_code int

Command exit code

0

Returns:

Type Description
str | None

Variable value or None if not set

Source code in src/anyenv/os_commands/env_var.py
def parse_command(self, output: str, exit_code: int = 0) -> str | None:
    """Parse Unix printenv result.

    Args:
        output: Raw command output
        exit_code: Command exit code

    Returns:
        Variable value or None if not set
    """
    if exit_code != 0:
        return None
    # printenv includes trailing newline
    return output.rstrip("\n") if output else None

UnixExistsCommand

Bases: ExistsCommand

Unix/Linux exists command implementation.

Source code in src/anyenv/os_commands/exists.py
class UnixExistsCommand(ExistsCommand):
    """Unix/Linux exists command implementation."""

    def create_command(self, path: str) -> str:
        """Generate Unix test -e command.

        Args:
            path: Path to test for existence

        Returns:
            The test command string
        """
        return f"test -e {sh_path(path)}"

    def parse_command(
        self,
        output: str,
        exit_code: int = 0,
    ) -> bool:
        """Parse Unix test result based on exit code.

        Args:
            output: Raw command output (ignored)
            exit_code: Command exit code

        Returns:
            True if path exists, False otherwise
        """
        return exit_code == 0

create_command

create_command(path: str) -> str

Generate Unix test -e command.

Parameters:

Name Type Description Default
path str

Path to test for existence

required

Returns:

Type Description
str

The test command string

Source code in src/anyenv/os_commands/exists.py
def create_command(self, path: str) -> str:
    """Generate Unix test -e command.

    Args:
        path: Path to test for existence

    Returns:
        The test command string
    """
    return f"test -e {sh_path(path)}"

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse Unix test result based on exit code.

Parameters:

Name Type Description Default
output str

Raw command output (ignored)

required
exit_code int

Command exit code

0

Returns:

Type Description
bool

True if path exists, False otherwise

Source code in src/anyenv/os_commands/exists.py
def parse_command(
    self,
    output: str,
    exit_code: int = 0,
) -> bool:
    """Parse Unix test result based on exit code.

    Args:
        output: Raw command output (ignored)
        exit_code: Command exit code

    Returns:
        True if path exists, False otherwise
    """
    return exit_code == 0

UnixFileInfoCommand

Bases: FileInfoCommand

Unix/Linux file info command implementation using ls -la.

Source code in src/anyenv/os_commands/file_info.py
class UnixFileInfoCommand(FileInfoCommand):
    """Unix/Linux file info command implementation using ls -la."""

    def create_command(self, path: str) -> str:
        """Generate ls -la command for file info.

        Uses ls -la instead of stat to avoid shell expansion issues with
        format specifiers like %s, %F, etc.

        Args:
            path: Path to get information about

        Returns:
            The ls command string
        """
        return f"ls -lad {sh_path(path)}"

    def parse_command(self, output: str, path: str) -> FileInfo:
        """Parse ls -la output for a single file/directory.

        Args:
            output: Raw ls -la command output
            path: Original path requested

        Returns:
            FileInfo object with parsed information
        """
        line = output.strip()
        if not line:
            msg = f"Empty output for path: {path}"
            raise ValueError(msg)

        parts = line.split()
        if len(parts) < MIN_LS_PARTS_2_TIMESTAMP:
            msg = f"Unexpected ls output format: {output}"
            raise ValueError(msg)

        permissions = parts[0]
        size = int(parts[4]) if parts[4].isdigit() else 0

        # Determine file type from permissions
        file_type: Literal["file", "directory", "link"]
        if permissions.startswith("d"):
            file_type = "directory"
        elif permissions.startswith("l"):
            file_type = "link"
        else:
            file_type = "file"

        # Extract timestamp - handle different formats
        # Format can be: "Mon DD HH:MM" or "Mon DD YYYY" or "YYYY-MM-DD HH:MM"
        if len(parts) >= MIN_LS_PARTS:
            # 3-part timestamp: month day time/year
            timestamp_str = f"{parts[5]} {parts[6]} {parts[7]}"
        else:
            # 2-part timestamp fallback
            timestamp_str = f"{parts[5]} {parts[6]}"

        # Convert timestamp to unix time (approximate - ls doesn't give precise timestamps)
        # For now, just use 0 since we can't reliably parse all date formats
        mtime = 0

        return FileInfo(
            name=Path(path).name,
            path=path,
            type=file_type,
            size=size,
            mtime=mtime,
            permissions=permissions,
            timestamp=timestamp_str,
        )

create_command

create_command(path: str) -> str

Generate ls -la command for file info.

Uses ls -la instead of stat to avoid shell expansion issues with format specifiers like %s, %F, etc.

Parameters:

Name Type Description Default
path str

Path to get information about

required

Returns:

Type Description
str

The ls command string

Source code in src/anyenv/os_commands/file_info.py
def create_command(self, path: str) -> str:
    """Generate ls -la command for file info.

    Uses ls -la instead of stat to avoid shell expansion issues with
    format specifiers like %s, %F, etc.

    Args:
        path: Path to get information about

    Returns:
        The ls command string
    """
    return f"ls -lad {sh_path(path)}"

parse_command

parse_command(output: str, path: str) -> FileInfo

Parse ls -la output for a single file/directory.

Parameters:

Name Type Description Default
output str

Raw ls -la command output

required
path str

Original path requested

required

Returns:

Type Description
FileInfo

FileInfo object with parsed information

Source code in src/anyenv/os_commands/file_info.py
def parse_command(self, output: str, path: str) -> FileInfo:
    """Parse ls -la output for a single file/directory.

    Args:
        output: Raw ls -la command output
        path: Original path requested

    Returns:
        FileInfo object with parsed information
    """
    line = output.strip()
    if not line:
        msg = f"Empty output for path: {path}"
        raise ValueError(msg)

    parts = line.split()
    if len(parts) < MIN_LS_PARTS_2_TIMESTAMP:
        msg = f"Unexpected ls output format: {output}"
        raise ValueError(msg)

    permissions = parts[0]
    size = int(parts[4]) if parts[4].isdigit() else 0

    # Determine file type from permissions
    file_type: Literal["file", "directory", "link"]
    if permissions.startswith("d"):
        file_type = "directory"
    elif permissions.startswith("l"):
        file_type = "link"
    else:
        file_type = "file"

    # Extract timestamp - handle different formats
    # Format can be: "Mon DD HH:MM" or "Mon DD YYYY" or "YYYY-MM-DD HH:MM"
    if len(parts) >= MIN_LS_PARTS:
        # 3-part timestamp: month day time/year
        timestamp_str = f"{parts[5]} {parts[6]} {parts[7]}"
    else:
        # 2-part timestamp fallback
        timestamp_str = f"{parts[5]} {parts[6]}"

    # Convert timestamp to unix time (approximate - ls doesn't give precise timestamps)
    # For now, just use 0 since we can't reliably parse all date formats
    mtime = 0

    return FileInfo(
        name=Path(path).name,
        path=path,
        type=file_type,
        size=size,
        mtime=mtime,
        permissions=permissions,
        timestamp=timestamp_str,
    )

UnixFindCommand

Bases: FindCommand

Unix/Linux find command implementation.

Source code in src/anyenv/os_commands/find.py
class UnixFindCommand(FindCommand):
    """Unix/Linux find command implementation."""

    def create_command(
        self,
        path: str,
        pattern: str | None = None,
        maxdepth: int | None = None,
        file_type: Literal["file", "directory", "all"] = "all",
        with_stats: bool = True,
    ) -> str:
        """Generate Unix find command.

        Args:
            path: Directory to search in
            pattern: Glob pattern for name matching (e.g., "*.py")
            maxdepth: Maximum directory depth to descend
            file_type: Filter by type - files only, directories only, or all
            with_stats: Include file stats using -printf (size, mtime, type, perms)

        Returns:
            The find command string
        """
        parts = ["find", sh_path(path)]

        if maxdepth is not None:
            parts.append(f"-maxdepth {int(maxdepth)}")

        if file_type == "file":
            parts.append("-type f")
        elif file_type == "directory":
            parts.append("-type d")
        # "all" doesn't add a type filter

        if pattern:
            parts.append(f"-name {sh_quote(pattern)}")

        if with_stats:
            # Use -printf to get file stats in tab-separated format:
            # %p = path, %s = size in bytes, %T@ = mtime as unix timestamp
            # %y = type (f=file, d=dir, l=link), %M = permissions like ls -l
            # Single quotes protect the format string from shell interpretation
            parts.append(r"-printf '%p\t%s\t%T@\t%y\t%M\n'")

        return " ".join(parts)

    def parse_command(self, output: str, base_path: str = "") -> list[DirectoryEntry]:
        """Parse Unix find output.

        Handles both plain path output and -printf formatted output with stats.
        Detects format automatically based on presence of tab separators.

        Args:
            output: Raw find command output
            base_path: Base path used in the find command

        Returns:
            List of DirectoryEntry objects
        """
        lines = output.strip().split("\n")
        if not lines or (len(lines) == 1 and not lines[0]):
            return []

        entries: list[DirectoryEntry] = []
        for line in lines:
            line = line.strip()
            if not line:
                continue

            # Check if this is -printf formatted output (contains tabs)
            if "\t" in line:
                # Parse tab-separated format: path\tsize\ttimestamp\ttype\tpermissions
                # Parse from the right since path may contain tabs (rare but possible)
                parts = line.rsplit("\t", 4)
                if len(parts) == 5:  # noqa: PLR2004
                    path_str, size_str, timestamp_str, type_char, permissions = parts

                    # Map find type char to our type
                    type_map: dict[str, EntryType] = {"f": "file", "d": "directory", "l": "link"}
                    entry_type: EntryType = type_map.get(type_char, "file")

                    # Parse size
                    try:
                        size = int(size_str)
                    except ValueError:
                        size = 0

                    # Extract name from path
                    name = path_str.rsplit("/", 1)[-1] if "/" in path_str else path_str

                    # Skip . and ..
                    if name in (".", ".."):
                        continue

                    entries.append(
                        DirectoryEntry(
                            name=name,
                            path=path_str,
                            type=entry_type,
                            size=size,
                            timestamp=timestamp_str,
                            permissions=permissions,
                        )
                    )
                    continue

            # Fallback: plain path output (no tabs)
            name = line.rsplit("/", 1)[-1] if "/" in line else line

            # Skip . and ..
            if name in (".", ".."):
                continue

            entries.append(
                DirectoryEntry(
                    name=name,
                    path=line,
                    type="file",  # Default; use file_type param to filter
                    size=0,
                    timestamp=None,
                    permissions=None,
                )
            )

        return entries

create_command

create_command(
    path: str,
    pattern: str | None = None,
    maxdepth: int | None = None,
    file_type: Literal["file", "directory", "all"] = "all",
    with_stats: bool = True,
) -> str

Generate Unix find command.

Parameters:

Name Type Description Default
path str

Directory to search in

required
pattern str | None

Glob pattern for name matching (e.g., "*.py")

None
maxdepth int | None

Maximum directory depth to descend

None
file_type Literal['file', 'directory', 'all']

Filter by type - files only, directories only, or all

'all'
with_stats bool

Include file stats using -printf (size, mtime, type, perms)

True

Returns:

Type Description
str

The find command string

Source code in src/anyenv/os_commands/find.py
def create_command(
    self,
    path: str,
    pattern: str | None = None,
    maxdepth: int | None = None,
    file_type: Literal["file", "directory", "all"] = "all",
    with_stats: bool = True,
) -> str:
    """Generate Unix find command.

    Args:
        path: Directory to search in
        pattern: Glob pattern for name matching (e.g., "*.py")
        maxdepth: Maximum directory depth to descend
        file_type: Filter by type - files only, directories only, or all
        with_stats: Include file stats using -printf (size, mtime, type, perms)

    Returns:
        The find command string
    """
    parts = ["find", sh_path(path)]

    if maxdepth is not None:
        parts.append(f"-maxdepth {int(maxdepth)}")

    if file_type == "file":
        parts.append("-type f")
    elif file_type == "directory":
        parts.append("-type d")
    # "all" doesn't add a type filter

    if pattern:
        parts.append(f"-name {sh_quote(pattern)}")

    if with_stats:
        # Use -printf to get file stats in tab-separated format:
        # %p = path, %s = size in bytes, %T@ = mtime as unix timestamp
        # %y = type (f=file, d=dir, l=link), %M = permissions like ls -l
        # Single quotes protect the format string from shell interpretation
        parts.append(r"-printf '%p\t%s\t%T@\t%y\t%M\n'")

    return " ".join(parts)

parse_command

parse_command(output: str, base_path: str = '') -> list[DirectoryEntry]

Parse Unix find output.

Handles both plain path output and -printf formatted output with stats. Detects format automatically based on presence of tab separators.

Parameters:

Name Type Description Default
output str

Raw find command output

required
base_path str

Base path used in the find command

''

Returns:

Type Description
list[DirectoryEntry]

List of DirectoryEntry objects

Source code in src/anyenv/os_commands/find.py
def parse_command(self, output: str, base_path: str = "") -> list[DirectoryEntry]:
    """Parse Unix find output.

    Handles both plain path output and -printf formatted output with stats.
    Detects format automatically based on presence of tab separators.

    Args:
        output: Raw find command output
        base_path: Base path used in the find command

    Returns:
        List of DirectoryEntry objects
    """
    lines = output.strip().split("\n")
    if not lines or (len(lines) == 1 and not lines[0]):
        return []

    entries: list[DirectoryEntry] = []
    for line in lines:
        line = line.strip()
        if not line:
            continue

        # Check if this is -printf formatted output (contains tabs)
        if "\t" in line:
            # Parse tab-separated format: path\tsize\ttimestamp\ttype\tpermissions
            # Parse from the right since path may contain tabs (rare but possible)
            parts = line.rsplit("\t", 4)
            if len(parts) == 5:  # noqa: PLR2004
                path_str, size_str, timestamp_str, type_char, permissions = parts

                # Map find type char to our type
                type_map: dict[str, EntryType] = {"f": "file", "d": "directory", "l": "link"}
                entry_type: EntryType = type_map.get(type_char, "file")

                # Parse size
                try:
                    size = int(size_str)
                except ValueError:
                    size = 0

                # Extract name from path
                name = path_str.rsplit("/", 1)[-1] if "/" in path_str else path_str

                # Skip . and ..
                if name in (".", ".."):
                    continue

                entries.append(
                    DirectoryEntry(
                        name=name,
                        path=path_str,
                        type=entry_type,
                        size=size,
                        timestamp=timestamp_str,
                        permissions=permissions,
                    )
                )
                continue

        # Fallback: plain path output (no tabs)
        name = line.rsplit("/", 1)[-1] if "/" in line else line

        # Skip . and ..
        if name in (".", ".."):
            continue

        entries.append(
            DirectoryEntry(
                name=name,
                path=line,
                type="file",  # Default; use file_type param to filter
                size=0,
                timestamp=None,
                permissions=None,
            )
        )

    return entries

UnixIsDirectoryCommand

Bases: IsDirectoryCommand

Unix/Linux is directory command implementation.

Source code in src/anyenv/os_commands/is_directory.py
class UnixIsDirectoryCommand(IsDirectoryCommand):
    """Unix/Linux is directory command implementation."""

    def create_command(self, path: str) -> str:
        """Generate Unix test -d command.

        Args:
            path: Path to test if it's a directory

        Returns:
            The test command string
        """
        return f"test -d {sh_path(path)}"

    def parse_command(
        self,
        output: str,
        exit_code: int = 0,
    ) -> bool:
        """Parse Unix test -d result based on exit code.

        Args:
            output: Raw command output (ignored)
            exit_code: Command exit code

        Returns:
            True if path is a directory, False otherwise
        """
        return exit_code == 0

create_command

create_command(path: str) -> str

Generate Unix test -d command.

Parameters:

Name Type Description Default
path str

Path to test if it's a directory

required

Returns:

Type Description
str

The test command string

Source code in src/anyenv/os_commands/is_directory.py
def create_command(self, path: str) -> str:
    """Generate Unix test -d command.

    Args:
        path: Path to test if it's a directory

    Returns:
        The test command string
    """
    return f"test -d {sh_path(path)}"

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse Unix test -d result based on exit code.

Parameters:

Name Type Description Default
output str

Raw command output (ignored)

required
exit_code int

Command exit code

0

Returns:

Type Description
bool

True if path is a directory, False otherwise

Source code in src/anyenv/os_commands/is_directory.py
def parse_command(
    self,
    output: str,
    exit_code: int = 0,
) -> bool:
    """Parse Unix test -d result based on exit code.

    Args:
        output: Raw command output (ignored)
        exit_code: Command exit code

    Returns:
        True if path is a directory, False otherwise
    """
    return exit_code == 0

UnixIsFileCommand

Bases: IsFileCommand

Unix/Linux is file command implementation.

Source code in src/anyenv/os_commands/is_file.py
class UnixIsFileCommand(IsFileCommand):
    """Unix/Linux is file command implementation."""

    def create_command(self, path: str) -> str:
        """Generate Unix test -f command.

        Args:
            path: Path to test if it's a file

        Returns:
            The test command string
        """
        return f"test -f {sh_path(path)}"

    def parse_command(
        self,
        output: str,
        exit_code: int = 0,
    ) -> bool:
        """Parse Unix test -f result based on exit code.

        Args:
            output: Raw command output (ignored)
            exit_code: Command exit code

        Returns:
            True if path is a file, False otherwise
        """
        return exit_code == 0

create_command

create_command(path: str) -> str

Generate Unix test -f command.

Parameters:

Name Type Description Default
path str

Path to test if it's a file

required

Returns:

Type Description
str

The test command string

Source code in src/anyenv/os_commands/is_file.py
def create_command(self, path: str) -> str:
    """Generate Unix test -f command.

    Args:
        path: Path to test if it's a file

    Returns:
        The test command string
    """
    return f"test -f {sh_path(path)}"

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse Unix test -f result based on exit code.

Parameters:

Name Type Description Default
output str

Raw command output (ignored)

required
exit_code int

Command exit code

0

Returns:

Type Description
bool

True if path is a file, False otherwise

Source code in src/anyenv/os_commands/is_file.py
def parse_command(
    self,
    output: str,
    exit_code: int = 0,
) -> bool:
    """Parse Unix test -f result based on exit code.

    Args:
        output: Raw command output (ignored)
        exit_code: Command exit code

    Returns:
        True if path is a file, False otherwise
    """
    return exit_code == 0

UnixListDirectoryCommand

Bases: ListDirectoryCommand

Unix/Linux list directory command implementation.

Source code in src/anyenv/os_commands/list_directory.py
class UnixListDirectoryCommand(ListDirectoryCommand):
    """Unix/Linux list directory command implementation."""

    def create_command(self, path: str = "") -> str:
        """Generate Unix ls command.

        Args:
            path: Directory path to list

        Returns:
            The ls command string
        """
        cmd = "ls -la"
        return f"{cmd} {sh_path(path)}" if path else cmd

    def parse_command(
        self,
        output: str,
        path: str = "",
    ) -> list[DirectoryEntry]:
        """Parse Unix ls output.

        Args:
            output: Raw ls command output
            path: Base directory path

        Returns:
            List of DirectoryEntry objects
        """
        lines = output.strip().split("\n")
        if not lines:
            return []

        # Filter out total line and empty lines
        file_lines = [line for line in lines if line and not line.startswith("total ")]

        files: list[DirectoryEntry] = []
        for line in file_lines:
            if not line.strip():
                continue

            parsed = self._parse_detailed_line(line, path)
            if parsed and parsed.name not in (".", ".."):
                files.append(parsed)

        return files

    def _parse_detailed_line(self, line: str, base_path: str) -> DirectoryEntry | None:
        """Parse detailed ls -la output line."""
        parts = line.split()
        if len(parts) < MIN_LS_PARTS:  # Minimum parts for valid ls -la line
            return None

        permissions = parts[0]
        size = int(parts[4]) if parts[4].isdigit() else 0

        # Handle different timestamp formats (2-part vs 3-part)
        if (
            len(parts) >= MIN_LS_PARTS_3_TIMESTAMP
            and not parts[7].startswith("-")
            and not parts[7].startswith("d")
        ):
            # 3-part timestamp: month day time/year
            timestamp = f"{parts[5]} {parts[6]} {parts[7]}"
            name = " ".join(parts[8:])
        elif len(parts) >= MIN_LS_PARTS_2_TIMESTAMP:
            # 2-part timestamp: date time
            timestamp = f"{parts[5]} {parts[6]}"
            name = " ".join(parts[7:])
        else:
            # Fallback: single part timestamp
            timestamp = parts[5]
            name = " ".join(parts[6:])

        # Determine file type
        file_type: Literal["file", "directory", "link"]
        if permissions.startswith("d"):
            file_type = "directory"
        elif permissions.startswith("l"):
            file_type = "link"
        else:
            file_type = "file"

        # Build full path
        full_path = f"{base_path.rstrip('/')}/{name}" if base_path else name

        return DirectoryEntry(
            name=name,
            path=full_path,
            type=file_type,
            size=size,
            timestamp=timestamp,
            permissions=permissions if permissions and not permissions.isspace() else None,
        )

create_command

create_command(path: str = '') -> str

Generate Unix ls command.

Parameters:

Name Type Description Default
path str

Directory path to list

''

Returns:

Type Description
str

The ls command string

Source code in src/anyenv/os_commands/list_directory.py
def create_command(self, path: str = "") -> str:
    """Generate Unix ls command.

    Args:
        path: Directory path to list

    Returns:
        The ls command string
    """
    cmd = "ls -la"
    return f"{cmd} {sh_path(path)}" if path else cmd

parse_command

parse_command(output: str, path: str = '') -> list[DirectoryEntry]

Parse Unix ls output.

Parameters:

Name Type Description Default
output str

Raw ls command output

required
path str

Base directory path

''

Returns:

Type Description
list[DirectoryEntry]

List of DirectoryEntry objects

Source code in src/anyenv/os_commands/list_directory.py
def parse_command(
    self,
    output: str,
    path: str = "",
) -> list[DirectoryEntry]:
    """Parse Unix ls output.

    Args:
        output: Raw ls command output
        path: Base directory path

    Returns:
        List of DirectoryEntry objects
    """
    lines = output.strip().split("\n")
    if not lines:
        return []

    # Filter out total line and empty lines
    file_lines = [line for line in lines if line and not line.startswith("total ")]

    files: list[DirectoryEntry] = []
    for line in file_lines:
        if not line.strip():
            continue

        parsed = self._parse_detailed_line(line, path)
        if parsed and parsed.name not in (".", ".."):
            files.append(parsed)

    return files

UnixPwdCommand

Bases: PwdCommand

Unix/Linux pwd command implementation.

Source code in src/anyenv/os_commands/pwd.py
class UnixPwdCommand(PwdCommand):
    """Unix/Linux pwd command implementation."""

    def create_command(self) -> str:
        """Generate Unix pwd command.

        Returns:
            The pwd command string
        """
        return "pwd"

    def parse_command(self, output: str, exit_code: int = 0) -> str | None:
        """Parse Unix pwd result.

        Args:
            output: Raw command output
            exit_code: Command exit code

        Returns:
            Current working directory or None on failure
        """
        if exit_code != 0:
            return None
        path = output.strip()
        return path if path else None

create_command

create_command() -> str

Generate Unix pwd command.

Returns:

Type Description
str

The pwd command string

Source code in src/anyenv/os_commands/pwd.py
def create_command(self) -> str:
    """Generate Unix pwd command.

    Returns:
        The pwd command string
    """
    return "pwd"

parse_command

parse_command(output: str, exit_code: int = 0) -> str | None

Parse Unix pwd result.

Parameters:

Name Type Description Default
output str

Raw command output

required
exit_code int

Command exit code

0

Returns:

Type Description
str | None

Current working directory or None on failure

Source code in src/anyenv/os_commands/pwd.py
def parse_command(self, output: str, exit_code: int = 0) -> str | None:
    """Parse Unix pwd result.

    Args:
        output: Raw command output
        exit_code: Command exit code

    Returns:
        Current working directory or None on failure
    """
    if exit_code != 0:
        return None
    path = output.strip()
    return path if path else None

UnixRemovePathCommand

Bases: RemovePathCommand

Unix/Linux remove path command implementation.

Source code in src/anyenv/os_commands/remove_path.py
class UnixRemovePathCommand(RemovePathCommand):
    """Unix/Linux remove path command implementation."""

    def create_command(self, path: str, recursive: bool = False) -> str:
        """Generate Unix rm command.

        Args:
            path: Path to remove
            recursive: Whether to remove directories recursively

        Returns:
            The rm command string
        """
        return f"rm -rf {sh_path(path)}" if recursive else f"rm {sh_path(path)}"

    def parse_command(
        self,
        output: str,
        exit_code: int = 0,
    ) -> bool:
        """Parse Unix rm result based on exit code.

        Args:
            output: Raw command output (ignored)
            exit_code: Command exit code

        Returns:
            True if path was removed successfully, False otherwise
        """
        return exit_code == 0

create_command

create_command(path: str, recursive: bool = False) -> str

Generate Unix rm command.

Parameters:

Name Type Description Default
path str

Path to remove

required
recursive bool

Whether to remove directories recursively

False

Returns:

Type Description
str

The rm command string

Source code in src/anyenv/os_commands/remove_path.py
def create_command(self, path: str, recursive: bool = False) -> str:
    """Generate Unix rm command.

    Args:
        path: Path to remove
        recursive: Whether to remove directories recursively

    Returns:
        The rm command string
    """
    return f"rm -rf {sh_path(path)}" if recursive else f"rm {sh_path(path)}"

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse Unix rm result based on exit code.

Parameters:

Name Type Description Default
output str

Raw command output (ignored)

required
exit_code int

Command exit code

0

Returns:

Type Description
bool

True if path was removed successfully, False otherwise

Source code in src/anyenv/os_commands/remove_path.py
def parse_command(
    self,
    output: str,
    exit_code: int = 0,
) -> bool:
    """Parse Unix rm result based on exit code.

    Args:
        output: Raw command output (ignored)
        exit_code: Command exit code

    Returns:
        True if path was removed successfully, False otherwise
    """
    return exit_code == 0

UnixWhichCommand

Bases: WhichCommand

Unix/Linux which command implementation.

Source code in src/anyenv/os_commands/which.py
class UnixWhichCommand(WhichCommand):
    """Unix/Linux which command implementation."""

    def create_command(self, executable: str) -> str:
        """Generate Unix which command.

        Args:
            executable: Name of executable to find

        Returns:
            The which command string
        """
        return f"which {sh_quote(executable)}"

    def parse_command(self, output: str, exit_code: int = 0) -> str | None:
        """Parse Unix which result.

        Args:
            output: Raw command output
            exit_code: Command exit code

        Returns:
            Path to executable or None if not found
        """
        if exit_code != 0:
            return None
        path = output.strip()
        return path if path else None

create_command

create_command(executable: str) -> str

Generate Unix which command.

Parameters:

Name Type Description Default
executable str

Name of executable to find

required

Returns:

Type Description
str

The which command string

Source code in src/anyenv/os_commands/which.py
def create_command(self, executable: str) -> str:
    """Generate Unix which command.

    Args:
        executable: Name of executable to find

    Returns:
        The which command string
    """
    return f"which {sh_quote(executable)}"

parse_command

parse_command(output: str, exit_code: int = 0) -> str | None

Parse Unix which result.

Parameters:

Name Type Description Default
output str

Raw command output

required
exit_code int

Command exit code

0

Returns:

Type Description
str | None

Path to executable or None if not found

Source code in src/anyenv/os_commands/which.py
def parse_command(self, output: str, exit_code: int = 0) -> str | None:
    """Parse Unix which result.

    Args:
        output: Raw command output
        exit_code: Command exit code

    Returns:
        Path to executable or None if not found
    """
    if exit_code != 0:
        return None
    path = output.strip()
    return path if path else None

WhichCommand

Bases: ABC

Base class for which/where commands to locate executables.

Source code in src/anyenv/os_commands/base.py
class WhichCommand(ABC):
    """Base class for which/where commands to locate executables."""

    @abstractmethod
    def create_command(self, executable: str) -> str:
        """Generate command to find executable path."""

    @abstractmethod
    def parse_command(self, output: str, exit_code: int = 0) -> str | None:
        """Parse output and return executable path or None if not found."""

create_command abstractmethod

create_command(executable: str) -> str

Generate command to find executable path.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def create_command(self, executable: str) -> str:
    """Generate command to find executable path."""

parse_command abstractmethod

parse_command(output: str, exit_code: int = 0) -> str | None

Parse output and return executable path or None if not found.

Source code in src/anyenv/os_commands/base.py
@abstractmethod
def parse_command(self, output: str, exit_code: int = 0) -> str | None:
    """Parse output and return executable path or None if not found."""

WindowsBase64EncodeCommand

Bases: Base64EncodeCommand

Windows base64 encode command implementation using PowerShell.

Source code in src/anyenv/os_commands/base64_encode.py
class WindowsBase64EncodeCommand(Base64EncodeCommand):
    """Windows base64 encode command implementation using PowerShell."""

    def create_command(self, path: str) -> str:
        """Generate PowerShell base64 encode command.

        Args:
            path: Path to file to encode

        Returns:
            The PowerShell command string
        """
        # Use PowerShell to read file and convert to base64
        path_expr = f"(Resolve-Path -LiteralPath {ps_literal(path)}).ProviderPath"
        return powershell(f"[Convert]::ToBase64String([IO.File]::ReadAllBytes({path_expr}))")

    def parse_command(self, output: str) -> bytes:
        """Parse PowerShell base64 output.

        Args:
            output: Raw base64 encoded output

        Returns:
            Decoded bytes
        """
        cleaned = output.replace("\n", "").replace("\r", "").strip()
        return base64.b64decode(cleaned)

create_command

create_command(path: str) -> str

Generate PowerShell base64 encode command.

Parameters:

Name Type Description Default
path str

Path to file to encode

required

Returns:

Type Description
str

The PowerShell command string

Source code in src/anyenv/os_commands/base64_encode.py
def create_command(self, path: str) -> str:
    """Generate PowerShell base64 encode command.

    Args:
        path: Path to file to encode

    Returns:
        The PowerShell command string
    """
    # Use PowerShell to read file and convert to base64
    path_expr = f"(Resolve-Path -LiteralPath {ps_literal(path)}).ProviderPath"
    return powershell(f"[Convert]::ToBase64String([IO.File]::ReadAllBytes({path_expr}))")

parse_command

parse_command(output: str) -> bytes

Parse PowerShell base64 output.

Parameters:

Name Type Description Default
output str

Raw base64 encoded output

required

Returns:

Type Description
bytes

Decoded bytes

Source code in src/anyenv/os_commands/base64_encode.py
def parse_command(self, output: str) -> bytes:
    """Parse PowerShell base64 output.

    Args:
        output: Raw base64 encoded output

    Returns:
        Decoded bytes
    """
    cleaned = output.replace("\n", "").replace("\r", "").strip()
    return base64.b64decode(cleaned)

WindowsCommandProvider

Bases: OSCommandProvider

Windows command provider using PowerShell and CMD.

Source code in src/anyenv/os_commands/providers.py
class WindowsCommandProvider(OSCommandProvider):
    """Windows command provider using PowerShell and CMD."""

    def __init__(self) -> None:
        """Initialize Windows command provider with Windows command instances."""
        super().__init__()
        self.commands = {
            "list_directory": WindowsListDirectoryCommand(),
            "file_info": WindowsFileInfoCommand(),
            "exists": WindowsExistsCommand(),
            "is_file": WindowsIsFileCommand(),
            "is_directory": WindowsIsDirectoryCommand(),
            "create_directory": WindowsCreateDirectoryCommand(),
            "remove_path": WindowsRemovePathCommand(),
            "copy_path": WindowsCopyPathCommand(),
            "base64_encode": WindowsBase64EncodeCommand(),
            "which": WindowsWhichCommand(),
            "pwd": WindowsPwdCommand(),
            "env_var": WindowsEnvVarCommand(),
            "find": WindowsFindCommand(),
        }

__init__

__init__() -> None

Initialize Windows command provider with Windows command instances.

Source code in src/anyenv/os_commands/providers.py
def __init__(self) -> None:
    """Initialize Windows command provider with Windows command instances."""
    super().__init__()
    self.commands = {
        "list_directory": WindowsListDirectoryCommand(),
        "file_info": WindowsFileInfoCommand(),
        "exists": WindowsExistsCommand(),
        "is_file": WindowsIsFileCommand(),
        "is_directory": WindowsIsDirectoryCommand(),
        "create_directory": WindowsCreateDirectoryCommand(),
        "remove_path": WindowsRemovePathCommand(),
        "copy_path": WindowsCopyPathCommand(),
        "base64_encode": WindowsBase64EncodeCommand(),
        "which": WindowsWhichCommand(),
        "pwd": WindowsPwdCommand(),
        "env_var": WindowsEnvVarCommand(),
        "find": WindowsFindCommand(),
    }

WindowsCopyPathCommand

Bases: CopyPathCommand

Windows copy path command implementation.

Source code in src/anyenv/os_commands/copy_path.py
class WindowsCopyPathCommand(CopyPathCommand):
    """Windows copy path command implementation."""

    def create_command(self, source: str, destination: str, recursive: bool = False) -> str:
        """Generate Windows copy command.

        Args:
            source: Source path to copy from
            destination: Destination path to copy to
            recursive: Whether to copy directories recursively

        Returns:
            The copy command string
        """
        script = f"Copy-Item -LiteralPath {ps_literal(source)} {ps_literal(destination)} -Force"
        return powershell(f"{script} -Recurse" if recursive else script)

    def parse_command(self, output: str, exit_code: int = 0) -> bool:
        """Parse Windows copy result.

        Args:
            output: Raw command output (ignored)
            exit_code: Command exit code

        Returns:
            True if copy was successful, False otherwise
        """
        return exit_code == 0

create_command

create_command(source: str, destination: str, recursive: bool = False) -> str

Generate Windows copy command.

Parameters:

Name Type Description Default
source str

Source path to copy from

required
destination str

Destination path to copy to

required
recursive bool

Whether to copy directories recursively

False

Returns:

Type Description
str

The copy command string

Source code in src/anyenv/os_commands/copy_path.py
def create_command(self, source: str, destination: str, recursive: bool = False) -> str:
    """Generate Windows copy command.

    Args:
        source: Source path to copy from
        destination: Destination path to copy to
        recursive: Whether to copy directories recursively

    Returns:
        The copy command string
    """
    script = f"Copy-Item -LiteralPath {ps_literal(source)} {ps_literal(destination)} -Force"
    return powershell(f"{script} -Recurse" if recursive else script)

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse Windows copy result.

Parameters:

Name Type Description Default
output str

Raw command output (ignored)

required
exit_code int

Command exit code

0

Returns:

Type Description
bool

True if copy was successful, False otherwise

Source code in src/anyenv/os_commands/copy_path.py
def parse_command(self, output: str, exit_code: int = 0) -> bool:
    """Parse Windows copy result.

    Args:
        output: Raw command output (ignored)
        exit_code: Command exit code

    Returns:
        True if copy was successful, False otherwise
    """
    return exit_code == 0

WindowsCreateDirectoryCommand

Bases: CreateDirectoryCommand

Windows create directory command implementation.

Source code in src/anyenv/os_commands/create_directory.py
class WindowsCreateDirectoryCommand(CreateDirectoryCommand):
    """Windows create directory command implementation."""

    def create_command(self, path: str, parents: bool = True) -> str:
        """Generate Windows directory creation command.

        Args:
            path: Directory path to create
            parents: Whether to create parent directories

        Returns:
            The directory creation command string
        """
        script = f"New-Item -ItemType Directory -Path {ps_literal(path)}"
        return powershell(f"{script} -Force" if parents else script)

    def parse_command(
        self,
        output: str,
        exit_code: int = 0,
    ) -> bool:
        """Parse Windows directory creation result.

        Args:
            output: Raw command output (ignored)
            exit_code: Command exit code

        Returns:
            True if directory was created successfully, False otherwise
        """
        return exit_code == 0

create_command

create_command(path: str, parents: bool = True) -> str

Generate Windows directory creation command.

Parameters:

Name Type Description Default
path str

Directory path to create

required
parents bool

Whether to create parent directories

True

Returns:

Type Description
str

The directory creation command string

Source code in src/anyenv/os_commands/create_directory.py
def create_command(self, path: str, parents: bool = True) -> str:
    """Generate Windows directory creation command.

    Args:
        path: Directory path to create
        parents: Whether to create parent directories

    Returns:
        The directory creation command string
    """
    script = f"New-Item -ItemType Directory -Path {ps_literal(path)}"
    return powershell(f"{script} -Force" if parents else script)

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse Windows directory creation result.

Parameters:

Name Type Description Default
output str

Raw command output (ignored)

required
exit_code int

Command exit code

0

Returns:

Type Description
bool

True if directory was created successfully, False otherwise

Source code in src/anyenv/os_commands/create_directory.py
def parse_command(
    self,
    output: str,
    exit_code: int = 0,
) -> bool:
    """Parse Windows directory creation result.

    Args:
        output: Raw command output (ignored)
        exit_code: Command exit code

    Returns:
        True if directory was created successfully, False otherwise
    """
    return exit_code == 0

WindowsEnvVarCommand

Bases: EnvVarCommand

Windows environment variable command implementation.

Source code in src/anyenv/os_commands/env_var.py
class WindowsEnvVarCommand(EnvVarCommand):
    """Windows environment variable command implementation."""

    def create_command(self, name: str) -> str:
        """Generate PowerShell environment variable command.

        Args:
            name: Name of environment variable

        Returns:
            The PowerShell command string
        """
        return powershell(f"[Environment]::GetEnvironmentVariable({ps_literal(name)})")

    def parse_command(self, output: str, exit_code: int = 0) -> str | None:
        """Parse PowerShell environment variable result.

        Args:
            output: Raw command output
            exit_code: Command exit code

        Returns:
            Variable value or None if not set
        """
        # PowerShell returns empty string for unset variables
        value = output.strip()
        return value if value else None

create_command

create_command(name: str) -> str

Generate PowerShell environment variable command.

Parameters:

Name Type Description Default
name str

Name of environment variable

required

Returns:

Type Description
str

The PowerShell command string

Source code in src/anyenv/os_commands/env_var.py
def create_command(self, name: str) -> str:
    """Generate PowerShell environment variable command.

    Args:
        name: Name of environment variable

    Returns:
        The PowerShell command string
    """
    return powershell(f"[Environment]::GetEnvironmentVariable({ps_literal(name)})")

parse_command

parse_command(output: str, exit_code: int = 0) -> str | None

Parse PowerShell environment variable result.

Parameters:

Name Type Description Default
output str

Raw command output

required
exit_code int

Command exit code

0

Returns:

Type Description
str | None

Variable value or None if not set

Source code in src/anyenv/os_commands/env_var.py
def parse_command(self, output: str, exit_code: int = 0) -> str | None:
    """Parse PowerShell environment variable result.

    Args:
        output: Raw command output
        exit_code: Command exit code

    Returns:
        Variable value or None if not set
    """
    # PowerShell returns empty string for unset variables
    value = output.strip()
    return value if value else None

WindowsExistsCommand

Bases: ExistsCommand

Windows exists command implementation.

Source code in src/anyenv/os_commands/exists.py
class WindowsExistsCommand(ExistsCommand):
    """Windows exists command implementation."""

    def create_command(self, path: str) -> str:
        """Generate PowerShell Test-Path command.

        Args:
            path: Path to test for existence

        Returns:
            The PowerShell command string
        """
        return powershell(f"Test-Path -LiteralPath {ps_literal(path)}")

    def parse_command(
        self,
        output: str,
        exit_code: int = 0,
    ) -> bool:
        """Parse PowerShell Test-Path result.

        Args:
            output: Raw PowerShell command output
            exit_code: Command exit code (ignored)

        Returns:
            True if path exists, False otherwise
        """
        return output.strip().lower() == "true"

create_command

create_command(path: str) -> str

Generate PowerShell Test-Path command.

Parameters:

Name Type Description Default
path str

Path to test for existence

required

Returns:

Type Description
str

The PowerShell command string

Source code in src/anyenv/os_commands/exists.py
def create_command(self, path: str) -> str:
    """Generate PowerShell Test-Path command.

    Args:
        path: Path to test for existence

    Returns:
        The PowerShell command string
    """
    return powershell(f"Test-Path -LiteralPath {ps_literal(path)}")

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse PowerShell Test-Path result.

Parameters:

Name Type Description Default
output str

Raw PowerShell command output

required
exit_code int

Command exit code (ignored)

0

Returns:

Type Description
bool

True if path exists, False otherwise

Source code in src/anyenv/os_commands/exists.py
def parse_command(
    self,
    output: str,
    exit_code: int = 0,
) -> bool:
    """Parse PowerShell Test-Path result.

    Args:
        output: Raw PowerShell command output
        exit_code: Command exit code (ignored)

    Returns:
        True if path exists, False otherwise
    """
    return output.strip().lower() == "true"

WindowsFileInfoCommand

Bases: FileInfoCommand

Windows file info command implementation.

Source code in src/anyenv/os_commands/file_info.py
class WindowsFileInfoCommand(FileInfoCommand):
    """Windows file info command implementation."""

    def create_command(self, path: str) -> str:
        """Generate PowerShell file info command.

        Args:
            path: Path to get information about

        Returns:
            The PowerShell command string
        """
        return powershell(
            f"$item = Get-Item -LiteralPath {ps_literal(path)} -ErrorAction Stop; "
            "$item.Name + '||' + $item.Length + '||' + "
            "($item.GetType().Name) + '||' + "
            "[int][double]::Parse($item.LastWriteTime.ToString('yyyyMMddHHmmss'))"
        )

    def parse_command(self, output: str, path: str) -> FileInfo:
        """Parse PowerShell output format: name||size||type||mtime.

        Args:
            output: Raw PowerShell command output
            path: Original path requested

        Returns:
            FileInfo object with parsed information
        """
        parts = output.strip().split("||")
        if len(parts) < EXPECTED_POWERSHELL_PARTS:
            msg = f"Unexpected PowerShell output format: {output}"
            raise ValueError(msg)

        file_type: Literal["file", "directory", "link"] = (
            "directory" if "directory" in parts[2].lower() else "file"
        )

        return FileInfo(
            name=parts[0],
            path=path,
            type=file_type,
            size=int(parts[1]) if parts[1].isdigit() else 0,
            mtime=int(parts[3]) if parts[3].isdigit() else 0,
        )

create_command

create_command(path: str) -> str

Generate PowerShell file info command.

Parameters:

Name Type Description Default
path str

Path to get information about

required

Returns:

Type Description
str

The PowerShell command string

Source code in src/anyenv/os_commands/file_info.py
def create_command(self, path: str) -> str:
    """Generate PowerShell file info command.

    Args:
        path: Path to get information about

    Returns:
        The PowerShell command string
    """
    return powershell(
        f"$item = Get-Item -LiteralPath {ps_literal(path)} -ErrorAction Stop; "
        "$item.Name + '||' + $item.Length + '||' + "
        "($item.GetType().Name) + '||' + "
        "[int][double]::Parse($item.LastWriteTime.ToString('yyyyMMddHHmmss'))"
    )

parse_command

parse_command(output: str, path: str) -> FileInfo

Parse PowerShell output format: name||size||type||mtime.

Parameters:

Name Type Description Default
output str

Raw PowerShell command output

required
path str

Original path requested

required

Returns:

Type Description
FileInfo

FileInfo object with parsed information

Source code in src/anyenv/os_commands/file_info.py
def parse_command(self, output: str, path: str) -> FileInfo:
    """Parse PowerShell output format: name||size||type||mtime.

    Args:
        output: Raw PowerShell command output
        path: Original path requested

    Returns:
        FileInfo object with parsed information
    """
    parts = output.strip().split("||")
    if len(parts) < EXPECTED_POWERSHELL_PARTS:
        msg = f"Unexpected PowerShell output format: {output}"
        raise ValueError(msg)

    file_type: Literal["file", "directory", "link"] = (
        "directory" if "directory" in parts[2].lower() else "file"
    )

    return FileInfo(
        name=parts[0],
        path=path,
        type=file_type,
        size=int(parts[1]) if parts[1].isdigit() else 0,
        mtime=int(parts[3]) if parts[3].isdigit() else 0,
    )

WindowsFindCommand

Bases: FindCommand

Windows find command implementation using PowerShell.

Source code in src/anyenv/os_commands/find.py
class WindowsFindCommand(FindCommand):
    """Windows find command implementation using PowerShell."""

    def create_command(
        self,
        path: str,
        pattern: str | None = None,
        maxdepth: int | None = None,
        file_type: Literal["file", "directory", "all"] = "all",
        with_stats: bool = True,
    ) -> str:
        """Generate Windows PowerShell Get-ChildItem command.

        Args:
            path: Directory to search in
            pattern: Glob pattern for name matching (e.g., "*.py")
            maxdepth: Maximum directory depth to descend
            file_type: Filter by type - files only, directories only, or all
            with_stats: Include file stats (always True for Windows, included for API consistency)

        Returns:
            The PowerShell command string
        """
        # Build Get-ChildItem command
        parts = [f"Get-ChildItem -LiteralPath {ps_literal(path)} -Recurse"]

        if maxdepth is not None:
            # PowerShell -Depth is 0-indexed (0 = immediate children only)
            # To match find behavior where maxdepth 1 = immediate children
            depth = maxdepth - 1 if maxdepth > 0 else 0
            parts.append(f"-Depth {int(depth)}")

        if pattern:
            parts.append(f"-Filter {ps_literal(pattern)}")

        if file_type == "file":
            parts.append("-File")
        elif file_type == "directory":
            parts.append("-Directory")

        # Output format: FullName|Length|Mode (pipe-separated for easy parsing)
        parts.append('| ForEach-Object { "$($_.FullName)|$($_.Length)|$($_.Mode)" }')

        return powershell(" ".join(parts))

    def parse_command(self, output: str, base_path: str = "") -> list[DirectoryEntry]:
        """Parse Windows PowerShell Get-ChildItem output.

        Args:
            output: Raw command output (path|size|mode per line)
            base_path: Base path used in the command

        Returns:
            List of DirectoryEntry objects
        """
        lines = output.strip().split("\n")
        if not lines or (len(lines) == 1 and not lines[0]):
            return []

        entries: list[DirectoryEntry] = []
        for line in lines:
            line = line.strip()
            if not line:
                continue

            parts = line.split("|")
            if len(parts) < 3:  # noqa: PLR2004
                continue

            full_path = parts[0]
            size_str = parts[1]
            mode = parts[2]

            # Extract name from path
            name = full_path.rsplit("\\", 1)[-1] if "\\" in full_path else full_path

            # Skip . and ..
            if name in (".", ".."):
                continue

            # Determine type from mode
            file_type: Literal["file", "directory", "link"]
            file_type = "directory" if mode.startswith("d") else "file"

            # Parse size
            try:
                size = int(size_str) if size_str else 0
            except ValueError:
                size = 0

            entries.append(
                DirectoryEntry(
                    name=name,
                    path=full_path,
                    type=file_type,
                    size=size,
                    timestamp=None,
                    permissions=mode,
                )
            )

        return entries

create_command

create_command(
    path: str,
    pattern: str | None = None,
    maxdepth: int | None = None,
    file_type: Literal["file", "directory", "all"] = "all",
    with_stats: bool = True,
) -> str

Generate Windows PowerShell Get-ChildItem command.

Parameters:

Name Type Description Default
path str

Directory to search in

required
pattern str | None

Glob pattern for name matching (e.g., "*.py")

None
maxdepth int | None

Maximum directory depth to descend

None
file_type Literal['file', 'directory', 'all']

Filter by type - files only, directories only, or all

'all'
with_stats bool

Include file stats (always True for Windows, included for API consistency)

True

Returns:

Type Description
str

The PowerShell command string

Source code in src/anyenv/os_commands/find.py
def create_command(
    self,
    path: str,
    pattern: str | None = None,
    maxdepth: int | None = None,
    file_type: Literal["file", "directory", "all"] = "all",
    with_stats: bool = True,
) -> str:
    """Generate Windows PowerShell Get-ChildItem command.

    Args:
        path: Directory to search in
        pattern: Glob pattern for name matching (e.g., "*.py")
        maxdepth: Maximum directory depth to descend
        file_type: Filter by type - files only, directories only, or all
        with_stats: Include file stats (always True for Windows, included for API consistency)

    Returns:
        The PowerShell command string
    """
    # Build Get-ChildItem command
    parts = [f"Get-ChildItem -LiteralPath {ps_literal(path)} -Recurse"]

    if maxdepth is not None:
        # PowerShell -Depth is 0-indexed (0 = immediate children only)
        # To match find behavior where maxdepth 1 = immediate children
        depth = maxdepth - 1 if maxdepth > 0 else 0
        parts.append(f"-Depth {int(depth)}")

    if pattern:
        parts.append(f"-Filter {ps_literal(pattern)}")

    if file_type == "file":
        parts.append("-File")
    elif file_type == "directory":
        parts.append("-Directory")

    # Output format: FullName|Length|Mode (pipe-separated for easy parsing)
    parts.append('| ForEach-Object { "$($_.FullName)|$($_.Length)|$($_.Mode)" }')

    return powershell(" ".join(parts))

parse_command

parse_command(output: str, base_path: str = '') -> list[DirectoryEntry]

Parse Windows PowerShell Get-ChildItem output.

Parameters:

Name Type Description Default
output str

Raw command output (path|size|mode per line)

required
base_path str

Base path used in the command

''

Returns:

Type Description
list[DirectoryEntry]

List of DirectoryEntry objects

Source code in src/anyenv/os_commands/find.py
def parse_command(self, output: str, base_path: str = "") -> list[DirectoryEntry]:
    """Parse Windows PowerShell Get-ChildItem output.

    Args:
        output: Raw command output (path|size|mode per line)
        base_path: Base path used in the command

    Returns:
        List of DirectoryEntry objects
    """
    lines = output.strip().split("\n")
    if not lines or (len(lines) == 1 and not lines[0]):
        return []

    entries: list[DirectoryEntry] = []
    for line in lines:
        line = line.strip()
        if not line:
            continue

        parts = line.split("|")
        if len(parts) < 3:  # noqa: PLR2004
            continue

        full_path = parts[0]
        size_str = parts[1]
        mode = parts[2]

        # Extract name from path
        name = full_path.rsplit("\\", 1)[-1] if "\\" in full_path else full_path

        # Skip . and ..
        if name in (".", ".."):
            continue

        # Determine type from mode
        file_type: Literal["file", "directory", "link"]
        file_type = "directory" if mode.startswith("d") else "file"

        # Parse size
        try:
            size = int(size_str) if size_str else 0
        except ValueError:
            size = 0

        entries.append(
            DirectoryEntry(
                name=name,
                path=full_path,
                type=file_type,
                size=size,
                timestamp=None,
                permissions=mode,
            )
        )

    return entries

WindowsIsDirectoryCommand

Bases: IsDirectoryCommand

Windows is directory command implementation.

Source code in src/anyenv/os_commands/is_directory.py
class WindowsIsDirectoryCommand(IsDirectoryCommand):
    """Windows is directory command implementation."""

    def create_command(self, path: str) -> str:
        """Generate PowerShell directory test command.

        Args:
            path: Path to test if it's a directory

        Returns:
            The PowerShell command string
        """
        return powershell(
            f"(Get-Item -LiteralPath {ps_literal(path)} -ErrorAction SilentlyContinue)"
            ".PSIsContainer"
        )

    def parse_command(
        self,
        output: str,
        exit_code: int = 0,
    ) -> bool:
        """Parse PowerShell directory test result.

        Args:
            output: Raw PowerShell command output
            exit_code: Command exit code (ignored)

        Returns:
            True if path is a directory, False otherwise
        """
        return output.strip().lower() == "true"

create_command

create_command(path: str) -> str

Generate PowerShell directory test command.

Parameters:

Name Type Description Default
path str

Path to test if it's a directory

required

Returns:

Type Description
str

The PowerShell command string

Source code in src/anyenv/os_commands/is_directory.py
def create_command(self, path: str) -> str:
    """Generate PowerShell directory test command.

    Args:
        path: Path to test if it's a directory

    Returns:
        The PowerShell command string
    """
    return powershell(
        f"(Get-Item -LiteralPath {ps_literal(path)} -ErrorAction SilentlyContinue)"
        ".PSIsContainer"
    )

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse PowerShell directory test result.

Parameters:

Name Type Description Default
output str

Raw PowerShell command output

required
exit_code int

Command exit code (ignored)

0

Returns:

Type Description
bool

True if path is a directory, False otherwise

Source code in src/anyenv/os_commands/is_directory.py
def parse_command(
    self,
    output: str,
    exit_code: int = 0,
) -> bool:
    """Parse PowerShell directory test result.

    Args:
        output: Raw PowerShell command output
        exit_code: Command exit code (ignored)

    Returns:
        True if path is a directory, False otherwise
    """
    return output.strip().lower() == "true"

WindowsIsFileCommand

Bases: IsFileCommand

Windows is file command implementation.

Source code in src/anyenv/os_commands/is_file.py
class WindowsIsFileCommand(IsFileCommand):
    """Windows is file command implementation."""

    def create_command(self, path: str) -> str:
        """Generate PowerShell file test command.

        Args:
            path: Path to test if it's a file

        Returns:
            The PowerShell command string
        """
        return powershell(
            f"$item = Get-Item -LiteralPath {ps_literal(path)} -ErrorAction SilentlyContinue; "
            "$item -ne $null -and -not $item.PSIsContainer"
        )

    def parse_command(
        self,
        output: str,
        exit_code: int = 0,
    ) -> bool:
        """Parse PowerShell file test result.

        Args:
            output: Raw PowerShell command output
            exit_code: Command exit code (ignored)

        Returns:
            True if path is a file, False otherwise
        """
        return output.strip().lower() == "true"

create_command

create_command(path: str) -> str

Generate PowerShell file test command.

Parameters:

Name Type Description Default
path str

Path to test if it's a file

required

Returns:

Type Description
str

The PowerShell command string

Source code in src/anyenv/os_commands/is_file.py
def create_command(self, path: str) -> str:
    """Generate PowerShell file test command.

    Args:
        path: Path to test if it's a file

    Returns:
        The PowerShell command string
    """
    return powershell(
        f"$item = Get-Item -LiteralPath {ps_literal(path)} -ErrorAction SilentlyContinue; "
        "$item -ne $null -and -not $item.PSIsContainer"
    )

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse PowerShell file test result.

Parameters:

Name Type Description Default
output str

Raw PowerShell command output

required
exit_code int

Command exit code (ignored)

0

Returns:

Type Description
bool

True if path is a file, False otherwise

Source code in src/anyenv/os_commands/is_file.py
def parse_command(
    self,
    output: str,
    exit_code: int = 0,
) -> bool:
    """Parse PowerShell file test result.

    Args:
        output: Raw PowerShell command output
        exit_code: Command exit code (ignored)

    Returns:
        True if path is a file, False otherwise
    """
    return output.strip().lower() == "true"

WindowsListDirectoryCommand

Bases: ListDirectoryCommand

Windows list directory command implementation.

Source code in src/anyenv/os_commands/list_directory.py
class WindowsListDirectoryCommand(ListDirectoryCommand):
    """Windows list directory command implementation."""

    def create_command(self, path: str = "") -> str:
        """Generate Windows PowerShell dir command.

        Args:
            path: Directory path to list

        Returns:
            The PowerShell command string
        """
        target = f" -LiteralPath {ps_literal(path)}" if path else ""
        return powershell(
            f"Get-ChildItem{target} | Format-Table -AutoSize Name, Mode, Length, LastWriteTime"
        )

    def parse_command(
        self,
        output: str,
        path: str = "",
    ) -> list[DirectoryEntry]:
        """Parse Windows PowerShell Get-ChildItem output.

        Args:
            output: Raw PowerShell command output
            path: Base directory path

        Returns:
            List of DirectoryEntry objects
        """
        lines = output.strip().split("\n")
        if not lines:
            return []

        files: list[DirectoryEntry] = []

        # Skip header lines and empty lines
        data_lines = []
        for line in lines:
            line = line.strip()
            if not line or line.startswith(("----", "Name", "Mode")):
                continue
            data_lines.append(line)

        # Parse PowerShell Format-Table output
        for line in data_lines:
            parsed = self._parse_powershell_line(line, path)
            if parsed and parsed.name not in (".", ".."):
                files.append(parsed)

        return files

    def _parse_powershell_line(self, line: str, base_path: str) -> DirectoryEntry | None:
        """Parse PowerShell Format-Table output line."""
        # PowerShell Format-Table output: Name Mode Length LastWriteTime
        # Split by multiple spaces to handle columns
        parts = line.split()
        if len(parts) < MIN_WINDOWS_DIR_PARTS:
            return None

        try:
            name = parts[0]
            mode = parts[1]
            length_str = parts[2]
            # LastWriteTime might be split across multiple parts
            timestamp_parts = parts[3:]
            timestamp = " ".join(timestamp_parts) if timestamp_parts else ""

            # Determine file type from mode
            file_type: Literal["file", "directory", "link"]
            if mode.startswith("d") or "-" not in mode:
                file_type = "directory"
                size = 0
            else:
                file_type = "file"
                # Parse size, handle non-numeric values
                try:
                    size = int(length_str) if length_str.isdigit() else 0
                except ValueError, AttributeError:
                    size = 0

            # Build full path
            full_path = f"{base_path}\\{name}".replace("/", "\\") if base_path else name

            return DirectoryEntry(
                name=name,
                path=full_path,
                type=file_type,
                size=size,
                timestamp=timestamp,
                permissions=mode,
            )
        except ValueError, IndexError:
            return None

create_command

create_command(path: str = '') -> str

Generate Windows PowerShell dir command.

Parameters:

Name Type Description Default
path str

Directory path to list

''

Returns:

Type Description
str

The PowerShell command string

Source code in src/anyenv/os_commands/list_directory.py
def create_command(self, path: str = "") -> str:
    """Generate Windows PowerShell dir command.

    Args:
        path: Directory path to list

    Returns:
        The PowerShell command string
    """
    target = f" -LiteralPath {ps_literal(path)}" if path else ""
    return powershell(
        f"Get-ChildItem{target} | Format-Table -AutoSize Name, Mode, Length, LastWriteTime"
    )

parse_command

parse_command(output: str, path: str = '') -> list[DirectoryEntry]

Parse Windows PowerShell Get-ChildItem output.

Parameters:

Name Type Description Default
output str

Raw PowerShell command output

required
path str

Base directory path

''

Returns:

Type Description
list[DirectoryEntry]

List of DirectoryEntry objects

Source code in src/anyenv/os_commands/list_directory.py
def parse_command(
    self,
    output: str,
    path: str = "",
) -> list[DirectoryEntry]:
    """Parse Windows PowerShell Get-ChildItem output.

    Args:
        output: Raw PowerShell command output
        path: Base directory path

    Returns:
        List of DirectoryEntry objects
    """
    lines = output.strip().split("\n")
    if not lines:
        return []

    files: list[DirectoryEntry] = []

    # Skip header lines and empty lines
    data_lines = []
    for line in lines:
        line = line.strip()
        if not line or line.startswith(("----", "Name", "Mode")):
            continue
        data_lines.append(line)

    # Parse PowerShell Format-Table output
    for line in data_lines:
        parsed = self._parse_powershell_line(line, path)
        if parsed and parsed.name not in (".", ".."):
            files.append(parsed)

    return files

WindowsPwdCommand

Bases: PwdCommand

Windows pwd command implementation.

Source code in src/anyenv/os_commands/pwd.py
class WindowsPwdCommand(PwdCommand):
    """Windows pwd command implementation."""

    def create_command(self) -> str:
        """Generate Windows cd command (prints current directory when no args).

        Returns:
            The cd command string
        """
        return "cd"

    def parse_command(self, output: str, exit_code: int = 0) -> str | None:
        """Parse Windows cd result.

        Args:
            output: Raw command output
            exit_code: Command exit code

        Returns:
            Current working directory or None on failure
        """
        if exit_code != 0:
            return None
        path = output.strip()
        return path if path else None

create_command

create_command() -> str

Generate Windows cd command (prints current directory when no args).

Returns:

Type Description
str

The cd command string

Source code in src/anyenv/os_commands/pwd.py
def create_command(self) -> str:
    """Generate Windows cd command (prints current directory when no args).

    Returns:
        The cd command string
    """
    return "cd"

parse_command

parse_command(output: str, exit_code: int = 0) -> str | None

Parse Windows cd result.

Parameters:

Name Type Description Default
output str

Raw command output

required
exit_code int

Command exit code

0

Returns:

Type Description
str | None

Current working directory or None on failure

Source code in src/anyenv/os_commands/pwd.py
def parse_command(self, output: str, exit_code: int = 0) -> str | None:
    """Parse Windows cd result.

    Args:
        output: Raw command output
        exit_code: Command exit code

    Returns:
        Current working directory or None on failure
    """
    if exit_code != 0:
        return None
    path = output.strip()
    return path if path else None

WindowsRemovePathCommand

Bases: RemovePathCommand

Windows remove path command implementation.

Source code in src/anyenv/os_commands/remove_path.py
class WindowsRemovePathCommand(RemovePathCommand):
    """Windows remove path command implementation."""

    def create_command(self, path: str, recursive: bool = False) -> str:
        """Generate Windows removal command.

        Args:
            path: Path to remove
            recursive: Whether to remove directories recursively

        Returns:
            The removal command string
        """
        literal = ps_literal(path)
        if recursive:
            return powershell(f"Remove-Item -LiteralPath {literal} -Recurse -Force")
        # Like `rm` without -r: directories are refused.
        return powershell(
            f"if (Test-Path -LiteralPath {literal} -PathType Container) {{ exit 1 }}; "
            f"Remove-Item -LiteralPath {literal} -Force"
        )

    def parse_command(
        self,
        output: str,
        exit_code: int = 0,
    ) -> bool:
        """Parse Windows removal result.

        Args:
            output: Raw command output (ignored)
            exit_code: Command exit code

        Returns:
            True if path was removed successfully, False otherwise
        """
        return exit_code == 0

create_command

create_command(path: str, recursive: bool = False) -> str

Generate Windows removal command.

Parameters:

Name Type Description Default
path str

Path to remove

required
recursive bool

Whether to remove directories recursively

False

Returns:

Type Description
str

The removal command string

Source code in src/anyenv/os_commands/remove_path.py
def create_command(self, path: str, recursive: bool = False) -> str:
    """Generate Windows removal command.

    Args:
        path: Path to remove
        recursive: Whether to remove directories recursively

    Returns:
        The removal command string
    """
    literal = ps_literal(path)
    if recursive:
        return powershell(f"Remove-Item -LiteralPath {literal} -Recurse -Force")
    # Like `rm` without -r: directories are refused.
    return powershell(
        f"if (Test-Path -LiteralPath {literal} -PathType Container) {{ exit 1 }}; "
        f"Remove-Item -LiteralPath {literal} -Force"
    )

parse_command

parse_command(output: str, exit_code: int = 0) -> bool

Parse Windows removal result.

Parameters:

Name Type Description Default
output str

Raw command output (ignored)

required
exit_code int

Command exit code

0

Returns:

Type Description
bool

True if path was removed successfully, False otherwise

Source code in src/anyenv/os_commands/remove_path.py
def parse_command(
    self,
    output: str,
    exit_code: int = 0,
) -> bool:
    """Parse Windows removal result.

    Args:
        output: Raw command output (ignored)
        exit_code: Command exit code

    Returns:
        True if path was removed successfully, False otherwise
    """
    return exit_code == 0

WindowsWhichCommand

Bases: WhichCommand

Windows where command implementation.

Source code in src/anyenv/os_commands/which.py
class WindowsWhichCommand(WhichCommand):
    """Windows where command implementation."""

    def create_command(self, executable: str) -> str:
        """Generate Windows where command.

        Args:
            executable: Name of executable to find

        Returns:
            The where command string
        """
        return powershell(f"where.exe {ps_literal(executable)}")

    def parse_command(self, output: str, exit_code: int = 0) -> str | None:
        """Parse Windows where result.

        Args:
            output: Raw command output
            exit_code: Command exit code

        Returns:
            Path to first matching executable or None if not found
        """
        if exit_code != 0:
            return None
        # where can return multiple paths, take the first one
        lines = output.strip().splitlines()
        return lines[0].strip() if lines else None

create_command

create_command(executable: str) -> str

Generate Windows where command.

Parameters:

Name Type Description Default
executable str

Name of executable to find

required

Returns:

Type Description
str

The where command string

Source code in src/anyenv/os_commands/which.py
def create_command(self, executable: str) -> str:
    """Generate Windows where command.

    Args:
        executable: Name of executable to find

    Returns:
        The where command string
    """
    return powershell(f"where.exe {ps_literal(executable)}")

parse_command

parse_command(output: str, exit_code: int = 0) -> str | None

Parse Windows where result.

Parameters:

Name Type Description Default
output str

Raw command output

required
exit_code int

Command exit code

0

Returns:

Type Description
str | None

Path to first matching executable or None if not found

Source code in src/anyenv/os_commands/which.py
def parse_command(self, output: str, exit_code: int = 0) -> str | None:
    """Parse Windows where result.

    Args:
        output: Raw command output
        exit_code: Command exit code

    Returns:
        Path to first matching executable or None if not found
    """
    if exit_code != 0:
        return None
    # where can return multiple paths, take the first one
    lines = output.strip().splitlines()
    return lines[0].strip() if lines else None

get_os_command_provider

get_os_command_provider(
    system: Literal["Windows", "Darwin", "Linux"] | None = None,
) -> OSCommandProvider

Auto-detect OS and return appropriate command provider.

Parameters:

Name Type Description Default
system Literal['Windows', 'Darwin', 'Linux'] | None

The system to use. If None, the current system is used.

None

Returns:

Type Description
OSCommandProvider

OS-specific command provider based on current platform

Source code in src/anyenv/os_commands/providers.py
def get_os_command_provider(
    system: Literal["Windows", "Darwin", "Linux"] | None = None,
) -> OSCommandProvider:
    """Auto-detect OS and return appropriate command provider.

    Args:
        system: The system to use. If None, the current system is used.

    Returns:
        OS-specific command provider based on current platform
    """
    system_ = system or platform.system()

    if system_ == "Windows":
        return WindowsCommandProvider()
    if system_ == "Darwin":  # macOS
        return MacOSCommandProvider()
    # Linux and other Unix-like systems
    return UnixCommandProvider()