Fix Windows path and HOME expansion handling

This commit is contained in:
PrabinDevkota 2026-03-30 04:39:00 +05:30
parent 956b8c5855
commit d129c2d7c3
2 changed files with 40 additions and 5 deletions

View file

@ -3081,7 +3081,14 @@ def compat_ord(c):
# compat_getenv, compat_os_path_expanduser, compat_setenv
if sys.version_info >= (3, 0):
compat_getenv = os.getenv
def compat_getenv(key, default=None):
env = os.getenv(key, default)
if env is None and compat_os_name in ('nt', 'ce') and key == 'HOME':
env = os.getenv('USERPROFILE')
if env is None and os.getenv('HOMEPATH') is not None:
env = os.path.join(os.getenv('HOMEDRIVE') or '', os.getenv('HOMEPATH'))
return env
compat_expanduser = os.path.expanduser
def compat_setenv(key, value, env=os.environ):
@ -3164,6 +3171,26 @@ else:
else:
compat_expanduser = os.path.expanduser
if sys.version_info >= (3, 0) and compat_os_name in ('nt', 'ce'):
def compat_expanduser(path):
"""Expand ~ and ~user constructs.
If user or $HOME is unknown, do nothing."""
if path[:1] != '~':
return path
i, n = 1, len(path)
while i < n and path[i] not in '/\\':
i = i + 1
userhome = compat_getenv('HOME')
if userhome is None:
return path
if i != 1: # ~user
userhome = os.path.join(os.path.dirname(userhome), path[1:i])
return userhome + path[i:]
compat_os_path_expanduser = compat_expanduser

View file

@ -2166,16 +2166,19 @@ def sanitize_path(s):
"""Sanitizes and normalizes path on Windows"""
if sys.platform != 'win32':
return s
drive_or_unc, _ = os.path.splitdrive(s)
norm_path = os.path.normpath(s)
drive_or_unc, _ = os.path.splitdrive(norm_path)
if sys.version_info < (2, 7) and not drive_or_unc:
drive_or_unc, _ = os.path.splitunc(s)
norm_path = os.path.normpath(remove_start(s, drive_or_unc)).split(os.path.sep)
drive_or_unc, _ = os.path.splitunc(norm_path)
norm_path = remove_start(norm_path, drive_or_unc).split(os.path.sep)
if drive_or_unc:
norm_path.pop(0)
sanitized_path = [
path_part if path_part in ['.', '..'] else re.sub(r'(?:[/<>:"\|\\?\*]|[\s.]$)', '#', path_part)
for path_part in norm_path]
if drive_or_unc:
if not sanitized_path:
return drive_or_unc
sanitized_path.insert(0, drive_or_unc + os.path.sep)
return os.path.join(*sanitized_path)
@ -2224,7 +2227,12 @@ def sanitized_Request(url, *args, **kwargs):
def expand_path(s):
"""Expand shell variables and ~"""
return os.path.expandvars(compat_expanduser(s))
path = compat_expanduser(s)
if sys.platform == 'win32' and '%HOME%' in path and os.getenv('HOME') is None:
home_path = compat_expanduser('~')
if home_path:
path = path.replace('%HOME%', home_path)
return os.path.expandvars(path)
def orderedSet(iterable):