"""Core directory traversal routines with .gitignore and boundaries integration."""
from __future__ import annotations
import contextlib
import errno
import os
from pathlib import Path # noqa: TC003 - runtime signature introspection
from typing import TYPE_CHECKING, Any
from findfmt.classifier import compute_relative_prefix
from findfmt.models import SortKey
from findfmt.parsers import ingest_from_file
from findfmt.sizes import calculate_accumulated_sizes
from findfmt.traversal._pruning import _TraversalFrame
from findfmt.traversal.boundaries import (
check_depth_limit,
check_file_limit,
classify_file,
filter_directory_entry,
has_matching_descendants,
init_visited_dirs,
is_candidate_file_entry,
matches_filter,
resolve_active_specs,
resolve_device,
should_skip_dir,
should_skip_symlink_dir,
yield_matching_items,
)
from findfmt.traversal.ignore import (
load_child_specs,
load_custom_gitignore_spec,
load_git_exclude_spec,
load_gitignore_spec,
load_global_gitignore_spec,
)
from findfmt.traversal.patterns import create_pattern_matcher
from findfmt.traversal.sorting import collect_directory_entries
if TYPE_CHECKING:
from collections.abc import Callable, Iterator
import pathspec
from findfmt.models import FileInfo, TraversalConfig
from findfmt.traversal.patterns import PatternMatcher
PathSpecType = pathspec.PathSpec[Any]
else:
PathSpecType = Any
__all__ = [
"find_files",
"load_custom_gitignore_spec",
"load_git_exclude_spec",
"load_gitignore_spec",
"load_global_gitignore_spec",
"matches_filter",
"should_skip_dir",
"traverse_directory",
]
def _scan_directory_entries( # noqa: PLR0913 - wide CLI/config signature
root: Path,
config: TraversalConfig,
specs: tuple[tuple[Path, PathSpecType], ...],
*,
root_dev: int | None = None,
matcher: PatternMatcher | None = None,
base_root: Path | None = None,
on_error: Callable[[OSError], None] | None = None,
) -> tuple[list[Path], list[tuple[Path, os.DirEntry[str]]]]:
"""Scan and partition directory entries into subdirectories and files."""
entries = collect_directory_entries(root, config, on_error=on_error)
if entries is None:
return [], []
subdirs: list[Path] = []
files: list[tuple[Path, os.DirEntry[str]]] = []
for entry in entries:
filtered = filter_directory_entry(
entry,
config,
specs,
root_dev,
matcher=matcher,
base_root=base_root,
)
if filtered is None:
continue
entry_path, is_dir = filtered
if is_dir:
if not should_skip_dir(entry.name, include_hidden=config.include_hidden):
subdirs.append(entry_path)
elif is_candidate_file_entry(entry, follow_symlinks=config.follow_symlinks):
files.append((entry_path, entry))
return subdirs, files
def _should_enter_subdir( # noqa: PLR0913 - wide CLI/config signature
subdir: Path,
config: TraversalConfig,
child_specs: tuple[tuple[Path, PathSpecType], ...],
*,
base_root: Path,
visited: set[Path] | None,
root_dev: int | None,
child_depth: int,
matcher: PatternMatcher,
child_inherit: bool,
prune_memo: dict[tuple[int, int], bool],
on_error: Callable[[OSError], None] | None,
) -> bool:
"""Return True if subdir passes empty-pruning and symlink-loop checks."""
if (
config.dirs_only
and config.prune_empty
and not has_matching_descendants(
subdir,
config,
child_specs,
root_dev=root_dev,
current_depth=child_depth,
matcher=matcher,
inherited_match=child_inherit,
base_root=base_root,
memo=prune_memo,
on_error=on_error,
)
):
return False
return not should_skip_symlink_dir(
subdir,
follow_symlinks=config.follow_symlinks,
visited=visited,
)
def _enter_directory( # noqa: PLR0913 - wide CLI/config signature
curr_dir: Path,
config: TraversalConfig,
specs: tuple[tuple[Path, PathSpecType], ...],
*,
stack: list[_TraversalFrame],
base_root: Path,
prefix: Path | None,
root_dev: int | None,
current_depth: int,
matcher: PatternMatcher,
inherited_match: bool,
accumulated_sizes: dict[Path, int] | None,
prune_memo: dict[tuple[int, int], bool],
on_error: Callable[[OSError], None] | None,
) -> Iterator[FileInfo]:
"""Scan a directory, yield immediate items if pre-order, and push descent frame."""
subdirs, files = _scan_directory_entries(
curr_dir,
config,
specs,
root_dev=root_dev,
matcher=matcher,
base_root=base_root,
on_error=on_error,
)
targets = subdirs if config.dirs_only else files
current_items = yield_matching_items(
targets,
config,
specs,
base_root=base_root,
prefix=prefix,
root_dev=root_dev,
current_depth=current_depth,
matcher=matcher,
inherited_match=inherited_match,
accumulated_sizes=accumulated_sizes,
prune_memo=prune_memo,
on_error=on_error,
)
can_descend = check_depth_limit(current_depth, config.max_depth) and bool(subdirs)
if config.dirs_first and can_descend:
stack.append(
_TraversalFrame(
subdirs=subdirs,
specs=specs,
depth=current_depth,
inherited_match=inherited_match,
deferred_items=current_items,
),
)
return
yield from current_items
if can_descend:
stack.append(
_TraversalFrame(
subdirs=subdirs,
specs=specs,
depth=current_depth,
inherited_match=inherited_match,
),
)
[docs]
def traverse_directory( # noqa: PLR0913 - wide CLI/config signature
root: Path,
config: TraversalConfig,
active_specs: tuple[tuple[Path, PathSpecType], ...] | None = None,
*,
base_root: Path | None = None,
visited_dirs: set[Path] | None = None,
prefix: Path | None = None,
root_dev: int | None = None,
current_depth: int = 1,
matcher: PatternMatcher | None = None,
inherited_match: bool = False,
accumulated_sizes: dict[Path, int] | None = None,
prune_memo: dict[tuple[int, int], bool] | None = None,
on_error: Callable[[OSError], None] | None = None,
) -> Iterator[FileInfo]:
"""Iteratively traverse a directory hierarchy honoring .gitignore, filters, and boundaries."""
check_depth_limit(0, config.max_depth)
check_file_limit(0, config.file_limit)
if base_root is None:
with contextlib.suppress(OSError, RuntimeError):
root = root.resolve()
effective_base = base_root if base_root is not None else root
active_matcher = matcher if matcher is not None else create_pattern_matcher(config)
effective_dev = resolve_device(
root,
one_file_system=config.one_file_system,
root_dev=root_dev,
)
active_visited = init_visited_dirs(
root,
follow_symlinks=config.follow_symlinks,
visited=visited_dirs,
)
specs = resolve_active_specs(
root,
active_specs,
respect_gitignore=config.respect_gitignore,
gitignore_file=config.gitignore_file,
)
active_prune_memo = prune_memo if prune_memo is not None else {}
stack: list[_TraversalFrame] = []
yield from _enter_directory(
root,
config,
specs,
stack=stack,
base_root=effective_base,
prefix=prefix,
root_dev=effective_dev,
current_depth=current_depth,
matcher=active_matcher,
inherited_match=inherited_match,
accumulated_sizes=accumulated_sizes,
prune_memo=active_prune_memo,
on_error=on_error,
)
while stack:
top = stack[-1]
if top.idx >= len(top.subdirs):
stack.pop()
if top.deferred_items is not None:
yield from top.deferred_items
continue
subdir = top.subdirs[top.idx]
top.idx += 1
child_specs = load_child_specs(subdir, top.specs) if config.respect_gitignore else top.specs
child_inherit = active_matcher.should_inherit_match(
subdir,
base_root=effective_base,
parent_inherited=top.inherited_match,
)
if not _should_enter_subdir(
subdir,
config,
child_specs,
base_root=effective_base,
visited=active_visited,
root_dev=effective_dev,
child_depth=top.depth + 1,
matcher=active_matcher,
child_inherit=child_inherit,
prune_memo=active_prune_memo,
on_error=on_error,
):
continue
yield from _enter_directory(
subdir,
config,
child_specs,
stack=stack,
base_root=effective_base,
prefix=prefix,
root_dev=effective_dev,
current_depth=top.depth + 1,
matcher=active_matcher,
inherited_match=child_inherit,
accumulated_sizes=accumulated_sizes,
prune_memo=active_prune_memo,
on_error=on_error,
)
def _classify_root_kind(resolved_root: Path, *, follow_symlinks: bool) -> tuple[bool, bool]:
"""Return (is_file_or_link, is_dir) for a resolved root path."""
try:
is_file = resolved_root.is_file() or (not follow_symlinks and resolved_root.is_symlink())
return is_file, (False if is_file else resolved_root.is_dir())
except (OSError, RuntimeError):
return False, False
def _traverse_single_root(
root: Path,
resolved_root: Path,
config: TraversalConfig,
matcher: PatternMatcher,
*,
on_error: Callable[[OSError], None] | None = None,
) -> Iterator[FileInfo]:
"""Yield matching items from a single root path (file or directory)."""
is_file, is_dir = _classify_root_kind(resolved_root, follow_symlinks=config.follow_symlinks)
if is_file:
if not config.dirs_only:
prefix = compute_relative_prefix(root.parent) if config.relative_prefix else None
info = classify_file(
resolved_root,
root_path=resolved_root.parent,
prefix=prefix,
follow_symlinks=config.follow_symlinks,
)
if matches_filter(info, config, matcher=matcher):
yield info
return
if not is_dir:
return
accumulated_sizes = (
calculate_accumulated_sizes(
resolved_root,
follow_symlinks=config.follow_symlinks,
include_hidden=config.include_hidden,
)
if config.accumulate_size
else None
)
prefix = compute_relative_prefix(root) if config.relative_prefix else None
yield from traverse_directory(
resolved_root,
config,
base_root=resolved_root,
prefix=prefix,
matcher=matcher,
accumulated_sizes=accumulated_sizes,
on_error=on_error,
)
def _report_root_error(
root: Path,
err: OSError | RuntimeError,
on_error: Callable[[OSError], None] | None,
) -> None:
"""Invoke on_error callback ensuring err.filename is populated."""
if isinstance(err, OSError) and on_error is not None:
if not err.filename:
err.filename = str(root)
on_error(err)
def _resolve_existing_root(
root: Path,
on_error: Callable[[OSError], None] | None,
*,
follow_symlinks: bool = False,
) -> Path | None:
"""Resolve a root path if it exists, reporting missing or inaccessible roots via on_error."""
try:
is_symlink = root.is_symlink()
if is_symlink and not follow_symlinks:
return root.parent.resolve() / root.name
resolved_root = root.resolve()
exists = resolved_root.exists()
except (OSError, RuntimeError) as err:
_report_root_error(root, err, on_error)
return None
if exists:
return (
root.parent.resolve() / root.name if is_symlink and not resolved_root.is_dir() else resolved_root
)
if not is_symlink:
_report_root_error(
root,
FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), str(root)),
on_error,
)
return None
[docs]
def find_files(
config: TraversalConfig,
*,
on_error: Callable[[OSError], None] | None = None,
) -> Iterator[FileInfo]:
"""Discover and classify files across all configured root paths or external listings."""
check_depth_limit(0, config.max_depth)
check_file_limit(0, config.file_limit)
if config.from_file is not None:
yield from ingest_from_file(config)
return
matcher = create_pattern_matcher(config)
roots = config.root_paths if config.sort_by == SortKey.NONE else sorted(config.root_paths)
for root in roots:
resolved_root = _resolve_existing_root(
root,
on_error,
follow_symlinks=config.follow_symlinks,
)
if resolved_root is not None:
yield from _traverse_single_root(
root,
resolved_root,
config,
matcher,
on_error=on_error,
)