fs_utils
Utility functions to interact with the filesystem.
Module
Functions
canonical_key_if_path
def canonical_key_if_path(value: str) ‑> str:Fold value with canonical_path_key only if it is a Windows path.
For a stored identifier that is usually, but not always, a file path: a
scan_id from a file-system datasource is one, while an ehr:<id> wave
key or a database connection string is not, and must keep its case.
Arguments
value: The identifier.
Returns
The canonical spelling of a \\server\share\… or X:\… path, or
value unchanged.
canonical_path_key
def canonical_path_key(path: str | os.PathLike[str]) ‑> bitfount.utils.fs_utils.FileKey:Return the one spelling of path that is used as a cache key.
os.path.normcase: on Windows the whole path is case-folded, and /
becomes \. \\IMG-SERVER-01\Scans\a.dcm and \\Img-Server-01\Scans\a.dcm
name the same file there, but Path.resolve() keeps whichever spelling of
the server and share it was given, so without this each spelling would be a
separate cache key. Elsewhere the path is returned unchanged.
The fold is lexical: it does not resolve the path. Call it on a path that
normalize_path has already resolved, as normalize_path does itself.
A Windows directory with per-directory case sensitivity turned on (a WSL feature) can hold two files whose names differ only in case. They would share one key. Imaging shares do not use that feature.
Arguments
path: The path to fold.
Returns The canonical spelling of path.
clear_location_sources
def clear_location_sources() ‑> None:Forget every registered LocationSource, and what they answered.
creation_time_stat_field
def creation_time_stat_field() ‑> Literal['st_ctime', 'st_birthtime', 'st_mtime']:Name the os.stat_result field get_file_creation_date reads on this platform.
Windows records a creation time in st_ctime and macOS in st_birthtime.
Linux exposes none through os.stat, so the last modification time,
st_mtime, stands in for it.
Returns The field's name.
forget_stored_locations
def forget_stored_locations() ‑> None:Have locate read every key's stored location afresh.
For a writer of stored locations: without it, this process would go on
using the answers it remembered from before the write, for up to
_STORED_LOCATION_TTL_SECONDS.
get_file_creation_date
def get_file_creation_date( path: str | os.PathLike[str], stat: os.stat_result | None = None,) ‑> datetime.date:Get the creation date of a file with consideration for different OSs.
If the stat object is provided, then the information will be extracted from
this in preference to getting a new one from the filesystem. Note that there is
no checking that the stat object is up-to-date or even corresponds to the same
file as path, so care should be taken to pass through the correct object.
It is not possible to get the creation date of a file on Linux. This method will return the last modification date instead. This will impact filtering of files by date.
Arguments
path: The path to the file.stat: An optionalstat_resultobject for the file, as returned byos.stat(path). This can be used to avoid making a new filesystem query.
Returns The creation date of the file.
get_file_last_modification_date
def get_file_last_modification_date( path: str | os.PathLike[str], stat: os.stat_result | None = None,) ‑> datetime.date:Get the last modification date of a file.
If the stat object is provided, then the information will be extracted from
this in preference to getting a new one from the filesystem. Note that there is
no checking that the stat object is up-to-date or even corresponds to the same
file as path, so care should be taken to pass through the correct object.
Arguments
path: The path to the file.stat: An optionalstat_resultobject for the file, as returned byos.stat(path). This can be used to avoid making a new filesystem query.
Returns The last modification date of the file.
get_file_size
def get_file_size( path: str | os.PathLike[str], stat: os.stat_result | None = None,) ‑> int:Get the size, in bytes, of a file on the filesystem.
If the stat object is provided, then the information will be extracted from
this in preference to getting a new one from the filesystem. Note that there is
no checking that the stat object is up-to-date or even corresponds to the same
file as path, so care should be taken to pass through the correct object.
Arguments
path: The path to the file.stat: An optionalstat_resultobject for the file, as returned byos.stat(path). This can be used to avoid making a new filesystem query.
Returns The size of the file, in bytes.
is_file
def is_file( path: str | os.PathLike[str] | os.DirEntry[str], stat: os.stat_result | None = None,) ‑> bool:Determine if a path is a file or not.
If the stat object is provided, then the information will be extracted from
this in preference to getting a new one from the filesystem. Note that there is
no checking that the stat object is up-to-date or even corresponds to the same
file as path, so care should be taken to pass through the correct object.
Arguments
path: The path to check. Can also be an os.DirEntry as from scandir() or scantree().stat: An optionalstat_resultobject for the path, as returned byos.stat(path). This can be used to avoid making a new filesystem query.
Returns The size of the file, in bytes.
is_likely_network_path
def is_likely_network_path(path: Path) ‑> bool:Checks if a path is likely to be on a Windows network drive.
Uses two checks (Windows only):
- UNC path prefix (
\\\\server\\share) — definitively network. GetDriveTypeWkernel API for mapped drives — reads local metadata, safe during network outages.
Returns False on non-Windows platforms.
is_unreachable_share
def is_unreachable_share(error: OSError) ‑> bool:Return whether error says a server or share did not answer.
Such an error is raised as FileNotFoundError on Windows, but says nothing
about the name looked up: no other spelling of it would answer either.
Arguments
error: The error an I/O call raised.
locate
def locate(key: str | os.PathLike[str]) ‑> bitfount.utils.fs_utils.FileLocation:Return the path to open for the path key key.
Call this immediately before opening, statting or listing a path that came
from a cache key, and keep using key itself to identify the file. See
PathLocator for when the two differ.
A stored location is returned unchecked; see PathLocator.locate for
what that means for one made stale by a rename.
Arguments
key: A path key, asnormalize_pathspells it.
Returns The on-disk spelling of key, or key itself when that is how it is spelled on disk or no single on-disk name matches it.
memoized_path_normalizer
def memoized_path_normalizer( *, strict: bool = False,) ‑> MemoizedPathNormalizer:Return a Path -> normalized str function that memoizes per parent directory.
normalize_path costs a filesystem round-trip, which is not affordable per
file on a network share: a walk of a million files would pay a million of
them. But alias-ness (symlink, Windows junction, mapped drive) is a property
of the directories on the way to a file, not of the file itself, so each
parent directory is resolved once and reused for every file within it. In a
typical walk that is one round-trip per directory and a dict lookup per file.
Only the parent is resolved; the file's own name is joined onto it
unresolved and then folded with canonical_path_key, as the parent was.
For a walk that is what you want — scandir yields the true on-disk name and
a symlinked file keeps its own name, matching what the caches hold. It
does mean this is not equivalent to normalize_path on an arbitrary
path: hand it a caller-supplied string whose filename is an 8.3 short name,
and that component is not expanded. Use normalize_path directly for those.
The memo holds each parent unfolded, so MemoizedPathNormalizer.location
gives a walked file's spelling before the fold, to open it by, at no extra
cost.
Pass strict=True when the result becomes a cache key, so a directory that
resolves only partially raises instead of yielding a plausible-looking
mapped-drive spelling — see resolve_path's note on Windows. Because the
memo is per directory, one unnoticed half-resolution would otherwise mis-key
every file beneath that directory, not just one.
The returned function is stateful (it owns the memo); make one per walk
rather than sharing one globally, so the memo cannot go stale against a
directory tree that changed between walks. Failures are not memoized, so a
directory that recovers resolves correctly on the next file. It is safe to
share between threads, and a pooled walk can prime it with each
directory as it lists it.
Arguments
strict: Propagated toresolve_pathfor each parent directory.
Returns
A callable mapping a walked Path to its normalized string spelling.
Raises
OSError: From the returned callable, only whenstrict=Trueand a parent directory could not be resolved.FileNotFoundErrordistinguishes "the directory is gone" (its files are gone too, so skipping them is correct) from "unreachable" (nothing beneath it can be trusted).
normalize_path
def normalize_path(path: str | os.PathLike[str], *, strict: bool = False) ‑> pathlib.Path:Normalize a path to handle mapped drives and UNC paths equivalently.
resolve_path, folded with canonical_path_key: the one spelling used as
a cache key, so that paths referring to the same location are treated as
equivalent. See resolve_path for how the path is resolved, its network
retries, and why a caller keying a cache off the result passes
strict=True.
Arguments
path: The path to normalize.strict: When True, require that the path actually resolve: raise the underlyingOSError(after any retries) instead of falling back to an unresolved absolute path.
Returns A normalized and absolute Path object that can be used for path comparisons and operations like relative_to().
Raises
OSError: Only whenstrict=Trueand the path could not be resolved.FileNotFoundError(a subclass) specifically means the path is not there, as distinct from being unreachable.
path_is_under
def path_is_under( path: str | os.PathLike[str], directory: str | os.PathLike[str],) ‑> bool:Return whether path sits inside directory.
Purely lexical: no filesystem access, so this is safe to call once per row of
a large inventory. Comparing Path objects (rather than string prefixes)
makes it robust to redundant separators and to the trailing-separator
ambiguity a startswith test has. directory is not considered to be
under itself.
Neither side is resolved here — callers that need symlink/.. normalisation
should resolve both sides first so the comparison is apples-to-apples. See
path_relative_to_base for the resolving, symlink-aware (and much more
expensive) variant.
Arguments
path: The candidate path.directory: The directory the candidate must be within.
Returns
True when path is strictly within directory.
path_keys_fold_case
def path_keys_fold_case() ‑> bool:Return whether path keys are case-folded on this platform.
A policy, not a probe of the file system: keys are folded on Windows, where
canonical_path_key (os.path.normcase) folds them, and nowhere else.
Returns
True on Windows.
path_relative_to_base
def path_relative_to_base( base: str | os.PathLike[str], file_path: str | os.PathLike[str], *, max_symlink_depth: int = 1,) ‑> pathlib.Path:Path of file_path relative to base.
(1) Resolved paths first: uses normalize_path on both and relative_to to check if they are relative (handles UNC / mapped drive equivalence).
(2) If that fails and symlinks are enabled in config (follow_symlinks_in_scantree), uses a BFS of paths under base up to max_symlink_depth (cached per base so many files under the same folder only trigger one walk): if file_path's resolved form lies under a symlink target, returns the corresponding relative path. When network_drive_robustness is enabled, the BFS uses robust scanning.
Arguments
base: The base (e.g. datasource root) path.file_path: The file path to express relative to base.max_symlink_depth: When the symlink fallback runs, how many directory levels under base to consider (1 = top level only). Default 1.
Returns A Path relative to base (e.g. "Y/foo" when base is /X and file is under /X/Y or under the resolved target of /X/Y).
Raises
ValueError: If file_path is not under base.
register_location_source
def register_location_source( db_path: str | os.PathLike[str], source: LocationSource,) ‑> None:Have locate and stat_key read stored locations from source.
Registering again for the same database replaces its source, so a cache that is opened many times holds one entry.
Arguments
db_path: The database source reads. Any spelling of the same file names the same entry.source: Where to read each key's stored location.
resolve_path
def resolve_path( path: str | os.PathLike[str], *, strict: bool = False, missing_is_final: bool = False,) ‑> pathlib.Path:Resolve a path to its absolute spelling, keeping its case.
This function resolves mapped drives (e.g., S:\patients) to their UNC equivalents
(e.g., \FSC\Filestorage1\Images\patients), and symlinks and relative paths
to their targets. The result is not case-folded: it is the spelling to open
the path by, where normalize_path folds it into the spelling to key it by.
On Windows, Path.resolve() automatically resolves mapped drives to UNC paths. On other platforms, this function resolves symlinks and relative paths.
When network_drive_robustness is enabled and the path appears to be on a
network drive, transient OSError failures from resolve() are retried with
exponential backoff before falling back to an absolute path.
Why strict matters on Windows
Path.resolve(strict=False) does not fail loudly when it cannot resolve a
path. On Windows it resolves the deepest prefix it can and joins the rest of
the path back as originally spelled
(ntpath._getfinalpathname_nonstrict), swallowing the network errors that
matter here — ERROR_BAD_NETPATH (53), ERROR_NETWORK_ACCESS_DENIED (65),
ERROR_BAD_NET_NAME (67), ERROR_NOT_READY (21). A share that blinks
therefore yields a mapped-drive spelling that looks like a successful
result, no exception is raised, and the retry logic above never runs.
For a caller that is about to use the result as a cache key that is not
an acceptable answer: the two spellings of one file would be written into
different primary keys depending on network weather. Pass strict=True
there. It turns the silent half-resolution into an OSError, which makes
the network retry reachable, and re-raises if the path still cannot be
resolved so the caller can abort rather than persist a suspect key.
Leave strict at False for paths that need not exist (an output directory
being computed, a file being probed), where a best-effort absolute path is
the useful answer.
Arguments
path: The path to resolve.strict: When True, require that the path actually resolve: raise the underlyingOSError(after any retries) instead of falling back to an unresolved absolute path.missing_is_final: When True, withstrict, raise a plainFileNotFoundErrorat once, with no retry and no warning: for a caller that has another spelling to try, where a name that is not there is an answer rather than a network failure. An unreachable share (ERROR_BAD_NETPATH,ERROR_BAD_NET_NAME) is still retried.
Returns
An absolute Path, resolved where it could be, in the case it was
resolved or given in.
Raises
OSError: Only whenstrict=Trueand the path could not be resolved.FileNotFoundError(a subclass) specifically means the path is not there, as distinct from being unreachable.
safe_append_to_file
def safe_append_to_file( func: Callable[[Path], R], initial_path: Path,) ‑> tuple[R, pathlib.Path]:Handle PermissionError when appending to a file.
Execute some function that writes/appends to a file and if it's not possible to append due to a PermissionError (e.g. the user has opened the file in Windows so can't be appended to) try backup paths to either create or append to.
The supplied func should take a single Path argument and return the result,
but should be able to handle the case when the file doesn't exist (i.e. writing
fresh) and when a file does exist but needs to be appended to.
Arguments
func: Function to execute, that takes in the destination file path and will append to an existing file or write to a new file.initial_path: The desired destination file path.
Returns A tuple of the result of the function and the actual path finally appended/written to.
safe_write_to_file
def safe_write_to_file( func: Callable[[Path], R], initial_path: Path,) ‑> tuple[R, pathlib.Path]:Handle PermissionError when writing to a file.
Execute some function that writes to a file and if it's not possible to write due to a PermissionError (e.g. the user has opened the file in Windows so can't be appended to) try to write to a new file instead.
Arguments
func: Function to execute, that takes in the destination file path.initial_path: The desired destination file path.
Returns A tuple of the result of the function and the actual path finally written to.
scantree
def scantree( root: str | os.PathLike[str], *, follow_symlinks: bool | None = None, workers: int = 1, stat_files: bool = False, on_directory: Callable[[str], None] | None = None, on_skipped: OnSkipped | None = None, on_subdirectory: OnSubdirectory | None = None,) ‑> Iterator[posix.DirEntry[str]]:Recursively iterate through a folder as in scandir(), yielding file entries.
A directory or entry that cannot be read is warned about and skipped, and passed to on_skipped when given.
Arguments
root: Root path to iterate from.follow_symlinks: If True, follow symbolic links to directories when recursing. If False, do not recurse into symlinked directories. If None (default), use config.settings.follow_symlinks_in_scantree.workers: How many directories to list at once. Above1the walk is breadth-first and yields in an undefined order; worth it where each listing is a network round trip. Ignored in network-drive robustness mode, which walks serially.stat_files: Withworkersabove1,stateach file on the pool so that the caller'sentry.stat()is already cached. Only worth it where the caller stats every file andDirEntrydoes not already carry the result (it does on Windows).on_directory: Called with each directory the walk could list, before that directory's files are yielded, such asMemoizedPathNormalizer.prime. Must not raise. Withworkersabove1it runs on the pool thread that listed the directory; the serial and robustness walks call it inline. Robustness mode may repeat a directory after a retry, so a consumer must tolerate that.on_skipped: Called with each path the walk could not read and the error, on whichever thread read it. Must not raise.on_subdirectory: Called with each directory listed and each subdirectory found in it, after on_directory and before the walk descends, such asMemoizedPathNormalizer.derive. Runs where on_directory does. Must not raise.
stat_key
def stat_key(key: str | os.PathLike[str]) ‑> os.stat_result:os.stat the file a path key names, by its on-disk spelling if need be.
Where keys are not folded, key is statted as it is. Otherwise a location stored for key is statted, once. Where none is stored, or the stored one has gone (a case-only rename since the walk recorded it), key is statted as spelled, which on a Windows file server always finds the file, and only a missing name is then looked for by listing.
Arguments
key: A path key, asnormalize_pathspells it.
Returns
The file's stat result.
Raises
OSError: Asos.statraises for the stored location, for any reason but a missing name, or as it raises for key when no other spelling of it is found.FileNotFoundErrormeans the file is not there.
Classes
LocationSource
class LocationSource(*args, **kwargs):Somewhere locate can read the on-disk spelling stored for a path key.
The pod's file_metadata table is one: the walk stores each file's
location beside its key. fs_utils uses sources only through this
protocol, and never imports the cache.
Ancestors
Methods
stored_location
def stored_location(self, key: str) ‑> bitfount.utils.fs_utils.FileLocation | None:Return the on-disk spelling stored for key, if one is.
May raise: locate treats any exception as no stored location.
Arguments
key: A path key, ascanonical_path_keyspells it.
Returns
The stored location, or None when none is stored.
MaxNetworkDriveRetriesExceededError
class MaxNetworkDriveRetriesExceededError(*args, **kwargs):Exception raised when the max number of network drive retries exceeded.
Ancestors
MemoizedPathNormalizer
class MemoizedPathNormalizer(*, strict: bool):A Path -> normalized str function that memoizes per parent directory.
Built by memoized_path_normalizer, which documents the behaviour. Safe to
call and to prime from several threads.
Arguments
strict: Propagated toresolve_pathfor each parent directory.
Methods
derive
def derive(self, parent: str, entry: os.DirEntry[str]) ‑> None:Resolve entry, a subdirectory of parent, from parent's resolution.
Resolving a directory costs several round trips on a network share, and
a walk used to pay them for every directory it listed. A directory
reached without a link resolves to its resolved parent joined with its
own name: scandir names it in its on-disk spelling, long name and
case included, and anything that changes where a path leads (a mapped
drive, a symlink, a junction, a DFS link) is either at the root, which
is resolved, or is a reparse point, which is not derived. So the
memo is filled here, from the listing, and prime finds it there.
Leaves entry for prime to resolve when it is a link or reparse
point, or when parent has not been resolved.
Arguments
parent: The directory listed, spelled as the walk spells it.entry: One of its subdirectories, as the listing returned it.
location
def location(self, scanned_path: Path) ‑> bitfount.utils.fs_utils.FileLocation:The on-disk spelling of a walked path: its key before the fold.
Read from the same memo as the key, so it costs nothing more, and
canonical_path_key of it is the key. Where keys are not folded, it is
the key.
Arguments
scanned_path: A walked path, as the normalizer is called with.
Returns The resolved parent joined with the walked name, both in their own case.
normalized_directory
def normalized_directory( self, directory: str | os.PathLike[str],) ‑> bitfount.utils.fs_utils.FileKey | None:The normalized spelling of directory, if prime resolved it.
Reads the memo rather than resolving, so a caller that has just primed a
directory can have its canonical spelling for free. None when the
resolution failed, which prime leaves unrecorded on purpose.
Arguments
directory: A directory spelled as the walk spells it.
Returns
The normalized path, or None if it has not been resolved.
prime
def prime(self, directory: str | os.PathLike[str]) ‑> None:Resolve directory ahead of its files, so their lookups hit the memo.
For a pooled walk, which calls this on the thread that lists the directory: the round trip then overlaps others instead of happening on the consumer, one directory at a time. A failure stores nothing, so the consumer's own lookup resolves the directory again and raises as it would have.
Arguments
directory: A directory whose files will be looked up next, spelled as the walk spells their parent.
PathLocator
class PathLocator( *, max_directories: int = 65536, max_listed_names: int = 500000, relist_after_seconds: float = 60.0,):Finds the on-disk spelling of a case-folded path key.
On Windows, path keys are folded (canonical_path_key), and a Windows file
server opens a file by any spelling of its name. A Samba or Linux NAS does
not: there only the server and share names compare case-insensitively, and
every folder and file below them must be spelled as on disk. A key such as
\\nas\share\patient1\scan.dcm then names nothing, though
\\nas\share\Patient1\Scan.DCM is there.
locate returns the location a registered LocationSource stores for the
key, without checking it: that costs no round trip to the share, and the
caller's own open is the one it makes. For a key with no stored location,
it returns the key unchanged when it exists as spelled, which costs one
existence check, and is always the case on a Windows file server.
Otherwise it walks down from the key's anchor (the drive, or the server and
share), matching each name case-insensitively against its folder's
listing. Listings and the spellings of folders are remembered, so a share
costs one listing per folder rather than one per file.
Safe to share between threads. Use locate, which shares one instance
across the process, rather than making one per call.
Arguments
max_directories: How many folder spellings to remember.max_listed_names: How many listed names to hold, across all listings. The oldest listings are dropped first.relist_after_seconds: How old a listing must be before a name missing from it causes the folder to be listed again.
Methods
locate
def locate(self, key: str | os.PathLike[str]) ‑> bitfount.utils.fs_utils.FileLocation:Return the on-disk spelling of key.
A stored location is not checked, so one made stale by a case-only
rename since the walk recorded it is returned as it is, and opening it
fails with FileNotFoundError until the next walk records the new
spelling. stat_key checks the location it stats, and looks for the
file when it is gone.
Arguments
key: A path key, asnormalize_pathspells it.
Returns The path to open. key itself when keys are not folded on this platform. Otherwise the location stored for key, if any. Without one, key itself when it exists as spelled, when it cannot be statted for any reason but a missing name (including a server or share that does not answer), or when no single on-disk name matches it, so that the caller's own error handling runs.
locate_missing
def locate_missing(self, key: str) ‑> bitfount.utils.fs_utils.FileLocation | None:The on-disk spelling of key, known not to exist as spelled.
For a caller that has already statted key and seen it missing, so that it is not statted again.
Arguments
key: A path key that astatfound missing.
Returns
The on-disk spelling, or None when no single on-disk name matches.
RootProbe
class RootProbe( root: str | os.PathLike[str], *, ttl_seconds: float = 10.0, clock: Callable[[], float] = <built-in function monotonic>,):Whether a datasource root is reachable, without re-probing a dead share.
The arbiter of whether a per-file or per-directory failure is transient: a failure while the root is unreachable says nothing about the file, so it is left for a later pass; with the root reachable, the failure is the file's own. Consulted only on failure paths.
Only an unreachable answer is reused, for the TTL: a probe of a dead share
can block until the SMB timeout, while a reachable one is a quick stat.
A reachable answer is never reused by a later failure, since the share may
have dropped in between and the file would be blamed for it. The probe is
single-flight: callers that arrive while one is running wait for it and
share its answer, whichever it is.
The root is a path key, and keeps identifying the root (root). Where keys
are case-folded, a root missing as spelled is looked for by its on-disk
spelling (locate): on a case-sensitive share its folders are spelled
otherwise on disk.
Arguments
root: The datasource root, as its path key.ttl_seconds: How long an unreachable answer is reused.clock: Monotonic clock, injectable for tests.
Variables
root : str- The probed root, as its path key.
Methods
reachable
def reachable(self) ‑> bool:Whether the root answers a stat now, or was unreachable just now.