Package Modules

Documentation for findfmt public API modules, subsystems, and data models.

1. Core Data Models (findfmt.models)

Core data models and configurations for findfmt.

class findfmt.models.FileInfo(path: Path, relative_path: Path, tags: frozenset[str] = <factory>, shebang: str | None = None, mime_type: str | None = None, is_executable: bool = False, is_symlink: bool = False, symlink_target: str | None = None, size_bytes: int = 0, permissions_str: str | None = None, owner_user: str | None = None, owner_group: str | None = None, inode: int | None = None, device: int | None = None, accumulated_size: int | None = None, mtime: float | None = None, ctime: float | None = None, indicator: str | None = None)[source]

Bases: object

Represents file metadata, classification tags, and content attributes.

Variables:
  • path (pathlib.Path) – Absolute path to the file.

  • relative_path (pathlib.Path) – Path relative to the traversal root.

  • tags (frozenset[str]) – Set of tags assigned by the classifier (e.g., ‘python’, ‘text’).

  • shebang (str | None) – Extracted shebang line if present, otherwise None.

  • mime_type (str | None) – Detected MIME type if available, otherwise None.

  • is_executable (bool) – Whether the file has executable permissions.

  • is_symlink (bool) – Whether the path is a symbolic link.

  • symlink_target (str | None) – Target path if the file is a symbolic link, otherwise None.

  • size_bytes (int) – File size in bytes.

  • permissions_str (str | None) – Formatted file mode in standard ls -l format (e.g. -rw-r–r–).

  • owner_user (str | None) – File owner username or UID if username is unavailable.

  • owner_group (str | None) – File owner group name or GID if group name is unavailable.

  • inode (int | None) – Filesystem inode number (st_ino).

  • device (int | None) – Filesystem device number (st_dev).

  • accumulated_size (int | None) – Accumulated directory disk usage in bytes if –du is active.

accumulated_size: int | None
ctime: float | None
device: int | None
indicator: str | None
inode: int | None
is_executable: bool
mime_type: str | None
mtime: float | None
owner_group: str | None
owner_user: str | None
path: Path
permissions_str: str | None
relative_path: Path
shebang: str | None
size_bytes: int
tags: frozenset[str]
to_dict(*, absolute: bool = False) → dict[str, Any][source]

Serialize file attributes to a dictionary representation.

Parameters:

absolute – Whether the ‘path’ entry contains the absolute path.

Returns:

Dictionary mapping attribute names to serialized values. If the path contains surrogate escapes (non-UTF-8 bytes), a ‘path_bytes’ entry is also included containing the raw byte values.

class findfmt.models.SortKey(*values)[source]

Bases: StrEnum

Sort criteria keys for directory traversal.

CTIME = 'ctime'
MTIME = 'mtime'
NAME = 'name'
NONE = 'none'
SIZE = 'size'
TIME = 'time'
VERSION = 'version'
class findfmt.models.TraversalConfig(root_paths: tuple[~pathlib.Path, ...]=<factory>, include_tags: frozenset[str] = <factory>, exclude_tags: frozenset[str] = <factory>, all_tags: bool = False, shebang_filter: str | None = None, respect_gitignore: bool = True, gitignore_file: Path | None = None, include_hidden: bool = False, follow_symlinks: bool = False, dirs_only: bool = False, one_file_system: bool = False, max_depth: int | None = None, file_limit: int | None = None, prune_empty: bool = False, include_patterns: tuple[str, ...]=(), exclude_patterns: tuple[str, ...]=(), ignore_case: bool = False, match_dirs: bool = False, relative_paths: bool = True, relative_prefix: bool = False, null_delimited: bool = False, show_tags: bool = False, show_summary: bool = False, output_format: str = 'text', sort_by: SortKey = SortKey.NAME, reverse_sort: bool = False, dirs_first: bool = False, files_first: bool = False, from_file: str | None = None, offline: bool = False, allow_outside_root: bool = False, show_permissions: bool = False, show_user: bool = False, show_group: bool = False, show_inodes: bool = False, show_device: bool = False, show_size: bool = False, human_readable: bool = False, show_si: bool = False, accumulate_size: bool = False, show_mtime: bool = False, show_ctime: bool = False, time_format: str | None = None, classify: bool = False, hide_control_chars: bool = False, literal: bool = False, quote_name: bool = False, base_href: str | None = None, intro_file: Path | None = None, outro_file: Path | None = None, html_title: str | None = None, no_links: bool = False, xml: bool = False, hyperlink: bool = False, hyperlink_schema: str = 'file://', hyperlink_authority: str | None = None, csv_safe: bool = False, locale: str | None = None)[source]

Bases: object

Configuration options for repository traversal and format filtering.

Variables:
  • root_paths (tuple[pathlib.Path, ...]) – Roots from which to begin file discovery.

  • include_tags (frozenset[str]) – Tags that files must have to be included.

  • exclude_tags (frozenset[str]) – Tags that disqualify a file from inclusion.

  • all_tags (bool) – If True, file must match all include_tags; if False, any tag.

  • shebang_filter (str | None) – Substring or interpreter name required in shebang.

  • respect_gitignore (bool) – Whether to ignore paths matched by gitignore rules.

  • gitignore_file (pathlib.Path | None) – External gitignore file path to apply across traversal scope.

  • include_hidden (bool) – Whether to inspect hidden files and directories.

  • follow_symlinks (bool) – Whether to resolve and traverse symbolic links.

  • dirs_only (bool) – Whether to list directories only, suppressing file entries.

  • one_file_system (bool) – Whether to confine traversal to the root filesystem device.

  • max_depth (int | None) – Maximum directory descent depth, or None for unlimited.

  • file_limit (int | None) – Maximum directory entries threshold before skipping descent, or None.

  • prune_empty (bool) – Whether to prune empty directories or directories with no matching files.

  • include_patterns (tuple[str, ...]) – Wildcard/glob patterns for including files (-P).

  • exclude_patterns (tuple[str, ...]) – Wildcard/glob patterns for excluding files (-I).

  • ignore_case (bool) – Whether pattern comparisons are case-insensitive.

  • match_dirs (bool) – Whether directory names are matched against patterns and inherit.

  • relative_paths (bool) – Whether to output relative paths rather than absolute.

  • relative_prefix (bool) – Whether to prepend input search path prefix to relative paths.

  • null_delimited (bool) – Whether to delimit output paths with NUL bytes (0).

  • show_tags (bool) – Whether to print identified tags alongside file paths.

  • show_summary (bool) – Whether to output summary statistics of matches.

  • output_format (str) – Requested output serialization format.

  • sort_by (findfmt.models.SortKey) – Criterion for ordering directory traversal entries.

  • reverse_sort (bool) – Whether to invert the active sort order.

  • dirs_first (bool) – Whether to list directories before files within directory levels.

  • files_first (bool) – Whether to list files before directories within directory levels.

  • from_file (str | None) – Input file path or ‘-’ for stdin to ingest directory structure from.

  • offline (bool) – Whether to enforce extension-only classification without disk access.

  • allow_outside_root (bool) – Whether to allow –from-file entries that resolve outside the root.

  • show_permissions (bool) – Whether to display file permissions in ls -l format.

  • show_user (bool) – Whether to display file owner username or UID.

  • show_group (bool) – Whether to display file owner group name or GID.

  • show_inodes (bool) – Whether to display filesystem inode numbers.

  • show_device (bool) – Whether to display filesystem device numbers.

  • show_size (bool) – Whether to display file size in bytes.

  • human_readable (bool) – Whether to format sizes using binary units (powers of 1024).

  • show_si (bool) – Whether to format sizes using SI metric units (powers of 1000).

  • accumulate_size (bool) – Whether to accumulate recursive directory disk usage.

  • show_mtime (bool) – Whether to display file modification date/time.

  • show_ctime (bool) – Whether to display inode status change date/time.

  • time_format (str | None) – Optional strftime format string for timestamps.

  • classify (bool) – Whether to append file classification indicators.

  • hide_control_chars (bool) – Whether to mask non-printable characters as ‘?’.

  • literal (bool) – Whether to print non-printable characters verbatim.

  • quote_name (bool) – Whether to enclose filenames in double quotes with backslash escaping.

  • base_href (str | None) – Optional base URL prefix for HTML hyperlinks.

  • intro_file (pathlib.Path | None) – Optional path to HTML fragment file prepended to directory listing.

  • outro_file (pathlib.Path | None) – Optional path to HTML fragment file appended to directory listing.

  • html_title (str | None) – Document title and heading for HTML output.

  • no_links (bool) – Whether to suppress hyperlinks in HTML mode.

  • xml (bool) – Whether XML output format flag is active.

  • hyperlink (bool) – Whether to emit OSC 8 terminal hyperlinks for paths.

  • hyperlink_schema (str) – URI schema for terminal hyperlinks.

  • hyperlink_authority (str | None) – Optional URI authority component for terminal hyperlinks.

  • csv_safe (bool) – Whether to neutralize spreadsheet formula injection in CSV/TSV output.

  • locale (str | None) – Optional locale string for translations and formatting.

