Skip to content

UnixFindCommand

Base classes

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

â‹” Inheritance diagram

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

🛈 DocStrings

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

:fa-brands-github: Show source on GitHub