Skip to content

Commit d2e902e

Browse files
mansenfranzenzooba
authored andcommitted
bpo-31047: Fix ntpath.abspath for invalid paths (GH-8544)
1 parent b7fd738 commit d2e902e

File tree

3 files changed

+26
-22
lines changed

3 files changed

+26
-22
lines changed

Lib/ntpath.py

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -496,38 +496,36 @@ def normpath(path):
496496
comps.append(curdir)
497497
return prefix + sep.join(comps)
498498

499+
def _abspath_fallback(path):
500+
"""Return the absolute version of a path as a fallback function in case
501+
`nt._getfullpathname` is not available or raises OSError. See bpo-31047 for
502+
more.
503+
504+
"""
505+
506+
path = os.fspath(path)
507+
if not isabs(path):
508+
if isinstance(path, bytes):
509+
cwd = os.getcwdb()
510+
else:
511+
cwd = os.getcwd()
512+
path = join(cwd, path)
513+
return normpath(path)
499514

500515
# Return an absolute path.
501516
try:
502517
from nt import _getfullpathname
503518

504519
except ImportError: # not running on Windows - mock up something sensible
505-
def abspath(path):
506-
"""Return the absolute version of a path."""
507-
path = os.fspath(path)
508-
if not isabs(path):
509-
if isinstance(path, bytes):
510-
cwd = os.getcwdb()
511-
else:
512-
cwd = os.getcwd()
513-
path = join(cwd, path)
514-
return normpath(path)
520+
abspath = _abspath_fallback
515521

516522
else: # use native Windows method on Windows
517523
def abspath(path):
518524
"""Return the absolute version of a path."""
519-
520-
if path: # Empty path must return current working directory.
521-
path = os.fspath(path)
522-
try:
523-
path = _getfullpathname(path)
524-
except OSError:
525-
pass # Bad path - return unchanged.
526-
elif isinstance(path, bytes):
527-
path = os.getcwdb()
528-
else:
529-
path = os.getcwd()
530-
return normpath(path)
525+
try:
526+
return _getfullpathname(path)
527+
except OSError:
528+
return _abspath_fallback(path)
531529

532530
# realpath is a no-op on systems without islink support
533531
realpath = abspath

Lib/test/test_ntpath.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,10 @@ def test_expanduser(self):
280280
@unittest.skipUnless(nt, "abspath requires 'nt' module")
281281
def test_abspath(self):
282282
tester('ntpath.abspath("C:\\")', "C:\\")
283+
with support.temp_cwd(support.TESTFN) as cwd_dir: # bpo-31047
284+
tester('ntpath.abspath("")', cwd_dir)
285+
tester('ntpath.abspath(" ")', cwd_dir + "\\ ")
286+
tester('ntpath.abspath("?")', cwd_dir + "\\?")
283287

284288
def test_relpath(self):
285289
tester('ntpath.relpath("a")', 'a')
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix ``ntpath.abspath`` for invalid paths on windows. Patch by Franz
2+
Woellert.

0 commit comments

Comments
 (0)