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
.tmpsuffix, 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_MAXalike.
- 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
Truewhen path is long enough to break a MAX_PATH consumer.Returns
Falseon non-Windows platforms, andFalsefor a path that already carries an extended-length prefix (such a path has opted out of the limit and rewriting it would be pointless).
- 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.
- dazzle_filekit.longpath.resolve_shim_root(target=None, candidates=None, probe=True)[source]¶
Return the shortest writable shim root, or
Noneif none is usable.With
probe=Falsethe first candidate is returned unchecked, which is what tests want when they are exercising the ordering rather than the filesystem.
- dazzle_filekit.longpath.budget_for(root, id_len=_ID_LEN)[source]¶
Longest filename a shim under root can serve.
<root>\<id>\<filename>must fit inUSABLE_PATH.
- class dazzle_filekit.longpath.ShimPlan(original, needed, anchor=None, link=None, shimmed=None, reason='', warnings=<factory>)[source]¶
Bases:
objectWhat (if anything) must exist for original to be openable.
- Parameters:
- 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.
- 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
linkandshimmedare updated to whatever was actually used, so a caller that readsplan.shimmedafterwards is never handed a path the collision loop moved away from.
- 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.rmdirdeletes 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 byos.path.islink,os.path.isdirandDirEntry.is_symlink, so a recursive shell delete will happily walk into the real data.
- 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.
- 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 toos.path.isjunctionand the failure arrives asValueError, while on 3.9-3.11 it falls back to a ctypesDeviceIoControlcall and the same condition arrives asctypes.ArgumentError, which derives fromExceptionand not fromValueError. 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.
Links¶
Intrinsic link primitives (L1).
This module answers the intrinsic question about a single filesystem object:
“what is this link, by looking only at it?” – its kind, its raw and resolved
target, whether it is broken, and whether it is a direct self-reference. It also
creates the three link kinds (symlink lives in operations; junctions and
hardlinks live here).
It deliberately does NOT answer relational questions (“is this link’s target inside some destination root?”, “what should we do with it during a move?”). Those depend on a second path and a policy – they are L3 (preservelib) concerns. See the dazzle-filekit #15 completion design.
Provenance: the detection/creation logic is ported from
preserve/preservelib/links.py (detect_link_type, get_link_target,
analyze_link, _create_junction, _create_hard_link), with three
changes that improve coverage/correctness without losing a code-path:
junction detection uses filekit’s
utils.validation.is_junction()(DeviceIoControl reparse-tag) instead of preservelib’s attribute-only check, which misclassified directory symlinks as junctions;junction target reading and creation use the DeviceIoControl reparse buffer and PowerShell
New-Itemrespectively, replacing preservelib’s bannedcmd /c dir /alandcmd /c mklink /jshell-outs;a hardlink (detected via
st_nlink > 1) is reported as a valid link with no traversable target – it is NOT markedis_broken(preservelib’sanalyze_linkmarked it broken becauseget_link_targetreturns None).
- class dazzle_filekit.links.LinkInfo(link_path, kind=None, raw_target=None, resolved_target=None, is_broken=False, is_circular=False, metadata=<factory>)[source]¶
Bases:
objectIntrinsic facts about a single link (no destination relationship).
- Variables:
link_path (pathlib.Path) – the link itself.
kind (str | None) –
'symlink'|'junction'|'hardlink'|None(not a link).raw_target (str | None) – target as stored in the link (readlink result for symlinks, the reparse PrintName for junctions).
Nonefor hardlinks (which have no single target) and for non-links.resolved_target (pathlib.Path | None) – absolute target after resolution (
Nonewhen there is no resolvable target).is_broken (bool) – a symlink/junction whose target cannot be read or does not exist. A hardlink is never broken.
is_circular (bool) – direct self-reference only – the resolved target IS the link’s own path. Chain-cycle detection requires walking the chain and is a traversal (L3 / dazzletreelib) concern, intentionally not done here.
metadata (Dict[str, Any]) – free-form extra context for callers.
- Parameters:
- to_dict()[source]¶
Serialize to the cross-layer LinkTargetDict (STACK-MAP D10).
link_pathis intentionally NOT in the dict: LinkTargetDict describes the link’s TARGET, and a caller already knows which link it analyzed. Readself.link_pathon the object when you need the link’s own path.- Return type:
LinkTargetDict
- dazzle_filekit.links.detect_link_type(path)[source]¶
Detect what kind of link
pathis, orNoneif it is not a link.Returns
'symlink','junction'(Windows), or'hardlink'(a file whosest_nlink > 1). Hard links are otherwise indistinguishable from regular files, so a single-name file is reported asNone.Existence is checked with
os.lstat(the link ITSELF), notPath.exists()(which follows the link): a junction whose target is missing is still a junction and must be reported as one, soanalyze_linkcan mark it broken. The previousexists()gate special-cased broken symlinks but silently dropped broken junctions (contributed from dazzlesum, whose walker must refuse to traverse broken junctions rather than treat them as plain directories).
- dazzle_filekit.links.read_link_target(path)[source]¶
Return the raw target of a symlink or junction, or
None.Symlinks use
os.readlink(); junctions read the reparse buffer viautils.validation.read_junction_target(). Hardlinks and non-links returnNone(a hardlink has no distinct target). On Windows the\\?\extended-length prefix is stripped so the target is canonical.
- dazzle_filekit.links.analyze_link(link_path)[source]¶
Analyze a single link intrinsically (no destination relationship).
See
LinkInfofor the meaning of each field. This never takes a destination path – relational analysis belongs at L3.
- dazzle_filekit.links.create_junction(target, link, force=False)[source]¶
Create a Windows NTFS junction at
linkpointing totarget.Uses PowerShell
New-Item -ItemType Junction(per the house rule that junctions/symlinks are created via PowerShell, nevercmd /c mklink). Junctions are directory-only and Windows-only.Returns True on success, False otherwise.
- dazzle_filekit.links.create_junction_raw(target, link, force=False)[source]¶
Create an NTFS junction by writing the mount-point reparse buffer directly (
FSCTL_SET_REPARSE_POINT), no subprocess.Differences from
create_junction()(PowerShellNew-Item):The target does NOT need to exist –
New-Itemrefuses a missing target, which makes intentionally-broken junctions impossible to recreate when mirroring a tree.The target string is stored VERBATIM:
\\?\C:\x(as returned byos.readlinkon another junction) and plainC:\xare both accepted; the NT-namespace SubstituteName (\??\...) and the user-facing PrintName are derived without other normalization, soos.readlinkround-trips byte-identically.
Unprivileged (junctions never require SeCreateSymbolicLinkPrivilege). Windows-only, directory-only. Returns True on success.
- dazzle_filekit.links.create_hardlink(target, link, force=False)[source]¶
Create a hard link at
linkpointing to the filetarget.Hard links are file-only and cannot cross filesystem boundaries. Returns True on success, False otherwise.
- dazzle_filekit.links.remove_link(path)[source]¶
Remove (detach) a symlink, junction, or hard link WITHOUT deleting its target.
The inverse of
create_junction()/create_hardlink()/create_symlink():a junction is detached with
os.rmdir– the reparse point is removed, the target directory tree is left untouched;a directory symlink (Windows) is likewise removed with
os.rmdir; a file symlink withunlink– the target file stays;a hard link is removed with
unlink, which only decrements the file’s link count (the data survives while another name remains).
Returns True on success, False if
pathis not a link or removal fails (the reason is logged). Ported from preservelib (R7); the conservation verdict returned this intrinsic link primitive to its L1 home.
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=Truefor link-following normalization, or use the defaultresolve=Falsefor 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 viaos.path.normpath(does not follow symlinks), and absolutizes via cwd join. Preserves the literal link path.resolve=True: callsPath.resolve()which follows symlinks and junctions to their target (POSIXrealpathsemantics). Falls back to.absolute()for paths that don’t exist.
- Parameters:
- Returns:
The normalized path as a Path object.
- Return type:
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.
- 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.
- 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 importingunctools.is_unc_pathdirectly.Behaviour (from the owner): normalizes
/->\then checks the\\prefix, so//server/shareis recognized on every platform. 0.3.0 collapsed filekit’s two previously-divergent copies (win32-only here, POSIX-//inutils.validation) onto this single delegate.
- dazzle_filekit.paths.get_relative_path(path, base_path, allow_cross_drive=True)[source]¶
Get the relative path from base_path to path.
- dazzle_filekit.paths.compute_relative_path(target, start, fallback_to_absolute=True)[source]¶
Compute the relative path FROM
startTOtargetvia 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 fromget_relative_path(), which usesPath.relative_toand only succeeds whentargetis a subpath ofstart(returning None for siblings). For example, with target/a/b/cand start/a/x:compute_relative_path->"../b/c"get_relative_path->None(not a subpath)
- Parameters:
- 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:
- Returns:
Destination path as a Path object
- Return type:
- 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:
- Returns:
List of matching file paths
- Return type:
- 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.
- 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:
- Returns:
List of matching file paths
- Return type:
- dazzle_filekit.paths.create_parent_dirs(path)[source]¶
Create parent directories for a path if they don’t exist.
- dazzle_filekit.paths.ensure_unique_path(path)[source]¶
Ensure a path is unique by appending a number if necessary.
- dazzle_filekit.paths.classify_fs_object(path)[source]¶
Classify WHAT kind of filesystem object a path is.
(Renamed from
get_path_typein 0.3.0 – #15 Phase C. The L1 name classifies the OBJECT; unctools’ siblingclassify_path_originclassifies WHERE a path’s name comes from. Behavior is unchanged: a junction still reports'directory'– uselinks.analyze_linkfor link-kind classification.)
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:
- 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’sos.pathsep– a Windows registry value parsed on a POSIX runner still splits on;.
- 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 forREG_EXPAND_SZ(viantpathexplicitly, 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.expandvarsALSO 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.
- dazzle_filekit.pathenv.path_value_contains(value, directory, platform=None)[source]¶
True if
directoryis amongvalue’s entries.Membership by normalized identity: quotes and trailing separators ignored,
%VAR%entries expanded, case-insensitive under the windows dialect.
- dazzle_filekit.pathenv.append_path_value(value, directory, platform=None)[source]¶
Return
valuewithdirectoryappended, if not already present.Pure string construction: no-op (returns
valueunchanged) when the directory is already a member under normalized identity; an emptyvalueyieldsdirectoryalone. The caller persists the result wherever it belongs (registry, rc file, environment) – this module never does I/O.
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_textwithnew_textinfile_path.Reads via the fallback-aware
open_file()and writes viaatomic_write_text()(so a crash mid-write cannot truncate the file). Returns True if the file was modified, False ifold_textwas not present (logged as a warning) or on error.
- 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 matchingpatternunderdirectory(viaprocess_files()).Returns
{str(path): modified?}(False for unmatched / errored files).
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
contentto a sibling.tmpfile and then renames it topathviaos.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:
- Raises:
OSError – If the write or rename fails. The
.tmpfile is left in place for inspection.- Return type:
None
Pattern source:
safedel/_store.py:_save_manifestandsafedel/_volumes.py:save_registryboth 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
dataas JSON topath.Thin wrapper around
atomic_write_text(path, json.dumps(...)). The defaultdefault=strhandles common non-JSON-native types (datetime,Path,pathlib.PurePath, etc.) by stringifying them – matches safedel’s_save_manifestbehavior.- Parameters:
data (Any) – The object to serialize. Must be JSON-compatible or have a string representation if non-native types are present.
indent (int) –
json.dumpsindent (keyword-only, default 2).sort_keys (bool) –
json.dumpssort_keys (keyword-only, default False).default (Callable[[Any], Any] | None) – Fallback serializer for non-JSON types (keyword-only, default
str). Set toNoneto getTypeErroron unknown types instead.trailing_newline (bool) – Append a trailing newline (keyword-only, default True, matching POSIX text file convention).
- Raises:
- 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:
objectStreaming counterpart of
atomic_write_text().For content too large – or too incremental – to build in memory: writes go to a sibling
.tmpfile, and on successful close the tmp is renamed overpathviaos.replace. Readers observingpathsee either the old contents or the complete new contents, never a partial write. On failure (an exception inside thewithblock, or an explicitclose(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 ofpath(shutil.copy2) and open it in append mode – for resuming an interrupted long-running write. Whenpathdoes not exist this degrades to a normal fresh write.fsync_on_flush: make eachflush()alsoos.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 toopen(), with the same defaults asatomic_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 isatomic_write_text().- Parameters:
- dazzle_filekit.operations.copy_tree_preserving_links(src, dst, *, dirs_exist_ok=False, ignore=None, ignore_dangling_symlinks=False, links='keep')[source]¶
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 insidesrcwas followed. From 0.5.0 the default really keeps junctions; passlinks="follow"for a copy of the contents.A junction that cannot be recreated under
"keep"raisesshutil.Errorafter the rest of the tree is copied, so a caller that removessrcafter a successful copy never does so on a partial one.srcitself is always entered, link or not.- Parameters:
dirs_exist_ok (bool) – If True, allow
dstto exist (keyword-only, default False – matches shutil.copytree’s default).ignore (Callable[[...], Any] | None) – Callable
(dir, contents) -> names_to_skippassed toshutil.copytree(keyword-only).ignore_dangling_symlinks (bool) – If True, skip symlinks whose target is missing (keyword-only, default False – by default
copytreeraises on dangling links).links (str)
- Returns:
The destination Path.
- Return type:
Pattern source:
safedel/_recover.py:338and other safedel call sites all usedshutil.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:
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:
- 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:
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:
- 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(): withtry_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 fromresolver(default: the unctools-backed resolver), re-raising the original error if every variant fails. This is the file-handle counterpart ofcopy_file(try_path_variants=True)and reproduces the oldunctools.safe_opencapability (STACK-MAP D7).mode,encodingand any extra**kwargsare forwarded to the built-inopen; the return value is the file object. Off by default, soopen_file(path)behaves exactly likeopen(path).
- 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_metadatawhich 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.metadatadirectly for access tocompare_metadata,metadata_to_json, etc.
- 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_metadatawhich honors all the richer fields when present:Windows: SDDL ACL restoration via
ConvertStringSecurityDescriptorToSecurityDescriptorW; creation time restoration viaSetFileTime+FILE_WRITE_ATTRIBUTESLinux/macOS: extended attributes via
os.setxattr, withcom.apple.quarantineskipped on restore
Old (v0.2.3) manifests without the new fields restore correctly – each advanced field is optional.
- 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:
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:
- 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:
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:
- dazzle_filekit.operations.process_files(directory, callback, pattern='*', recursive=True, *, try_path_variants=False, resolver=None)[source]¶
Apply
callbackto every file underdirectorymatchingpattern.The flat batch-apply primitive – the L1 home of the old
unctools.process_files: globsdirectoryforpattern(recursive by default), callscallback(Path)on each file, and returns{str(path): result}. Per-file exceptions are swallowed (logged, result recorded asNone) 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:
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
directorydoes not exist under the given name, retry under the variant names fromresolver(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:
- dazzle_filekit.operations.create_directory_structure(dest_path, directory_paths)[source]¶
Create a directory structure at destination path.
- dazzle_filekit.operations.remove_directory(path, recursive=False, force=False)[source]¶
Remove a directory.
- dazzle_filekit.operations.create_symlink(target, link, force=False, target_is_directory=None)[source]¶
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:
- Returns:
True if symlink was created successfully, False otherwise
- Return type:
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.
- dazzle_filekit.metadata.is_win32_available()[source]¶
Check if pywin32 is available for ctime restoration.
- Return type:
- 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.
- dazzle_filekit.metadata.compare_metadata(metadata1, metadata2)[source]¶
Compare two metadata dictionaries and return differences.
- dazzle_filekit.metadata.get_metadata_summary(metadata)[source]¶
Get a human-readable summary of file metadata.
- dazzle_filekit.metadata.metadata_to_json(metadata)[source]¶
Convert metadata to a JSON-serializable format.
- dazzle_filekit.metadata.collect_timestamp_info(path)[source]¶
Collect timestamp information from a file.
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:
- Returns:
Dictionary mapping algorithm names to hash values
- Return type:
- 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*sumfamily,shasum,md5) and returns the first runnable one, or None if none work. Results are cached per algorithm for the life of the process (passuse_cache=Falseto re-probe).
- 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:
algorithm (str) – Hash algorithm name (
md5/sha1/sha256/sha512).tool (str | None) – Tool to use (
fsum/certutil/sha256sum/…/shasum); auto-detected viadetect_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:
- Returns:
Tuple of (overall_success, details) where details is a dictionary mapping algorithm names to tuples of (success, expected_hash, actual_hash)
- Return type:
- dazzle_filekit.verification.verify_files_with_manifest(files, algorithm='SHA256')[source]¶
Verify a set of files against provided hashes.
- dazzle_filekit.verification.calculate_directory_hashes(directory, pattern='*', recursive=True, algorithm='SHA256')[source]¶
Calculate hashes for all files in a directory.
- dazzle_filekit.verification.save_hashes_to_file(hashes, output_file, include_header=True)[source]¶
Save a dictionary of file hashes to a text file.
- dazzle_filekit.verification.load_hashes_from_file(hash_file)[source]¶
Load file hashes from a text file.
- dazzle_filekit.verification.compare_directories(dir1, dir2, algorithm='SHA256', recursive=True)[source]¶
Compare the contents of two directories by hashing files.
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/nullis a legal POSIX path –is_valid_pathsays 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, …), seePOSIX_DEVICE_PATHSKernel 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 resolvesC:\tmp\nulto the device regardless of location, seeWINDOWS_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:
- Returns:
True if the path names a device or pseudo-filesystem entry.
- Return type:
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.
- dazzle_filekit.utils.validation.is_safe_path(path, base_dir)[source]¶
Check if a path is safe (doesn’t escape outside its base directory).
- dazzle_filekit.utils.validation.validate_path_chars(path)[source]¶
Validate characters in a path and return any errors.
- 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 – preferunctools.is_unc_path. 0.3.0 collapsed this andpaths.is_unc_pathonto the single delegate (they previously diverged on POSIX: this returned//-prefix True;pathsreturned False).
Check if a path is hidden.
- 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_POINTvsIO_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 usesDeviceIoControl(FSCTL_GET_REPARSE_POINT)to read the reparse tag and check it’s specificallyIO_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 inwin32con), and the bareexcept: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 sameFILE_ATTRIBUTE_REPARSE_POINTflag. Fixed in v0.2.4 by porting the correct implementation fromdazzlecmd/projects/core/links/links.py:_is_junction_win.
- 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 theMountPointReparseBufferPrintName (falling back to SubstituteName with its\??\prefix stripped). This is the clean, no-subprocess replacement for parsingcmd /c dir /aloutput.Returns None on non-Windows, for non-junctions, or on any error.
- 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 isC:+ TAB +empby 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
stris iterable, so passing one to aList[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 withrecursive=Truethat 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.PathLikeis included because a barePathcurrently 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
pathcontains a control character one of the eight silent escapes produces – the fingerprint of"C: emp"written without a raw string.- Return type:
- 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:
- dazzle_filekit.utils.validation.recover_unescaped_path(path)[source]¶
Return
(path, recovered). Literal wins; recovery only on miss.If
pathexists as given, return it untouched – recovery never overrides a working interpretation.Otherwise, if it carries silent-escape damage AND the re-escaped candidate exists, return the candidate with
recovered=True.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:
- 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:
- dazzle_filekit.utils.compat.is_wsl()[source]¶
Check if the current Python process is running inside WSL.
- Detection strategy:
Check for
WSL_DISTRO_NAMEenvironment variable (set by WSL 2+)Fall back to scanning
/proc/versionformicrosoftorwslReturn False on non-Linux platforms
- Returns:
True if running inside WSL, False otherwise.
- Return type:
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:
- 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:
- dazzle_filekit.utils.compat.fix_path_separators(path)[source]¶
Fix path separators to match the current platform.
- 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.
- dazzle_filekit.utils.compat.path_exists_case_sensitive(path)[source]¶
Return True if
pathexists 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.
- dazzle_filekit.utils.compat.get_case_sensitive_path(path)[source]¶
Return
pathwith 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 asfix_path_case(), exposed under the original name for migration parity.
- dazzle_filekit.utils.compat.get_system_encoding()[source]¶
Get the default encoding for the current system.
- Returns:
String representing the system encoding
- Return type:
- 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:
- 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:
- dazzle_filekit.utils.compat.get_app_data_dir(app_name)[source]¶
Get the application data directory in a cross-platform way.
- 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:
- Returns:
Path object for the best match found
- Return type:
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.
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:
NamedTupleDisk usage statistics.
- exception dazzle_filekit.utils.disk.InsufficientSpaceError(message, required, available, path=None)[source]¶
Bases:
ExceptionRaised when destination lacks sufficient space for an operation.
- 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.
- 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:
- 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.
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 |
|---|---|
|
|
|
|
|
|
|
|
|
UNC with |
|
|
other POSIX absolute |
|
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. (Usenormalize_cross_platform_pathfor 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/yand/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,ValueErrorA 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, throughFileOperationError– 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:
PortablePathError – the path has no portable form (see module docs).
ValueError –
flavoris not one ofFLAVORS.
- Parameters:
- Return type:
- dazzle_filekit.portable.decode_portable_path(key, *, runtime)[source]¶
The native path a key names on
runtime, orNonewhen that runtime has no native form for it (a UNC key on POSIX, aROOTkey 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'
- 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 fortarget_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).
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:
objectOne item of the batch and where it goes.
- 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:
- dazzle_filekit.batch_layout.plan_batch(paths, *, flavor, is_link=None, drop_nested=True, target_flavor=None)[source]¶
Plan where each of
pathsgoes 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. Checkplan.okbefore usingplan.items.- Return type:
>>> 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,TimeoutErrorThe 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
LockTimeoutErrorif the lock is still held elsewhere aftertimeoutseconds;timeout=0means a single attempt.
- dazzle_filekit.locking.try_lock(fd)[source]¶
One non-blocking attempt on an open lock-file descriptor. True if taken.
- dazzle_filekit.locking.unlock(fd)[source]¶
Release a lock taken by
try_lock()(closing the descriptor also does).- Parameters:
fd (int)
- Return type:
None