Source code for dazzle_filekit.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 :mod:`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 :func:`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-Item`` respectively, replacing preservelib's
  banned ``cmd /c dir /al`` and ``cmd /c mklink /j`` shell-outs;
* a hardlink (detected via ``st_nlink > 1``) is reported as a valid link with
  no traversable target -- it is NOT marked ``is_broken`` (preservelib's
  ``analyze_link`` marked it broken because ``get_link_target`` returns None).
"""
from __future__ import annotations

import logging
import os
import subprocess
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, Optional, Union

from dazzle_lib import LinkTargetDict  # cross-layer "what is this link" shape (D10)

from .utils.validation import is_junction, read_junction_target

logger = logging.getLogger(__name__)

# Link kinds reported by :func:`detect_link_type` / :class:`LinkInfo`.
LINK_SYMLINK = "symlink"
LINK_JUNCTION = "junction"
LINK_HARDLINK = "hardlink"


[docs] @dataclass class LinkInfo: """Intrinsic facts about a single link (no destination relationship). Attributes: link_path: the link itself. kind: ``'symlink'`` | ``'junction'`` | ``'hardlink'`` | ``None`` (not a link). raw_target: target as stored in the link (readlink result for symlinks, the reparse PrintName for junctions). ``None`` for hardlinks (which have no single target) and for non-links. resolved_target: absolute target after resolution (``None`` when there is no resolvable target). is_broken: a symlink/junction whose target cannot be read or does not exist. A hardlink is never broken. is_circular: 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: free-form extra context for callers. """ link_path: Path kind: Optional[str] = None raw_target: Optional[str] = None resolved_target: Optional[Path] = None is_broken: bool = False is_circular: bool = False metadata: Dict[str, Any] = field(default_factory=dict)
[docs] def to_dict(self) -> LinkTargetDict: """Serialize to the cross-layer LinkTargetDict (STACK-MAP D10). ``link_path`` is intentionally NOT in the dict: LinkTargetDict describes the link's TARGET, and a caller already knows which link it analyzed. Read ``self.link_path`` on the object when you need the link's own path. """ return { "kind": self.kind, "raw_target": self.raw_target, "resolved_target": str(self.resolved_target) if self.resolved_target else None, "is_broken": self.is_broken, "is_circular": self.is_circular, }
def _strip_extended_prefix(target: str) -> str: """Strip the Windows ``\\\\?\\`` extended-length prefix that ``os.readlink`` returns for absolute symlink targets (``\\\\?\\UNC\\`` -> ``\\\\``).""" if target.startswith("\\\\?\\UNC\\"): return "\\\\" + target[len("\\\\?\\UNC\\"):] if target.startswith("\\\\?\\"): return target[len("\\\\?\\"):] return target def _remove_existing(link: Path) -> bool: """Remove an existing link/empty target at ``link`` so a new one can be created. Returns True on success.""" try: if link.is_symlink() or link.is_file(): link.unlink() elif link.is_dir(): # A junction or directory symlink is removed with rmdir without # touching its target; a real (empty) directory is removed too. os.rmdir(link) return True except OSError as e: logger.error(f"Failed to remove existing path {link}: {e}") return False
[docs] def create_junction( target: Union[str, Path], link: Union[str, Path], force: bool = False, ) -> bool: """Create a Windows NTFS junction at ``link`` pointing to ``target``. Uses PowerShell ``New-Item -ItemType Junction`` (per the house rule that junctions/symlinks are created via PowerShell, never ``cmd /c mklink``). Junctions are directory-only and Windows-only. Returns True on success, False otherwise. """ target_path = Path(target) link_path = Path(link) if os.name != "nt": logger.error("Junctions are only supported on Windows") return False if link_path.exists() or link_path.is_symlink(): if not force: logger.warning(f"Link path already exists: {link_path}") return False if not _remove_existing(link_path): return False try: link_path.parent.mkdir(parents=True, exist_ok=True) except OSError as e: logger.error(f"Failed to create parent directories for {link_path}: {e}") return False # Single-quote the paths for PowerShell, doubling any embedded single quote. link_ps = str(link_path).replace("'", "''") target_ps = str(target_path).replace("'", "''") ps = ( "$ErrorActionPreference='Stop'; " f"New-Item -ItemType Junction -Path '{link_ps}' -Target '{target_ps}' | Out-Null" ) try: result = subprocess.run( ["powershell", "-NoProfile", "-NonInteractive", "-Command", ps], capture_output=True, text=True, check=False, ) if result.returncode == 0: logger.debug(f"Created junction: {link_path} -> {target_path}") return True logger.warning(f"New-Item junction failed: {result.stderr.strip()}") return False except Exception as e: # noqa: BLE001 - subprocess/env failures are non-fatal logger.warning(f"PowerShell junction creation failed: {e}") return False
[docs] def create_junction_raw( target: Union[str, Path], link: Union[str, Path], force: bool = False, ) -> bool: """Create an NTFS junction by writing the mount-point reparse buffer directly (``FSCTL_SET_REPARSE_POINT``), no subprocess. Differences from :func:`create_junction` (PowerShell ``New-Item``): - The target does NOT need to exist -- ``New-Item`` refuses 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 by ``os.readlink`` on another junction) and plain ``C:\\x`` are both accepted; the NT-namespace SubstituteName (``\\??\\...``) and the user-facing PrintName are derived without other normalization, so ``os.readlink`` round-trips byte-identically. Unprivileged (junctions never require SeCreateSymbolicLinkPrivilege). Windows-only, directory-only. Returns True on success. """ raw_target = os.fspath(target) link_path = Path(link) if os.name != "nt": logger.error("Junctions are only supported on Windows") return False if link_path.exists() or link_path.is_symlink(): if not force: logger.warning(f"Link path already exists: {link_path}") return False if not _remove_existing(link_path): return False # SubstituteName lives in the NT namespace (\??\); PrintName is the # user-facing form. os.readlink() renders \??\ as \\?\, so accept both. if raw_target.startswith("\\??\\"): substitute = raw_target print_name = raw_target[4:] elif raw_target.startswith("\\\\?\\"): substitute = "\\??\\" + raw_target[4:] print_name = raw_target[4:] else: substitute = "\\??\\" + raw_target print_name = raw_target try: link_path.parent.mkdir(parents=True, exist_ok=True) os.mkdir(link_path) except OSError as e: logger.error(f"Failed to create junction directory {link_path}: {e}") return False try: import ctypes from ctypes import wintypes kernel32 = ctypes.windll.kernel32 GENERIC_WRITE = 0x40000000 OPEN_EXISTING = 3 FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000 FILE_FLAG_BACKUP_SEMANTICS = 0x02000000 FILE_SHARE_READ_WRITE_DELETE = 0x01 | 0x02 | 0x04 FSCTL_SET_REPARSE_POINT = 0x000900A4 IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003 subst_b = substitute.encode("utf-16-le") print_b = print_name.encode("utf-16-le") # MountPointReparseBuffer: 4 offset/length WORDs + PathBuffer holding # SubstituteName \0 PrintName \0 (UTF-16LE, lengths exclude the NULs). path_buffer = subst_b + b"\x00\x00" + print_b + b"\x00\x00" reparse_data_length = 8 + len(path_buffer) header = ( IO_REPARSE_TAG_MOUNT_POINT.to_bytes(4, "little") + reparse_data_length.to_bytes(2, "little") + b"\x00\x00" # Reserved + (0).to_bytes(2, "little") # SubstituteNameOffset + len(subst_b).to_bytes(2, "little") # SubstituteNameLength + (len(subst_b) + 2).to_bytes(2, "little") # PrintNameOffset + len(print_b).to_bytes(2, "little") # PrintNameLength ) buf = header + path_buffer handle = kernel32.CreateFileW( str(link_path), GENERIC_WRITE, FILE_SHARE_READ_WRITE_DELETE, None, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, None, ) if handle == wintypes.HANDLE(-1).value: raise OSError(f"CreateFileW failed for {link_path}") try: bytes_returned = wintypes.DWORD(0) ok = kernel32.DeviceIoControl( handle, FSCTL_SET_REPARSE_POINT, buf, len(buf), None, 0, ctypes.byref(bytes_returned), None, ) if not ok: raise OSError( f"FSCTL_SET_REPARSE_POINT failed " f"(winerror={ctypes.get_last_error()})" ) finally: kernel32.CloseHandle(handle) logger.debug(f"Created raw junction: {link_path} -> {raw_target}") return True except Exception as e: # noqa: BLE001 - report and clean up the stub dir logger.error(f"Raw junction creation failed for {link_path}: {e}") try: os.rmdir(link_path) except OSError: pass return False