dazzle-filekit 0.3.3__tar.gz → 0.3.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/PKG-INFO +1 -1
  2. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/__init__.py +3 -1
  3. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/links.py +120 -0
  4. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/metadata.py +152 -20
  5. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/operations.py +22 -8
  6. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit.egg-info/PKG-INFO +1 -1
  7. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit.egg-info/SOURCES.txt +1 -0
  8. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/pyproject.toml +1 -1
  9. dazzle_filekit-0.3.4/tests/test_link_fidelity_v034.py +182 -0
  10. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_pathenv_edgecases.py +17 -13
  11. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/LICENSE +0 -0
  12. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/README.md +0 -0
  13. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/_fallback.py +0 -0
  14. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/content.py +0 -0
  15. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/pathenv.py +0 -0
  16. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/paths.py +0 -0
  17. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/platform/__init__.py +0 -0
  18. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/platform/unix.py +0 -0
  19. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/platform/windows.py +0 -0
  20. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/utils/__init__.py +0 -0
  21. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/utils/compat.py +0 -0
  22. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/utils/disk.py +0 -0
  23. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/utils/logger.py +0 -0
  24. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/utils/validation.py +0 -0
  25. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit/verification.py +0 -0
  26. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit.egg-info/dependency_links.txt +0 -0
  27. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit.egg-info/requires.txt +0 -0
  28. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/dazzle_filekit.egg-info/top_level.txt +0 -0
  29. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/setup.cfg +0 -0
  30. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/setup.py +0 -0
  31. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_ads_and_junction_v024.py +0 -0
  32. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_atomic_stream_writer.py +0 -0
  33. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_atomic_write_retry.py +0 -0
  34. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_auto_naming.py +0 -0
  35. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_compat.py +0 -0
  36. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_content_and_process.py +0 -0
  37. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_disk.py +0 -0
  38. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_fallback.py +0 -0
  39. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_import_stability.py +0 -0
  40. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_junction_detection_improvements.py +0 -0
  41. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_link_primitives.py +0 -0
  42. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_metadata_v024_roundtrip.py +0 -0
  43. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_native_hash_backend.py +0 -0
  44. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_operations_primitives_v024.py +0 -0
  45. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_pathenv.py +0 -0
  46. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_paths_platform_simulation.py +0 -0
  47. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_paths_v024_enrichments.py +0 -0
  48. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_phase_b_absorb_and_v9.py +0 -0
  49. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_phase_c_renames.py +0 -0
  50. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_phase_d_typeddicts.py +0 -0
  51. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_resolver_ops.py +0 -0
  52. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_smoke.py +0 -0
  53. {dazzle_filekit-0.3.3 → dazzle_filekit-0.3.4}/tests/test_symlink_timestamps_v031.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dazzle-filekit
3
- Version: 0.3.3
3
+ Version: 0.3.4
4
4
  Summary: Cross-platform file operations toolkit with path handling, verification, and metadata preservation
5
5
  Author: Dustin
6
6
  Author-email: Dustin Darcy <6962246+djdarcy@users.noreply.github.com>
@@ -120,6 +120,7 @@ from .links import (
120
120
  detect_link_type,
121
121
  read_link_target,
122
122
  create_junction,
123
+ create_junction_raw,
123
124
  create_hardlink,
124
125
  remove_link,
125
126
  )
@@ -137,7 +138,7 @@ from .pathenv import (
137
138
  append_path_value,
138
139
  )
139
140
 
140
- __version__ = '0.3.3'
141
+ __version__ = '0.3.4'
141
142
 
142
143
  def configure_logging(level=logging.INFO, log_file=None):
