Generated API

Signatures and docstrings pulled directly from the source, so this page cannot drift from the code the way hand-written prose can. Every public callable in dazzle_filekit carries a docstring — this is what they say.

Tip

For the narrative version — what to reach for, why one function differs from its near-twin, and the Windows behaviour that surprises people — read API Reference instead. This page is the reference of record; that one is the one to learn from.


Long paths

Long-path shims (L2).

This module answers one question: “this path is too long for a MAX_PATH-bound consumer – what shorter path names the same bytes?”

It exists because utils.validation.is_valid_path() already detects the condition (it returns False for paths over 260 that lack a \\?\ prefix) but nothing in filekit offered a remedy. This is that remedy.

Why a shim rather than the extended-length prefix

\\?\ lifts the limit at the Win32 API layer, and that is enough for a well-behaved caller. It is not enough for an application that builds the correct extended path and then copies it into a fixed MAX_PATH buffer – observed in the wild in more than one PDF reader, which truncates the tail and then reports the file as missing. Nothing outside such an application can fix its internal buffer. What can be changed is the length of the string handed to it, and a directory junction at a short location does exactly that: same bytes, shorter name, no cooperation required from the consumer.

Scope

Windows-only in effect. PATH_MAX is 4096 on Linux and 1024 on macOS/BSD, so the condition this module treats does not arise there; needs_shim() returns False on POSIX and every other entry point degrades to a no-op. Note that NAME_MAX is 255 on every platform – a single path component longer than that cannot be rescued by any amount of linking, because the offending name must itself appear in the shimmed path. plan_shim() reports that case rather than pretending to solve it.

Safety

Shim removal never recurses. remove_shim() re-verifies that its target is a junction immediately before deleting (closing the check-then-act window) and uses os.rmdir, which removes the reparse point only. This matters because every naive test misidentifies a junction: os.path.islink() is False, os.path.isdir() is True, and DirEntry.is_symlink() is False – a junction presents as an ordinary directory. Deleting one recursively through a careless code path would delete the target’s contents.

dazzle_filekit.longpath.MAX_PATH = 260

The Windows legacy path limit, inclusive of the terminating NUL.

dazzle_filekit.longpath.USABLE_PATH = 259

Longest path a MAX_PATH-bound consumer can actually hold (260 minus the NUL).

dazzle_filekit.longpath.DEFAULT_THRESHOLD = 240

some handlers append to the path they are given (a .tmp suffix, a backup name), so a path that merely fits can still overflow once the consumer touches it.

Type:

Default trigger length. Deliberately below USABLE_PATH

dazzle_filekit.longpath.NAME_MAX = 255

Longest single filename permitted by NTFS and by POSIX NAME_MAX alike.

dazzle_filekit.longpath.SHIM_DIR_NAME = '.dzs'

Directory name used for shim roots. Short by design – every character here is one taken away from the filename it has to accommodate.

dazzle_filekit.longpath.needs_shim(path, threshold=DEFAULT_THRESHOLD)[source]

Return True when path is long enough to break a MAX_PATH consumer.

Returns False on non-Windows platforms, and False for a path that already carries an extended-length prefix (such a path has opted out of the limit and rewriting it would be pointless).

Parameters:
Return type:

bool

dazzle_filekit.longpath.candidate_roots(target=None)[source]

Ordered shim-root candidates, shortest first.

The root’s own length is subtracted from the budget available to the filename, so this order is not cosmetic. A 49-character root (%LOCALAPPDATA%\dazzlecmd\longpath) leaves a 244-character filename needing 294 characters and still broken; a 7-character root does not.

%USERPROFILE% is included because it is the one location guaranteed writable, but it is deliberately ranked below the drive roots: its length varies with the username, so the same code serves every file on one machine and silently drops the longest ones on another.

Parameters:

target (str | Path | None)

Return type:

List[Path]

dazzle_filekit.longpath.resolve_shim_root(target=None, candidates=None, probe=True)[source]

Return the shortest writable shim root, or None if none is usable.

With probe=False the first candidate is returned unchecked, which is what tests want when they are exercising the ordering rather than the filesystem.

Parameters:
Return type:

Path | None

dazzle_filekit.longpath.budget_for(root, id_len=_ID_LEN)[source]

Longest filename a shim under root can serve.

<root>\<id>\<filename> must fit in USABLE_PATH.

Parameters:
Return type:

int

class dazzle_filekit.longpath.ShimPlan(original, needed, anchor=None, link=None, shimmed=None, reason='', warnings=<factory>)[source]

Bases: object

What (if anything) must exist for original to be openable.

Parameters:
original: Path
needed: bool
anchor: Path | None = None
shimmed: Path | None = None
reason: str = ''
warnings: List[str]
property usable: bool

True when this plan yields a path a MAX_PATH consumer can open.

resolved()[source]

The path to hand onward – shimmed when possible, else the original.

Never raises. A consumer that cannot be helped is still given its original path, so the caller degrades to today’s behaviour rather than failing outright.

Return type:

Path

dazzle_filekit.longpath.plan_shim(path, root=None, threshold=DEFAULT_THRESHOLD, id_len=_ID_LEN)[source]

Decide how to shorten path, without touching the filesystem.

Chooses the shallowest ancestor directory whose junction still brings the result under USABLE_PATH. Shallowest rather than deepest so one shim covers as much of the tree as possible and repeat opens reuse it; where the filename is long enough that only its immediate parent fits, that is what gets chosen.

Parameters:
Return type:

ShimPlan

dazzle_filekit.longpath.create_shim(plan, max_id_len=16)[source]

Materialise plan’s junction, reusing an existing one for the same anchor.

Anchor ids collide. The id is a truncated hash, so two unrelated directories can map to the same link name – at the 4-character default that is an even chance somewhere around three hundred distinct anchors, not a remote possibility on a large library. An earlier version treated any junction at the expected link as proof of a previous mint for this anchor and returned success; on a collision the caller then read a different directory’s file, silently and with no error. Whether an existing junction points at our anchor is therefore verified, not assumed, and a collision is resolved by lengthening the id until a matching or free slot is found.

On success the plan’s link and shimmed are updated to whatever was actually used, so a caller that reads plan.shimmed afterwards is never handed a path the collision loop moved away from.

Parameters:
Return type:

bool

dazzle_filekit.longpath.remove_shim(link)[source]

Remove a shim junction, leaving its target untouched.

Refuses anything that is not a junction. The check is made immediately before the delete rather than trusted from an earlier scan, so a directory swapped in after a listing is not removed.

That narrows the check-then-act window; it does not close it. The check and the delete remain two calls, and there is no atomic “unlink only if still a reparse point” primitive to use instead. Measured consequence of the surviving race: if a real directory replaces the junction between the two calls, os.rmdir deletes it when it is empty and refuses it when it is not – so the blast radius is bounded to an empty directory, and no file contents can be lost through this path.

Uses os.rmdir, which unlinks the reparse point without descending into it. Never call a recursive remove on a shim: a junction is reported as an ordinary directory by os.path.islink, os.path.isdir and DirEntry.is_symlink, so a recursive shell delete will happily walk into the real data.

Parameters:

link (str | Path)

Return type:

bool

dazzle_filekit.longpath.reap_shims(root, max_age_seconds=86400.0, now=None)[source]

Remove shims under root older than max_age_seconds.

Only junctions are considered; anything else in the directory is left alone. Returns the shims actually removed.

Parameters:
Return type:

List[Path]

dazzle_filekit.longpath.shim_path(path, root=None, threshold=DEFAULT_THRESHOLD)[source]

Convenience: return an openable path for path, creating a shim if needed.

Falls back to the original path whenever a shim is unnecessary, impossible, or fails to materialise – so a caller is never left worse off than if this module did not exist.

Never raises for a path-shaped input. The whole body is guarded, and the guard has to be wider than it first looks. A malformed root – an embedded NUL, say – surfaces differently depending on the interpreter: on 3.12+ utils.validation.is_junction() delegates to os.path.isjunction and the failure arrives as ValueError, while on 3.9-3.11 it falls back to a ctypes DeviceIoControl call and the same condition arrives as ctypes.ArgumentError, which derives from Exception and not from ValueError. Catching only the latter passes every test on a 3.13 dev box and raises on a 3.10 CI runner.

A caller substituting this for a bare path must not have to grow an exception handler it did not previously need.

Parameters:
Return type:

Path



Paths

Path handling and normalization utilities.

This module provides functions for path manipulation, normalization, and transformation across different platforms, focusing on preserving path information when copying files.

Philosophy note: the normalizers here are HOST-directional – they convert portable path formats toward the RUNNING OS’s native form (/mnt/c/... becomes C:\... on Windows and vice versa). For strings whose platform semantics are fixed by PROVENANCE instead – a PATH environment value from a Windows registry key stays ;-separated and case-insensitive no matter which host parses it – use the declared-platform helpers in dazzle_filekit.pathenv.

