Skip to content

WindowsFindCommand

Base classes

Name Children Inherits
FindCommand
anyenv.os_commands.base
Base class for recursive find commands.

â‹” Inheritance diagram

graph TD
  3142369212["find.WindowsFindCommand"]
  1345197150["base.FindCommand"]
  925645236["abc.ABC"]
  2751680898["builtins.object"]
  1345197150 --> 3142369212
  925645236 --> 1345197150
  2751680898 --> 925645236

🛈 DocStrings

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

:fa-brands-github: Show source on GitHub