Code source de findfmt.classifier

"""File classification and content analysis engine."""

from __future__ import annotations

import io
import mimetypes
import os
import stat
from pathlib import Path

import identify.identify as identify_engine

from findfmt.metadata import extract_metadata
from findfmt.models import FileInfo
from findfmt.utils.strings import get_classification_indicator

mimetypes.init()

__all__ = [
    "classify_file",
    "compute_relative_prefix",
    "extract_shebang",
    "extract_shebang_from_buffer",
    "get_known_tags",
]


[docs] def get_known_tags() -> frozenset[str]: """Retrieve all known format and type tags recognized by the engine. Returns: frozenset of all recognized string tags. """ return frozenset(identify_engine.ALL_TAGS)
[docs] def extract_shebang_from_buffer(buffer: bytes) -> str | None: """Extract shebang interpreter line from a pre-read file buffer. Args: buffer: Initial bytes read from the file. Returns: The raw shebang line string if present and valid, or None. """ if buffer.startswith(b"#!"): return buffer.split(b"\n", 1)[0].decode("utf-8", errors="replace").strip() return None
[docs] def extract_shebang(path: Path) -> str | None: """Extract the shebang interpreter from the top of an executable file. Args: path: Path to the target file. Returns: The raw shebang line string if present and readable, or None. """ try: if path.is_file(): with path.open("rb") as f: return extract_shebang_from_buffer(f.readline(512)) except (OSError, UnicodeDecodeError): pass return None
[docs] def compute_relative_prefix(root: Path) -> Path | None: """Compute relative prefix from an input root path. Args: root: Target search root path. Returns: Relative Path prefix to prepend, or None if no prefix is needed. """ if root.is_absolute(): try: rel = root.resolve().relative_to(Path.cwd().resolve()) return rel if rel != Path() else None except ValueError: return root return root if root != Path() else None
def _resolve_relative( path: Path, root_path: Path | None, prefix: Path | None = None, ) -> Path: """Compute relative path from root_path if provided.""" if root_path is None: return path try: rel = path.relative_to(root_path) except ValueError: try: rel_str = os.path.relpath(path, root_path) if rel_str.startswith(".."): return path rel = Path(rel_str) except (ValueError, OSError): return path return prefix / rel if prefix is not None and prefix != Path() else rel def _read_initial_buffer( path: Path, max_bytes: int = 2048, ) -> tuple[bytes, os.stat_result | None]: """Read initial bytes once for shebang, encoding, and content checks. Opens target file non-blocking and verifies regular file status via fstat to prevent hanging on unwritten FIFOs or swapped named pipes. """ flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) try: fd = os.open(path, flags) except OSError: return b"", None try: st = os.fstat(fd) return (os.read(fd, max_bytes), st) if stat.S_ISREG(st.st_mode) else (b"", st) except OSError: return b"", None finally: os.close(fd) def _inspect_file_content( path: Path, size_bytes: int, stat_result: os.stat_result | None, ) -> tuple[bytes | None, bool, int, os.stat_result | None]: """Read content buffer safely and detect swapped non-regular entries.""" buffer, opened_stat = _read_initial_buffer(path) if opened_stat is not None and not stat.S_ISREG(opened_stat.st_mode): return buffer, False, opened_stat.st_size, opened_stat return buffer, True, size_bytes, stat_result def _identify_tags_from_buffer( name: str, buffer: bytes, *, is_executable: bool, ) -> set[str]: """Identify file tags directly from an in-memory buffer.""" tags = {identify_engine.FILE} tags.add( identify_engine.EXECUTABLE if is_executable else identify_engine.NON_EXECUTABLE, ) t = identify_engine.tags_from_filename(name) if t: tags.update(t) elif is_executable and buffer.startswith(b"#!"): parts = identify_engine.parse_shebang(io.BytesIO(buffer)) if parts: tags.update(identify_engine.tags_from_interpreter(parts[0])) if not (identify_engine.ENCODING_TAGS & tags): if identify_engine.is_text(io.BytesIO(buffer)): tags.add(identify_engine.TEXT) else: tags.add(identify_engine.BINARY) return tags def _identify_tags( # noqa: PLR0913 - wide CLI/config signature path: Path, str_path: str, *, exists: bool, is_regular_or_symlink: bool = True, buffer: bytes | None = None, is_executable: bool = False, ) -> set[str]: """Extract identify tags with fallback handling, using buffer if available.""" try: if not exists or not is_regular_or_symlink: return set(identify_engine.tags_from_filename(path.name)) if buffer is not None: return _identify_tags_from_buffer(path.name, buffer, is_executable=is_executable) return set(identify_engine.tags_from_path(str_path)) except (ValueError, OSError): return set(identify_engine.tags_from_filename(path.name)) def _shebang_info( path: Path, str_path: str, *, is_file: bool, is_symlink: bool, buffer: bytes | None = None, ) -> tuple[str | None, set[str]]: """Extract shebang and interpreter tags if applicable.""" if not (is_file and not is_symlink): return None, set() shebang = extract_shebang_from_buffer(buffer) if buffer is not None else extract_shebang(path) if shebang is None: return None, set() parts = ( identify_engine.parse_shebang(io.BytesIO(buffer)) if buffer is not None else identify_engine.parse_shebang_from_file(str_path) ) tags = {tag for part in parts for tag in identify_engine.tags_from_interpreter(part)} return shebang, tags def _mime_info(str_path: str) -> tuple[str | None, set[str]]: """Extract MIME type and MIME-derived tags.""" mime_type, _ = mimetypes.guess_type(str_path) tags: set[str] = {f"mime:{mime_type}", mime_type.split("/", 1)[0]} if mime_type is not None else set() return mime_type, tags def _check_executable( path: Path, *, exists: bool, shebang: str | None = None, stat_result: os.stat_result | None = None, ) -> bool: """Determine whether a file is executable across POSIX and Windows platforms.""" if not exists: return False if os.name == "nt": pathext = os.environ.get("PATHEXT", ".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC").split(";") exts = tuple( e.strip().upper() if e.strip().startswith(".") else f".{e.strip().upper()}" for e in pathext if e.strip() ) return path.name.upper().endswith(exts) or bool(shebang) return stat_result is not None and bool(stat_result.st_mode & 0o111) def _read_symlink_target(path: Path, *, is_symlink: bool) -> str | None: """Read symlink destination via Path.readlink if path is a symbolic link.""" if not is_symlink: return None try: return str(path.readlink()).removeprefix("\\\\?\\") except OSError: return None def _augment_symlink_tags( tags: set[str], path: Path, *, is_symlink: bool, symlink_target: str | None, follow_symlinks: bool, ) -> None: """Include symlink tag and filename tags for symbolic links.""" if not is_symlink: return tags.add(identify_engine.SYMLINK) tags.update(identify_engine.tags_from_filename(path.name)) if follow_symlinks and symlink_target is not None: tags.update(identify_engine.tags_from_filename(Path(symlink_target).name)) def _inspect_entry_metadata( entry: os.DirEntry[str], *, follow_symlinks: bool = False, ) -> tuple[bool, bool, bool, int, os.stat_result | None]: """Inspect metadata from an os.DirEntry object.""" try: is_symlink = entry.is_symlink() is True except OSError: is_symlink = False try: stat_result = entry.stat(follow_symlinks=follow_symlinks or not is_symlink) size_bytes = stat_result.st_size exists = True is_file = stat.S_ISREG(stat_result.st_mode) except OSError: stat_result, size_bytes, exists, is_file = None, 0, False, False return is_symlink, exists, is_file, size_bytes, stat_result def _inspect_path_metadata( path: Path, *, follow_symlinks: bool = False, ) -> tuple[bool, bool, bool, int, os.stat_result | None]: """Inspect filesystem metadata directly from a Path object.""" is_symlink = False try: st = path.stat(follow_symlinks=False) is_symlink = stat.S_ISLNK(st.st_mode) if is_symlink and follow_symlinks: st = path.stat() except OSError: return is_symlink, False, False, 0, None return is_symlink, True, stat.S_ISREG(st.st_mode), st.st_size, st def _inspect_metadata( path: Path, entry: os.DirEntry[str] | None = None, *, follow_symlinks: bool = False, ) -> tuple[bool, bool, bool, int, os.stat_result | None]: """Inspect filesystem metadata safely, reusing DirEntry when available.""" if entry is not None: return _inspect_entry_metadata(entry, follow_symlinks=follow_symlinks) return _inspect_path_metadata(path, follow_symlinks=follow_symlinks) def _adjust_nt_tags(tags: set[str], *, is_executable: bool) -> None: """Adjust executable tags on Windows platform.""" if os.name != "nt": return add_tag, discard_tag = ( ("executable", "non-executable") if is_executable else ("non-executable", "executable") ) tags.discard(discard_tag) tags.add(add_tag) def _extract_timestamps_and_indicator( stat_result: os.stat_result | None, *, is_symlink: bool, is_executable: bool, ) -> tuple[float | None, float | None, str | None]: """Extract mtime, ctime, and classification indicator safely.""" mtime = stat_result.st_mtime if stat_result is not None else None ctime = stat_result.st_ctime if stat_result is not None else None is_dir = stat.S_ISDIR(stat_result.st_mode) if stat_result is not None else False indicator = get_classification_indicator( is_dir=is_dir, is_symlink=is_symlink, is_executable=is_executable and not is_dir, stat_result=stat_result, ) return mtime, ctime, indicator def _resolve_file_location( path: Path, *, entry: os.DirEntry[str] | None, is_symlink: bool, exists: bool, ) -> Path: """Return resolved path for standalone regular files, keeping link and entry locations.""" return path.resolve() if entry is None and not is_symlink and exists and not path.is_absolute() else path
[docs] def classify_file( # noqa: PLR0913 - wide CLI/config signature path: Path, root_path: Path | None = None, prefix: Path | None = None, accumulated_size: int | None = None, *, entry: os.DirEntry[str] | None = None, follow_symlinks: bool = False, ) -> FileInfo: """Classify a given file path by inspection of name, content, and metadata. Args: path: The path of the file to classify. root_path: Optional root directory used to compute relative_path. prefix: Optional prefix to prepend to relative_path. accumulated_size: Optional accumulated directory disk usage in bytes. entry: Optional os.DirEntry metadata from scandir. follow_symlinks: Whether to follow symbolic links for content and target classification. Returns: FileInfo containing metadata, identified tags, shebang, and MIME info. """ str_path = str(path) is_symlink, exists, is_file, size_bytes, stat_result = _inspect_metadata( path, entry=entry, follow_symlinks=follow_symlinks, ) symlink_target = _read_symlink_target(path, is_symlink=is_symlink) permissions_str, owner_user, owner_group, inode, device = extract_metadata(stat_result) follow_target = not is_symlink or follow_symlinks buffer: bytes | None = None if exists and is_file and follow_target: buffer, is_file, size_bytes, stat_result = _inspect_file_content( path, size_bytes, stat_result, ) if not is_file: permissions_str, owner_user, owner_group, inode, device = extract_metadata(stat_result) shebang, shebang_tags = _shebang_info( path, str_path, is_file=is_file, is_symlink=not follow_target, buffer=buffer, ) is_executable = _check_executable( path, exists=exists and follow_target, shebang=shebang, stat_result=stat_result, ) tags = _identify_tags( path, str_path, exists=exists, is_regular_or_symlink=is_file or is_symlink, buffer=buffer, is_executable=is_executable, ) tags.update(shebang_tags) _augment_symlink_tags( tags, path, is_symlink=is_symlink, symlink_target=symlink_target, follow_symlinks=follow_symlinks, ) _adjust_nt_tags(tags, is_executable=is_executable) mime_type, mime_tags = _mime_info(str_path) tags.update(mime_tags) relative_path = _resolve_relative(path, root_path, prefix=prefix) resolved_path = _resolve_file_location(path, entry=entry, is_symlink=is_symlink, exists=exists) effective_size = accumulated_size if accumulated_size is not None else size_bytes mtime, ctime, indicator = _extract_timestamps_and_indicator( stat_result, is_symlink=is_symlink, is_executable=is_executable, ) return FileInfo( path=resolved_path, relative_path=relative_path, tags=frozenset(tags), shebang=shebang, mime_type=mime_type, is_executable=is_executable, is_symlink=is_symlink, symlink_target=symlink_target, size_bytes=effective_size, permissions_str=permissions_str, owner_user=owner_user, owner_group=owner_group, inode=inode, device=device, accumulated_size=accumulated_size, mtime=mtime, ctime=ctime, indicator=indicator, )