accumulate_size: bool
all_tags: bool
allow_outside_root: bool
base_href: str | None
classify: bool
csv_safe: bool
dirs_first: bool
dirs_only: bool
exclude_patterns: tuple[str, ...]
exclude_tags: frozenset[str]
file_limit: int | None
files_first: bool
from_file: str | None
gitignore_file: Path | None
hide_control_chars: bool
html_title: str | None
human_readable: bool
ignore_case: bool
include_hidden: bool
include_patterns: tuple[str, ...]
include_tags: frozenset[str]
intro_file: Path | None
literal: bool
locale: str | None
match_dirs: bool
max_depth: int | None
null_delimited: bool
offline: bool
one_file_system: bool
output_format: str
outro_file: Path | None
prune_empty: bool
quote_name: bool
relative_paths: bool
relative_prefix: bool
respect_gitignore: bool
reverse_sort: bool
root_paths: tuple[Path, ...]
shebang_filter: str | None
show_ctime: bool
show_device: bool
show_group: bool
show_inodes: bool
show_mtime: bool
show_permissions: bool
show_si: bool
show_size: bool
show_summary: bool
show_tags: bool
show_user: bool
sort_by: SortKey
time_format: str | None
xml: bool

2. File Classifier (findfmt.classifier)

File classification and content analysis engine.

findfmt.classifier.classify_file(path: Path, root_path: Path | None = None, prefix: Path | None = None, accumulated_size: int | None = None, *, entry: DirEntry[str] | None = None, follow_symlinks: bool = False) → FileInfo[source]

Classify a given file path by inspection of name, content, and metadata.

Parameters:
  • 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.

findfmt.classifier.compute_relative_prefix(root: Path) → Path | None[source]

Compute relative prefix from an input root path.

Parameters:

root – Target search root path.

Returns:

Relative Path prefix to prepend, or None if no prefix is needed.

findfmt.classifier.extract_shebang(path: Path) → str | None[source]

Extract the shebang interpreter from the top of an executable file.

Parameters:

path – Path to the target file.

Returns:

The raw shebang line string if present and readable, or None.

findfmt.classifier.extract_shebang_from_buffer(buffer: bytes) → str | None[source]

Extract shebang interpreter line from a pre-read file buffer.

Parameters:

buffer – Initial bytes read from the file.

Returns:

The raw shebang line string if present and valid, or None.

findfmt.classifier.get_known_tags() → frozenset[str][source]

Retrieve all known format and type tags recognized by the engine.

Returns:

frozenset of all recognized string tags.

3. Filesystem Metadata (findfmt.metadata)

POSIX filesystem metadata extraction and caching utilities.

findfmt.metadata.clear_metadata_cache() → None[source]

Clear in-memory caches for user and group name lookups.

findfmt.metadata.extract_metadata(stat_result: os.stat_result | None) → tuple[str | None, str | None, str | None, int | None, int | None][source]

Extract POSIX permissions, ownership, and filesystem identifiers safely.

Parameters:

stat_result – Standard library stat_result or None if stat failed.

Returns:

Tuple of (permissions_str, owner_user, owner_group, inode, device).

findfmt.metadata.format_metadata_parts(file_info: FileInfo, *, show_inodes: bool = False, show_device: bool = False, show_permissions: bool = False, show_user: bool = False, show_group: bool = False, show_size: bool = False, human_readable: bool = False, show_si: bool = False, show_mtime: bool = False, show_ctime: bool = False, time_format: str | None = None) → list[str][source]

Format active POSIX metadata fields into string representations.

Parameters:
  • file_info – FileInfo instance containing metadata.

  • show_inodes – Whether to include inode number.

  • show_device – Whether to include device number.

  • show_permissions – Whether to include permissions string.

  • show_user – Whether to include owner username.

  • show_group – Whether to include owner group name.

  • show_size – Whether to include exact byte size.

  • human_readable – Whether to include binary human-readable size.

  • show_si – Whether to include SI metric human-readable size.

  • show_mtime – Whether to include file modification date/time.

  • show_ctime – Whether to include inode status change date/time.

  • time_format – Optional strftime format string for timestamps.

Returns:

List of formatted string metadata fields.

findfmt.metadata.format_permissions(mode: int) → str[source]

Format file mode bits into standard ls -l permissions string.

Parameters:

mode – Integer mode bitmask (e.g., from stat_result.st_mode).

Returns:

Standard 10-character permissions string (e.g., ‘-rw-r–r–‘).

findfmt.metadata.resolve_group_name(gid: int) → str[source]

Resolve file owner group name from numeric GID with caching.

Parameters:

gid – Numeric group identifier.

Returns:

Resolved group name if available; otherwise string representation of GID.

findfmt.metadata.resolve_user_name(uid: int) → str[source]

Resolve file owner username from numeric UID with caching.

Parameters:

uid – Numeric user identifier.

Returns:

Resolved username if available; otherwise string representation of UID.

4. Size Formatting & Accumulation (findfmt.sizes)

File size calculation, formatting, and disk usage accumulation utilities.

findfmt.sizes.calculate_accumulated_sizes(root: Path, *, follow_symlinks: bool = False, include_hidden: bool = True, visited: set[Path] | None = None) → dict[Path, int][source]

Calculate accumulated directory sizes iteratively using post-order traversal.

Parameters:
  • root – Target directory path to accumulate.

  • follow_symlinks – Whether to traverse directory symlinks.

  • include_hidden – Whether to include hidden files and directories.

  • visited – Set of visited resolved paths to detect and break symlink cycles.

Returns:

Dictionary mapping each directory path to its accumulated size in bytes.

findfmt.sizes.format_size(size_bytes: int, *, human_readable: bool = False, si: bool = False, exact: bool = False) → str[source]

Format byte count into human-readable representation according to active flags.

Parameters:
  • size_bytes – File size in integer bytes.

  • human_readable – Whether to format using binary units (powers of 1024: KiB, MiB, GiB).

  • si – Whether to format using SI decimal units (powers of 1000: kB, MB, GB).

  • exact – Whether to format using exact bytes.

Returns:

Formatted size representation string.

findfmt.sizes.format_size_binary(size_bytes: int) → str[source]

Format byte count using IEC binary units (powers of 1024: KiB, MiB, GiB, TiB, PiB, EiB).

Parameters:

size_bytes – Size in integer bytes.

Returns:

Formatted binary size string (e.g., ‘1.0 KiB’, ‘2.5 MiB’).

findfmt.sizes.format_size_bytes(size_bytes: int) → str[source]

Format byte count into exact byte representation with unit suffix.

Parameters:

size_bytes – Size in integer bytes.

Returns:

Exact byte count string (e.g., ‘1024 B’).

findfmt.sizes.format_size_si(size_bytes: int) → str[source]