dazzle_filekit.paths.normalize_cross_platform_path(path, *, resolve=False, expand=True)[source]

Canonical path normalizer. Handles portable path formats across platforms.

expand=False (0.5.0) skips stripping whitespace and expanding ~ and environment variables: the path is taken literally, and only its FORMAT is normalized (drive forms, separators, the \\?\ prefix). The default, expand=True, is unchanged.

This is the path-normalization entry point in filekit. Pass resolve=True for link-following normalization, or use the default resolve=False for link-safe (literal) normalization.

Applies all portable-format conversions via _prepare_path_format:

/c/Users/foo -> C:Usersfoo (MSYS/Git Bash style) /mnt/c/Users/foo -> C:Usersfoo (WSL style) c:/Users/foo -> C:Usersfoo (forward-slash Windows) ~/foo -> C:UsersMefoo (tilde expansion) %USERPROFILE%/foo -> C:UsersMefoo (env var, Windows) $HOME/foo -> /home/me/foo (env var, Unix) ./relative -> <cwd>/relative (relative to cwd) \?C:... -> C:... (extended-length prefix)

Then, based on resolve:

  • resolve=False (default): collapses . and .. LEXICALLY via os.path.normpath (does not follow symlinks), and absolutizes via cwd join. Preserves the literal link path.

  • resolve=True: calls Path.resolve() which follows symlinks and junctions to their target (POSIX realpath semantics). Falls back to .absolute() for paths that don’t exist.

Parameters:
  • path (str | Path) – The path to normalize.

  • resolve (bool) – If True, follow symlinks. If False (default), preserve the literal link path and use lexical .. collapsing. This is a keyword-only argument.

  • expand (bool)

Returns:

The normalized path as a Path object.

Return type:

Path

Examples

# Link-safe (default) – preserves a symlink’s literal path normalize_cross_platform_path(“/mnt/c/code/my-link”) # -> Path(“C:/code/my-link”)

# Link-following – follows a symlink to its target normalize_cross_platform_path(“/mnt/c/code/my-link”, resolve=True) # -> Path(“C:/code/actual-target”)

dazzle_filekit.paths.is_same_file(path1, path2)[source]

Check if two paths refer to the same file or directory.

This is more reliable than simple string comparison as it handles different path representations that point to the same file.

Parameters:
  • path1 (str | Path) – First path

  • path2 (str | Path) – Second path

Returns:

True if paths refer to the same file, False otherwise

Return type:

bool

dazzle_filekit.paths.split_drive_letter(path)[source]

Split a path into drive letter and path components.

This is primarily useful on Windows where paths have drive letters.

Parameters:

path (str | Path) – The path to split

Returns:

Tuple of (drive_letter, path_without_drive)

Return type:

Tuple[str, str]

dazzle_filekit.paths.is_unc_path(path)[source]

Check if a path is a UNC (\\server\share) path.

This is a thin convenience WRAPPER, not the canonical home. UNC detection is a path-IDENTITY question, which the stack assigns to L0 – so this delegates to unctools.is_unc_path (the owner). It is kept public in filekit only as a convenience for file-operation callers, and may be deprecated in 0.4.0 in favour of importing unctools.is_unc_path directly.

Behaviour (from the owner): normalizes / -> \ then checks the \\ prefix, so //server/share is recognized on every platform. 0.3.0 collapsed filekit’s two previously-divergent copies (win32-only here, POSIX-// in utils.validation) onto this single delegate.

Parameters:

path (str | Path)

Return type:

bool

dazzle_filekit.paths.get_relative_path(path, base_path, allow_cross_drive=True)[source]

Get the relative path from base_path to path.

Parameters:
  • path (str | Path) – Target path

  • base_path (str | Path) – Base reference path

  • allow_cross_drive (bool) – Whether to allow paths on different drives

Returns:

Relative path, or None if cross-drive and not allowed

Return type:

Path | None

dazzle_filekit.paths.compute_relative_path(target, start, fallback_to_absolute=True)[source]

Compute the relative path FROM start TO target via os.path.relpath.

This is the ..-traversing relative path between two arbitrary locations – the operation needed to store a link’s target relative to the link’s own directory. It is distinct from get_relative_path(), which uses Path.relative_to and only succeeds when target is a subpath of start (returning None for siblings). For example, with target /a/b/c and start /a/x:

  • compute_relative_path -> "../b/c"

  • get_relative_path -> None (not a subpath)

Parameters:
  • target (str | Path) – The path being pointed at.

  • start (str | Path) – The reference location, typically the link’s parent directory.

  • fallback_to_absolute (bool) – On a cross-drive ValueError (Windows), return the absolute target instead of None.

Returns:

The relative path as a string, the absolute target on a cross-drive fallback, or None.

Return type:

str | None

dazzle_filekit.paths.create_dest_path(source_path, source_base, dest_base, path_style='relative', include_base=False)[source]

Create a destination path based on the source path and selected style.

Parameters:
  • source_path (str | Path) – Source file path

  • source_base (str | Path) – Base directory for source files

  • dest_base (str | Path) – Destination base directory

  • path_style (str) – Path style (‘relative’, ‘absolute’, ‘flat’)

  • include_base (bool) – Whether to include the source_base name in the path

Returns:

Destination path as a Path object

Return type:

Path

dazzle_filekit.paths.find_files(search_paths, patterns=None, recursive=True, exclude_patterns=None)[source]

Find files in search paths matching the given patterns.

Parameters:
  • search_paths (List[str | Path]) – List of directories to search

  • patterns (List[str] | None) – List of glob patterns to match (e.g., [”.txt”, “.csv”])

  • recursive (bool) – Whether to search recursively

  • exclude_patterns (List[str] | None) – List of glob patterns to exclude

Returns:

List of matching file paths

Return type:

List[Path]

dazzle_filekit.paths.collect_files_from_include_file(include_file)[source]

Collect a list of files from an include file.

The include file should contain one file path per line. Blank lines and lines starting with # are ignored.

Parameters:

include_file (str | Path) – Path to the include file

Returns:

List of file paths

Return type:

List[Path]

dazzle_filekit.paths.find_regex_files(search_paths, regex_patterns, recursive=True, exclude_patterns=None)[source]

Find files in search paths matching the given regex patterns.

Parameters:
  • search_paths (List[str | Path]) – List of directories to search

  • regex_patterns (List[str]) – List of regex patterns to match

  • recursive (bool) – Whether to search recursively

  • exclude_patterns (List[str] | None) – List of glob patterns to exclude

Returns:

List of matching file paths

Return type:

List[Path]

dazzle_filekit.paths.create_parent_dirs(path)[source]

Create parent directories for a path if they don’t exist.

Parameters:

path (str | Path) – The path whose parents should be created

Returns:

True if successful or directories already exist, False on error

Return type:

bool

dazzle_filekit.paths.ensure_unique_path(path)[source]

Ensure a path is unique by appending a number if necessary.

Parameters:

path (str | Path) – Original path

Returns:

Unique path that doesn’t exist yet

Return type:

Path

dazzle_filekit.paths.classify_fs_object(path)[source]

Classify WHAT kind of filesystem object a path is.

