bpo-31047: Fix ntpath.abspath for invalid paths (GH-8544) · python/cpython@b0bf51b (original) (raw)

3 files changed

lines changed

Original file line number Diff line number Diff line change
@@ -518,38 +518,36 @@ def normpath(path):
518 518 comps.append(curdir)
519 519 return prefix + sep.join(comps)
520 520
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)
521 536
522 537 # Return an absolute path.
523 538 try:
524 539 from nt import _getfullpathname
525 540
526 541 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
537 543
538 544 else: # use native Windows method on Windows
539 545 def abspath(path):
540 546 """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)
553 551
554 552 # realpath is a no-op on systems without islink support
555 553 realpath = abspath
Original file line number Diff line number Diff line change
@@ -303,6 +303,10 @@ def test_abspath(self):
303 303 try:
304 304 import nt
305 305 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 + "\\?")
306 310 except ImportError:
307 311 self.skipTest('nt module not available')
308 312
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
1 +Fix ``ntpath.abspath`` for invalid paths on windows. Patch by Franz
2 +Woellert.