Format byte count using SI decimal metric units (powers of 1000: kB, MB, GB, TB, PB, EB).

Parameters:

size_bytes – Size in integer bytes.

Returns:

Formatted SI decimal size string (e.g., ‘1.0 kB’, ‘2.5 MB’).

5. Traversal Subsystem (findfmt.traversal)

Filesystem traversal, filtering, and ignore engine package for findfmt.

exception findfmt.traversal.InvalidSortCriteriaError(criteria: str)[source]

Bases: FindFmtError, ValueError

Raised when an invalid sort criteria is passed to resolve_sort_key.

__init__(criteria: str) → None[source]

Initialize InvalidSortCriteriaError.

Parameters:

criteria – The invalid sort criteria value.

class findfmt.traversal.PatternMatcher(include_patterns: tuple[str, ...] = (), exclude_patterns: tuple[str, ...] = (), *, ignore_case: bool = False, match_dirs: bool = False)[source]

Bases: object

Compiled pattern matcher for include (-P) and exclude (-I) glob rules.

__init__(include_patterns: tuple[str, ...] = (), exclude_patterns: tuple[str, ...] = (), *, ignore_case: bool = False, match_dirs: bool = False) → None[source]

Initialize PatternMatcher with compiled inclusion/exclusion specifications.

classmethod from_config(config: TraversalConfig) → PatternMatcher[source]

Construct PatternMatcher from TraversalConfig options.

matches_dir(path: Path | str, *, base_root: Path | None = None) → bool[source]

Determine whether a directory name/path matches include patterns (-P).

matches_file(path: Path | str, *, base_root: Path | None = None, inherited_match: bool = False) → bool[source]

Determine whether a file path satisfies active pattern criteria.

should_exclude(path: Path | str, *, is_dir: bool, base_root: Path | None = None) → bool[source]

Determine whether a file or directory path matches exclude patterns (-I).

should_inherit_match(dir_path: Path | str, *, base_root: Path | None = None, parent_inherited: bool = False) → bool[source]

Determine whether children of a directory inherit pattern inclusion.

to_posix(path: Path | str, base_root: Path | None) → tuple[str, str][source]

Convert path to POSIX relative path and basename string pair.

exception findfmt.traversal.TraversalError[source]

Bases: FindFmtError

Base exception for directory traversal errors.

findfmt.traversal.create_pattern_matcher(config: TraversalConfig) → PatternMatcher[source]

Create a PatternMatcher instance from TraversalConfig.

findfmt.traversal.find_files(config: TraversalConfig, *, on_error: Callable[[OSError], None] | None = None) → Iterator[FileInfo][source]

Discover and classify files across all configured root paths or external listings.

findfmt.traversal.is_path_ignored(entry_path: Path, *, is_dir: bool, specs: tuple[tuple[Path, Any], ...]) → bool[source]

Check if an entry matches any active gitignore rule.

Evaluates specs in reverse hierarchical order (deepest to shallowest).

Parameters:
  • entry_path – Path of the directory or file entry to test.

  • is_dir – Whether the entry is a directory.

  • specs – Active (base_path, spec) pairs.

Returns:

True if the entry is ignored, False otherwise.

findfmt.traversal.load_custom_gitignore_spec(path: Path | str | None) → Any | None[source]

Load custom gitignore patterns from an external specification file.

findfmt.traversal.load_git_exclude_spec(root: Path) → Any | None[source]

Load exclude patterns from .git/info/exclude if present.

Supports both standard Git repositories with a .git directory and submodules or worktrees with a .git pointer file.

Parameters:

root – Git repository root directory.

Returns:

PathSpec instance if exclude patterns exist, or None.

findfmt.traversal.load_gitignore_spec(directory: Path) → Any | None[source]

Load gitignore patterns from a directory if a .gitignore file exists.

Parameters:

directory – Directory to check for .gitignore.

Returns:

PathSpec instance if rules exist, or None.

findfmt.traversal.load_global_gitignore_spec(spec_file: Path | None = None, *, root: Path | None = None) → Any | None[source]

Load global gitignore patterns from git config or standard user paths.

findfmt.traversal.matches_filter(file_info: FileInfo, config: TraversalConfig, *, matcher: PatternMatcher | None = None, inherited_match: bool = False) → bool[source]

Determine whether a classified file satisfies filter criteria.

findfmt.traversal.natural_sort_key(name: str, *, ignore_case: bool = False) → tuple[tuple[_SortChunk, ...], str][source]

Generate natural version sort key chunking embedded integers.

Parameters:
  • name – Entry filename to chunk.

  • ignore_case – Whether string chunks are compared case-insensitively.

Returns:

Tuple of parsed SortChunk tokens, with filename tie-breaker.

findfmt.traversal.resolve_sort_key(value: str | SortKey | None, *, unsorted: bool = False) → SortKey[source]

Resolve CLI sort parameter and unsorted flag to canonical SortKey enum.

Parameters:
  • value – Input string or SortKey enum from CLI.

  • unsorted – Whether the raw unsorted flag (-U) was passed.

Returns:

Canonical SortKey enum value.

Raises:

ValueError – If input string does not match any recognized criteria.

findfmt.traversal.should_skip_dir(dir_name: str, *, include_hidden: bool) → bool[source]

Determine if a directory should be skipped during descent.

findfmt.traversal.sort_directory_entries(entries: list[os.DirEntry[str]], config: TraversalConfig) → list[os.DirEntry[str]][source]

Sort directory entries according to traversal configuration.

Parameters:
  • entries – Mutable list of os.DirEntry objects to sort.

  • config – Traversal configuration containing sort criteria.

Returns:

Sorted list of directory entries.

findfmt.traversal.traverse_directory(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][source]

Iteratively traverse a directory hierarchy honoring .gitignore, filters, and boundaries.

6. Input Parsers (findfmt.parsers)

External listing parsers and stream ingestion package.

class findfmt.parsers.ParsedEntry(path_str: str, is_symlink: bool = False, symlink_target: str | None = None, is_dir: bool = False)[source]

Bases: object

Represents an ingested entry extracted from an external input stream.

Variables:
  • path_str (str) – Reconstructed relative or absolute path string.

  • is_symlink (bool) – Whether the entry was designated as a symbolic link.

  • symlink_target (str | None) – Target path if entry is a symlink, otherwise None.

  • is_dir (bool) – Whether the entry represents a directory node.

is_dir: bool
path_str: str
exception findfmt.parsers.ParserError[source]

Bases: FindFmtError, ValueError

Base exception for external input parsing and outline ingestion errors.

findfmt.parsers.classify_file_offline(path: Path, *, relative_path: Path, is_symlink: bool = False, symlink_target: str | None = None) → FileInfo[source]

Classify a file based solely on filename heuristics without filesystem IO.

Parameters:
  • path – Representative path for the file.

  • relative_path – Relative path representation.

  • is_symlink – Flag indicating whether entry represents a symbolic link.

  • symlink_target – Optional target path destination of the symlink.

Returns:

Populated FileInfo instance.

findfmt.parsers.detect_input_format(lines: list[str]) → str[source]

Auto-detect whether input lines represent NUL-delimited, outline, or flat listing.

Parameters:

lines – List of raw input string lines or NUL-delimited records.

Returns:

‘nul’ if NUL-delimited records or embedded newlines are detected, ‘outline’ if indented hierarchical structure is detected, else ‘flat’.

findfmt.parsers.ingest_from_file(config: TraversalConfig, input_stream: TextIO | None = None) → Iterator[FileInfo][source]

Ingest path listings from an external file or standard input stream.

Bypasses standard filesystem traversal, parses directory hierarchy or flat paths, classifies entries with online or offline fallback, and applies active filter criteria and sorting.

Parameters:
  • config – Traversal configuration containing from_file and offline flags.

  • input_stream – Optional input text stream override for testing.

Yields:

Classified and filtered FileInfo instances.

findfmt.parsers.parse_flat_listing(lines: Iterable[str]) → Iterator[ParsedEntry][source]

