Skip to content

GH-92737: Corrected posixpath behaviour to not assume '//' is equivalent to '/'. #103798

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
17 changes: 14 additions & 3 deletions Lib/posixpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,16 +524,27 @@ def relpath(path, start=None):
start = os.fspath(start)

try:
start_list = [x for x in abspath(start).split(sep) if x]
path_list = [x for x in abspath(path).split(sep) if x]
start_abs = abspath(normpath(start))
path_abs = abspath(normpath(path))

_, start_root, start_rest = splitroot(start_abs)
_, path_root, path_rest = splitroot(path_abs)

if start_root != path_root:
raise ValueError(
f"Path is on root {path_root!r}, start on root {start_root!r}"
)

start_list = [x for x in start_rest.split(sep) if x]
path_list = [x for x in path_rest.split(sep) if x]
# Work out how much of the filepath is shared by start and path.
i = len(commonprefix([start_list, path_list]))

rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list)
except (TypeError, AttributeError, BytesWarning, DeprecationWarning):
except (TypeError, ValueError, AttributeError, BytesWarning, DeprecationWarning):
genericpath._check_arg_types('relpath', path, start)
raise

Expand Down
6 changes: 6 additions & 0 deletions Lib/test/test_posixpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,12 @@ def test_relpath(self):
self.assertEqual(posixpath.relpath("/", "/"), '.')
self.assertEqual(posixpath.relpath("/a", "/a"), '.')
self.assertEqual(posixpath.relpath("/a/b", "/a/b"), '.')
self.assertRaises(ValueError, posixpath.relpath, "/foo/bar", "//foo")
self.assertRaises(ValueError, posixpath.relpath, "//foo/bar", "/foo")
self.assertRaises(ValueError, posixpath.relpath, "//foo/bar", "///foo")
self.assertEqual(posixpath.relpath("//foo/bar", "//foo"), "bar")
self.assertEqual(posixpath.relpath("///foo/bar", "/foo"), "bar")
self.assertEqual(posixpath.relpath("/foo/bar/baz", "///foo"), "bar/baz")
finally:
os.getcwd = real_getcwd

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fixed posixpath.relpath to not assume '//' is equivalent to '/'. Patch by
Adam Chhina.