GH-106330: Fix matching of empty path in `pathlib.PurePath.match()` (GH-106331)

We match paths using the `_lines` attribute, which is derived from the
path's string representation. The bug arises because an empty path's string
representation is `'.'` (not `''`), which is matched by the `'*'` wildcard.
This commit is contained in:
Barney Gale 2023-07-03 21:29:44 +01:00 committed by GitHub
parent e5862113dd
commit b4efdf8cda
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 12 additions and 2 deletions

View File

@ -463,8 +463,12 @@ class PurePath:
try:
return self._lines_cached
except AttributeError:
trans = _SWAP_SEP_AND_NEWLINE[self._flavour.sep]
self._lines_cached = str(self).translate(trans)
path_str = str(self)
if path_str == '.':
self._lines_cached = ''
else:
trans = _SWAP_SEP_AND_NEWLINE[self._flavour.sep]
self._lines_cached = path_str.translate(trans)
return self._lines_cached
def __eq__(self, other):

View File

@ -384,6 +384,10 @@ class PurePathTest(unittest.TestCase):
self.assertTrue(P('A.py').match('a.PY', case_sensitive=False))
self.assertFalse(P('c:/a/B.Py').match('C:/A/*.pY', case_sensitive=True))
self.assertTrue(P('/a/b/c.py').match('/A/*/*.Py', case_sensitive=False))
# Matching against empty path
self.assertFalse(P().match('*'))
self.assertTrue(P().match('**'))
self.assertFalse(P().match('**/*'))
def test_ordering_common(self):
# Ordering is tuple-alike.

View File

@ -0,0 +1,2 @@
Fix incorrect matching of empty paths in :meth:`pathlib.PurePath.match`.
This bug was introduced in Python 3.12.0 beta 1.