143
144
  """
@@ -275,6 +276,7 @@ __all__ = [
275
276
  'detect_link_type',
276
277
  'read_link_target',
277
278
  'create_junction',
279
+ 'create_junction_raw',
278
280
  'create_hardlink',
279
281
  'remove_link',
280
282
 
@@ -286,6 +286,126 @@ def create_junction(
286
286
  return False
287
287
 
288
288
 
289
+ def create_junction_raw(
290
+ target: Union[str, Path],
291
+ link: Union[str, Path],
292
+ force: bool = False,
293
+ ) -> bool:
294
+ """Create an NTFS junction by writing the mount-point reparse buffer
295
+ directly (``FSCTL_SET_REPARSE_POINT``), no subprocess.
296
+
297
+ Differences from :func:`create_junction` (PowerShell ``New-Item``):
298
+
299
+ - The target does NOT need to exist -- ``New-Item`` refuses a missing
300
+ target, which makes intentionally-broken junctions impossible to
301
+ recreate when mirroring a tree.
302
+ - The target string is stored VERBATIM: ``\\\\?\\C:\\x`` (as returned by
303
+ ``os.readlink`` on another junction) and plain ``C:\\x`` are both
304
+ accepted; the NT-namespace SubstituteName (``\\??\\...``) and the
305
+ user-facing PrintName are derived without other normalization, so
306
+ ``os.readlink`` round-trips byte-identically.
307
+
308
+ Unprivileged (junctions never require SeCreateSymbolicLinkPrivilege).
309
+ Windows-only, directory-only. Returns True on success.
310
+ """
311
+ raw_target = os.fspath(target)
312
+ link_path = Path(link)
313
+
314
+ if os.name != "nt":
315
+ logger.error("Junctions are only supported on Windows")
316
+ return False
317
+
318
+ if link_path.exists() or link_path.is_symlink():
319
+ if not force:
320
+ logger.warning(f"Link path already exists: {link_path}")
321
+ return False
322
+ if not _remove_existing(link_path):
323
+ return False
324
+
325
+ # SubstituteName lives in the NT namespace (\??\); PrintName is the
326
+ # user-facing form. os.readlink() renders \??\ as \\?\, so accept both.
327
+ if raw_target.startswith("\\??\\"):
328
+ substitute = raw_target
329
+ print_name = raw_target[4:]
330
+ elif raw_target.startswith("\\\\?\\"):
331
+ substitute = "\\??\\" + raw_target[4:]
332
+ print_name = raw_target[4:]
333
+ else:
334
+ substitute = "\\??\\" + raw_target
335
+ print_name = raw_target
336
+
337
+ try:
338
+ link_path.parent.mkdir(parents=True, exist_ok=True)
339
+ os.mkdir(link_path)
340
+ except OSError as e:
341
+ logger.error(f"Failed to create junction directory {link_path}: {e}")
342
+ return False
343
+
344
+ try:
345
+ import ctypes
346
+ from ctypes import wintypes
347
+
348
+ kernel32 = ctypes.windll.kernel32
349
+
350
+ GENERIC_WRITE = 0x40000000
351
+ OPEN_EXISTING = 3
352
+ FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000
353
+ FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
354
+ FILE_SHARE_READ_WRITE_DELETE = 0x01 | 0x02 | 0x04
355
+ FSCTL_SET_REPARSE_POINT = 0x000900A4
356
+ IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003
357
+
358
+ subst_b = substitute.encode("utf-16-le")
359
+ print_b = print_name.encode("utf-16-le")
360
+ # MountPointReparseBuffer: 4 offset/length WORDs + PathBuffer holding
361
+ # SubstituteName \0 PrintName \0 (UTF-16LE, lengths exclude the NULs).
362
+ path_buffer = subst_b + b"\x00\x00" + print_b + b"\x00\x00"
363
+ reparse_data_length = 8 + len(path_buffer)
364
+ header = (
365
+ IO_REPARSE_TAG_MOUNT_POINT.to_bytes(4, "little")
366
+ + reparse_data_length.to_bytes(2, "little")
367
+ + b"\x00\x00" # Reserved
368
+ + (0).to_bytes(2, "little") # SubstituteNameOffset
369
+ + len(subst_b).to_bytes(2, "little") # SubstituteNameLength
370
+ + (len(subst_b) + 2).to_bytes(2, "little") # PrintNameOffset
371
+ + len(print_b).to_bytes(2, "little") # PrintNameLength
372
+ )
373
+ buf = header + path_buffer
374
+
375
+ handle = kernel32.CreateFileW(
376
+ str(link_path), GENERIC_WRITE,
377
+ FILE_SHARE_READ_WRITE_DELETE,
378
+ None, OPEN_EXISTING,
379
+ FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
380
+ None,
381
+ )
382
+ if handle == wintypes.HANDLE(-1).value:
383
+ raise OSError(f"CreateFileW failed for {link_path}")
384
+ try:
385
+ bytes_returned = wintypes.DWORD(0)
386
+ ok = kernel32.DeviceIoControl(
387
+ handle, FSCTL_SET_REPARSE_POINT,
388
+ buf, len(buf), None, 0,
389
+ ctypes.byref(bytes_returned), None,
390
+ )
391
+ if not ok:
392
+ raise OSError(
393
+ f"FSCTL_SET_REPARSE_POINT failed "
394
+ f"(winerror={ctypes.get_last_error()})"
395
+ )
396
+ finally:
397
+ kernel32.CloseHandle(handle)
398
+ logger.debug(f"Created raw junction: {link_path} -> {raw_target}")
399
+ return True
400
+ except Exception as e: # noqa: BLE001 - report and clean up the stub dir
401
+ logger.error(f"Raw junction creation failed for {link_path}: {e}")
402
+ try:
403
+ os.rmdir(link_path)
404
+ except OSError:
405
+ pass
406
+ return False
407
+
408
+
289
409
  def create_hardlink(
290
410
  target: Union[str, Path],
291
411
  link: Union[str, Path],
@@ -194,8 +194,93 @@ def _collect_windows_metadata(path: Path) -> Dict[str, Any]:
194
194
  logger.error(f"Error collecting Windows metadata for {path}: {e}")
195
195
  return windows_metadata
196
196
 
197
+ _FILE_ATTRIBUTE_REPARSE_POINT = 0x400
198
+
199
+ # Nanoseconds between 1601-01-01 (FILETIME epoch) and 1970-01-01 (Unix epoch)
200
+ _FILETIME_EPOCH_OFFSET_NS = 11644473600 * 10**9
201
+
202
+
203
+ def _set_link_times_exact_windows(
204
+ path_str: str,
205
+ created_ns: Optional[int],
206
+ accessed_ns: Optional[int],
207
+ modified_ns: Optional[int],
208
+ ) -> bool:
209
+ """Set timestamps on a link node with exact 100ns precision.
210
+
211
+ Opens the node with ``FILE_FLAG_OPEN_REPARSE_POINT`` (never follows to
212
+ the target) and calls ``SetFileTime`` with FILETIMEs computed directly
213
+ from integer nanoseconds -- the float/datetime/pywintypes chain rounds
214
+ to microseconds or worse, which a mirror's verify pass would flag.
215
+ Pure ctypes; works without pywin32. Returns True on success.
216
+ """
217
+ try:
218
+ import ctypes
219
+ from ctypes import wintypes
220
+
221
+ kernel32 = ctypes.windll.kernel32
222
+
223
+ FILE_WRITE_ATTRIBUTES = 0x100
224
+ OPEN_EXISTING = 3
225
+ FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000
226
+ FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
227
+ FILE_SHARE_ALL = 0x01 | 0x02 | 0x04
228
+
229
+ def _ft(ns: Optional[int]):
230
+ if ns is None:
231
+ return None
232
+ ticks = (ns + _FILETIME_EPOCH_OFFSET_NS) // 100
233
+ return wintypes.FILETIME(
234
+ ticks & 0xFFFFFFFF, (ticks >> 32) & 0xFFFFFFFF
235
+ )
236
+
237
+ handle = kernel32.CreateFileW(
238
+ path_str, FILE_WRITE_ATTRIBUTES, FILE_SHARE_ALL, None,
239
+ OPEN_EXISTING,
240
+ FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
241
+ None,
242
+ )
243
+ if handle == wintypes.HANDLE(-1).value:
244
+ return False
245
+ try:
246
+ ft_c = _ft(created_ns)
247
+ ft_a = _ft(accessed_ns)
248
+ ft_m = _ft(modified_ns)
249
+ ok = kernel32.SetFileTime(
250
+ handle,
251
+ ctypes.byref(ft_c) if ft_c else None,
252
+ ctypes.byref(ft_a) if ft_a else None,
253
+ ctypes.byref(ft_m) if ft_m else None,
254
+ )
255
+ return bool(ok)
256
+ finally:
257
+ kernel32.CloseHandle(handle)
258
+ except Exception as e: # noqa: BLE001 - caller falls back to pywin32
259
+ logger.debug(f"_set_link_times_exact_windows({path_str}) failed: {e}")
260
+ return False
261
+
262
+
263
+ def _is_link_node(path_obj: Path) -> bool:
264
+ """True for any link NODE whose own metadata must be set without
265
+ following to the target: symlinks everywhere, plus junctions (and any
266
+ other reparse point) on Windows. ``Path.is_symlink()`` alone is False for
267
+ junctions (IO_REPARSE_TAG_MOUNT_POINT vs IO_REPARSE_TAG_SYMLINK), which
268
+ routed junctions to the target-following ``os.utime`` path before v0.3.4.
269
+ """
270
+ if path_obj.is_symlink():
271
+ return True
272
+ if platform.system() != 'Windows':
273
+ return False
274
+ try:
275
+ attrs = os.lstat(str(path_obj)).st_file_attributes
276
+ except OSError:
277
+ return False
278
+ return bool(attrs & _FILE_ATTRIBUTE_REPARSE_POINT)
279
+
280
+
197
281
  def _set_symlink_timestamps(path_obj: Path, timestamps: Dict[str, Any]) -> bool:
198
- """Apply timestamps to a symlink ITSELF, never the target it points to.
282
+ """Apply timestamps to a link node ITSELF (symlink or junction), never
283
+ the target it points to.
199
284
 
200
285
  ``os.utime()`` and a default Win32 ``CreateFile`` both follow the reparse
201
286
  point to the target -- so applying timestamps to a link the naive way
@@ -208,22 +293,58 @@ def _set_symlink_timestamps(path_obj: Path, timestamps: Dict[str, Any]) -> bool:
208
293
  accessed = timestamps.get('accessed')
209
294
  modified = timestamps.get('modified')
210
295
  created = timestamps.get('created')
296
+ # Optional exact-precision variants: integer nanoseconds. The float-
297
+ # seconds path bottoms out in datetime/pywintypes at microsecond (or
298
+ # worse) resolution; mirroring wants the NTFS 100ns tick preserved, so
299
+ # *_ns keys, when present, take precedence and travel through an exact
300
+ # integer FILETIME conversion.
301
+ accessed_ns = timestamps.get('accessed_ns')
302
+ modified_ns = timestamps.get('modified_ns')
303
+ created_ns = timestamps.get('created_ns')
211
304
 
212
305
  if platform.system() != 'Windows':
213
- if (os.utime in os.supports_follow_symlinks
214
- and accessed is not None and modified is not None):
215
- try:
306
+ if os.utime not in os.supports_follow_symlinks:
307
+ logger.warning(
308
+ f"Cannot set link timestamps for {path_obj} on this platform "
309
+ f"without following to the target; skipped."
310
+ )
311
+ return False
312
+ try:
313
+ if accessed_ns is not None and modified_ns is not None:
314
+ os.utime(path_obj, ns=(accessed_ns, modified_ns),
315
+ follow_symlinks=False)
316
+ return True
317
+ if accessed is not None and modified is not None:
216
318
  os.utime(path_obj, (accessed, modified), follow_symlinks=False)
217
319
  return True
218
- except Exception as e:
219
- logger.warning(f"Error applying symlink timestamps to {path_obj}: {e}")
220
- return False
320
+ except Exception as e:
321
+ logger.warning(f"Error applying symlink timestamps to {path_obj}: {e}")
322
+ return False
221
323
  logger.warning(
222
- f"Cannot set link timestamps for {path_obj} on this platform without "
223
- f"following to the target; skipped."
324
+ f"Cannot set link timestamps for {path_obj}: no usable "
325
+ f"accessed/modified values; skipped."
224
326
  )
225
327
  return False
226
328
 
329
+ # Windows exact path: integer ns -> FILETIME (100ns ticks since 1601)
330
+ # via ctypes SetFileTime. No float/datetime rounding, no pywin32 needed.
331
+ if any(v is not None for v in (created_ns, accessed_ns, modified_ns)):
332
+ if _set_link_times_exact_windows(
333
+ str(path_obj), created_ns, accessed_ns, modified_ns
334
+ ):
335
+ return True
336
+ logger.debug(
337
+ f"Exact ns SetFileTime failed for {path_obj}; falling back to "
338
+ f"pywin32 float path"
339
+ )
340
+ # Fall through to the float path with whatever float values exist.
341
+ if accessed is None and accessed_ns is not None:
342
+ accessed = accessed_ns / 1e9
343
+ if modified is None and modified_ns is not None:
344
+ modified = modified_ns / 1e9
345
+ if created is None and created_ns is not None:
346
+ created = created_ns / 1e9
347
+
227
348
  # Windows: open the link itself (FILE_FLAG_OPEN_REPARSE_POINT) + SetFileTime.
228
349
  if not is_win32_available():
229
350
  logger.warning(
@@ -289,13 +410,13 @@ def apply_file_metadata(path: Union[str, Path], metadata: FileMetadataDict) -> b
289
410
  logger.warning(f"Error applying permissions to {path}: {e}")
290
411
  success = False
291
412
 
292
- # Apply timestamps. Symlinks need special handling: os.utime() and the
293
- # default Win32 handle follow the reparse point and would write to the
294
- # TARGET, so route links through a link-targeting helper that sets all
295
- # three times on the link itself.
413
+ # Apply timestamps. Link nodes (symlinks AND junctions) need special
414
+ # handling: os.utime() and the default Win32 handle follow the reparse
415
+ # point and would write to the TARGET, so route them through a
416
+ # link-targeting helper that sets all three times on the node itself.
296
417
  if 'timestamps' in metadata:
297
418
  timestamps = metadata['timestamps']
298
- if path_obj.is_symlink():
419
+ if _is_link_node(path_obj):
299
420
  if not _set_symlink_timestamps(path_obj, timestamps):
300
421
  success = False
301
422
  else:
@@ -932,15 +1053,26 @@ def restore_windows_creation_time(
932
1053
  # Raw value for FILE_WRITE_ATTRIBUTES (0x100) -- not always in win32con
933
1054
  FILE_WRITE_ATTRIBUTES = 0x100
934
1055
 
935
- # Directories require FILE_FLAG_BACKUP_SEMANTICS to open
936
- if path_obj.is_dir():
1056
+ # Directories require FILE_FLAG_BACKUP_SEMANTICS to open. For link
1057
+ # nodes (symlink/junction) decide dir-ness from lstat attributes --
1058
+ # is_dir() follows the reparse point and reports False for a BROKEN
1059
+ # directory link, whose handle still needs BACKUP_SEMANTICS.
1060
+ if _is_link_node(path_obj):
1061
+ try:
1062
+ node_attrs = os.lstat(path_str).st_file_attributes
1063
+ except OSError:
1064
+ node_attrs = 0
1065
+ if node_attrs & stat.FILE_ATTRIBUTE_DIRECTORY:
1066
+ flags = win32con.FILE_FLAG_BACKUP_SEMANTICS
1067
+ else:
1068
+ flags = win32con.FILE_ATTRIBUTE_NORMAL
1069
+ # Open the link itself, not the target it points to, so the
1070
+ # creation time lands on the link (otherwise CreateFile follows it).
1071
+ flags |= 0x00200000 # FILE_FLAG_OPEN_REPARSE_POINT
1072
+ elif path_obj.is_dir():
937
1073
  flags = win32con.FILE_FLAG_BACKUP_SEMANTICS
938
1074
  else:
939
1075
  flags = win32con.FILE_ATTRIBUTE_NORMAL
940
- # Symlinks: open the link itself, not the target it points to, so the
941
- # creation time lands on the link (otherwise CreateFile follows it).
942
- if path_obj.is_symlink():
943
- flags |= 0x00200000 # FILE_FLAG_OPEN_REPARSE_POINT
944
1076
 
945
1077
  # Handle readonly files: clear attribute, set time, restore attribute
946
1078
  readonly_cleared = False
@@ -958,6 +958,11 @@ def create_symlink(
958
958
  >>> create_symlink('C:\\data\\folder', 'C:\\links\\folder_link', target_is_directory=True)
959
959
  True
960
960
  """
