Changelog¶
All notable changes to dazzle-filekit will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
[0.5.4] - 2026-11-23¶
Fixed¶
copy_tree_preserving_linksno longer crashes on a reparse point it cannot read. Whenis_junctioncannot read an entry’s reparse tag it answers “junction”, so the copy holds the entry back and later recreates it fromos.readlink. For a WSL symlink, an app execution alias or a cloud placeholder that raisesValueError, which escaped mid-copy and left later junctions in the tree unrecreated. The entry is now listed in theshutil.Errorraised at the end, like any junction that could not be recreated (“not a junction or symlink; its target cannot be read”); the rest of the tree is copied.
Tests¶
tests/test_copy_tree_foreign_reparse.py(1; fails on 0.5.3).
[0.5.3] - 2026-11-19¶
Added¶
exclusive_lock(path, timeout=5.0)– an exclusive lock on one dedicated lock file, on every OS (dazzle_filekit.locking). A context manager over Windowsmsvcrt.locking(byte 0, non-blocking) and POSIXflock. It retries until the deadline and then raisesLockTimeoutErrornaming the file, rather than waiting without limit; the lock is released when the block ends and by the operating system when the holder dies.pathmust be a lock file of its own, never the data it protects: on Windows the lock is mandatory and would make that byte unreadable to other handles.try_lockandunlockexpose the single non-blocking attempt for callers that manage the descriptor themselves.current_flavor()indazzle_filekit.portable:"windows","wsl"or"posix"for the running interpreter, so a store can record which flavor its portable keys were written in. It is the one function inportablethat looks at the runtime;encode_portable_pathanddecode_portable_pathstill requireflavorandruntimeexplicitly.
[0.5.2] - 2026-11-19¶
Fixed¶
create_dest_path(path_style="absolute")returned a destination outsidedest_basefor a UNC source (\\server\share\..., and\\?\UNC\...). A UNC path has no drive letter, and joining it ontodest_basegave back the source path itself. UNC sources now go through the portable key and land atdest_base\UNC\server\share\.... Drive-letter sources keep exactly the layout they had, so no existing destination moves. (#19)
[0.5.1] - 2026-11-18¶
Two fixes found by reviewing 0.5.0 against the rest of the DazzleLib stack, before 0.5.0 was published.
Fixed¶
import dazzle_filekitfailed whenunctoolscould not be imported. The docs promise the package loads without it, and it did through 0.4.3; 0.5.0’s newportablemodule importedunctoolsat module top. The import now happens only when a UNC path is actually encoded. Drive and POSIX paths need nounctoolsat all. A test now pins the promise, which nothing did before.normalize_cross_platform_pathturned\\?\UNC\server\share\xinto a path under the current folder. Only\\?\was stripped, leavingUNC\server\share\x, which is relative. The extended-length network form is now unwrapped to\\server\share\x, with either slash and in any letter case. This predates 0.5.0; it matters more now thatexpand=Falseinvites callers to pass paths through literally.
Changed¶
PortablePathErrornow also derives fromdazzle_lib’sFileOperationError, so it sits under the stack’s common rootDazzleError. It is still aValueError.docs/api-stability.md: two tables still describedcopy_tree_preserving_linksas ashutil.copytree(symlinks=True)wrapper.
[0.5.0] - 2026-11-18¶
A portable name for any absolute path, a planner that lays out a batch of paths without collisions, and a tree copy that really keeps junctions.
Added¶
dazzle_filekit.portable–encode_portable_path(path, *, flavor)turns an absolute path into a/-joined key whose first part names the root: a drive letter (C),UNC/<server>/<share>, orROOT.flavoris required, because the same text means different things on different systems:/mnt/d/xis drive D under WSL and an ordinary folder on plain Linux.decode_portable_path(key, *, runtime)goes back, returningNonewhere the root has no native form.key_to_relpathjoins parts into a relative path that cannot climb out of its folder and can exist on the target system. Nothing is expanded, resolved, or looked up on disk; a path with no portable form (a device path, a drive-relative path,..above the root) raisesPortablePathError.dazzle_filekit.batch_layout.plan_batch– given a list of absolute paths, returns where each would sit under a shared folder so that no two collide: one base per root (the items’ common parent), a/-joined relative path per item, and a numbered prefix when the batch spans more than one root. Duplicates are merged, an item inside another item is dropped with a warning (or reported as an error, the caller’s choice), and anything that cannot be placed is listed as an error in the returned plan instead of raising.normalize_cross_platform_path(..., expand=False)takes the path literally: no whitespace strip, no~, no environment variables. For paths a program received as arguments, where the shell has already expanded what the user meant to expand and a remaining~names a real folder.copy_tree_preserving_links(..., links="keep" | "follow" | "skip")– the caller chooses what happens to symlinks and junctions inside the tree.
Fixed¶
copy_tree_preserving_linksentered junctions and copied their targets, despite its name and docstring. It wasshutil.copytree(symlinks=True), which keeps symlinks but treats a junction as a folder. With the defaultlinks="keep"a junction is now recreated at the destination as a junction with the same target, and nothing behind it is read. If one cannot be recreated the copy raisesshutil.Error, so a caller that removes the source after a successful copy does not do so on a partial one. This changes the result for trees that contain junctions; passlinks="follow"to copy the contents as before.
[0.4.3] - 2026-07-31¶
Documentation release. No packaged behaviour changes; the only source edit is a one-word docstring correction.
Added¶
The rendered docs site is now live at https://dazzle-filekit.readthedocs.io/, and both
README.mdanddocs/README.mdpoint at it. Nothing in the repo previously did, so a reader had no way to discover it existed.Read the Docs site – Sphinx + MyST + autodoc, published from the existing Markdown so one source serves both GitHub and the rendered site. Adds
docs/conf.py,.readthedocs.yaml(ubuntu-24.04 / py3.12 /fail_on_warning/ PDF + ePub),docs/requirements.txt, a landing page carrying the DazzleLib stack diagram and a “which path function do I want?” flowchart, anddocs/autoapi.mdgenerating 136 signatures from the package’s own docstrings.sphinx.ext.viewcoderenders 111[source]links – chosen overlinkcodebecause this config builds PDF/ePub, where GitHub links would be dead text.docs/recipes.md– task-shaped examples showing the combinations you actually reach for rather than isolated snippets. Example coverage of the public API rose from 26/85 callables to 55/85.A
docsjob in CI. Read the Docs builds on push, after merge – too late to protect a pull request. This job runs the same build with the same-W, so a dead cross-reference fails PR checks. It alsopip install ., which doubles as a check that filekit imports cleanly on Linux with no Windows extras present.Four executable documentation probes under
tests/one-offs/: 81 documentation claims now run against a real temporary tree rather than being trusted as prose.
Fixed¶
README.md:find_files("/directory", ...)did not fail – it hung.search_pathsis aList; a string is iterated character by character, andPath("/")is the drive root, so withrecursive=Truethe default the documented example attempted to walk the entire filesystem. Corrected to the list form. (The guard that now rejects this shipped in 0.4.2, from #16.)README.md: the entire File Verification example raisedTypeErroron both lines.calculate_file_hashtakesalgorithms(a list) and returns a dict;verify_file_hashtakes a dict of expected hashes and returns a tuple. The docs described a string-in/string-out API that never existed.docs/api-reference.mdcoverage went from 66% to 100% (98/98 public symbols). Two entire shipped modules had no entry:content(v0.3.0) andpathenv(v0.3.3). Also corrects thecalculate_file_hash/verify_file_hashsignatures, records thatcalculate_file_hash_nativereturnsNonerather than falling back on the caller’s behalf, and documents thatcalculate_directory_hasheskeys are relative whileverify_files_with_manifestresolves them against the cwd – verify from elsewhere and every file reports failed with an actual hash ofNone, meaning “not found” rather than “changed”.BREAKING_CHANGES.mdnever recorded v0.3.0, the project’s only clean break. A reader following that file’s own instruction to “read top-to-bottom and apply each migration in order” would have migrated nothing. The full 0.3.0 migration table is restored, with 0.4.x marked additive.docs/preservelib-integration.mdadvised pinning>=0.3.0,<0.4on the reasoning that “a future 0.4.0 may break again”. It did not – 0.4.0 was additive-only – and that cap excluded every current release.docs/platform-support.mdquoted “Test Counts (v0.2.4): 241 passed”. Replaced with measured CI numbers across all three platforms.CONTRIBUTING.mdwas a hollow template – every section announced itself and then said nothing – and the new include-stub was about to publish that on the docs site. Rewritten around what this project actually gets wrong.docs/unctools-integration.mdclaimed filekit’s twois_unc_pathexport sites were “one canonical definition”. They are separate objects that agree on all 20 inputs tested; the page now says so precisely. An earlier draft of that page also recommendedclassify_path_originfor telling a network path from a local one – measured, it reportsuncfor extended-length local paths too, so the advice was replaced with the approach that works.dazzle_filekit/links.py:LinkInfo’s docstring usedFields:, which napoleon does not recognize – it parsed as a malformed block quote and failed the docs build. Changed toAttributes:, correct for a dataclass and the only non-napoleon section in the package. Improveshelp()output as well.setup.pywas left at0.4.1by the 0.4.2 release; all three version locations agree again.Two of 0.4.2’s recovery tests asserted Windows semantics without a platform gate, so they ran on the
ubuntu-latestandmacos-latestCI legs and failed there. Recovery re-inserts a backslash, which is a path separator on Windows and an ordinary filename character everywhere else: on POSIX the candidate names one file calledx\tdirrather than a directoryx/tdir.test_recovery_for_every_silent_escapeandtest_multiple_escapes_in_one_pathare now gated onos.sep; the type-guard tests are deliberately left ungated, since rejecting a bare string must hold on every platform. This is the third POSIX-only CI failure in this repo (v0.3.3, v0.4.0, and here), which is whyCONTRIBUTING.mdleads with it andtests/one-offs/run_suite_under_wsl.shexists.docs/unctools-integration.mdlinked togithub.com/DazzleLib/dazzlecmd, which 404s – dazzlecmd lives underDazzleTools/. Caught by the newlinkcheckstep on its first run, which is a reasonable argument for the step existing.linkcheckskips anchors ongithub.comURLs only. GitHub emits heading ids in a form the checker cannot match (bothid="x"andid="user-content-x", injected client-side), so every#anchorinto a blob reported broken while resolving fine in a browser – verified by hand against the STACK-MAP anchors this project links to. The URLs themselves are still checked: 12 GitHub links, all passing, 0 broken overall.
[0.4.2] - 2026-07-31¶
Added¶
is_device_path(path)– answers “is this string a PLACE?”, a different question fromis_valid_path’s “is this string LEGAL?”./dev/nullis a perfectly legal POSIX path, yet nothing is ever stored there, so any consumer that harvests paths out of shell commands, config files, or logs needs the former. Recognizes POSIX devices and sinks (/dev/null,/dev/stdout,/dev/tty, …), kernel pseudo-filesystems (/proc/,/sys/,/dev/fd/N), and Windows reserved device names (NUL,CON,COM1,LPT9, …) – the latter position-independent and extension-blind, since Windows resolvesC:\anywhere\nulto the device. Both families are recognized on both platforms deliberately: a Windows host routinely parses Git-Bash/WSL commands containing2>/dev/null, and a POSIX host may read Windows-authored scripts. The question is about the string, not the host.POSIX_DEVICE_PATHSandWINDOWS_INVALID_NAMESexported from the package root alongside it.Bare-string guard on every collection-taking entry point (#16).
find_files,find_regex_files,calculate_total_size,copy_files_with_path, andmove_files_with_pathnow raiseTypeError– with the bracketed form spelled out (Did you mean [...]?) – when handed a singlestr/bytes/Pathwhere a list is expected. A string is iterable, so it was consumed one character at a time; any realistic path contains a separator,Path("/")is the drive root, and withrecursive=Truethe default,find_files("C:\\proj")recursively globbed the whole drive. The failure was not loud, it was expensive – it looked like a slow operation rather than a mistake.ensure_path_collectionis exported for callers building similar APIs.Unescaped-backslash path diagnosis and recovery (#16).
"C:\temp"written without a raw string isC:+ TAB +empbefore any library sees it; eight escapes bite silently (\a \b \f \n \r \t \v \0) and they cover an awkward share of real directory names (temp,tools,test,bin,build,backup, …). New public helpers:recover_unescaped_path(two-step, literal first – recovery never overrides a working interpretation, and on Windows it structurally cannot pick a wrong path, since NTFS forbids characters below 0x20 in names outright, so the literal and the recovered path can never both exist), plushas_unescaped_backslash_damage,suggest_reescaped_path, andSILENT_ESCAPE_ORIGINS. Wiring is warn-only by design:find_files/find_regex_filesdiagnose a mangled miss in the log (did you mean ...? use a raw string) but never silently operate on a path the caller did not pass – recovery is the caller’s opt-in via the public helper.Driven by Claude-Session-Backup #56, where
2>/dev/nullharvested out of Bash commands was being indexed as a session’s top working directory (119 hits, outranking the actual repository).
Fixed¶
is_valid_pathrejected every forward-slash path on Windows._is_valid_windows_pathsplit on backslash only, soC:/code/projectcollapsed into a single “component” containing/and:– both members ofWINDOWS_INVALID_CHARS– and was reported invalid. Windows accepts/everywhere it accepts\(the Win32 API normalizes it; every stdlib path call honors it), so this was a false negative for one of the two common path spellings. Side effect: the reserved-name and trailing-dot/space checks never actually ran on a forward-slash path, being short-circuited by the bogus character rejection – soC:/tmp/nulwas rejected for the wrong reason. Now splits on[\\/]and skips empty components (UNC prefixes, trailing separators). Invalid characters, reserved names, and trailing dots/spaces remain rejected.The regression suite proves the premise before testing the fix:
tests/test_valid_path_separators.pyfirst demonstrates against the real filesystem that Windows resolves a forward-slash path (os.path.isdir+os.path.samefile+ a write through that spelling), then requiresis_valid_pathto agree with the OS.
Tests¶
88 new (645 pass, 12 skipped): device/sink detection across both platforms’ naming, substring safety (
console-appandnull-handlingare not devices), case sensitivity (/DEV/NULLis an ordinary path), degenerate input, and the separator regression above. The #16 suite covers all five guarded entry points (bare str, bytes, AND bare Path – which previously died with “‘WindowsPath’ object is not iterable”), the drive-walk regression (find_files("C:\\")must raise, not enumerate the disk), all eight silent escapes round-tripped against real directories, literal-first precedence, and the warn-only diagnosis infind_files(fires on mangled misses, silent on ordinary ones).
[0.4.1] - 2026-07-30¶
Fixed¶
Twelve
longpathtests asserted Windows path semantics without@win_only, so they ran on theubuntu-latestandmacos-latestlegs of the CI matrix and failed there – 11 failures on the one leg that finished before fail-fast cancelled the rest._same_diris built onos.path.normcase/normpath/splitdrive, each of which is a no-op or behaves differently off Windows:posixpath.splitdrive("C:")returns("", "C:")(no drive concept),normcasedoes not case-fold, andnormpath("C:\\")leaves the backslash as an ordinary character. So_same_dir("C:", "C:\\")isFalseon Windows – the 0.4.0 fix – andTrueunder posixpath, and the case-insensitivity assertions invert with it. The module is Windows-only in effect, so exercising its Windows semantics on a POSIX host tests nothing;@win_onlyis the correct gate rather than a workaround. Library code is unchanged.shim_pathcould still propagatectypes.ArgumentErroron Python 3.9-3.11. The same malformed input (an embedded NUL inroot) surfaces as a different exception type per interpreter: 3.12+ routesis_junctionthroughos.path.isjunctionand raisesValueError, while 3.9-3.11 fall back to a ctypesDeviceIoControlcall whosectypes.ArgumentErrorderives fromException, notValueError– soexcept (OSError, ValueError)missed it despite its message reading “ValueError: embedded null character”. Invisible on a 3.13 dev box; caught by thewindows-latest3.9/3.10/3.11 CI legs. The guard now covers all three types, and the regression tests force each type directly so any interpreter catches it.Same class as the v0.3.3 “Windows-host-locked probe suite” that ubuntu CI caught on push.
tests/one-offs/run_suite_under_wsl.shis added so the Linux leg can be reproduced from a Windows dev box before pushing, andtests/one-offs/thinking/probe_same_dir_under_posix_semantics.pymeasures which comparisons change meaning off Windows (2 of 5 in its sample).
[0.4.0] - 2026-07-30¶
Additive-only release: no symbol removed, renamed, or behavior-changed. Bumped to a minor rather than a patch not for API surface but for risk class – unlike pathenv (0.3.3, pure string logic, no I/O), this release introduces a module that creates and deletes filesystem objects. A consumer upgrading a patch release should not discover that it can mint reparse points on their system drive.
Added¶
longpathmodule – the remedy for the conditionutils.validation.is_valid_pathhas always merely detected (a path overMAX_PATHlacking a\\?\prefix).\\?\lifts the limit at the Win32 API layer, which suffices for a well-behaved caller; it does not help an application that builds the correct extended path and then copies it into a fixed 260-byte buffer, truncating the tail and reporting the file missing. That was observed in the wild in two independent PDF readers, and nothing outside such an application can repair its internal buffer. What can be changed is the length of the string handed to it – solongpathplaces a directory junction at a short root, giving the same bytes a shorter name with no cooperation required from the consumer.needs_shim(path, threshold=240)– the trigger. ReturnsFalseon POSIX (PATH_MAXis 4096 on Linux, 1024 on macOS/BSD, so the condition does not arise) andFalsefor a path already carrying an extended-length prefix. The 240 default sits deliberately below the 259 usable maximum: some handlers append to the path they are given, so a path that merely fits can still overflow once the consumer touches it.plan_shim(path, root, threshold, id_len)->ShimPlan– pure decision, no filesystem writes. Selects the shallowest ancestor whose junction still brings the result underUSABLE_PATH, so one shim covers the widest subtree and repeat opens reuse it; where the filename is long enough that only its immediate parent fits, that is chosen instead. A component longer thanNAME_MAX(255) is reported inplan.reasonrather than faked – no link can shorten a single path component, because the offending name must still appear in the shimmed path.resolve_shim_root/candidate_roots/budget_for– root selection, shortest writable first, probed at runtime. Root length is subtracted from the filename’s budget, so the ordering is load-bearing rather than cosmetic: a 49-character root leaves a 244-character filename needing 294 characters and still broken, where a 7-character root does not.%USERPROFILE%is included as the one tier guaranteed writable but deliberately ranked below the drive roots, because its length varies with the username – the same code would serve every file on one machine and silently drop the longest on another.create_shim/remove_shim/reap_shims– shim lifecycle.remove_shimre-verifies that its target is a junction immediately before deleting, closing the check-then-act window rather than trusting an earlier scan, and usesos.rmdir, which unlinks the reparse point without descending into it. This is not theoretical caution: every naive test misidentifies a junction (os.path.islink()False,os.path.isdir()True,DirEntry.is_symlink()False), the same class of bug 0.3.1 and 0.3.4 fixed inapply_file_metadata.reap_shimsconsiders only junctions and leaves anything else in the directory alone.shim_path(path, root, threshold)– convenience wrapper that never leaves a caller worse off than if this module did not exist: an unnecessary shim, an impossible plan, an unwritable root, or a failed junction all fall back to the original path rather than raising.
Fixed¶
setup.pycarriedversion="0.3.3", two releases behindpyproject.toml. All three version locations (setup.py,pyproject.toml,__init__.__version__) now agree at 0.4.0.
[0.3.4] - 2026-07-22¶
Fixed¶
apply_file_metadatacorrupted a junction target directory’s timestamps instead of the junction’s – the same follow-the-reparse-point bug class fixed for symlinks in 0.3.1, unfixed for junctions because the gate usedPath.is_symlink()(False for IO_REPARSE_TAG_MOUNT_POINT). Link routing now uses_is_link_node(), which treats any reparse point (symlink or junction) as a link node. Surfaced by the linkmirror engine work (mirroring all NTFS links from a failing drive; DazzleTools/preserve#48 Phase 2 scope).restore_windows_creation_timeopened BROKEN directory links withoutFILE_FLAG_BACKUP_SEMANTICS: dir-ness was probed withis_dir(), which follows the reparse point and reports False when the target is missing. Link nodes now decide dir-ness fromos.lstatattributes.create_symlinkauto-detection oftarget_is_directoryprobed relative targets against the process CWD instead of the link’s parent directory. Note: a BROKEN target still probes False – callers recreating an existing link (mirroring) must passtarget_is_directoryexplicitly from the source link’s own kind.create_symlinklaundered the target throughPath(), normalizing segments (a\.\b->a\b,/->\) before storing. The raw caller string is now passed through verbatim on every creation method, soos.readlinkround-trips byte-identically (measured: relative targets store verbatim; absolute targets are canonicalized to\\?\form by the kernel regardless of API – seetests/one-offs/probe_symlink_target_fidelity.py).
[0.3.3] - 2026-07-19¶
Additive-only release: no symbol removed, renamed, or behavior-changed. The one internal refactor (regex single-sourcing) is verified bit-identical; the deliberately-NOT-unified pattern is documented in place.
Added¶
pathenvmodule – declared-platform PATH-environment-value helpers (split_path_value,normalize_path_entry,path_value_contains,append_path_value,host_path_platform,PLATFORM_WINDOWS/PLATFORM_POSIX), homed from dazzlecmd-lib’s self-setup work (dazzlecmd#103). A PATH value’s platform semantics are fixed by its provenance, not the parsing host: a Windows registryPathvalue stays;-separated,%VAR%-bearing (expanded viantpathidentically on any host), and case-insensitive even on a POSIX CI runner. This is the deliberate mirror ofnormalize_cross_platform_path’s host-directional philosophy – both module docstrings cross-reference the distinction. Pure string logic, no I/O; persistence stays with callers.paths._MANGLED_MNT_RE– the MSYS-mangled WSL pattern promoted to a shared module constant.
Changed¶
Internal only (stack-survey B1 seam):
utils/compat.resolve_cross_platform_pathnow uses the sharedpaths._WSL_MNT_RE/paths._MANGLED_MNT_REconstants instead of inline byte-identical copies. The third inline pattern (windows drive-letter) is deliberately NOT swapped – the shared constant anchors with a trailing$, the inline one does not (equivalent except for pathological embedded-newline input), and this release preserves behavior bit-for-bit; the comment at the site records the nuance.
Fixed¶
atomic_write_text(and thereforeatomic_write_json) absorbs transient WindowsPermissionError [WinError 5]on the finalos.replacewith a bounded retry (6 attempts, 10-160ms backoff, ~0.3s worst case). Antivirus/indexer processes briefly lock freshly-written files; the first rename can fail even though no cooperating process holds the file – observed in the wild as one random victim test per dazzlecmd full-suite run (tmp.config.json -> config.json). A persistent permission problem still raises.
[0.3.2] - 2026-06-22¶
Added¶
links.remove_link(path)– detach a symlink, junction, or hard link without deleting its target: a junction or directory symlink is removed withos.rmdir(the target tree is untouched); a file symlink withunlink; a hard link withunlink(only the link count drops). Returnsbool; composes on the reparse-tag-correctdetect_link_type. Completes the intrinsic link primitive family (create_junction/create_hardlink/remove_link). Ported from preservelib (stack R7 conservation verdict – the primitive returns to its L1 home for the P3 dazzle-preservelib extraction to delegate to). Red-green verified (the “target survives” assertion fails on an implementation that follows into the target).
[0.3.1] - 2026-06-20¶
Fixed¶
apply_file_metadatacorrupted a symlink target’s timestamps instead of the link’s.os.utime()(and the default Win32CreateFileused for creation time) follow the reparse point to the target, so applying a record’s timestamps to a link wrote them to the target file and left the link untouched – with a “set the link to the original symlink’s time” strategy this actively rewrote the target’s mtime. Symlinks are now routed through a link-targeting path: Windows opens the link withFILE_FLAG_OPEN_REPARSE_POINT+SetFileTime(all three times); POSIX usesos.utime(follow_symlinks=False). Regular-file behavior is unchanged.restore_windows_creation_timegained the same reparse-point handling for direct symlink calls.Surfaced by the dazzle-linklib / dazzlelink link-record extraction: the tool’s
recreate/importtimestamp strategies (symlink,target) recreate a symlink and restore its timestamps, which now land on the link as intended.
[0.3.0] - 2026-06-17¶
Restores the file-operation capabilities unctools shed in its 0.2.0
“probe-not-mutate” split (STACK-MAP D7): content I/O has no home in the
path-identity layer, so it lands here in L1 – as the Option D resolver
edge, where filekit’s operations optionally consult a
dazzle_lib.PathVariantResolver (default: unctools) to retry under a path’s
alternative names (UNC <-> mapped drive). Refs DazzleLib/dazzle-filekit#15.
Added¶
open_file(path, ..., *, try_path_variants=False, resolver=None, **kwargs)– fallback-awareopen()(forwards kwargs, returns the handle); reproduces unctools’ removedsafe_open.process_files(directory, callback, pattern='*', recursive=True, *, try_path_variants=False, resolver=None)– flat batch-apply over a glob set with directory-name fallback; reproducesunctools.process_files.dazzle_filekit.contentmodule –replace_in_file/batch_replace_in_files: read-modify-write text replacement built onopen_file+atomic_write_text(crash-safe) +process_files; reproduces unctools’ removedreplace_in_filefamily.path_exists_case_sensitive/get_case_sensitive_pathinutils.compat(besidefix_path_case) – absorb unctools’ removed case-sensitivity helpers.
Intrinsic link primitives (#15 Phase A) – the L1 home of preservelib’s intrinsic link analysis and junction/hardlink creation (relational, destination-relative analysis stays at L3):
dazzle_filekit.linksmodule –LinkInfo(intrinsic-only:kind/raw_target/resolved_target/is_broken/is_circular; no destination parameter) andanalyze_link(link_path).detect_link_type('symlink'/'junction'/'hardlink'viast_nlink > 1/None) andread_link_target(symlinks viaos.readlink; junctions via the reparse buffer – nocmd /c dir /al).create_junction(PowerShellNew-Item -ItemType Junction, notcmd /c mklink /j) andcreate_hardlink(os.link, file-only, cross-device aware).utils.validation.read_junction_target– reads a junction’s target from itsDeviceIoControl(FSCTL_GET_REPARSE_POINT)reparse buffer.paths.compute_relative_path(target, start)–os.path.relpath-based..-traversing relative path with a Windows cross-drive fallback. Distinct fromget_relative_path(subpath-containment only).Ported from
preserve/preservelib/links.pywith three coverage/correctness improvements: DeviceIoControl junction detection (vs attribute-only), no bannedcmdshell-outs, and hardlinks reported as valid (notis_broken).
Changed¶
copy_file/move_file/copy_files_with_path/move_files_with_pathgaintry_path_variants=/resolver=keyword-only args: when set, the operation retries across path-name variant combinations (reproduces unctools’safe_copy/batch_copyfallback). Default off – existing behavior is unchanged.dazzle-lib>=0.2.0andunctools>=0.2.2are now hard dependencies (previouslyunctoolswas an optional[unctools]extra). filekit already requires pywin32 on Windows and unctools’ base is pure-Python, so the cost is small; this removes the optional-load awkwardness and makes the fallback always available. (unctools>=0.2.2carries the drive-map enrichment that absorbed the removedget_drive_mappings.)create_symlink(Windows) absorbed dazzlelink’s escalation chain (#15 Phase B):_create_windows_symlinknow inlines thewin32file.CreateSymbolicLinkunprivileged-create API path and the PowerShellStart-Process -Verb RunAselevation path, and no longer importsdazzlelink(the L1->L2 upward edge is cut). filekit’s bool contract is preserved – total failure returnsFalse(dazzlelink raised).get_path_typerenamed toclassify_fs_object(#15 Phase C): the L1 name says it classifies WHAT a filesystem object is (file/directory/symlink/…); unctools’ siblingclassify_path_originclassifies WHERE a path’s name comes from. Behavior is identical (a junction still reports'directory'– uselinks.analyze_linkfor link-kind).is_unc_pathcollapsed to one canonical, platform-independent definition (#15 Phase C):paths.is_unc_pathandutils.validation.is_unc_pathnow both delegate to the L0 ownerunctools.is_unc_path(normalizes/->\then checks\\). This is a behavior change:is_unc_path('//server/share')is nowTrueon every platform – a strict superset that resolves the prior divergence (the oldpathscopy returnedFalsefor forward-slash UNC; thevalidationcopy returnedTrueonly on POSIX).Metadata/link signatures consume the stack’s shared TypedDicts (#15 Phase D):
collect_file_metadata->dazzle_lib.FileMetadataDict,collect_timestamp_info->TimestampsDict,apply_file_metadata(metadata=)acceptsFileMetadataDict, andlinks.LinkInfo.to_dict->LinkTargetDict. These cross-layer payload shapes are owned bydazzle-lib(STACK-MAP D10); typing filekit’s producers against them makes the contract explicit and machine-checkable. (LinkInfo.to_dictomitslink_path– the schema describes the target; the caller already holds the link path.)
Removed¶
utils.compat.get_drive_mappings()(#15 Phase B / stack V9): drive↔UNC mapping is path-identity knowledge owned by the L0 layer. Itswin32wnet.WNetGetUniversalNameprovider-chain scan was folded intounctools’UNCConverter(unctools 0.2.2) so no coverage is lost. Useunctools.converter.get_mappings()(UNC→drive) orunctools.converter.UNCConverter().get_reverse_mappings()(drive→UNC, the directionget_drive_mappingsreturned). (Zero callers in the ecosystem; not previously exported from the top-level package.)paths.normalize_path/paths.normalize_path_no_resolve(#15 Phase C, clean break – no shims): these were thin wrappers overnormalize_cross_platform_path. Migrate:normalize_path(p)→normalize_cross_platform_path(p, resolve=True)(link-following);normalize_path_no_resolve(p)→normalize_cross_platform_path(p)(defaultresolve=False, link-safe). In-tree consumers (dazzlecmd) updated in the same cycle.
Notes¶
normalize_path’s separator normalization is preserved:convert_to_local/convert_to_uncperform the same/->\step internally.
[0.2.4] - 2026-04-11¶
Added¶
dazzle_filekit.metadata module (byte-identical port from preservelib, now public):
Rich
collect_file_metadata()andapply_file_metadata()delegates that capture a strict superset of v0.2.3’s outputrestore_windows_creation_time()– NTFS ctime restoration viapywin32.SetFileTimewithFILE_WRITE_ATTRIBUTES=0x100,FILE_FLAG_BACKUP_SEMANTICSfor directories, and the readonly-clear-then-restore danceis_win32_available()– cached pywin32 availability probecompare_metadata()/metadata_to_json()/get_metadata_summary()– diffing and JSON-safe projection helperscollect_timestamp_info()/apply_timestamp_strategy()– timestamp-only workflow helpersSDDL ACL round-trip on Windows (JSON-serializable, replaces non-serializable pywin32 handle objects)
Unix xattrs capture/apply via
os.listxattr/getxattr/setxattr(skipscom.apple.quarantineon restore to avoid security surprises)Windows attribute flag booleans (
is_hidden,is_system,is_readonly,is_archive) derived from the attribute bitmaskOwner/group as
DOMAIN\NamestringsFile
sizefield, ISO timestamp projections (modified_iso,accessed_iso,created_iso)
dazzle_filekit.operations primitives:
atomic_write_text(path, content, *, encoding='utf-8', newline=None)– tmp+os.replaceatomic text write; creates parent dirs; atomic on Windows since Python 3.3atomic_write_json(path, data, *, indent=2, sort_keys=False, default=str, trailing_newline=True)– thin JSON wrapper;default=strhandlesPath/datetime/etc. out of the boxcopy_tree_preserving_links(src, dst, *, dirs_exist_ok=False, ignore=None, ignore_dangling_symlinks=False)–shutil.copytreewrapper withsymlinks=Truehard-wired and documented intent
dazzle_filekit.platform.windows (NTFS alternate data streams):
detect_alternate_streams(path)– enumerates ADS via ctypesFindFirstStreamW/FindNextStreamW; filters out::$DATAand:Zone.Identifier:$DATA(browser download markers)has_significant_ads(path)– returns True if any non-ignored stream exists
dazzle_filekit.utils.compat:
is_wsl()– WSL detection viaWSL_DISTRO_NAMEenv var +/proc/versionscan; returns False on non-Linux platforms
New runtime dependency:
pywin32 >= 305on Windows (conditional marker, no-op on Linux/macOS). Powers SDDL ACLs, ctime restoration, junction detection, and ADS enumeration. The module falls back toattribcommand if pywin32 is missing, but the rich feature set requires it.
Changed¶
Path normalization consolidated via shared _prepare_path_format helper:
normalize_cross_platform_path(path, *, resolve=False)is now the canonical path normalizer. The newresolve=keyword-only parameter optionally follows symlinks viaPath.resolve().normalize_path(path)andnormalize_path_no_resolve(path)are now thin backwards-compatibility wrappers around the canonical function. They preserve their v0.2.3 signatures and behavior; their docstrings note thatnormalize_cross_platform_pathis the preferred entry point for new code.normalize_cross_platform_pathgained tilde expansion, env var expansion (%USERPROFILE%/$HOME), relative-to-absolute via cwd,os.path.normpath..collapsing, and\\?\extended-length prefix stripping on Windows. This was the v0.2.3 behavior gap that made it less capable thannormalize_path_no_resolve; now they’re equivalent.normalize_pathandnormalize_path_no_resolvegained WSL/mnt/c/conversion (onlynormalize_cross_platform_pathhad it in v0.2.3).Platform-direction drive conversion is now platform-aware and bidirectional: on Windows,
/mnt/c/Users/fooand/c/Users/foobecomeC:\Users\foo; on Linux,C:\Users\fooandC:/Users/foobecome/c/Users/foo. A legitimate Linux path like/c/Users/foois no longer misinterpreted as an MSYS drive on Linux.Bare
/c(MSYS drive with no subpath) now maps to drive rootC:\rather than the drive-relativeC:(whichos.path.isabsdoesn’t consider absolute).
Metadata API is now richer by default:
operations.collect_file_metadataandoperations.apply_file_metadatadelegate to the newmetadata.pymodule. No signature changes; the returned dict is a strict superset.
Fixed¶
validation.is_junction(path) – the v0.2.3 implementation referenced win32file.FILE_ATTRIBUTE_REPARSE_POINT, which does not exist (the constant lives in win32con). The bare except: clause silently swallowed the AttributeError and returned False for everything – including real junctions. Fixed in v0.2.4 by porting the correct DeviceIoControl(FSCTL_GET_REPARSE_POINT) implementation from dazzlecmd/projects/core/links/links.py. The fix also correctly distinguishes junctions (IO_REPARSE_TAG_MOUNT_POINT) from directory symlinks (IO_REPARSE_TAG_SYMLINK), which the original version would have misclassified even if the attribute lookup had worked.
normalize_path() / normalize_cross_platform_path(..., resolve=True) on Python 3.9 Windows – Path.resolve() on Python 3.9 Windows returns a relative WindowsPath for nonexistent relative inputs instead of prepending cwd. This is a Python 3.9 behavior quirk that was fixed in 3.10+, but it left normalize_path("./a/b/file.txt") returning Path("a/b/file.txt") on Python 3.9 Windows – callers expecting an absolute path got a surprise. Caught by tests/characterization/test_paths_v023_baseline.py::test_relative_path_resolved_against_cwd on the v0.2.4 CI matrix (Windows Python 3.9 failed, 14 other jobs green). Fixed by pre-absolutizing via Path.absolute() before .resolve() in the resolve=True branch of normalize_cross_platform_path. On Python 3.10+ this is a no-op since .resolve() handles absolutization itself. Latent bug also existed in v0.2.3 but was never tested.
Infrastructure¶
docs/api-stability.md+tests/test_import_stability.py– locked-in public API surface with 54 canary assertions covering every external caller (claude-session-logger, dazzlecmd safedel/fixpath/links, github-traffic-tracker, preservelib, README examples). (Moved from repo root todocs/during the v0.2.4 doc-organization pass; contributor-facing, not consumer-facing.)BREAKING_CHANGES.md– forward-looking log with Phase 4 edge-case target matrix and migration procedures.docs/preservelib-integration.md– guide for preservelib to depend on filekit and the layering contract (primitives vs workflow).tests/test_paths_platform_simulation.py– 23 tests that monkeypatchsys.platformto exercise both the Windows-direction and Unix-direction branches of_prepare_path_formatfrom a single host OS. Catches the exact class of bug that broke WSL on 2026-04-11 while the Windows suite was 208/208 green.scripts/run-cross-platform-tests.sh– convenience wrapper for running the suite on both Windows and WSL from a single command, for local dev cross-checking.Test count: 241 passing + 9 skipped on Windows, 200 passing + 50 skipped on Linux (WSL). Zero failures on either platform. Stability canary: 54 assertions green.
Out of scope (deferred)¶
safedel migration to the new filekit primitives (
atomic_write_json,copy_tree_preserving_links,metadatamodule). filekit v0.2.4 is backwards-compatible, so safedel continues to work unmodified. A follow-up commit can rewire safedel’s internal atomic-write helpers and its_lib/preservelib/metadata.pycopy to point at filekit.Renaming or removing any locked symbol in
docs/api-stability.md.Upstream
C:\code\preserve\preservelib\reconciliation with safedel’s diverged rich copy.
[0.2.3] - 2026-04-10¶
Added¶
normalize_path_no_resolve()- Normalize paths without resolving symlinks or junctionsHandles MSYS (
/c/), tilde, extended-length prefix (\\?\), relative pathsUses
os.path.normpath()instead ofPath.resolve()to preserve link identityUse case: tools that need the literal path to a link, not its target (e.g., safe-delete, link management)
Fixed¶
Synced version strings across
pyproject.toml,__init__.py, andsetup.py(were 0.2.2, 0.2.1, 0.2.0 respectively)
[0.2.2] - 2026-03-18¶
Added¶
resolve_cross_platform_path()- Bidirectional path probing that tries alternate platform formats when the normalized path doesn’t existOn Windows: probes WSL
/mnt/c/→C:\, MSYS/c/→C:\, and MSYS-mangled WSL paths (where Git Bash prepends its install dir to/mnt/c/...)On Linux/macOS: probes Windows
C:\→/mnt/c/(WSL) or/c/(MSYS)Returns the first existing candidate, or the normalized form if none exist
Changed¶
path_exists_cross_platform()now usesresolve_cross_platform_path()for more accurate existence checks across platform boundaries
[0.2.1] - 2026-01-29¶
Added¶
create_symlink()- Cross-platform symbolic link creation with Windows fallbacksUnix: Uses
os.symlinkdirectlyWindows: Tries
os.symlink, thendazzlelinklibrary, thenmklinkcommandSupports
forceparameter to replace existing linksAuto-detects target type (file vs directory) when not specified
Changed¶
Updated PyPI badge from badge.fury.io to shields.io (badge.fury.io was not working)
[0.2.0] - 2026-01-24¶
Added¶
normalize_cross_platform_path()- Normalize paths from Git Bash style (/c/...), WSL style (/mnt/c/...), and Windows style (C:\...) to native platform formatpath_exists_cross_platform()- Check if a path exists, handling cross-platform path formatsExport
is_windows()andis_unix()from main package for convenienceDisk space utilities:
get_disk_usage(),check_disk_space(),calculate_total_size(),ensure_disk_space()DiskUsagenamed tuple withused_percentandfree_percentpropertiesInsufficientSpaceErrorexception for disk space validation53 unit tests for compat and disk modules
Platform support documentation (
docs/platform-support.md)
Fixed¶
Added missing
Dictimport toutils/compat.pyfor proper type annotations
[0.1.1] - 2026-01-15¶
Changed¶
Version bump for initial PyPI release preparation
[0.1.0] - 2026-01-10¶
Added¶
Initial release
Path operations:
normalize_path,is_same_file,split_drive_letter,is_unc_path,get_relative_path,create_dest_path,find_files,find_regex_files,collect_files_from_include_file,create_parent_dirs,ensure_unique_path,get_path_typeFile operations:
copy_file,move_file,collect_file_metadata,apply_file_metadata,copy_files_with_path,move_files_with_path,create_directory_structure,remove_file,remove_directoryVerification functions:
calculate_file_hash,verify_file_hash,verify_files_with_manifest,calculate_directory_hashes,save_hashes_to_file,load_hashes_from_file,compare_directories,verify_copied_filesUtility functions:
is_windows,is_unix,is_admin,is_root,fix_path_separators,fix_path_case,get_system_encoding,get_system_temp_dir,get_home_dir,get_app_data_dirValidation functions:
is_valid_path,is_safe_path,validate_path_chars,is_absolute_path,is_relative_path,is_hidden_path,is_symlink,is_junctionCross-platform support for Windows, Linux, and macOS
Optional UNC path support via unctools integration