bpo-9949: Call normpath() in realpath() and avoid unnecessary prefixes (GH-15369)

This commit is contained in:
Steve Dower 2019-08-21 16:45:02 -07:00 committed by GitHub
parent 7ebdda0dbe
commit 06be2c7f35
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 5 deletions

View File

@ -458,7 +458,8 @@ def normpath(path):
# in the case of paths with these prefixes: # in the case of paths with these prefixes:
# \\.\ -> device names # \\.\ -> device names
# \\?\ -> literal paths # \\?\ -> literal paths
# do not do any normalization, but return the path unchanged # do not do any normalization, but return the path
# unchanged apart from the call to os.fspath()
return path return path
path = path.replace(altsep, sep) path = path.replace(altsep, sep)
prefix, path = splitdrive(path) prefix, path = splitdrive(path)
@ -575,7 +576,7 @@ else:
return abspath(tail) return abspath(tail)
def realpath(path): def realpath(path):
path = os.fspath(path) path = normpath(path)
if isinstance(path, bytes): if isinstance(path, bytes):
prefix = b'\\\\?\\' prefix = b'\\\\?\\'
unc_prefix = b'\\\\?\\UNC\\' unc_prefix = b'\\\\?\\UNC\\'
@ -586,6 +587,7 @@ else:
unc_prefix = '\\\\?\\UNC\\' unc_prefix = '\\\\?\\UNC\\'
new_unc_prefix = '\\\\' new_unc_prefix = '\\\\'
cwd = os.getcwd() cwd = os.getcwd()
did_not_exist = not exists(path)
had_prefix = path.startswith(prefix) had_prefix = path.startswith(prefix)
path = _getfinalpathname_nonstrict(path) path = _getfinalpathname_nonstrict(path)
# The path returned by _getfinalpathname will always start with \\?\ - # The path returned by _getfinalpathname will always start with \\?\ -
@ -603,7 +605,10 @@ else:
if _getfinalpathname(spath) == path: if _getfinalpathname(spath) == path:
path = spath path = spath
except OSError as ex: except OSError as ex:
pass # If the path does not exist and originally did not exist, then
# strip the prefix anyway.
if ex.winerror in {2, 3} and did_not_exist:
path = spath
return path return path

View File

@ -333,11 +333,11 @@ class TestNtpath(unittest.TestCase):
self.assertEqual(ntpath.realpath(ABSTFN + "1\\.."), self.assertEqual(ntpath.realpath(ABSTFN + "1\\.."),
ntpath.dirname(ABSTFN)) ntpath.dirname(ABSTFN))
self.assertEqual(ntpath.realpath(ABSTFN + "1\\..\\x"), self.assertEqual(ntpath.realpath(ABSTFN + "1\\..\\x"),
ntpath.dirname(P + ABSTFN) + "\\x") ntpath.dirname(ABSTFN) + "\\x")
os.symlink(ABSTFN + "x", ABSTFN + "y") os.symlink(ABSTFN + "x", ABSTFN + "y")
self.assertEqual(ntpath.realpath(ABSTFN + "1\\..\\" self.assertEqual(ntpath.realpath(ABSTFN + "1\\..\\"
+ ntpath.basename(ABSTFN) + "y"), + ntpath.basename(ABSTFN) + "y"),
P + ABSTFN + "x") ABSTFN + "x")
self.assertIn(ntpath.realpath(ABSTFN + "1\\..\\" self.assertIn(ntpath.realpath(ABSTFN + "1\\..\\"
+ ntpath.basename(ABSTFN) + "1"), + ntpath.basename(ABSTFN) + "1"),
expected) expected)