Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Doc/library/glob.rst
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ The :mod:`glob` module defines the following functions:
.. versionchanged:: 3.11
Added the *include_hidden* parameter.

.. versionchanged:: next
Fixed ``~`` expansion to user's home directory.


.. function:: iglob(pathname, *, root_dir=None, dir_fd=None, recursive=False, \
include_hidden=False)
Expand Down
9 changes: 9 additions & 0 deletions Lib/glob.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ def iglob(pathname, *, root_dir=None, dir_fd=None, recursive=False,
"""
sys.audit("glob.glob", pathname, recursive)
sys.audit("glob.glob/2", pathname, recursive, root_dir, dir_fd)
# expand ~; see issue 84037
if isinstance(pathname, str):
if pathname == '~' or pathname.startswith('~' + os.sep):
from pathlib import Path
pathname = pathname.replace('~', str(Path.home()), 1)
else:
if pathname == b'~' or pathname.startswith(b'~' + os.sep.encode('ascii')):
from pathlib import Path
pathname = pathname.replace(b'~', bytes(Path.home()), 1)
if root_dir is not None:
root_dir = os.fspath(root_dir)
else:
Expand Down
16 changes: 16 additions & 0 deletions Lib/test/test_glob.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import shutil
import sys
import unittest
import unittest.mock
import warnings

from test.support import is_wasi, Py_DEBUG
Expand Down Expand Up @@ -210,6 +211,21 @@ def test_glob_bytes_directory_with_trailing_slash(self):
[os.fsencode(self.norm('aaa') + os.sep),
os.fsencode(self.norm('aab') + os.sep)])

def test_glob_tilde_expansion(self):
with unittest.mock.patch('pathlib.Path.home', return_value=self.tempdir):
results = glob.glob('~')
self.assertEqual([self.tempdir], results)

results = glob.glob('~/*')
self.assertIn(self.tempdir + '/a', results)

# test it is not expanded when it is not a path
tilde_file = os.path.join(self.tempdir, '~file')
create_empty_file(tilde_file)
with change_cwd(self.tempdir):
results = glob.glob('~*')
self.assertIn('~file', results)

@skip_unless_symlink
def test_glob_symlinks(self):
eq = self.assertSequencesEqual_noorder
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Implement ``~`` expansion in :func:`glob.glob`.
Loading