Source code for dazzle_filekit.utils.compat
"""
Compatibility utilities for cross-platform operations.
This module provides utilities for handling platform-specific differences
and ensuring consistent behavior across different operating systems.
"""
import os
import sys
import platform
import logging
from pathlib import Path
from typing import Dict, Optional, Union
# Set up module-level logger
logger = logging.getLogger(__name__)
# Detect platform
PLATFORM = platform.system().lower()
[docs]
def is_windows() -> bool:
"""
Check if the current platform is Windows.
Returns:
bool: True if Windows, False otherwise
"""
return PLATFORM == 'windows'
[docs]
def is_unix() -> bool:
"""
Check if the current platform is Unix-like (Linux, macOS, etc.).
Returns:
bool: True if Unix-like, False otherwise
"""
return PLATFORM in ('linux', 'darwin', 'freebsd', 'openbsd', 'netbsd')
[docs]
def is_wsl() -> bool:
"""Check if the current Python process is running inside WSL.
Detection strategy:
1. Check for ``WSL_DISTRO_NAME`` environment variable (set by WSL 2+)
2. Fall back to scanning ``/proc/version`` for ``microsoft`` or ``wsl``
3. Return False on non-Linux platforms
Returns:
True if running inside WSL, False otherwise.
Examples:
>>> if is_wsl():
... print("Running in WSL -- /mnt/c/ is DrvFs")
"""
if PLATFORM != "linux":
return False
# WSL 2+ sets this env var
if os.environ.get("WSL_DISTRO_NAME"):
return True
# Fallback: scan /proc/version
try:
with open("/proc/version", "r") as f:
version_str = f.read().lower()
return "microsoft" in version_str or "wsl" in version_str
except OSError:
return False
[docs]
def is_admin() -> bool:
"""
Check if the current process has administrative privileges on Windows.
Returns:
bool: True if admin, False otherwise
"""
if not is_windows():
return False
try:
import ctypes
return ctypes.windll.shell32.IsUserAnAdmin() != 0
except:
try:
import win32security
return win32security.IsUserAnAdmin()
except:
logger.debug("Cannot check admin status on Windows - missing required libraries")
return False
[docs]
def is_root() -> bool:
"""
Check if the current process has root privileges on Unix-like systems.
Returns:
bool: True if root, False otherwise
"""
if not is_unix():
return False
try:
return os.geteuid() == 0
except AttributeError:
logger.debug("Cannot check root status - os.geteuid() not available")
return False
[docs]
def fix_path_separators(path: str) -> str:
"""
Fix path separators to match the current platform.
Args:
path: Path string to fix
Returns:
Path string with corrected separators
"""
if is_windows():
# Convert forward slashes to backslashes on Windows
return path.replace('/', '\\')
else:
# Convert backslashes to forward slashes on Unix
return path.replace('\\', '/')
[docs]
def fix_path_case(path: Union[str, Path]) -> str:
"""
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.
Args:
path: Path to fix
Returns:
Path with correct case
"""
path_obj = Path(path)
if not path_obj.exists():
# Can't fix case for non-existent paths
return str(path)
if is_windows():
try:
# On Windows, try to get the actual case from the file system
# This is a no-op on case-sensitive file systems
import win32file
win_path = str(path_obj.resolve())
short_path = win32file.GetShortPathName(win_path)
return win32file.GetLongPathName(short_path)
except:
# Fall back to resolving the path
return str(path_obj.resolve())
else:
# On Unix, just resolve the path
return str(path_obj.resolve())
[docs]
def path_exists_case_sensitive(path: Union[str, Path]) -> bool:
"""
Return True if ``path`` exists with the case it is stored under.
Absorbs unctools' removed internal helper (STACK-MAP D8). On Windows
(case-insensitive but case-preserving) this compares the requested path
against the filesystem's actual-case form; on case-sensitive Unix, mere
existence suffices.
Args:
path: The path to check.
Returns:
True if the path exists (and, on Windows, matches the stored case).
"""
p = Path(path)
if not p.exists():
return False
if not is_windows():
return True
actual = fix_path_case(path)
return os.path.normpath(str(path)).lower() == os.path.normpath(str(actual)).lower()
[docs]
def get_case_sensitive_path(path: Union[str, Path]) -> str:
"""
Return ``path`` with the filesystem's actual stored case on Windows, or
unchanged on Unix / for non-existent paths.
Absorbs unctools' removed ``get_case_sensitive_path`` (STACK-MAP D8); it is
the same operation as :func:`fix_path_case`, exposed under the original name
for migration parity.
Args:
path: The path to convert.
Returns:
The case-corrected path string.
"""
return fix_path_case(path)
[docs]
def get_system_encoding() -> str:
"""
Get the default encoding for the current system.
Returns:
String representing the system encoding
"""
# Default system encoding
encoding = sys.getfilesystemencoding()
# Fall back to utf-8 if no encoding is detected
if not encoding:
if is_windows():
encoding = 'cp1252' # Windows default
else:
encoding = 'utf-8' # Unix default
return encoding
[docs]
def get_system_temp_dir() -> Path:
"""
Get the system temporary directory in a cross-platform way.
Returns:
Path to the system temporary directory
"""
import tempfile
return Path(tempfile.gettempdir())
[docs]
def get_home_dir() -> Path:
"""
Get the user's home directory in a cross-platform way.
Returns:
Path to the user's home directory
"""
return Path.home()
[docs]
def get_app_data_dir(app_name: str) -> Path:
"""
Get the application data directory in a cross-platform way.
Args:
app_name: Name of the application
Returns:
Path to the application data directory
"""
if is_windows():
# Windows: %APPDATA%\app_name
base_dir = os.environ.get('APPDATA', str(Path.home() / 'AppData' / 'Roaming'))
return Path(base_dir) / app_name
elif platform.system() == 'Darwin':
# macOS: ~/Library/Application Support/app_name
return Path.home() / 'Library' / 'Application Support' / app_name
else:
# Linux/Unix: ~/.config/app_name
xdg_config_home = os.environ.get('XDG_CONFIG_HOME', str(Path.home() / '.config'))
return Path(xdg_config_home) / app_name
# v0.2.4: normalize_cross_platform_path moved to dazzle_filekit.paths as the
# canonical path normalizer (now with an optional ``resolve=`` kwarg). The
# re-export below keeps existing imports working:
#
# from dazzle_filekit.utils.compat import normalize_cross_platform_path
#
# Prefer the direct import from dazzle_filekit for new code:
#
# from dazzle_filekit import normalize_cross_platform_path
from ..paths import normalize_cross_platform_path # noqa: F401
# get_drive_mappings() was removed in 0.3.0 (DazzleLib stack V9). Drive<->UNC
# mapping is path-identity knowledge owned by the L0 layer: this function's
# WNetGetUniversalName provider-chain scan was folded into unctools' UNCConverter
# (unctools 0.2.2, _get_mappings_with_wnetuniversalname). Use
# `unctools.converter.get_mappings()` (UNC->drive) or
# `unctools.converter.UNCConverter().get_reverse_mappings()` (drive->UNC) instead.