Skip to content

WindowsListDirectoryCommand

Base classes

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

â‹” Inheritance diagram

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

🛈 DocStrings

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

:fa-brands-github: Show source on GitHub