Parse newline- or NUL-delimited flat file paths into structured ParsedEntry records.

Supports outputs from standard Unix tools such as ‘find’, ‘find -print0’, ‘fd -0’, ‘git ls-files’, and ‘findfmt -i’ / ‘findfmt -0’, normalizing leading ‘./’ indicators and detecting directory suffixes.

Parameters:

lines – Iterable yielding raw lines or NUL-delimited records of input text.

Yields:

ParsedEntry instances for non-empty path records.

Parse a symlink token and its target destination if present.

Detects standard Unix symlink notation (‘link_name -> target_path’) using quote-aware scanning that ignores arrows inside quoted segments and splits on the last unquoted ‘ -> ‘ delimiter while preserving interior quotes.

Parameters:

token – Raw entry string or line segment to inspect.

Returns:

Tuple of (clean_path, is_symlink, symlink_target).

findfmt.parsers.parse_tab_outline(lines: Iterable[str]) → Iterator[ParsedEntry][source]

Parse hierarchical outline text into reconstructed full path entries.

Reconstructs nested directory hierarchies based on indentation depth (supporting tabs or consistent whitespace), resolving parent-child relationships and symlink targets.

Parameters:

lines – Iterable yielding raw lines of outline text.

Yields:

ParsedEntry instances with fully qualified path strings.

7. Output Formatters (findfmt.formatters)

Output formatting engines for findfmt.

class findfmt.formatters.CsvFormatter(*, absolute: bool = False, delimiter: str = ',', quoting: int = 0, lineterminator: str = '\n', csv_safe: bool = False)[source]

Bases: Formatter

RFC 4180 compliant comma-separated values serializer.

__init__(*, absolute: bool = False, delimiter: str = ',', quoting: int = 0, lineterminator: str = '\n', csv_safe: bool = False) → None[source]

Initialize CsvFormatter.

Parameters:
  • absolute – Whether to emit absolute paths.

  • delimiter – Column delimiter character (defaults to comma).

  • quoting – Quoting mode from standard library csv module.

  • lineterminator – Record terminator string (defaults to newline).

  • csv_safe – Whether to neutralize formula injection triggers with a single quote.

format(files: Iterable[FileInfo]) → str[source]

Format FileInfo objects into an RFC 4180 CSV string.

Parameters:

files – Iterable of classified file objects.

Returns:

Formatted CSV document with header row.

stream(files: Iterable[FileInfo], stream: TextIO) → None[source]

Stream CSV records directly to a text stream.

Parameters:
  • files – Iterable of classified file objects.

  • stream – Target text stream.

class findfmt.formatters.CsvTableFormatter(*, absolute: bool = False, table_style: str = 'rounded', console_width: int | None = None, force_color: bool | None = None, csv_safe: bool = False)[source]

Bases: Formatter

Aligned ASCII/Unicode table constructed directly from CSV schema.

__init__(*, absolute: bool = False, table_style: str = 'rounded', console_width: int | None = None, force_color: bool | None = None, csv_safe: bool = False) → None[source]

Initialize CsvTableFormatter.

Parameters:
  • absolute – Whether to emit absolute paths.

  • table_style – Border style name mapping to rich.box styles.

  • console_width – Optional terminal output column width override.

  • force_color – Explicit color enable override flag.

  • csv_safe – Whether to neutralize formula injection triggers with a single quote.

Raises:

UnsupportedBoxStyleError – If table_style is not recognized.

format(files: Iterable[FileInfo]) → str[source]

Render CSV records into an aligned table string.

stream(files: Iterable[FileInfo], stream: TextIO) → None[source]

Stream aligned CSV table directly to a text stream.

class findfmt.formatters.Formatter(*, absolute: bool = False)[source]

Bases: ABC

Abstract base class for all findfmt output formatters.

__init__(*, absolute: bool = False) → None[source]

Initialize formatter.

Parameters:

absolute – Whether to format paths as absolute rather than relative.

abstractmethod format(files: Iterable[FileInfo]) → str[source]

Format an iterable of FileInfo instances into a string.

Parameters:

files – Iterable of classified file objects.

Returns:

Formatted string representation.

stream(files: Iterable[FileInfo], stream: TextIO) → None[source]

Stream formatted output directly to a text stream.

Parameters:
  • files – Iterable of classified file objects.

  • stream – Target text output stream (e.g., sys.stdout).

class findfmt.formatters.HtmlFormatter(*, absolute: bool = False, base_href: str | None = None, title: str | None = None, intro: str | None = None, intro_file: Path | None = None, outro: str | None = None, outro_file: Path | None = None, no_links: bool = False, no_indent: bool = False, show_permissions: bool = False, show_user: bool = False, show_group: bool = False, show_inodes: bool = False, show_device: bool = False, show_size: bool = False, human_readable: bool = False, show_si: bool = False, accumulate_size: bool = False, show_mtime: bool = False, show_ctime: bool = False, time_format: str | None = None, classify: bool = False, hide_control_chars: bool = False, literal: bool = False, quote_name: bool = False)[source]

Bases: Formatter

Semantic, accessible HTML5 document serializer with intro/outro templating.

__init__(*, absolute: bool = False, base_href: str | None = None, title: str | None = None, intro: str | None = None, intro_file: Path | None = None, outro: str | None = None, outro_file: Path | None = None, no_links: bool = False, no_indent: bool = False, show_permissions: bool = False, show_user: bool = False, show_group: bool = False, show_inodes: bool = False, show_device: bool = False, show_size: bool = False, human_readable: bool = False, show_si: bool = False, accumulate_size: bool = False, show_mtime: bool = False, show_ctime: bool = False, time_format: str | None = None, classify: bool = False, hide_control_chars: bool = False, literal: bool = False, quote_name: bool = False) → None[source]

Initialize HtmlFormatter.

Parameters:
  • absolute – Whether to emit absolute paths.

  • base_href – Base URL or path prefix for clickable hyperlinks.

  • title – Document title and heading text.

  • intro – Custom HTML fragment string to prepend before directory listing.

  • intro_file – Path to HTML file fragment to prepend.

  • outro – Custom HTML fragment string to append after directory listing.

  • outro_file – Path to HTML file fragment to append.

  • no_links – Whether to suppress hyperlinks and render plain text paths.

  • no_indent – Whether to suppress indentation lines in tree listing.

  • show_permissions – Whether to include permissions string.

  • show_user – Whether to include owner username or UID.

  • show_group – Whether to include owner group or GID.

  • show_inodes – Whether to include filesystem inode number.

  • show_device – Whether to include filesystem device number.

  • show_size – Whether to include exact byte size.

  • human_readable – Whether to format size using binary units.

  • show_si – Whether to format size using SI metric units.

  • accumulate_size – Whether to accumulate recursive directory disk usage.

  • show_mtime – Whether to include last modification time.

  • show_ctime – Whether to include last status change time.

  • time_format – Optional strftime syntax format string for dates.

  • classify – Whether to append file type classification indicator.

  • hide_control_chars – Whether to mask non-printable characters.

  • literal – Whether to emit non-printable characters verbatim.

  • quote_name – Whether to enclose filenames in double quotes.

format(files: Iterable[FileInfo]) → str[source]

Format an iterable of FileInfo instances into an HTML5 document string.

Parameters:

files – Iterable of classified file objects.

Returns:

Semantic HTML5 document string.

stream(files: Iterable[FileInfo], stream: TextIO) → None[source]

Stream formatted HTML output directly to a text stream.

Parameters:
  • files – Iterable of classified file objects.

  • stream – Target text stream.

class findfmt.formatters.IpynbFormatter(*, absolute: bool = False)[source]

Bases: Formatter

Jupyter Notebook v4 JSON serializer pre-populated with analysis code.

__init__(*, absolute: bool = False) → None[source]

Initialize IpynbFormatter.

Parameters:

absolute – Whether to emit absolute paths.

format(files: Iterable[FileInfo]) → str[source]