(Renamed from get_path_type in 0.3.0 – #15 Phase C. The L1 name classifies the OBJECT; unctools’ sibling classify_path_origin classifies WHERE a path’s name comes from. Behavior is unchanged: a junction still reports 'directory' – use links.analyze_link for link-kind classification.)

Parameters:

path (str | Path) – Path to check

Returns:

‘file’, ‘directory’, ‘symlink’, ‘socket’, ‘pipe’, ‘block_device’, ‘char_device’, ‘nonexistent’, or ‘unknown’

Return type:

Path type


PATH environment values

PATH-environment-value helpers – declared-platform parsing and compare.

A PATH value is a string whose platform semantics are fixed by its PROVENANCE, not by the host parsing it: a Windows registry Path value stays ;-separated, %VAR%-bearing, and case-insensitive even when a POSIX CI runner is the one reading it, and a POSIX PATH stays :-separated everywhere. That is the opposite philosophy from dazzle_filekit.paths.normalize_cross_platform_path(), which is deliberately HOST-directional (it converts filesystem paths toward the running OS’s native form). Both philosophies are correct – for their own domain. This module is the declared-platform domain’s home.

Origin: extracted from the dazzlecmd self-setup work (dazzlecmd#103), where PATH membership had to be decided against Windows registry values with normalized comparison (quotes, trailing slashes, %VAR% expansion, casefold) on any host. See the dazzlecmd stack-survey (C6) for the layering rationale.

platform arguments accept PLATFORM_WINDOWS, PLATFORM_POSIX, or None meaning the running host. The functions are pure string logic – no filesystem I/O, no registry access; persistence stays with callers.

dazzle_filekit.pathenv.host_path_platform()[source]

The running host’s PATH dialect: "windows" or "posix".

Return type:

str

dazzle_filekit.pathenv.split_path_value(value, platform=None)[source]

Split a PATH value into its non-empty entries.

The separator follows the DECLARED platform (; for windows, : for posix), never the host’s os.pathsep – a Windows registry value parsed on a POSIX runner still splits on ;.

Parameters:
  • value (str)

  • platform (str | None)

Return type:

List[str]

dazzle_filekit.pathenv.normalize_path_entry(entry, platform=None)[source]

Normalize ONE PATH entry for identity comparison.

Windows dialect: strips whitespace and surrounding double quotes (quoted entries are legal in Windows PATH values), expands %VAR% references the way the OS does for REG_EXPAND_SZ (via ntpath explicitly, so behavior is identical on any host), canonicalizes separators to \, drops trailing separators, and casefolds (Windows PATH lookup is case-insensitive). Note an inherited stdlib behavior, pinned by test: ntpath.expandvars ALSO expands POSIX-spelled $VAR / ${VAR} references, so those expand under this dialect too. Undefined references of either spelling stay literal.

POSIX dialect: strips whitespace and quotes, canonicalizes separators to /, drops trailing slashes; case is preserved.

Output is deterministic for a given (entry, platform) pair regardless of the host running this code.

Parameters:
  • entry (str)

  • platform (str | None)

Return type:

str

dazzle_filekit.pathenv.path_value_contains(value, directory, platform=None)[source]

True if directory is among value’s entries.

Membership by normalized identity: quotes and trailing separators ignored, %VAR% entries expanded, case-insensitive under the windows dialect.

Parameters:
  • value (str)

  • directory (str)

  • platform (str | None)

Return type:

bool

dazzle_filekit.pathenv.append_path_value(value, directory, platform=None)[source]

Return value with directory appended, if not already present.

Pure string construction: no-op (returns value unchanged) when the directory is already a member under normalized identity; an empty value yields directory alone. The caller persists the result wherever it belongs (registry, rc file, environment) – this module never does I/O.

Parameters:
  • value (str)

  • directory (str)

  • platform (str | None)

Return type:

str


Content operations

Text-content file operations.

The L1 home of unctools’ removed replace_in_file / batch_replace_in_files (STACK-MAP D7: editing a file’s content is a file operation, so it belongs in dazzle-filekit, not the path-identity layer). Built on the fallback-aware open_file (read), atomic_write_text (crash-safe write – a strict upgrade over the original’s plain write), and process_files (batch).

dazzle_filekit.content.replace_in_file(file_path, old_text, new_text, *, encoding='utf-8', try_path_variants=False, resolver=None)[source]

Replace old_text with new_text in file_path.

Reads via the fallback-aware open_file() and writes via atomic_write_text() (so a crash mid-write cannot truncate the file). Returns True if the file was modified, False if old_text was not present (logged as a warning) or on error.

Parameters:
  • file_path (str | Path)

  • old_text (str)

  • new_text (str)

  • encoding (str)

  • try_path_variants (bool)

  • resolver (PathVariantResolver | None)

Return type:

bool

dazzle_filekit.content.batch_replace_in_files(directory, old_text, new_text, pattern='*.txt', recursive=True, *, encoding='utf-8', try_path_variants=False, resolver=None)[source]

Run replace_in_file() over every file matching pattern under directory (via process_files()).

Returns {str(path): modified?} (False for unmatched / errored files).

Parameters:
  • directory (str | Path)

  • old_text (str)

  • new_text (str)

  • pattern (str)

  • recursive (bool)

  • encoding (str)

  • try_path_variants (bool)

  • resolver (PathVariantResolver | None)

Return type:

Dict[str, bool]


File operations

File operations for copying, moving and verifying files.

This module provides functions for file operations with attribute preservation across different platforms, including timestamps, permissions, and other metadata.

dazzle_filekit.operations.atomic_write_text(path, content, *, encoding='utf-8', newline=None)[source]

Atomically write text content to path.

Writes content to a sibling .tmp file and then renames it to path via os.replace (atomic on POSIX and Windows since Python 3.3). Readers observing the file see either the old contents or the new contents – never a partial write.

Creates parent directories if they don’t exist.

Parameters:
  • path (str | Path) – Destination file path.

  • content (str) – Text content to write.

  • encoding (str) – Text encoding (keyword-only, default utf-8).

  • newline (str | None) – Newline translation, passed to open() (keyword-only, default None = universal).

Raises:

OSError – If the write or rename fails. The .tmp file is left in place for inspection.

Return type:

None

Pattern source: safedel/_store.py:_save_manifest and safedel/_volumes.py:save_registry both used this idiom; this function centralizes it.

dazzle_filekit.operations.atomic_write_json(path, data, *, indent=2, sort_keys=False, default=str, trailing_newline=True)[source]

Atomically write data as JSON to path.

Thin wrapper around atomic_write_text(path, json.dumps(...)). The default default=str handles common non-JSON-native types (datetime, Path, pathlib.PurePath, etc.) by stringifying them – matches safedel’s _save_manifest behavior.

Parameters:
  • path (str | Path) – Destination JSON file path.

  • data (Any) – The object to serialize. Must be JSON-compatible or have a string representation if non-native types are present.

  • indent (int) – json.dumps indent (keyword-only, default 2).

  • sort_keys (bool) – json.dumps sort_keys (keyword-only, default False).

  • default (Callable[[Any], Any] | None) – Fallback serializer for non-JSON types (keyword-only, default str). Set to None to get TypeError on unknown types instead.

  • trailing_newline (bool) – Append a trailing newline (keyword-only, default True, matching POSIX text file convention).

Raises:
  • TypeError – If data contains non-JSON types and default is None.

  • OSError – If the underlying write fails.

Return type:

None

class dazzle_filekit.operations.AtomicStreamWriter(path, *, encoding='utf-8', newline=None, resume_from_existing=False, fsync_on_flush=False, buffering=-1)[source]

Bases: object

Streaming counterpart of atomic_write_text().

For content too large – or too incremental – to build in memory: writes go to a sibling .tmp file, and on successful close the tmp is renamed over path via os.replace. Readers observing path see either the old contents or the complete new contents, never a partial write. On failure (an exception inside the with block, or an explicit close(success=False)) the destination is untouched and the tmp is removed.

Options (all keyword-only):

  • resume_from_existing: seed the tmp with the current contents of path (shutil.copy2) and open it in append mode – for resuming an interrupted long-running write. When path does not exist this degrades to a normal fresh write.

  • fsync_on_flush: make each flush() also os.fsync, bounding data loss to the last flush for observers tailing the tmp during very long runs (fsync failures are swallowed – not every platform/filesystem supports it).

  • encoding / newline / buffering: passed to open(), with the same defaults as atomic_write_text().

Usage:

with AtomicStreamWriter(dest, fsync_on_flush=True) as w:
    for chunk in produce():
        w.write(chunk)
        w.flush()

Provenance: generalized from dazzlesum’s MonolithicWriter (its streaming checksum-manifest writer), minus the domain concerns (headers, footers, overwrite prompts). The one-shot sibling of this class is atomic_write_text().

Parameters:
  • path (str | Path)

  • encoding (str)

  • newline (str | None)

  • resume_from_existing (bool)

  • fsync_on_flush (bool)

  • buffering (int)

open()[source]

Open the tmp file for writing (called automatically by with).

Return type:

AtomicStreamWriter

write(text)[source]

Write text to the tmp file.

Parameters:

text (str)

Return type:

None

flush()[source]

Flush buffered writes to the tmp file (and fsync when enabled).

Return type:

None

close(success=True)[source]

Finalize: rename tmp over path on success, discard it otherwise.

Idempotent; safe to call after the with block has already closed the writer.

Parameters:

success (bool)

Return type:

None

Copy a directory tree; the caller chooses what happens to links in it.

links (keyword-only, 0.5.0) covers symlinks AND Windows junctions:

  • "keep" (default): each link is recreated at the destination as a link with the same target. Nothing behind a link is read or copied.

  • "follow": a link is replaced by a copy of what it points at.

  • "skip": links are left out of the copy.

Why the choice exists: shutil.copytree(symlinks=True) keeps symlinks but ENTERS junctions and copies their targets (measured 2026-11-18, Python 3.12, Windows 11). Through 0.4.3 this function was that call, so despite its name a junction inside src was followed. From 0.5.0 the default really keeps junctions; pass links="follow" for a copy of the contents.

A junction that cannot be recreated under "keep" raises shutil.Error after the rest of the tree is copied, so a caller that removes src after a successful copy never does so on a partial one. src itself is always entered, link or not.

Parameters:
  • src (str | Path) – Source directory path.

  • dst (str | Path) – Destination directory path.

  • dirs_exist_ok (bool) – If True, allow dst to exist (keyword-only, default False – matches shutil.copytree’s default).

  • ignore (Callable[[...], Any] | None) – Callable (dir, contents) -> names_to_skip passed to shutil.copytree (keyword-only).

  • ignore_dangling_symlinks (bool) – If True, skip symlinks whose target is missing (keyword-only, default False – by default copytree raises on dangling links).

  • links (str)

Returns:

The destination Path.

Return type:

Path

Pattern source: safedel/_recover.py:338 and other safedel call sites all used shutil.copytree(..., symlinks=True). Centralized here so the safety property has a name.

dazzle_filekit.operations.copy_file(source, destination, preserve_attrs=True, overwrite=False, *, try_path_variants=False, resolver=None)[source]

Copy a file with attribute preservation.

Parameters:
  • source (str | Path) – Source file path

  • destination (str | Path) – Destination file path

  • preserve_attrs (bool) – Whether to preserve file attributes

  • overwrite (bool) – Whether to overwrite the destination if it exists

  • try_path_variants (bool) – If True, retry under alternative names for source/ destination (e.g. a UNC path and its mapped-drive equivalent) when the first attempt fails (STACK-MAP D7 fallback). Off by default; default behavior is unchanged.

  • resolver (PathVariantResolver | None) – A dazzle_lib.PathVariantResolver supplying name variants; only consulted when try_path_variants=True (default: unctools).

Returns:

True if successful, False otherwise

Return type:

bool

dazzle_filekit.operations.move_file(source, destination, preserve_attrs=True, overwrite=False, *, try_path_variants=False, resolver=None)[source]

Move a file with attribute preservation.

Parameters:
  • source (str | Path) – Source file path

  • destination (str | Path) – Destination file path

  • preserve_attrs (bool) – Whether to preserve file attributes

  • overwrite (bool) – Whether to overwrite the destination if it exists

  • try_path_variants (bool) – If True, retry under alternative names for source/ destination when the first attempt fails (STACK-MAP D7 fallback). Off by default; default behavior is unchanged.

  • resolver (PathVariantResolver | None) – A dazzle_lib.PathVariantResolver supplying name variants; only consulted when try_path_variants=True (default: unctools).

Returns:

True if successful, False otherwise

Return type:

bool

dazzle_filekit.operations.open_file(path, mode='r', encoding=None, *, try_path_variants=False, resolver=None, **kwargs)[source]

Open a file, optionally retrying under alternative path names.

A fallback-aware open(): with try_path_variants=True, a failed open (e.g. a UNC name blocked by a Windows security zone, even though the file exists) is retried under the path’s other names from resolver (default: the unctools-backed resolver), re-raising the original error if every variant fails. This is the file-handle counterpart of copy_file(try_path_variants=True) and reproduces the old unctools.safe_open capability (STACK-MAP D7).

mode, encoding and any extra **kwargs are forwarded to the built-in open; the return value is the file object. Off by default, so open_file(path) behaves exactly like open(path).

Parameters:
  • path (str | Path)

  • mode (str)

  • encoding (str | None)

  • try_path_variants (bool)

  • resolver (PathVariantResolver | None)

dazzle_filekit.operations.collect_file_metadata(path)[source]

Collect file metadata for preservation.

As of v0.2.4, this is a thin wrapper around dazzle_filekit.metadata.collect_file_metadata which captures a strict superset of v0.2.3’s output:

  • File mode, size, owner/group, timestamps (with ISO projections)

  • Windows: attribute flag booleans (is_hidden/is_system/…), SDDL ACL string (JSON-safe), owner/group as DOMAINName

  • Linux/macOS: extended attributes (xattrs) as base64

Callers that only read the v0.2.3 fields are unaffected; the new keys are additive. Use dazzle_filekit.metadata directly for access to compare_metadata, metadata_to_json, etc.

Parameters:

path (str | Path) – Path to the file

Returns:

Dictionary of file metadata

Return type:

Dict[str, Any]

dazzle_filekit.operations.apply_file_metadata(path, metadata)[source]

Apply metadata to a file.

As of v0.2.4, this is a thin wrapper around dazzle_filekit.metadata.apply_file_metadata which honors all the richer fields when present:

  • Windows: SDDL ACL restoration via ConvertStringSecurityDescriptorToSecurityDescriptorW; creation time restoration via SetFileTime + FILE_WRITE_ATTRIBUTES

  • Linux/macOS: extended attributes via os.setxattr, with com.apple.quarantine skipped on restore

Old (v0.2.3) manifests without the new fields restore correctly – each advanced field is optional.

Parameters:
  • path (str | Path) – Path to the file

  • metadata (Dict[str, Any]) – Metadata to apply

Returns:

True if successful, False otherwise

Return type:

bool

dazzle_filekit.operations.copy_files_with_path(source_files, source_base, dest_base, path_style='relative', include_base=False, preserve_attrs=True, overwrite=False, *, try_path_variants=False, resolver=None)[source]

Copy multiple files preserving their path structure.

Parameters:
  • source_files (List[str | Path]) – List of source file paths

  • source_base (str | Path) – Base directory for source files

  • dest_base (str | Path) – Destination base directory

  • path_style (str) – Path style (‘relative’, ‘absolute’, ‘flat’)

  • include_base (bool) – Whether to include the base directory name

  • preserve_attrs (bool) – Whether to preserve file attributes

  • overwrite (bool) – Whether to overwrite existing files

  • try_path_variants (bool)

  • resolver (PathVariantResolver | None)

Returns:

Dictionary mapping source paths to tuples of (success, destination_path)

Return type:

Dict[str, Tuple[bool, Path]]

dazzle_filekit.operations.move_files_with_path(source_files, source_base, dest_base, path_style='relative', include_base=False, preserve_attrs=True, overwrite=False, *, try_path_variants=False, resolver=None)[source]

Move multiple files preserving their path structure.

Parameters:
  • source_files (List[str | Path]) – List of source file paths

  • source_base (str | Path) – Base directory for source files

  • dest_base (str | Path) – Destination base directory

  • path_style (str) – Path style (‘relative’, ‘absolute’, ‘flat’)

  • include_base (bool) – Whether to include the base directory name

  • preserve_attrs (bool) – Whether to preserve file attributes

  • overwrite (bool) – Whether to overwrite existing files

  • try_path_variants (bool)

  • resolver (PathVariantResolver | None)

Returns:

Dictionary mapping source paths to tuples of (success, destination_path)

Return type:

Dict[str, Tuple[bool, Path]]

dazzle_filekit.operations.process_files(directory, callback, pattern='*', recursive=True, *, try_path_variants=False, resolver=None)[source]

Apply callback to every file under directory matching pattern.

The flat batch-apply primitive – the L1 home of the old unctools.process_files: globs directory for pattern (recursive by default), calls callback(Path) on each file, and returns {str(path): result}. Per-file exceptions are swallowed (logged, result recorded as None) so one bad file does not abort the batch.

This is NOT a tree traversal (no depth/filter model – that is dazzletreelib’s domain); it is the generic sibling of copy_files_with_path.

Parameters:
  • directory (str | Path) – Directory to scan.

  • callback (Callable[[Path], Any]) – Called with each matching file’s Path; its return value is stored in the result map.

  • pattern (str) – Glob pattern (default *).

  • recursive (bool) – Recurse into subdirectories (default True).

  • try_path_variants (bool) – If True and directory does not exist under the given name, retry under the variant names from resolver (the directory-name fallback the original did).

  • resolver (PathVariantResolver | None) – A dazzle_lib.PathVariantResolver; only consulted when try_path_variants=True (default: unctools).

Returns:

{str(file_path): callback_result_or_None}.

Return type:

Dict[str, Any]

dazzle_filekit.operations.create_directory_structure(dest_path, directory_paths)[source]

Create a directory structure at destination path.

Parameters:
  • dest_path (str | Path) – Base destination path

  • directory_paths (List[str | Path]) – List of directory paths to create

Returns:

True if successful, False otherwise

Return type:

bool

dazzle_filekit.operations.remove_file(path, force=False)[source]

Remove a file.

Parameters:
  • path (str | Path) – Path to the file

  • force (bool) – Whether to force removal (ignore errors)

Returns:

True if successful, False otherwise

Return type:

bool

dazzle_filekit.operations.remove_directory(path, recursive=False, force=False)[source]

Remove a directory.

Parameters:
  • path (str | Path) – Path to the directory

  • recursive (bool) – Whether to remove contents recursively

  • force (bool) – Whether to force removal (ignore errors)

Returns:

True if successful, False otherwise

Return type:

bool

Create a symbolic link with cross-platform handling.

On Unix systems, uses os.symlink directly. On Windows, attempts an escalating chain (see _create_windows_symlink): 1. os.symlink (requires Developer Mode or admin on Windows 10+) 2. win32file.CreateSymbolicLink with the unprivileged-create flag 3. mklink via a non-elevated cmd subprocess 4. PowerShell elevation (Start-Process -Verb RunAs)

Parameters:
  • target (str | Path) – The target path the symlink will point to

  • link (str | Path) – The path where the symlink will be created

  • force (bool) – If True, remove existing file/symlink at link path first

  • target_is_directory (bool | None) – Whether target is a directory (auto-detected if None)

Returns:

True if symlink was created successfully, False otherwise

Return type:

bool

Example

>>> create_symlink('/path/to/file.txt', '/path/to/link.txt')
True
>>> create_symlink('C:\data\folder', 'C:\links\folder_link', target_is_directory=True)
True

Metadata

Rich file metadata capture and application.

This module provides functionality for collecting, storing, and applying file metadata across platforms, with first-class support for:

  • Windows SDDL ACL round-trip (JSON-serializable)

  • Windows creation time restoration via pywin32 SetFileTime

  • Linux/macOS extended attributes (xattrs) capture and apply

  • File mode, timestamps (with ISO projections), and owner/group

Ported into filekit in v0.2.4 from the preservelib module bundled with dazzlecmd/projects/core/safedel. The port is byte-identical to the source; any future enhancements should land here first and flow out to downstream preservelib copies.

Two top-level entry points are re-exported from dazzle_filekit:

from dazzle_filekit import collect_file_metadata, apply_file_metadata

Or use the module directly:

from dazzle_filekit import metadata md = metadata.collect_file_metadata(path) metadata.apply_file_metadata(target, md)

See is_win32_available() to check whether the richer Windows code path is available (requires pywin32; shipped as a dependency in v0.2.4).

dazzle_filekit.metadata.collect_file_metadata(path)[source]

Collect file metadata for preservation.

Parameters:

path (str | Path) – The file path to collect metadata from

Returns:

A dictionary of file metadata

Return type:

FileMetadataDict

dazzle_filekit.metadata.apply_file_metadata(path, metadata)[source]

Apply metadata to a file.

Parameters:
  • path (str | Path) – The file path to apply metadata to

  • metadata (FileMetadataDict) – The metadata to apply

Returns:

True if successful, False otherwise

Return type:

bool

dazzle_filekit.metadata.is_win32_available()[source]

Check if pywin32 is available for ctime restoration.

Return type:

bool

dazzle_filekit.metadata.restore_windows_creation_time(path, created)[source]

Restore the Windows creation time (ctime) of a file or directory.

Windows NTFS stores three timestamps: creation, last-modified, last-accessed. Python’s os.utime() can set modified and accessed but NOT creation time. This function uses pywin32 SetFileTime() to restore the creation time captured in the manifest.

Parameters:
  • path (str | Path) – File or directory path

  • created (float | datetime) – Creation time as epoch float or datetime object

Returns:

True on success, False on any failure (pywin32 missing, permission denied, etc.). This is best-effort – failure should not block recovery.

Return type:

bool

dazzle_filekit.metadata.compare_metadata(metadata1, metadata2)[source]

Compare two metadata dictionaries and return differences.

Parameters:
  • metadata1 (Dict[str, Any]) – First metadata dictionary

  • metadata2 (Dict[str, Any]) – Second metadata dictionary

Returns:

Dictionary of differences

Return type:

Dict[str, Any]

dazzle_filekit.metadata.get_metadata_summary(metadata)[source]

Get a human-readable summary of file metadata.

Parameters:

metadata (Dict[str, Any]) – The metadata to summarize

Returns:

Dictionary with summarized metadata

Return type:

Dict[str, Any]

dazzle_filekit.metadata.metadata_to_json(metadata)[source]

Convert metadata to a JSON-serializable format.

Parameters:

metadata (Dict[str, Any]) – The metadata to convert

Returns:

JSON-serializable dictionary

Return type:

Dict[str, Any]

dazzle_filekit.metadata.collect_timestamp_info(path)[source]

Collect timestamp information from a file.

Parameters:

path (str | Path) – Path to the file

Returns:

Dictionary with timestamp information

Return type:

TimestampsDict

dazzle_filekit.metadata.apply_timestamp_strategy(path, strategy, link_timestamps=None, target_timestamps=None)[source]

Apply timestamps to a file based on a strategy.

Parameters:
  • path (str | Path) – Path to the file

  • strategy (str) – Strategy to use (‘current’, ‘symlink’, ‘target’, ‘preserve-all’)

  • link_timestamps (Dict[str, Any] | None) – Timestamps from the original symlink (optional)

  • target_timestamps (Dict[str, Any] | None) – Timestamps from the target file (optional)

Returns:

True if successful, False otherwise

Return type:

bool


Verification

File verification utilities for hashing and comparing files.

This module provides functions for calculating file hashes using various algorithms and verifying file integrity through hash comparison.

dazzle_filekit.verification.calculate_file_hash(file_path, algorithms=None, buffer_size=65536, preserve_case=True)[source]

Calculate hash values for a file using one or more algorithms.

This is the core implementation used by both dazzle_filekit and preservelib.

Parameters:
  • file_path (str | Path) – Path to the file

  • algorithms (List[str]) – List of hash algorithms to use (default: [‘SHA256’])

  • buffer_size (int) – Size of the buffer for reading the file in chunks

  • preserve_case (bool) – If True, preserve the case of algorithm names in output

Returns:

Dictionary mapping algorithm names to hash values

Return type:

Dict[str, str]

dazzle_filekit.verification.detect_native_hash_tool(algorithm='sha256', use_cache=True)[source]

Detect an available native checksum tool for algorithm.

Probes the platform’s likely tools (Windows: fsum, certutil; Unix: the *sum family, shasum, md5) and returns the first runnable one, or None if none work. Results are cached per algorithm for the life of the process (pass use_cache=False to re-probe).

Parameters:
  • algorithm (str) – Hash algorithm name (md5/sha1/sha256/sha512).

  • use_cache (bool) – Reuse (and populate) the per-process detection cache.

Returns:

The tool name (e.g. 'sha256sum'), or None.

Return type:

str | None

dazzle_filekit.verification.calculate_file_hash_native(file_path, algorithm='sha256', tool=None)[source]

Calculate a file’s hash with a native checksum tool.

Parameters:
  • file_path (str | Path) – Path to the file.

  • algorithm (str) – Hash algorithm name (md5/sha1/sha256/sha512).

  • tool (str | None) – Tool to use (fsum/certutil/sha256sum/…/shasum); auto-detected via detect_native_hash_tool() when None.

Returns:

The lowercase hex digest, or None when no tool is available or the tool fails (the reason is logged at debug level) – callers fall back to calculate_file_hash().

Return type:

str | None

dazzle_filekit.verification.verify_file_hash(file_path, expected_hashes)[source]

Verify a file against expected hash values.

Parameters:
  • file_path (str | Path) – Path to the file

  • expected_hashes (Dict[str, str]) – Dictionary mapping algorithm names to expected hash values

Returns:

Tuple of (overall_success, details) where details is a dictionary mapping algorithm names to tuples of (success, expected_hash, actual_hash)

Return type:

Tuple[bool, Dict[str, Tuple[bool, str, str]]]

dazzle_filekit.verification.verify_files_with_manifest(files, algorithm='SHA256')[source]

Verify a set of files against provided hashes.

Parameters:
  • files (Dict[str, str]) – Dictionary mapping file paths to expected hashes

  • algorithm (str) – Hash algorithm to use

Returns:

Dictionary mapping file paths to tuples of (success, expected_hash, actual_hash)

Return type:

Dict[str, Tuple[bool, str | None, str | None]]

dazzle_filekit.verification.calculate_directory_hashes(directory, pattern='*', recursive=True, algorithm='SHA256')[source]

Calculate hashes for all files in a directory.

Parameters:
  • directory (str | Path) – Directory path

  • pattern (str) – Glob pattern to match files

  • recursive (bool) – Whether to recurse into subdirectories

  • algorithm (str) – Hash algorithm to use

Returns:

Dictionary mapping file paths to hash values

Return type:

Dict[str, str]

dazzle_filekit.verification.save_hashes_to_file(hashes, output_file, include_header=True)[source]

Save a dictionary of file hashes to a text file.

Parameters:
  • hashes (Dict[str, str]) – Dictionary mapping file paths to hash values

  • output_file (str | Path) – Path to the output file

  • include_header (bool) – Whether to include a header with timestamp

Returns:

True if successful, False otherwise

Return type:

bool

dazzle_filekit.verification.load_hashes_from_file(hash_file)[source]

Load file hashes from a text file.

Parameters:

hash_file (str | Path) – Path to the hash file

Returns:

Dictionary mapping file paths to hash values

Return type:

Dict[str, str]

dazzle_filekit.verification.compare_directories(dir1, dir2, algorithm='SHA256', recursive=True)[source]

Compare the contents of two directories by hashing files.

Parameters:
  • dir1 (str | Path) – First directory

  • dir2 (str | Path) – Second directory

  • algorithm (str) – Hash algorithm to use

  • recursive (bool) – Whether to recurse into subdirectories

Returns:

Dictionary with comparison results

Return type:

Dict[str, Any]

dazzle_filekit.verification.verify_copied_files(source_files, dest_files, algorithm='SHA256')[source]

Verify that files were copied correctly by comparing hashes.

Parameters:
  • source_files (Dict[str, Path]) – Dictionary mapping source keys to source paths

  • dest_files (Dict[str, Path]) – Dictionary mapping source keys to destination paths

  • algorithm (str) – Hash algorithm to use

Returns:

Dictionary mapping source keys to tuples of (success, source_hash, dest_hash)

Return type:

Dict[str, Tuple[bool, str | None, str | None]]


Validation

Path validation utilities for dazzle_filekit.

This module provides functions for validating path strings and objects, ensuring they meet the requirements for various file operations.

dazzle_filekit.utils.validation.is_device_path(path)[source]

Check whether a path names a device / sink rather than a real file or directory.

This is deliberately NOT the same question as is_valid_path(). /dev/null is a legal POSIX path – is_valid_path says True – yet nothing is ever stored there, so any tool that harvests paths out of shell commands, config files, or logs will want to discard it.

Recognized:
  • POSIX character devices and shell sinks (/dev/null, /dev/stdout, /dev/tty, …), see POSIX_DEVICE_PATHS

  • Kernel pseudo-filesystems (/proc/..., /sys/..., /dev/fd/N)

  • Windows reserved device names (NUL, CON, AUX, COM1, LPT1, …), with or without an extension and with or without a directory prefix – Windows resolves C:\tmp\nul to the device regardless of location, see WINDOWS_INVALID_NAMES

Both platforms’ names are recognized on BOTH platforms on purpose: a Windows host routinely reads Git-Bash/WSL commands containing 2>/dev/null, and a POSIX host may parse Windows-authored scripts. The question being answered is about the string, not about the host.

Parameters:

path (str | Path) – Path to test (str or Path)

Returns:

True if the path names a device or pseudo-filesystem entry.

Return type:

bool

Examples

>>> is_device_path('/dev/null')
True
>>> is_device_path('NUL')
True
>>> is_device_path('C:/tmp/nul.txt')
True
>>> is_device_path('/home/user/dev/null-handling')
False
dazzle_filekit.utils.validation.is_valid_path(path)[source]

Check if a path is valid on the current platform.

Parameters:

path (str | Path) – Path to validate

Returns:

True if path is valid, False otherwise

Return type:

bool

dazzle_filekit.utils.validation.is_safe_path(path, base_dir)[source]

Check if a path is safe (doesn’t escape outside its base directory).

Parameters:
  • path (str | Path) – Path to validate

  • base_dir (str | Path) – Base directory that the path should be under

Returns:

True if path is safe, False otherwise

Return type:

bool

dazzle_filekit.utils.validation.validate_path_chars(path)[source]

Validate characters in a path and return any errors.

Parameters:

path (str | Path) – Path to validate

Returns:

List of error messages (empty if path is valid)

Return type:

List[str]

dazzle_filekit.utils.validation.is_absolute_path(path)[source]

Check if a path is absolute.

Parameters:

path (str | Path) – Path to check

Returns:

True if the path is absolute, False otherwise

Return type:

bool

dazzle_filekit.utils.validation.is_relative_path(path)[source]

Check if a path is relative.

Parameters:

path (str | Path) – Path to check

Returns:

True if the path is relative, False otherwise

Return type:

bool

dazzle_filekit.utils.validation.is_unc_path(path)[source]

Check if a path is a UNC (\\server\share) path.

Thin convenience WRAPPER over the canonical owner unctools.is_unc_path (UNC detection is path-identity = L0’s domain). Kept public only for convenience; may be deprecated in 0.4.0 – prefer unctools.is_unc_path. 0.3.0 collapsed this and paths.is_unc_path onto the single delegate (they previously diverged on POSIX: this returned //-prefix True; paths returned False).

Parameters:

path (str | Path)

Return type:

bool

dazzle_filekit.utils.validation.is_hidden_path(path)[source]

Check if a path is hidden.

Parameters:

path (str | Path) – Path to check

Returns:

True if the path is hidden, False otherwise

Return type:

bool

Check if a path is a symbolic link.

Parameters:

path (str | Path) – Path to check

Returns:

True if the path is a symbolic link, False otherwise

Return type:

bool

dazzle_filekit.utils.validation.is_junction(path)[source]

Check if a path is a Windows junction point (NOT a symlink).

This is the distinction that matters for safe deletion and tree traversal: junctions and symlinks both have the reparse-point attribute set, but they have different reparse tags (IO_REPARSE_TAG_MOUNT_POINT vs IO_REPARSE_TAG_SYMLINK) and different cross-platform semantics.

Implementation: on Python 3.12+ this is os.path.isjunction (the same mount-point reparse-tag check, answered from a single lstat – no handle open). On older Pythons it uses DeviceIoControl(FSCTL_GET_REPARSE_POINT) to read the reparse tag and check it’s specifically IO_REPARSE_TAG_MOUNT_POINT. Both methods are reliable; the ctypes path is the only option before 3.12.

History: in filekit <= v0.2.3, this function referenced win32file.FILE_ATTRIBUTE_REPARSE_POINT (which doesn’t exist – the constant lives in win32con), and the bare except: clause silently returned False for everything, including real junctions. Additionally, even if the attribute check had worked, it would have misclassified directory symlinks as junctions since they share the same FILE_ATTRIBUTE_REPARSE_POINT flag. Fixed in v0.2.4 by porting the correct implementation from dazzlecmd/projects/core/links/links.py:_is_junction_win.

Parameters:

path (str | Path) – Path to check

Returns:

True if the path is specifically a junction (mount-point reparse point), False otherwise. Returns False for symlinks, plain directories, files, and nonexistent paths.

Return type:

bool

dazzle_filekit.utils.validation.read_junction_target(path)[source]

Return the target of a Windows junction, or None.

Reads the junction’s reparse point with DeviceIoControl(FSCTL_GET_REPARSE_POINT) and decodes the MountPointReparseBuffer PrintName (falling back to SubstituteName with its \??\ prefix stripped). This is the clean, no-subprocess replacement for parsing cmd /c dir /al output.

Returns None on non-Windows, for non-junctions, or on any error.

Parameters:

path (str | Path)

Return type:

str | None

dazzle_filekit.utils.validation.SILENT_ESCAPE_ORIGINS = {'\x00': '0', '\x07': 'a', '\x08': 'b', '\t': 't', '\n': 'n', '\x0b': 'v', '\x0c': 'f', '\r': 'r'}

The eight escape sequences Python resolves SILENTLY in a non-raw string. "C:\temp" in source is C: + TAB + emp by the time any library sees it – the backslash is already gone. Everything else either passes through intact (\d, \p, …) or raises SyntaxError loudly.

dazzle_filekit.utils.validation.ensure_path_collection(value, param='paths')[source]

Reject a single path where a collection of paths is expected.

A str is iterable, so passing one to a List[path] parameter is not a TypeError – it is consumed one CHARACTER at a time. Any realistic path contains a separator, Path("/") is the drive root, and with recursive=True that recursively globs the whole drive. The failure is not loud, it is expensive, which is worse: it looks like a slow operation rather than a mistake.

os.PathLike is included because a bare Path currently dies with “‘WindowsPath’ object is not iterable” – correct, but a long way from telling the caller to add brackets.

Parameters:

param (str)

dazzle_filekit.utils.validation.has_unescaped_backslash_damage(path)[source]

Whether path contains a control character one of the eight silent escapes produces – the fingerprint of "C:        emp" written without a raw string.

Return type:

bool

dazzle_filekit.utils.validation.suggest_reescaped_path(path)[source]

The path the caller almost certainly meant: every silent-escape control character replaced by the backslash sequence that produced it. Purely lexical; no filesystem access.

Return type:

str

dazzle_filekit.utils.validation.recover_unescaped_path(path)[source]

Return (path, recovered). Literal wins; recovery only on miss.

  1. If path exists as given, return it untouched – recovery never overrides a working interpretation.

  2. Otherwise, if it carries silent-escape damage AND the re-escaped candidate exists, return the candidate with recovered=True.

  3. Otherwise return the original unchanged.

Step 2 cannot pick a wrong path on Windows, structurally: every silent escape produces a character below 0x20, and NTFS forbids those in filenames outright – so the literal and the recovered path can never BOTH exist. (On POSIX, control characters in filenames are legal-but- bizarre; the literal-first ordering means such a file always wins.)

Public and opt-in by design: filekit itself only warns (see find_files), so the library never silently operates on a path the caller did not pass.


Cross-platform compatibility

Compatibility utilities for cross-platform operations.

This module provides utilities for handling platform-specific differences and ensuring consistent behavior across different operating systems.

dazzle_filekit.utils.compat.is_windows()[source]

Check if the current platform is Windows.

Returns:

True if Windows, False otherwise

Return type:

bool

dazzle_filekit.utils.compat.is_unix()[source]

Check if the current platform is Unix-like (Linux, macOS, etc.).

Returns:

True if Unix-like, False otherwise

Return type:

bool

dazzle_filekit.utils.compat.is_wsl()[source]

Check if the current Python process is running inside WSL.

Detection strategy:
  1. Check for WSL_DISTRO_NAME environment variable (set by WSL 2+)

  2. Fall back to scanning /proc/version for microsoft or wsl

  3. Return False on non-Linux platforms

Returns:

True if running inside WSL, False otherwise.

Return type:

bool

Examples

>>> if is_wsl():
...     print("Running in WSL -- /mnt/c/ is DrvFs")
dazzle_filekit.utils.compat.is_admin()[source]

Check if the current process has administrative privileges on Windows.

Returns:

True if admin, False otherwise

Return type:

bool

dazzle_filekit.utils.compat.is_root()[source]

Check if the current process has root privileges on Unix-like systems.

Returns:

True if root, False otherwise

Return type:

bool

dazzle_filekit.utils.compat.fix_path_separators(path)[source]

Fix path separators to match the current platform.

Parameters:

path (str) – Path string to fix

Returns:

Path string with corrected separators

Return type:

str

dazzle_filekit.utils.compat.fix_path_case(path)[source]

Fix path case for case-sensitive file systems.

This is mostly a no-op except on Windows where it can resolve the actual case of files.

Parameters:

path (str | Path) – Path to fix

Returns:

Path with correct case

Return type:

str

dazzle_filekit.utils.compat.path_exists_case_sensitive(path)[source]

Return True if path exists with the case it is stored under.

Absorbs unctools’ removed internal helper (STACK-MAP D8). On Windows (case-insensitive but case-preserving) this compares the requested path against the filesystem’s actual-case form; on case-sensitive Unix, mere existence suffices.

Parameters:

path (str | Path) – The path to check.

Returns:

True if the path exists (and, on Windows, matches the stored case).

Return type:

bool

dazzle_filekit.utils.compat.get_case_sensitive_path(path)[source]

Return path with the filesystem’s actual stored case on Windows, or unchanged on Unix / for non-existent paths.

Absorbs unctools’ removed get_case_sensitive_path (STACK-MAP D8); it is the same operation as fix_path_case(), exposed under the original name for migration parity.

Parameters:

path (str | Path) – The path to convert.

Returns:

The case-corrected path string.

Return type:

str

dazzle_filekit.utils.compat.get_system_encoding()[source]

Get the default encoding for the current system.

Returns:

String representing the system encoding

Return type:

str

dazzle_filekit.utils.compat.get_system_temp_dir()[source]

Get the system temporary directory in a cross-platform way.

Returns:

Path to the system temporary directory

Return type:

Path

dazzle_filekit.utils.compat.get_home_dir()[source]

Get the user’s home directory in a cross-platform way.

Returns:

Path to the user’s home directory

Return type:

Path

dazzle_filekit.utils.compat.get_app_data_dir(app_name)[source]

Get the application data directory in a cross-platform way.

Parameters:

app_name (str) – Name of the application

Returns:

Path to the application data directory

Return type:

Path

dazzle_filekit.utils.compat.resolve_cross_platform_path(path)[source]

Resolve a path by normalizing it and probing alternate platform formats.

First normalizes using normalize_cross_platform_path(). If the result doesn’t exist, tries alternate platform representations:

On Windows:

/mnt/c/Users/… -> C:Users... (WSL mount) /c/Users/… -> C:Users... (MSYS/Git Bash) …/mnt/c/Users/… -> C:Users... (MSYS-mangled WSL)

On Linux/macOS:

C:Users... -> /mnt/c/Users/… (WSL) C:Users... -> /c/Users/… (MSYS)

Returns the first existing candidate, or the normalized form if none exist.

Parameters:

path (str | Path) – Path string in any supported format

Returns:

Path object for the best match found

Return type:

Path

Examples

# On Windows, if C:Usersfoofile.txt exists: resolve_cross_platform_path(“/mnt/c/Users/foo/file.txt”) # -> Path(“C:/Users/foo/file.txt”)

dazzle_filekit.utils.compat.path_exists_cross_platform(path)[source]

Check if a path exists, handling cross-platform path formats.

This is useful when receiving paths from external sources (like Claude Code) that may be in a different format than the current platform expects.

Uses resolve_cross_platform_path() to try alternate platform formats if the normalized path doesn’t exist.

Parameters:

path (str | Path) – Path string in any supported format

Returns:

True if the path exists, False otherwise

Return type:

bool


Disk space

Disk space checking utilities.

This module provides utilities for checking disk space availability before performing file operations.

class dazzle_filekit.utils.disk.DiskUsage(total, used, free)[source]

Bases: NamedTuple

Disk usage statistics.

Parameters:
total: int

Alias for field number 0

used: int

Alias for field number 1

free: int

Alias for field number 2

property used_percent: float

Percentage of disk used.

property free_percent: float

Percentage of disk free.

exception dazzle_filekit.utils.disk.InsufficientSpaceError(message, required, available, path=None)[source]

Bases: Exception

Raised when destination lacks sufficient space for an operation.

Parameters:
dazzle_filekit.utils.disk.get_disk_usage(path)[source]

Get disk usage statistics for the drive/mount containing path.

If the path doesn’t exist, walks up the directory tree to find the nearest existing parent and reports its disk usage.

Parameters:

path (str | Path) – Path to check (file or directory)

Returns:

DiskUsage named tuple with total, used, and free space in bytes

Raises:

OSError – If no valid path can be found in the directory tree

Return type:

DiskUsage

dazzle_filekit.utils.disk.check_disk_space(dest_path, required_bytes, safety_margin=0.1, raise_on_insufficient=False)[source]

Check if destination has sufficient space for an operation.

Parameters:
  • dest_path (str | Path) – Destination path to check

  • required_bytes (int) – Number of bytes required

  • safety_margin (float) – Additional margin as fraction (0.1 = 10% extra)

  • raise_on_insufficient (bool) – If True, raises InsufficientSpaceError instead of returning False

Returns:

  • has_space: Boolean indicating if space is sufficient

  • required_with_margin: Required bytes including safety margin

  • available: Available bytes

  • message: Human-readable status message

Return type:

Tuple of

Raises:

InsufficientSpaceError – If raise_on_insufficient=True and space is insufficient

dazzle_filekit.utils.disk.calculate_total_size(paths, follow_symlinks=True)[source]

Calculate total size of files in the list.

For directories, calculates the total size of all files within.

Parameters:
  • paths (List[str | Path]) – List of file or directory paths

  • follow_symlinks (bool) – Whether to follow symbolic links

Returns:

Total size in bytes

Return type:

int

dazzle_filekit.utils.disk.ensure_disk_space(dest_path, source_paths, safety_margin=0.1)[source]

Ensure destination has enough space for source files.

Convenience function that combines calculate_total_size and check_disk_space.

Parameters:
  • dest_path (str | Path) – Destination path

  • source_paths (List[str | Path]) – List of source file/directory paths

  • safety_margin (float) – Additional margin as fraction (0.1 = 10% extra)

Returns:

Tuple of (has_space, message)

Return type:

Tuple[bool, str]


Portable path keys

Portable path key: one literal, runtime-neutral encoding of an absolute path.

A store that keeps copies of files elsewhere (a trash, a backup) needs to map an original absolute path to a place under its root, and back. This module gives that mapping one canonical form, the key:

Input

Key

X:\a\b

X/a/b (drive upper-cased)

\\server\share\a

UNC/server/share/a

\\?\UNC\server\share\a

UNC/server/share/a

\\?\X:\a

X/a

//server/share/a

UNC with flavor="windows"; ROOT/server/share/a otherwise

/mnt/<x>/a

X/a with flavor="wsl"; ROOT/mnt/<x>/a otherwise

other POSIX absolute /a/b

ROOT/a/b

Refused with PortablePathError: device paths (\\.\), \\?\Volume{...}, \\?\GLOBALROOT, \\server with no share, relative and drive-relative (C:foo) paths, .. that climbs above the root, NUL anywhere, and – for \\?\ paths – components that only exist because the prefix disables Windows’ name rules (trailing dot or space, reserved device names).

Rules that hold for every key:

  • Literal. No ~ or environment-variable expansion, no stripping of surrounding whitespace. (Use normalize_cross_platform_path for user input; this is for names that already exist.)

  • Lexical. . parts are dropped and .. is folded against the preceding part, without touching the filesystem; folding above the root is refused rather than clamped.

  • Never empty parts, never . or ..; parts joined with /.

  • ``flavor`` is required, because //x/y and /mnt/<x> mean different things on different runtimes, and a durable key must not depend on which Python wrote it.

key_to_relpath() is the only way a key (or any list of parts) becomes a path on disk: it refuses parts the target filesystem cannot hold.

Pure: no I/O – except current_flavor() (0.5.3), the one function that inspects the running interpreter. UNC parsing delegates to unctools.get_unc_path_elements; the \\?\ and \\.\ prefixes are recognised here first, because unctools reads them as an ordinary server named ? or ..

exception dazzle_filekit.portable.PortablePathError[source]

Bases: FileOperationError, ValueError

A path or key that cannot be expressed in, or converted from, the portable key form. The message names the part at fault.

It is a ValueError (the argument was bad) and also sits under the stack’s common root, dazzle_lib.DazzleError, through FileOperationError – so a caller can catch one root for every DazzleLib library.

dazzle_filekit.portable.encode_portable_path(path, *, flavor)[source]

Encode an absolute path as a portable key.

>>> encode_portable_path(r"C:\Users\x\a.txt", flavor="windows")
'C/Users/x/a.txt'
>>> encode_portable_path("/mnt/c/Users/x", flavor="wsl")
'C/Users/x'
>>> encode_portable_path("/mnt/d/x", flavor="posix")
'ROOT/mnt/d/x'
Raises:
Parameters:
Return type:

str

dazzle_filekit.portable.decode_portable_path(key, *, runtime)[source]

The native path a key names on runtime, or None when that runtime has no native form for it (a UNC key on POSIX, a ROOT key on Windows, a drive key on plain POSIX).

>>> decode_portable_path("C/Users/x", runtime="windows")
'C:\\Users\\x'
>>> decode_portable_path("C/Users/x", runtime="wsl")
'/mnt/c/Users/x'
Parameters:
Return type:

str | None

dazzle_filekit.portable.key_to_relpath(parts_or_key, *, target_flavor)[source]

Turn a key ("C/Users/x") or a list of parts into a relative path for target_flavor’s filesystem, refusing any part it cannot hold.

This is the only way a key or relpath should become a disk path: join the result under a store root you own.

>>> key_to_relpath("UNC/srv/share/a.txt", target_flavor="windows")
'UNC\\srv\\share\\a.txt'
>>> key_to_relpath("ROOT/home/u/a:b", target_flavor="windows")
Traceback (most recent call last):
...
dazzle_filekit.portable.PortablePathError: part 'a:b' has characters Windows cannot store (':') in 'ROOT/home/u/a:b'

Refused everywhere: empty, ., .., NUL, / inside a part. On a Windows target also: \ / : * ? " < > | and control characters, a trailing dot or space, and reserved device names (CON, NUL.txt).

Parameters:
Return type:

str


Batch layout

Lay out a batch of absolute paths under common bases, without collisions.

A tool that stages many items into one folder (a trash batch, a backup set) has to give each a distinct place there. Using the bare name fails as soon as two items share one (a/x.json and b/x.json). Using each item’s full path is safe but long. plan_batch keeps what is shared out of the stored paths: for each root (a drive, a network share, the POSIX root) it finds the common parent folder of the batch’s items – the base – and gives every item its path relative to that base. For example:

C:\Users\me\.claude\session-states\1.json
C:\Users\me\claude\context-window\1.json
  -> base   C:\Users\me
     items  .claude/session-states/1.json
            claude/context-window/1.json

A batch of one item keeps just its name. A batch that spans roots gets one base per root, and each item’s path is prefixed with its base’s number (0/..., 1/...), so the result is still one tree with no collisions.

The function is pure: it reads no disk. Whether an item is a link is asked through is_link, a function the caller supplies.

Rules (each reported, never silent):

  • exact duplicates, and on case-insensitive roots (drives, shares, WSL drives) duplicates that differ only by case, are merged – a warning;

  • an item inside another item of the batch is dropped, the ancestor carries it – a warning; but an item under a LINK is an error, because the link would be staged as a link and the item is in the link’s target;

  • a root itself (C:\, /, a share) as an item is an error;

  • two items that would still land on one relative path are an error;

  • a path with no portable form is an error (see portable).

When errors is non-empty the plan must not be executed.

Stdlib only, plus this package’s portable module.

class dazzle_filekit.batch_layout.BatchItem(original, base_index, relpath)[source]

Bases: object

One item of the batch and where it goes.

Parameters:
  • original (str)

  • base_index (int)

  • relpath (str)

original: str
base_index: int
relpath: str
class dazzle_filekit.batch_layout.BatchPlan(bases: List[Dict[str, Optional[str]]]=<factory>, items: List[dazzle_filekit.batch_layout.BatchItem] = <factory>, warnings: List[str] = <factory>, errors: List[str] = <factory>, dropped: List[Dict[str, str]]=<factory>)[source]

Bases: object

Parameters:
bases: List[Dict[str, str | None]]
items: List[BatchItem]
warnings: List[str]
errors: List[str]
dropped: List[Dict[str, str]]
property ok: bool

True when the plan may be executed.

dazzle_filekit.batch_layout.plan_batch(paths, *, flavor, is_link=None, drop_nested=True, target_flavor=None)[source]

Plan where each of paths goes in one batch.

Parameters:
  • paths (Sequence[str | PathLike[str]]) – absolute paths, in flavor’s form.

  • flavor (str) – "windows", "wsl" or "posix" – how to read them.

  • is_link (Callable[[str], bool] | None) – optional path -> bool; True for an item that is a link (symlink, junction). Only used for the nesting rule.

  • drop_nested (bool) – drop an item that is inside another item (default). With False such a pair is an error instead.

  • target_flavor (str | None) – the filesystem the relative paths will be created on (default: flavor); they are validated for it.

Returns:

A BatchPlan. Check plan.ok before using plan.items.

Return type:

BatchPlan

>>> p = plan_batch([r"C:\a\x.json", r"C:\b\x.json"], flavor="windows")
>>> [(i.relpath) for i in p.items], p.bases[0]["native"]
(['a/x.json', 'b/x.json'], 'C:\\')

Exclusive lock

An exclusive lock on one dedicated lock file, on every OS.

exclusive_lock(path, timeout=5.0) holds an exclusive lock on path for the length of a with block. path must be a dedicated lock file – never the data file the lock protects: on Windows the lock is a mandatory byte-range lock (byte 0 becomes unreadable through other handles), on POSIX an advisory flock. The file is created if missing and may stay empty.

Acquiring never blocks indefinitely: it retries a non-blocking attempt until timeout seconds have passed, then raises LockTimeoutError naming the file. (Windows’ own blocking mode, LK_LOCK, gives up after about ten seconds with an error, so it is not used.) The lock is released when the block ends, and by the operating system when the holder’s process dies – measured on Windows: a holder killed with taskkill /f freed the lock for the next process at its first attempt, under 0.09 s.

Added in 0.5.3 (first consumer: dz relaunch’s store; csb’s lock is the next candidate).

exception dazzle_filekit.locking.LockTimeoutError[source]

Bases: FileOperationError, TimeoutError

The lock file stayed locked by another holder until the deadline.

dazzle_filekit.locking.exclusive_lock(path, *, timeout=5.0, poll=0.02, clock=time.monotonic, sleep=time.sleep)[source]

Hold an exclusive lock on the dedicated lock file path.

Yields the open descriptor (callers normally ignore it). Raises LockTimeoutError if the lock is still held elsewhere after timeout seconds; timeout=0 means a single attempt.

Parameters:
Return type:

Iterator[int]

dazzle_filekit.locking.try_lock(fd)[source]

One non-blocking attempt on an open lock-file descriptor. True if taken.

Parameters:

fd (int)

Return type:

bool

dazzle_filekit.locking.unlock(fd)[source]

Release a lock taken by try_lock() (closing the descriptor also does).

Parameters:

fd (int)

Return type:

None