Skip to content

UnixListDirectoryCommand

Base classes

Name Children Inherits
ListDirectoryCommand
anyenv.os_commands.base
Base class for list directory commands.

â‹” Inheritance diagram

graph TD
  2115302927["list_directory.UnixListDirectoryCommand"]
  4141724308["base.ListDirectoryCommand"]
  925645236["abc.ABC"]
  2751680898["builtins.object"]
  4141724308 --> 2115302927
  925645236 --> 4141724308
  2751680898 --> 925645236

🛈 DocStrings

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

:fa-brands-github: Show source on GitHub