Format FileInfo objects into a valid Jupyter Notebook v4 JSON string.

Parameters:

files – Iterable of classified file objects.

Returns:

Formatted Jupyter Notebook JSON string.

class findfmt.formatters.JsonFormatter(*, absolute: bool = False, indent: int | None = 2, no_indent: bool = False)[source]

Bases: Formatter

Deterministic JSON array formatter with configurable indentation.

__init__(*, absolute: bool = False, indent: int | None = 2, no_indent: bool = False) → None[source]

Initialize JsonFormatter.

Parameters:
  • absolute – Whether to emit absolute paths.

  • indent – Indentation spaces for pretty-printing, or None for compact.

  • no_indent – Whether to suppress indentation and emit compact JSON.

format(files: Iterable[FileInfo]) → str[source]

Format FileInfo objects into a deterministic JSON array.

Parameters:

files – Iterable of classified file objects.

Returns:

JSON array string ending with a newline.

class findfmt.formatters.JsonlFormatter(*, absolute: bool = False)[source]

Bases: Formatter

Line-delimited JSON (NDJSON) record serializer for streaming pipelines.

__init__(*, absolute: bool = False) → None[source]

Initialize JsonlFormatter.

Parameters:

absolute – Whether to emit absolute paths.

format(files: Iterable[FileInfo]) → str[source]

Format an iterable of FileInfo objects into line-delimited JSON.

Parameters:

files – Iterable of classified file objects.

Returns:

Concatenated JSON lines string.

format_item(file_info: FileInfo) → str[source]

Serialize a single FileInfo item to a compact JSON line.

Parameters:

file_info – Classified file information.

Returns:

Single line JSON string ending with a newline.

stream(files: Iterable[FileInfo], stream: TextIO) → None[source]

Stream FileInfo records as JSON lines directly to the output stream.

Parameters:
  • files – Iterable of classified file objects.

  • stream – Target text stream.

class findfmt.formatters.MarkdownFormatter(*, absolute: bool = False, no_indent: bool = False)[source]

Bases: Formatter

GitHub Flavored Markdown (GFM) column-aligned table serializer.

__init__(*, absolute: bool = False, no_indent: bool = False) → None[source]

Initialize MarkdownFormatter.

Parameters:
  • absolute – Whether to emit absolute paths.

  • no_indent – Whether to strip column whitespace padding.

format(files: Iterable[FileInfo]) → str[source]

Format FileInfo objects into a GFM table string.

stream(files: Iterable[FileInfo], stream: TextIO) → None[source]

Stream formatted Markdown table to a text stream.

class findfmt.formatters.OutputFormat(*values)[source]

Bases: StrEnum

Supported output serialization formats.

CSV = 'csv'
CSV_TABLE = 'csv-table'
HTML = 'html'
IPYNB = 'ipynb'
JSON = 'json'
JSONL = 'jsonl'
MARKDOWN = 'markdown'
MD = 'md'
NDJSON = 'ndjson'
RST = 'rst'
TABLE = 'table'
TEXT = 'text'
TREE = 'tree'
TSV = 'tsv'
XML = 'xml'
YAML = 'yaml'
class findfmt.formatters.RstFormatter(*, absolute: bool = False, table_style: str = 'grid')[source]

Bases: Formatter

reStructuredText grid or simple table serializer for Sphinx docs.

__init__(*, absolute: bool = False, table_style: str = 'grid') → None[source]

Initialize RstFormatter.

format(files: Iterable[FileInfo]) → str[source]

Format FileInfo objects into a reStructuredText table string.

stream(files: Iterable[FileInfo], stream: TextIO) → None[source]

Stream formatted reStructuredText table to a text stream.

class findfmt.formatters.TextFormatter(*, absolute: bool = False, show_tags: bool = False, delimiter: str = '\n', show_permissions: bool = False, show_user: bool = False, show_group: bool = False, show_inodes: bool = False, show_device: bool = False, show_size: bool = False, human_readable: bool = False, show_si: bool = False, show_mtime: bool = False, show_ctime: bool = False, time_format: str | None = None, classify: bool = False, hide_control_chars: bool = False, literal: bool = False, quote_name: bool = False, hyperlink: bool = False, hyperlink_schema: str = 'file://', hyperlink_authority: str | None = None)[source]

Bases: Formatter

Standard line-oriented or NUL-delimited plain text formatter.

__init__(*, absolute: bool = False, show_tags: bool = False, delimiter: str = '\n', show_permissions: bool = False, show_user: bool = False, show_group: bool = False, show_inodes: bool = False, show_device: bool = False, show_size: bool = False, human_readable: bool = False, show_si: bool = False, show_mtime: bool = False, show_ctime: bool = False, time_format: str | None = None, classify: bool = False, hide_control_chars: bool = False, literal: bool = False, quote_name: bool = False, hyperlink: bool = False, hyperlink_schema: str = 'file://', hyperlink_authority: str | None = None) → None[source]

Initialize TextFormatter.

Parameters:
  • absolute – Whether to emit absolute paths.

  • show_tags – Whether to append classification tags.

  • delimiter – Line terminator string (typically ‘n’ or ‘0’).

  • show_permissions – Whether to display permissions string in ls -l style.

  • show_user – Whether to display file owner username or UID.

  • show_group – Whether to display file owner group name or GID.

  • show_inodes – Whether to display filesystem inode number.

  • show_device – Whether to display filesystem device number.

  • show_size – Whether to display exact byte size.

  • human_readable – Whether to format sizes using binary units.

  • show_si – Whether to format sizes using SI metric units.

  • show_mtime – Whether to display file modification date/time.

  • show_ctime – Whether to display last status change date/time.

  • time_format – Optional strftime syntax format string for dates/times.

  • classify – Whether to append file classification indicator characters.

  • hide_control_chars – Whether to mask non-printable and bidirectional control characters with ‘?’.

  • literal – Whether to emit literal control characters.

  • quote_name – Whether to enclose filenames in double quotes.

  • hyperlink – Whether to wrap paths in OSC 8 terminal hyperlink escapes.

  • hyperlink_schema – URI schema for terminal hyperlinks.

  • hyperlink_authority – Optional URI authority component for terminal hyperlinks.

format(files: Iterable[FileInfo]) → str[source]

Format all files into a concatenated text string.

Parameters:

files – Iterable of classified file objects.

Returns:

Concatenated formatted text string.

format_item(file_info: FileInfo) → str[source]

Format an individual file record as a text line.

Parameters:

file_info – Classified file information.

Returns:

Formatted line string including trailing delimiter.

stream(files: Iterable[FileInfo], stream: TextIO) → None[source]

Stream formatted text items directly to the output stream.

Parameters:
  • files – Iterable of classified file objects.

  • stream – Target text stream.

class findfmt.formatters.TsvFormatter(*, absolute: bool = False, lineterminator: str = '\n', csv_safe: bool = False)[source]

Bases: Formatter

Tab-separated values (TSV) serializer for Unix pipelines.

__init__(*, absolute: bool = False, lineterminator: str = '\n', csv_safe: bool = False) → None[source]

Initialize TsvFormatter.

Parameters:
  • absolute – Whether to emit absolute paths.

  • lineterminator – Record terminator string (defaults to newline).

  • csv_safe – Whether to neutralize formula injection triggers with a single quote.

format(files: Iterable[FileInfo]) → str[source]

Format FileInfo objects into a TSV string.

Parameters:

files – Iterable of classified file objects.

Returns:

Formatted TSV document with header row.

stream(files: Iterable[FileInfo], stream: TextIO) → None[source]

Stream TSV records directly to a text stream.

Parameters:
  • files – Iterable of classified file objects.

  • stream – Target text stream.

exception findfmt.formatters.UnsupportedBoxStyleError(table_style: str, valid_styles: str)[source]

Bases: FindFmtError, ValueError

Raised when an unsupported table border style is requested in Rich table formatters.

__init__(table_style: str, valid_styles: str) → None[source]

