Skip to content

Commit b0bf51b

Browse files
authored
bpo-31047: Fix ntpath.abspath for invalid paths (GH-8544)
1 parent 3da5c5c commit b0bf51b

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
@@ -518,38 +518,36 @@ def normpath(path):
518518
comps.append(curdir)
519519
return prefix + sep.join(comps)
520520

521+
def _abspath_fallback(path):
522+
"""Return the absolute version of a path as a fallback function in case
523+
`nt._getfullpathname` is not available or raises OSError. See bpo-31047 for
524+
more.
525+
526+
"""
527+
528+
path = os.fspath(path)
529+
if not isabs(path):
530+
if isinstance(path, bytes):
531+
cwd = os.getcwdb()
532+
else:
533+
cwd = os.getcwd()
534+
path = join(cwd, path)
535+
return normpath(path)
521536

522537
# Return an absolute path.
523538
try:
524539
from nt import _getfullpathname
525540

526541
except ImportError: # not running on Windows - mock up something sensible
527-
def abspath(path):
528-
"""Return the absolute version of a path."""
529-
path = os.fspath(path)
530-
if not isabs(path):
531-
if isinstance(path, bytes):
532-
cwd = os.getcwdb()
533-
else:
534-
cwd = os.getcwd()
535-
path = join(cwd, path)
536-
return normpath(path)
542+
abspath = _abspath_fallback
537543

538544
else: # use native Windows method on Windows
539545
def abspath(path):
540546
"""Return the absolute version of a path."""
541-
542-
if path: # Empty path must return current working directory.
543-
path = os.fspath(path)
544-
try:
545-
path = _getfullpathname(path)
546-
except OSError:
547-
pass # Bad path - return unchanged.
548-
elif isinstance(path, bytes):
549-
path = os.getcwdb()
550-
else:
551-
path = os.getcwd()
552-
return normpath(path)
547+
try:
548+
return _getfullpathname(path)
549+
except OSError:
550+
return _abspath_fallback(path)
553551

554552
# realpath is a no-op on systems without islink support
555553
realpath = abspath

Lib/test/test_ntpath.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,10 @@ def test_abspath(self):
303303
try:
304304
import nt
305305
tester('ntpath.abspath("C:\\")', "C:\\")
306+
with support.temp_cwd(support.TESTFN) as cwd_dir: # bpo-31047
307+
tester('ntpath.abspath("")', cwd_dir)
308+
tester('ntpath.abspath(" ")', cwd_dir + "\\ ")
309+
tester('ntpath.abspath("?")', cwd_dir + "\\?")
306310
except ImportError:
307311
self.skipTest('nt module not available')
308312

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)