"""File and directory existence / permission probes.""" import os import stat import grp import pwd def file_exists(path: str) -> bool: """Check if *path* exists and is a regular file.""" return os.path.isfile(path) def dir_exists(path: str) -> bool: """Check if *path* exists and is a directory.""" return os.path.isdir(path) def file_permissions(path: str) -> int: """Return the permission mode of *path* as an octal int (e.g. ``0o755``). Raises ``FileNotFoundError`` if *path* doesn't exist. """ return stat.S_IMODE(os.stat(path).st_mode) def file_contains(path: str, text: str) -> bool: """Check if a file contains the specified text.""" with open(path, "r", errors="replace") as f: return text in f.read() def file_owned_by(path: str, username: str) -> bool: """Check if a file is owned by the specified user.""" st = os.stat(path) owner = pwd.getpwuid(st.st_uid).pw_name return owner == username def file_group(path: str) -> str: """Get the group owner of a file.""" st = os.stat(path) return grp.getgrgid(st.st_gid).gr_name