Initialize UnsupportedBoxStyleError.

Parameters:
  • table_style – The invalid table style requested.

  • valid_styles – Comma-separated list of valid box styles.

exception findfmt.formatters.UnsupportedFormatError(format_type: str, valid_formats: str)[source]

Bases: FindFmtError, ValueError

Raised when an unsupported output format is requested.

__init__(format_type: str, valid_formats: str) → None[source]

Initialize UnsupportedFormatError.

Parameters:
  • format_type – The invalid format requested.

  • valid_formats – Comma-separated list of valid formats.

exception findfmt.formatters.UnsupportedTableStyleError(table_style: str)[source]

Bases: FindFmtError, ValueError

Raised when an unsupported table border style is requested in RST formatter.

__init__(table_style: str) → None[source]

Initialize UnsupportedTableStyleError.

Parameters:

table_style – The invalid table style requested.

class findfmt.formatters.XmlFormatter(*, absolute: bool = False, no_indent: bool = False, show_permissions: bool = False, show_user: bool = False, show_group: bool = False, show_inodes: bool = False, show_device: bool = False, show_size: bool = False, human_readable: bool = False, show_si: bool = False, accumulate_size: bool = False, show_mtime: bool = False, show_ctime: bool = False, time_format: str | None = None, classify: bool = False, hide_control_chars: bool = False, literal: bool = False, quote_name: bool = False)[source]

Bases: Formatter

Hierarchical XML document serializer utilizing ElementTree.

__init__(*, absolute: bool = False, no_indent: bool = False, show_permissions: bool = False, show_user: bool = False, show_group: bool = False, show_inodes: bool = False, show_device: bool = False, show_size: bool = False, human_readable: bool = False, show_si: bool = False, accumulate_size: bool = False, show_mtime: bool = False, show_ctime: bool = False, time_format: str | None = None, classify: bool = False, hide_control_chars: bool = False, literal: bool = False, quote_name: bool = False) → None[source]

Initialize XmlFormatter.

Parameters:
  • absolute – Whether to emit absolute paths.

  • no_indent – Whether to suppress pretty-printing indentation.

  • show_permissions – Whether to include permissions string.

  • show_user – Whether to include owner username or UID.

  • show_group – Whether to include owner group or GID.

  • show_inodes – Whether to include filesystem inode number.

  • show_device – Whether to include filesystem device number.

  • show_size – Whether to include exact byte size.

  • human_readable – Whether to format size using binary units.

  • show_si – Whether to format size using SI metric units.

  • accumulate_size – Whether to accumulate recursive directory disk usage.

  • show_mtime – Whether to include last modification time.

  • show_ctime – Whether to include last status change time.

  • time_format – Optional strftime syntax format string for dates.

  • classify – Whether to append file type classification indicator.

  • hide_control_chars – Whether to mask non-printable characters.

  • literal – Whether to emit non-printable characters verbatim.

  • quote_name – Whether to enclose filenames in double quotes.

format(files: Iterable[FileInfo]) → str[source]

Format an iterable of FileInfo instances into an XML document string.

Parameters:

files – Iterable of classified file objects.

Returns:

Well-formed XML document string ending with a newline.

stream(files: Iterable[FileInfo], stream: TextIO) → None[source]

Stream formatted XML output directly to a text stream.

Parameters:
  • files – Iterable of classified file objects.

  • stream – Target text stream.

class findfmt.formatters.YamlFormatter(*, absolute: bool = False, indent: int = 2, no_indent: bool = False)[source]

Bases: Formatter

Block-style YAML document serializer using PyYAML.

__init__(*, absolute: bool = False, indent: int = 2, no_indent: bool = False) → None[source]

Initialize YamlFormatter.

Parameters:
  • absolute – Whether to emit absolute paths.

  • indent – Indentation spaces for nested YAML structures.

  • no_indent – Whether to suppress indentation and emit compact YAML.

format(files: Iterable[FileInfo]) → str[source]

Format FileInfo objects into a clean YAML document string.

Parameters:

files – Iterable of classified file objects.

Returns:

YAML document string ending with a newline.

findfmt.formatters.get_formatter(format_type: OutputFormat | str, *, absolute: bool = False, show_tags: bool = False, delimiter: str | None = None, **kwargs: object) → Formatter[source]

Retrieve the appropriate formatter instance for the given format.

Parameters:
  • format_type – Requested output format enum or string name.

  • absolute – Whether to emit absolute paths.

  • show_tags – Whether to display tags (for text format).

  • delimiter – Optional delimiter string (for text/csv format).

  • **kwargs – Extra formatter configuration arguments.

Returns:

Configured Formatter instance.

Raises:

UnsupportedFormatError – If format_type is not a recognized output format.

findfmt.formatters.sanitize_csv_cell(cell: str) → str[source]

Neutralize spreadsheet formula injection by prefixing trigger characters with a single quote.

Spreadsheet applications (e.g. Excel, LibreOffice Calc, Google Sheets) interpret cells beginning with ‘=’, ‘+’, ‘-’, ‘@’, TAB, or CR as executable formulas or commands. Prefixing such cells with a single quote (’) forces spreadsheet engines to treat the content strictly as text.

Parameters:

cell – Raw cell string value.

Returns:

Sanitized cell string prefixed with “’” if beginning with a formula trigger, else unchanged.

findfmt.formatters.write_stream_safe(stream: TextIO, content: str) → None[source]

Write text content to a text stream, handling surrogate escapes safely.

If the target stream or its wrapper raises UnicodeEncodeError, this attempts to encode with errors=’surrogateescape’ and write directly to the stream’s underlying binary buffer.

Parameters:
  • stream – Target text stream.

  • content – String content potentially containing surrogate code points.

8. Command-Line Interface (findfmt.cli)

Command-line interface package for findfmt.

9. Internationalization (findfmt.i18n)

Internationalization (i18n) and localization (l10n) runtime engine for findfmt.

findfmt.i18n.detect_locale(env: Mapping[str, str] | None = None) → str[source]

Detect the active locale following POSIX precedence order.

Order: LANGUAGE -> LC_ALL -> LC_MESSAGES -> LANG -> fallback ‘C’.

Parameters:

env – Optional mapping of environment variables (defaults to os.environ).

Returns:

The highest-precedence detected locale code string, or ‘C’.

findfmt.i18n.detect_locales(env: Mapping[str, str] | None = None) → list[str][source]

Return a deduplicated list of preferred locale codes in order of precedence.

Order: LANGUAGE (split by ‘:’) -> LC_ALL -> LC_MESSAGES -> LANG -> fallback [‘C’].

Parameters:

env – Optional mapping of environment variables (defaults to os.environ).

Returns:

List of preferred locale code strings.

findfmt.i18n.format_integer(value: int, *, grouping: bool = False) → str[source]

Format an integer respecting LC_NUMERIC thousands separator if requested.

Parameters:
  • value – Integer value to format.

  • grouping – Whether to insert thousands grouping separators.

Returns:

Formatted integer string.

findfmt.i18n.format_number(value: float, decimals: int = 1, *, grouping: bool = False) → str[source]

Format a floating point number respecting LC_NUMERIC decimal separator.

Parameters:
  • value – Float or int value to format.

  • decimals – Number of decimal places.

  • grouping – Whether to insert thousands grouping separators.

Returns:

Formatted number string.

findfmt.i18n.get_current_locale() → str[source]

Return the currently active locale identifier.

Returns:

Active locale string (e.g. ‘en_US’, ‘es’, ‘C’).

findfmt.i18n.get_current_translation() → NullTranslations[source]

Return the active gettext translation catalog object.

Returns:

Active gettext.NullTranslations or GNUTranslations instance.

findfmt.i18n.locale_callback(value: str | None) → str | None[source]

Typer/Click callback for –locale / –lang option.

Parameters:

value – Explicit locale override string, or None if omitted.

Returns:

The locale string value passed in.

findfmt.i18n.ngettext(singular: str, plural: str, n: int) → str[source]