961
+ # Keep the caller's raw target string for creation: Path() round-trips
962
+ # normalize segments (``a\.\b`` -> ``a\b``, ``/`` -> ``\\``), but a link's
963
+ # stored target must be able to reproduce the caller's bytes exactly
964
+ # (mirroring reads it back via os.readlink and expects equality).
965
+ raw_target = os.fspath(target)
961
966
  target_path = Path(target)
962
967
  link_path = Path(link)
963
968
 
@@ -983,26 +988,34 @@ def create_symlink(
983
988
  logger.error(f"Failed to create parent directories for {link_path}: {e}")
984
989
  return False
985
990
 
986
- # Auto-detect if target is a directory
991
+ # Auto-detect if target is a directory. Relative targets resolve against
992
+ # the LINK's parent directory (link semantics), not the process CWD. A
993
+ # broken target probes False -- callers recreating an existing link (e.g.
994
+ # mirroring) must pass target_is_directory explicitly from the source
995
+ # link's own kind, since a broken DIRECTORY symlink cannot be inferred.
987
996
  if target_is_directory is None:
988
- target_is_directory = target_path.is_dir()
997
+ probe = (target_path if target_path.is_absolute()
998
+ else link_path.parent / raw_target)
999
+ target_is_directory = probe.is_dir()
989
1000
 
990
1001
  # Try to create symlink
991
1002
  if platform.system() != 'Windows':
992
1003
  # Unix: straightforward symlink
993
1004
  try:
994
- os.symlink(target_path, link_path)
995
- logger.debug(f"Created symlink: {link_path} -> {target_path}")
1005
+ os.symlink(raw_target, str(link_path))
1006
+ logger.debug(f"Created symlink: {link_path} -> {raw_target}")
996
1007
  return True
997
1008
  except Exception as e:
998
1009
  logger.error(f"Failed to create symlink on Unix: {e}")
999
1010
  return False
1000
1011
 
1001
1012
  # Windows: try multiple methods
1002
- return _create_windows_symlink(target_path, link_path, target_is_directory)
1013
+ return _create_windows_symlink(raw_target, link_path, target_is_directory)
1003
1014
 
1004
1015
 
1005
- def _create_windows_symlink(target: Path, link: Path, is_directory: bool) -> bool:
1016
+ def _create_windows_symlink(
1017
+ target: Union[str, Path], link: Path, is_directory: bool
1018
+ ) -> bool:
1006
1019
  """
1007
1020
  Create a symbolic link on Windows using an escalating chain of methods.
1008
1021
 
@@ -1021,14 +1034,15 @@ def _create_windows_symlink(target: Path, link: Path, is_directory: bool) -> boo
1021
1034
  returns False (dazzlelink raised).
1022
1035
 
1023
1036
  Args:
1024
- target: Target path
1037
+ target: Target path. Passed through VERBATIM (no Path normalization)
1038
+ so the stored reparse target reproduces the caller's bytes.
1025
1039
  link: Link path to create
1026
1040
  is_directory: Whether target is a directory
1027
1041
 
1028
1042
  Returns:
1029
1043
  True if successful, False otherwise
1030
1044
  """
1031
- target_str = str(target)
1045
+ target_str = os.fspath(target)
1032
1046
  link_str = str(link)
1033
1047
 
1034
1048
  # Method 1: os.symlink (Developer Mode enabled)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dazzle-filekit
3
- Version: 0.3.3
3
+ Version: 0.3.4
4
4
  Summary: Cross-platform file operations toolkit with path handling, verification, and metadata preservation
5
5
  Author: Dustin
6
6
  Author-email: Dustin Darcy <6962246+djdarcy@users.noreply.github.com>
@@ -34,6 +34,7 @@ tests/test_disk.py
34
34
  tests/test_fallback.py
35
35
  tests/test_import_stability.py
36
36
  tests/test_junction_detection_improvements.py
37
+ tests/test_link_fidelity_v034.py
37
38
  tests/test_link_primitives.py
38
39
  tests/test_metadata_v024_roundtrip.py
39
40
  tests/test_native_hash_backend.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "dazzle-filekit"
7
- version = "0.3.3"
7
+ version = "0.3.4"
8
8
  description = "Cross-platform file operations toolkit with path handling, verification, and metadata preservation"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -0,0 +1,182 @@
1
+ """Regression tests for link-node fidelity (v0.3.4).
2
+
3
+ Three defects surfaced while designing the linkmirror engine (mirroring all
4
+ NTFS links from a failing drive onto its replacement):
5
+
6
+ 1. JUNCTION TIMESTAMPS: ``apply_file_metadata`` gated the reparse-aware
7
+ timestamp path with ``Path.is_symlink()``, which is False for junctions
8
+ (IO_REPARSE_TAG_MOUNT_POINT). Junctions fell through to plain
9
+ ``os.utime``, which follows the reparse point and stamps the TARGET
10
+ directory -- the exact bug class fixed for symlinks in 0.3.1.
11
+
12
+ 2. BROKEN DIRECTORY SYMLINKS: ``create_symlink`` auto-derived
13
+ ``target_is_directory`` from ``target.is_dir()``, which is always False
14
+ for a nonexistent target -- so a broken DIRECTORY symlink was recreated
15
+ as a FILE symlink. Additionally, relative targets were probed against the
16
+ process CWD instead of the link's parent directory.
17
+
18
+ 3. TARGET STRING FIDELITY: the target was laundered through ``Path()``
19
+ before creation, which normalizes away segments like ``a\\.\\b`` and
20
+ flips ``/`` to ``\\`` -- a mirror must store the source's raw target
21
+ bytes. (Measured 2026-07-21, tests/one-offs/probe_symlink_target_fidelity.py:
22
+ os.symlink/CreateSymbolicLinkW store RELATIVE targets verbatim and the
23
+ kernel canonicalizes ABSOLUTE targets to \\\\?\\ form regardless of API --
24
+ so passing the raw string through unchanged is both necessary and
25
+ sufficient for readlink round-trip fidelity.)
26
+ """
27
+
28
+ import os
29
+ import platform
30
+
31
+ import pytest
32
+
33
+ from dazzle_filekit import apply_file_metadata
34
+ from dazzle_filekit.links import create_junction
35
+ from dazzle_filekit.operations import create_symlink
36
+
37
+ IS_WINDOWS = platform.system() == "Windows"
38
+
39
+ EPOCH_2020 = 1577836800.0 # 2020-01-01
40
+
41
+ FILE_ATTRIBUTE_DIRECTORY = 0x10
42
+
43
+
44
+ def _symlinks_available(tmp_path):
45
+ probe_t = tmp_path / "_probe_target.txt"
46
+ probe_t.write_text("x", encoding="utf-8")
47
+ probe_l = tmp_path / "_probe_link.txt"
48
+ try:
49
+ os.symlink(str(probe_t), str(probe_l))
50
+ except (OSError, NotImplementedError):
51
+ return False
52
+ os.unlink(str(probe_l))
53
+ return True
54
+
55
+
56
+ # ---------------------------------------------------------------------------
57
+ # 1. Junction timestamps target the junction, never the target directory
58
+ # ---------------------------------------------------------------------------
59
+
60
+ @pytest.mark.skipif(not IS_WINDOWS, reason="junctions are Windows-only")
61
+ def test_apply_timestamps_to_junction_does_not_touch_target_dir(tmp_path):
62
+ target_dir = tmp_path / "target_dir"
63
+ target_dir.mkdir()
64
+ (target_dir / "payload.txt").write_text("x", encoding="utf-8")
65
+ junction = tmp_path / "junc"
66
+ assert create_junction(str(target_dir), str(junction)) is True
67
+
68
+ target_mtime_before = os.lstat(str(target_dir)).st_mtime
69
+
70
+ ok = apply_file_metadata(
71
+ str(junction),
72
+ {"timestamps": {"created": EPOCH_2020, "modified": EPOCH_2020,
73
+ "accessed": EPOCH_2020}},
74
+ )
75
+ assert ok is True
76
+
77
+ # The junction NODE received the timestamp...
78
+ assert abs(os.lstat(str(junction)).st_mtime - EPOCH_2020) < 2
79
+ # ...and the target directory was not touched.
80
+ assert abs(os.lstat(str(target_dir)).st_mtime - target_mtime_before) < 2
81
+
82
+
83
+ # ---------------------------------------------------------------------------
84
+ # 2. Broken directory symlinks keep their directory kind
85
+ # ---------------------------------------------------------------------------
86
+
87
+ @pytest.mark.skipif(not IS_WINDOWS, reason="symlink kind is a Windows concept")
88
+ def test_broken_directory_symlink_keeps_directory_kind(tmp_path):
89
+ if not _symlinks_available(tmp_path):
90
+ pytest.skip("symlink creation not permitted on this platform/account")
91
+ link = tmp_path / "broken_dir_link"
92
+ ok = create_symlink(
93
+ r"no\such\directory", str(link), target_is_directory=True
94
+ )
95
+ assert ok is True
96
+ attrs = os.lstat(str(link)).st_file_attributes
97
+ assert attrs & FILE_ATTRIBUTE_DIRECTORY, (
98
+ "broken directory symlink was created as a FILE symlink"
99
+ )
100
+
101
+
102
+ @pytest.mark.skipif(not IS_WINDOWS, reason="symlink kind is a Windows concept")
103
+ def test_relative_target_kind_probed_against_link_parent(tmp_path):
104
+ """Auto-detection must resolve relative targets against the LINK's parent,
105
+ not the process CWD."""
106
+ if not _symlinks_available(tmp_path):
107
+ pytest.skip("symlink creation not permitted on this platform/account")
108
+ # tmp_path/sub/real_dir exists; CWD has no 'real_dir'
109
+ sub = tmp_path / "sub"
110
+ (sub / "real_dir").mkdir(parents=True)
111
+ link = sub / "dir_link"
112
+ old_cwd = os.getcwd()
113
+ os.chdir(str(tmp_path)) # ensure CWD != link parent
114
+ try:
115
+ ok = create_symlink("real_dir", str(link)) # no explicit kind
116
+ finally:
117
+ os.chdir(old_cwd)
118
+ assert ok is True
119
+ attrs = os.lstat(str(link)).st_file_attributes
120
+ assert attrs & FILE_ATTRIBUTE_DIRECTORY, (
121
+ "relative dir target probed against CWD instead of link parent"
122
+ )
123
+
124
+
125
+ # ---------------------------------------------------------------------------
126
+ # 3. Raw target string is stored verbatim (readlink round-trip)
127
+ # ---------------------------------------------------------------------------
128
+
129
+ def test_relative_target_stored_verbatim(tmp_path):
130
+ if not _symlinks_available(tmp_path):
131
+ pytest.skip("symlink creation not permitted on this platform/account")
132
+ link = tmp_path / "verbatim_link"
133
+ raw = r"sub\.\odd_but_legal.txt" if IS_WINDOWS else "sub/./odd_but_legal.txt"
134
+ assert create_symlink(raw, str(link), target_is_directory=False) is True
135
+ assert os.readlink(str(link)) == raw, (
136
+ "target string was normalized; a mirror must store source bytes"
137
+ )
138
+
139
+
140
+ @pytest.mark.skipif(not IS_WINDOWS, reason="junctions are Windows-only")
141
+ def test_create_junction_raw_roundtrip_and_broken_target(tmp_path):
142
+ """create_junction_raw must (a) round-trip readlink byte-identically with
143
+ a New-Item-created junction's form, and (b) create junctions whose target
144
+ does not exist -- which New-Item refuses."""
145
+ from dazzle_filekit.links import create_junction_raw
146
+ from dazzle_filekit.utils.validation import is_junction
147
+
148
+ real_target = tmp_path / "real_dir"
149
+ real_target.mkdir()
150
+
151
+ # (a) existing target: readlink form matches what the OS renders
152
+ junc = tmp_path / "junc_ok"
153
+ assert create_junction_raw(str(real_target), str(junc)) is True
154
+ assert is_junction(str(junc))
155
+ assert os.readlink(str(junc)) == "\\\\?\\" + str(real_target)
156
+ # readlink -> recreate -> readlink is stable (the mirror round-trip)
157
+ junc2 = tmp_path / "junc_ok2"
158
+ assert create_junction_raw(os.readlink(str(junc)), str(junc2)) is True
159
+ assert os.readlink(str(junc2)) == os.readlink(str(junc))
160
+
161
+ # (b) BROKEN target: creation succeeds, link classifies as junction,
162
+ # target stays broken (not resolved, not "fixed")
163
+ broken = tmp_path / "junc_broken"
164
+ missing = str(tmp_path / "no_such_dir")
165
+ assert create_junction_raw(missing, str(broken)) is True
166
+ assert is_junction(str(broken))
167
+ assert os.readlink(str(broken)) == "\\\\?\\" + missing
168
+ assert not os.path.exists(os.readlink(str(broken)))
169
+
170
+
171
+ def test_broken_relative_target_stored_verbatim(tmp_path):
172
+ """The founding case: test_broken_links\\src\\broken_link on D: stores a
173
+ relative target whose file does not exist; the mirror must reproduce it
174
+ unresolved and unrepaired."""
175
+ if not _symlinks_available(tmp_path):
176
+ pytest.skip("symlink creation not permitted on this platform/account")
177
+ link = tmp_path / "broken_link"
178
+ raw = (r"test_broken_links\src\nonexistent.txt" if IS_WINDOWS
179
+ else "test_broken_links/src/nonexistent.txt")
180
+ assert create_symlink(raw, str(link), target_is_directory=False) is True
181
+ assert os.readlink(str(link)) == raw
182
+ assert not os.path.exists(str(link)) # still broken, not "fixed"
@@ -117,19 +117,23 @@ class TestUnicodeAndLength:
117
117
 
118
118
  class TestPlatformNoneHostBehavior:
119
119
  def test_platform_none_uses_actual_host(self):
120
- # On this machine (win32) host_path_platform() must be "windows".
121
- assert host_path_platform() == PLATFORM_WINDOWS
122
- assert os.name == "nt"
123
-
124
- def test_split_platform_none_matches_os_pathsep_semantics(self):
125
- # platform=None should behave like the *declared* host dialect, which
126
- # on windows is ';' -- confirm it does NOT fall back to os.pathsep
127
- # doing something different (os.pathsep IS ';' on windows so this
128
- # is a weak check, but documents the intended contract).
129
- assert split_path_value("C:\\a;C:\\b") == ["C:\\a", "C:\\b"]
130
-
131
- def test_append_platform_none_windows_host(self):
132
- assert append_path_value("C:\\one", "C:\\two") == "C:\\one;C:\\two"
120
+ expected = PLATFORM_WINDOWS if os.name == "nt" else PLATFORM_POSIX
121
+ assert host_path_platform() == expected
122
+
123
+ def test_split_platform_none_uses_host_dialect(self):
124
+ # platform=None means the RUNNING host's dialect: ';' on a
125
+ # Windows host, ':' on POSIX.
126
+ if os.name == "nt":
127
+ assert split_path_value("C:\\a;C:\\b") == ["C:\\a", "C:\\b"]
128
+ else:
129
+ assert split_path_value("/a:/b") == ["/a", "/b"]
130
+
131
+ def test_append_platform_none_uses_host_dialect(self):
132
+ if os.name == "nt":
133
+ assert append_path_value("C:\\one", "C:\\two") == \
134
+ "C:\\one;C:\\two"
135
+ else:
136
+ assert append_path_value("/one", "/two") == "/one:/two"
133
137
 
134
138
 
135
139
  class TestMixedSeparatorsWithinOneEntry:
File without changes
File without changes
File without changes
File without changes