Skip to content

MacOSFindCommand

Base classes

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

â‹” Inheritance diagram

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

🛈 DocStrings

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

:fa-brands-github: Show source on GitHub