Translate singular or plural message string according to count n.

Parameters:
  • singular – Singular message template.

  • plural – Plural message template.

  • n – Quantity determining singular or plural form.

Returns:

Translated string matching plural rules for n.

findfmt.i18n.override_locale(locale_name: str | None, localedir: Path | str | None = None, domain: str = 'findfmt') → Generator[str, None, None][source]

Context manager to temporarily override active locale and restore on exit.

Parameters:
  • locale_name – Target locale identifier to activate.

  • localedir – Optional custom catalog directory.

  • domain – Translation domain name.

Yields:

The activated locale name.

findfmt.i18n.reset_locale() → str[source]

Reset locale and translation catalog based on current environment variables.

Returns:

The detected active locale code.

findfmt.i18n.set_locale(locale_name: str | None = None, localedir: Path | str | None = None, domain: str = 'findfmt') → str[source]

Set the active translation locale and initialize the gettext catalog.

If locale_name is None, detect_locales() will be called to resolve candidate languages from environment variables. If locale_name is ‘C’ or ‘POSIX’, NullTranslations is used. Otherwise, gettext.translation() attempts to load a catalog from localedir, falling back to NullTranslations if not found.

Parameters:
  • locale_name – Explicit locale identifier (e.g. ‘es_ES’, ‘fr’), or None.

  • localedir – Directory containing locale message catalogs.

  • domain – Translation domain name (default: ‘findfmt’).

Returns:

The resolved active locale code.

10. Runtime Diagnostics (findfmt.cli.diagnostics)

System diagnostics and runtime environment inspection.

findfmt.cli.diagnostics.diagnostics_callback(ctx: Context | bool | None = None, value: bool = False) → None[source]

Display runtime environment diagnostics and exit.

Parameters:
  • ctx – Typer context, if provided by Click callback.

  • value – Boolean flag indicating if diagnostics flag was passed.

Raises:

typer.Exit – Upon printing diagnostics.

findfmt.cli.diagnostics.generate_config_callback(ctx: Context | bool | None = None, value: bool = False) → None[source]

Output the annotated reference TOML configuration and exit.

Parameters:
  • ctx – Typer context, if provided by Click callback.

  • value – Boolean flag indicating if generate-config flag was passed.

Raises:

typer.Exit – Upon printing the reference configuration.

findfmt.cli.diagnostics.get_diagnostics(ctx: Context | None = None) → str[source]

Compile runtime environment diagnostics.

Parameters:

ctx – Optional Click/Typer context.

Returns:

Formatted multi-line diagnostics string ending in a newline.

findfmt.cli.diagnostics.get_git_version() → str | None[source]

Retrieve git executable version string if git is available.

Returns:

Git version string or None if git is not detected.

findfmt.cli.diagnostics.get_version() → str[source]

Retrieve package version or fallback string.

Returns:

Version string.

findfmt.cli.diagnostics.show_config_callback(ctx: typer.Context | _click.Context | bool | None = None, value: bool = False) → None[source]

Display active configuration settings and exit.

Parameters:
  • ctx – Typer context, if provided by Click callback.

  • value – Boolean flag indicating if show-config flag was passed.

Raises:

typer.Exit – Upon printing configuration settings.

findfmt.cli.diagnostics.version_callback(ctx: Context | bool | None = None, value: bool = False) → None[source]

Display the version of findfmt and exit.

Parameters:
  • ctx – Typer context, if provided by Click callback.

  • value – Boolean flag indicating if version flag was passed.

Raises:

typer.Exit – Upon printing version.

11. Match Summaries (findfmt.cli.summary)

CLI summary reporting and tag argument normalization helpers.

findfmt.cli.summary.parse_tag_arguments(tag_args: Sequence[str] | None) → frozenset[str][source]

Parse repeatable or comma-delimited tag arguments into a normalized frozenset.

Parameters:

tag_args – Raw arguments provided to tag filter flags.

Returns:

frozenset of lowercase tag strings.

findfmt.cli.summary.write_summary(match_count: int, tag_counter: Counter[str], *, total_bytes: int | None = None, stream: TextIO | None = None, force_color: bool | None = None) → None[source]

Write Rich-formatted execution summary to stderr.

Parameters:
  • match_count – Total number of files matched.

  • tag_counter – Frequency counter of tags matched.

  • total_bytes – Optional total size in bytes of matched files.

  • stream – Optional target output stream (defaults to sys.stderr).

  • force_color – Explicit color enable override flag.

12. Terminal Utilities (findfmt.cli.terminal)

Terminal control, interactive paging, and ANSI color management.

class findfmt.cli.terminal.PagerController(*, pager: bool | None = None, stream: TextIO | None = None, term_height: int | None = None, console: Console | None = None, pager_impl: Pager | None = None, env: Mapping[str, str] | None = None, force_color: bool | None = None)[source]

Bases: object

Controller for interactive terminal paging and TTY/color handling.

__init__(*, pager: bool | None = None, stream: TextIO | None = None, term_height: int | None = None, console: Console | None = None, pager_impl: Pager | None = None, env: Mapping[str, str] | None = None, force_color: bool | None = None) → None[source]

Initialize PagerController.

Parameters:
  • pager – Pager override flag (True=force, False=disable, None=auto).

  • stream – Target output text stream (defaults to sys.stdout).

  • term_height – Terminal height override for testing.

  • console – Optional pre-configured Rich Console.

  • pager_impl – Optional custom Rich Pager instance.

  • env – Optional environment mapping for color resolution.

  • force_color – Explicit color enable override flag.

display(content: str) → None[source]

Route formatted content to pager or write directly to target stream.

Parameters:

content – Formatted output string to display.

should_page(line_count: int) → bool[source]

Determine whether output with line_count should be routed through a pager.

Parameters:

line_count – Number of lines in output.

Returns:

True if pager should be invoked, False otherwise.

findfmt.cli.terminal.get_console(stream: TextIO | None = None, *, env: Mapping[str, str] | None = None, width: int | None = None, force_color: bool | None = None) → Console[source]

Construct a Rich Console honoring environment variables and TTY settings.

Parameters:
  • stream – Target output text stream (defaults to sys.stdout).

  • env – Environment variable mapping override.

  • width – Optional terminal output column width override.

  • force_color – Explicit color enable override flag.

Returns:

Configured Rich Console instance.

findfmt.cli.terminal.get_terminal_height(fallback: int = 24) → int[source]

Return current terminal height in lines with fallback.

Parameters:

fallback – Fallback row count when terminal size query fails.

Returns:

Detected terminal height row count.

findfmt.cli.terminal.is_color_enabled(stream: TextIO | None = None, *, env: Mapping[str, str] | None = None, force_color: bool | None = None) → bool[source]

Evaluate whether ANSI color sequences should be emitted.

Precedence order: 1. If force_color is explicitly set, its boolean value is honored. 2. If NO_COLOR is present and non-empty, color is disabled. 3. If CLICOLOR_FORCE is set and non-zero, color is forced. 4. If CLICOLOR is set to “0”, color is disabled. 5. Otherwise, color is enabled only if stream is an interactive TTY.

Parameters:
  • stream – Target output text stream (defaults to sys.stdout).

  • env – Environment variable mapping override.

  • force_color – Explicit color enable override flag.

Returns:

True if colors should be emitted, False otherwise.

findfmt.cli.terminal.should_use_pager(output_lines: int, *, pager: bool | None = None, stream: TextIO | None = None, term_height: int | None = None) → bool[source]

Determine whether output should be routed through an interactive pager.

Parameters:
  • output_lines – Number of lines in the rendered output.

  • pager – Explicit CLI override (True=force, False=disable, None=auto).

  • stream – Target output stream (defaults to sys.stdout).

  • term_height – Terminal height override (defaults to detected terminal height).

Returns:

True if interactive pager should be activated, False otherwise.

findfmt.cli.terminal.strip_ansi(text: str) → str[source]

Remove ANSI escape sequences from text string.

