Skip to content

Commit e320740

Browse files
committed
[3.12] pythonGH-106330: Fix matching of empty path in pathlib.PurePath.match() (pythonGH-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. (cherry picked from commit b4efdf8) Co-authored-by: Barney Gale <[email protected]>
1 parent 887a7e6 commit e320740

File tree

3 files changed

+12
-2
lines changed

3 files changed

+12
-2
lines changed

Lib/pathlib.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -501,8 +501,12 @@ def _lines(self):
501501
try:
502502
return self._lines_cached
503503
except AttributeError:
504-
trans = _SWAP_SEP_AND_NEWLINE[self._flavour.sep]
505-
self._lines_cached = str(self).translate(trans)
504+
path_str = str(self)
505+
if path_str == '.':
506+
self._lines_cached = ''
507+
else:
508+
trans = _SWAP_SEP_AND_NEWLINE[self._flavour.sep]
509+
self._lines_cached = path_str.translate(trans)
506510
return self._lines_cached
507511

508512
def __eq__(self, other):

Lib/test/test_pathlib.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,10 @@ def test_match_common(self):
317317
self.assertTrue(P('A.py').match('a.PY', case_sensitive=False))
318318
self.assertFalse(P('c:/a/B.Py').match('C:/A/*.pY', case_sensitive=True))
319319
self.assertTrue(P('/a/b/c.py').match('/A/*/*.Py', case_sensitive=False))
320+
# Matching against empty path
321+
self.assertFalse(P().match('*'))
322+
self.assertTrue(P().match('**'))
323+
self.assertFalse(P().match('**/*'))
320324

321325
def test_ordering_common(self):
322326
# Ordering is tuple-alike.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix incorrect matching of empty paths in :meth:`pathlib.PurePath.match`.
2+
This bug was introduced in Python 3.12.0 beta 1.

0 commit comments

Comments
 (0)