Parameters:

text – Input string potentially containing ANSI escapes.

Returns:

Clean string free of ANSI escape sequences.

13. Common Utilities (findfmt.utils)

Utility functions and helpers for findfmt.

findfmt.utils.build_file_uri(path: PurePath | str, *, schema: str = 'file://', authority: str | None = None) → str[source]

Construct a well-formed URI for a filesystem path.

Parameters:
  • path – Filesystem path object or string.

  • schema – URI schema prefix (e.g. ‘file://’, ‘vscode://file/’, ‘subl://’).

  • authority – Optional URI authority component (e.g. ‘localhost’, hostname).

Returns:

Fully qualified, URL-encoded URI string.

findfmt.utils.cell_width(text: str) → int[source]

Calculate the terminal monospace cell display width of a string.

Accounts for ANSI escape sequences (which occupy 0 display cells) and East Asian full-width/double-width characters (which occupy 2 display cells).

Parameters:

text – String whose display width is to be measured.

Returns:

Total number of terminal display cells occupied by the string.

findfmt.utils.format_display_path(path_str: str, *, quote_name: bool = False, hide_control_chars: bool = False, literal: bool = False, indicator: str | None = None, hyperlink: bool = False, uri: str | None = None, escape_markup: bool = False) → str[source]

Format path string applying control character masking, quoting, indicators, and links.

Parameters:
  • path_str – Raw path or filename string.

  • quote_name – Whether to enclose in double quotes with backslash escaping.

  • hide_control_chars – Whether to mask non-printable and bidirectional control characters as ‘?’.

  • literal – Whether to output characters verbatim without masking.

  • indicator – Optional classification indicator character to append.

  • hyperlink – Whether to wrap formatted path in an OSC 8 terminal hyperlink.

  • uri – Target destination URI for terminal hyperlink.

  • escape_markup – Whether to escape Rich console markup characters ([ and ]).

Returns:

Formatted path or filename string.

Format a clickable hyperlink using either raw OSC 8 escapes or Rich markup.

Parameters:
  • text – Display text visible in terminal.

  • uri – Destination hyperlink target URI.

  • rich_markup – If True, returns Rich markup; otherwise raw OSC 8 sequence.

Returns:

Formatted hyperlink string.

Wrap text in an OSC 8 terminal hyperlink escape sequence.

Parameters:
  • text – Display text visible in terminal.

  • uri – Destination hyperlink target URI.

Returns:

ANSI string containing OSC 8 escape sequences wrapping the text.

Format text as Rich console hyperlink markup.

Parameters:
  • text – Display text visible in terminal.

  • uri – Destination hyperlink target URI.

Returns:

Rich markup string in [link=uri]text[/link] format.

findfmt.utils.format_timestamp(ts: float | None, fmt: str | None = None) → str[source]

Format POSIX timestamp into a human-readable date/time string.

Parameters:
  • ts – Epoch timestamp in seconds, or None if unavailable.

  • fmt – Optional strftime format string (defaults to localized format or ‘%b %d %H:%M’).

Returns:

Formatted date/time string, or ‘-’ if timestamp is None or cannot be formatted.

findfmt.utils.get_classification_indicator(*, is_dir: bool = False, is_symlink: bool = False, is_executable: bool = False, stat_result: os.stat_result | None = None) → str | None[source]

Return the POSIX classification indicator character for a file.

Parameters:
  • is_dir – Whether the path represents a directory.

  • is_symlink – Whether the path represents a symbolic link.

  • is_executable – Whether the path is executable.

  • stat_result – Optional stat_result for inspecting mode bits.

Returns:

Indicator character (‘/’, ‘*’, ‘@’, ‘=’, ‘|’, ‘>’) or None.

findfmt.utils.mask_control_characters(text: str) → str[source]

Replace non-printable and bidirectional control characters with question marks.

Parameters:

text – Input string potentially containing control characters.

Returns:

String with C0 (ord < 32), DEL (ord == 127), C1 (128 <= ord <= 159), and Unicode format (Cf) control characters replaced by ‘?’.

findfmt.utils.pad_to_cell_width(text: str, width: int, align: str = 'left', fillchar: str = ' ') → str[source]

Pad a string to target cell width respecting double-width CJK characters.

Parameters:
  • text – Input string to pad.

  • width – Desired display width in terminal cells.

  • align – Alignment direction (‘left’, ‘right’, or ‘center’).

  • fillchar – Single-width character used for padding (defaults to ‘ ‘).

Returns:

Padded string with target cell width.

findfmt.utils.quote_filename(text: str) → str[source]

Enclose filename in double quotes, escaping embedded quotes and backslashes.

Parameters:

text – Input filename or path string.

Returns:

Double-quoted string with interior backslashes and double quotes escaped.

findfmt.utils.strip_ansi_escapes(text: str) → str[source]

Strip ANSI escape sequences (CSI, OSC, and 8-bit C1 sequences) from text.

Parameters:

text – Input string potentially containing ANSI escape sequences.

Returns:

String with all recognized ANSI escape sequences removed.

14. Runtime Dispatch Gateway (findfmt.core)

Runtime dispatch gateway between findfmt._rust_ext and pure-Python fallback (#578, #583).

findfmt.core.classify_file(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[source]

Classify a file via findfmt._rust_ext when available, falling back to pure Python.

findfmt.core.find_files(config: TraversalConfig, *, on_error: Callable[[OSError], None] | None = None) → Iterator[FileInfo][source]

Discover and classify files via findfmt._rust_ext when available, falling back to pure Python.

findfmt.core.get_active_backend() → Literal['rust', 'python'][source]

Return the active runtime execution backend identifier (‘rust’ or ‘python’).

findfmt.core.is_rust_backend_active() → bool[source]

Return True when findfmt._rust_ext is enabled and exposes gateway entrypoints.

findfmt.core.is_rust_extension_loaded() → bool[source]

Return True when findfmt._rust_ext imported cleanly and is not disabled.

15. Domain Exceptions (findfmt.exceptions)

Exception hierarchy for the findfmt package.

exception findfmt.exceptions.FindFmtError[source]

Bases: Exception

Base exception for all findfmt library errors.

Downstream callers can catch this exception to handle any findfmt-specific failure without having to catch generic exceptions.

exception findfmt.exceptions.InvalidSortCriteriaError(criteria: str)[source]

Bases: FindFmtError, ValueError

Raised when an invalid sort criteria is passed to resolve_sort_key.

__init__(criteria: str) → None[source]

Initialize InvalidSortCriteriaError.

Parameters:

criteria – The invalid sort criteria value.

exception findfmt.exceptions.ParserError[source]

Bases: FindFmtError, ValueError

Base exception for external input parsing and outline ingestion errors.

exception findfmt.exceptions.TraversalError[source]

Bases: FindFmtError

Base exception for directory traversal errors.

exception findfmt.exceptions.UnsupportedBoxStyleError(table_style: str, valid_styles: str)[source]

Bases: FindFmtError, ValueError

Raised when an unsupported table border style is requested in Rich table formatters.

__init__(table_style: str, valid_styles: str) → None[source]

Initialize UnsupportedBoxStyleError.

Parameters:
  • table_style – The invalid table style requested.

  • valid_styles – Comma-separated list of valid box styles.

exception findfmt.exceptions.UnsupportedFormatError(format_type: str, valid_formats: str)[source]

Bases: FindFmtError, ValueError

Raised when an unsupported output format is requested.

__init__(format_type: str, valid_formats: str) → None[source]

Initialize UnsupportedFormatError.

Parameters:
  • format_type – The invalid format requested.

  • valid_formats – Comma-separated list of valid formats.

exception findfmt.exceptions.UnsupportedTableStyleError(table_style: str)[source]

Bases: FindFmtError, ValueError

Raised when an unsupported table border style is requested in RST formatter.

__init__(table_style: str) → None[source]

Initialize UnsupportedTableStyleError.

Parameters:

table_style – The invalid table style requested.