blob: a491363f3f9395e412d4b3b72877b9cc4518e222 [file] [log] [blame]
Guido van Rossumab096c91997-04-02 05:47:11 +00001"""Filename globbing utility."""
Guido van Rossum65a96201991-01-01 18:17:49 +00002
Guido van Rossumbba77af1992-01-12 23:26:24 +00003import os
Guido van Rossum9694fca1997-10-22 21:00:49 +00004import re
Guido van Rossumd8faa362007-04-27 19:54:29 +00005import fnmatch
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +03006import itertools
7import stat
Steve Dower60419a72019-06-24 08:42:54 -07008import sys
Guido van Rossum65a96201991-01-01 18:17:49 +00009
Serhiy Storchaka04b57002015-11-09 23:18:19 +020010__all__ = ["glob", "iglob", "escape"]
Guido van Rossumbba77af1992-01-12 23:26:24 +000011
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +030012def glob(pathname, *, root_dir=None, dir_fd=None, recursive=False):
Tim Peters07e99cb2001-01-14 23:47:14 +000013 """Return a list of paths matching a pathname pattern.
Guido van Rossumab096c91997-04-02 05:47:11 +000014
Petri Lehtinenee4a20b2013-02-23 19:53:03 +010015 The pattern may contain simple shell-style wildcards a la
16 fnmatch. However, unlike fnmatch, filenames starting with a
17 dot are special cases that are not matched by '*' and '?'
18 patterns.
Guido van Rossumab096c91997-04-02 05:47:11 +000019
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030020 If recursive is true, the pattern '**' will match any files and
21 zero or more directories and subdirectories.
Tim Peters07e99cb2001-01-14 23:47:14 +000022 """
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +030023 return list(iglob(pathname, root_dir=root_dir, dir_fd=dir_fd, recursive=recursive))
Johannes Gijsbers836f5432005-01-08 13:13:19 +000024
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +030025def iglob(pathname, *, root_dir=None, dir_fd=None, recursive=False):
Benjamin Petersond23f8222009-04-05 19:13:16 +000026 """Return an iterator which yields the paths matching a pathname pattern.
Johannes Gijsbers836f5432005-01-08 13:13:19 +000027
Petri Lehtinenee4a20b2013-02-23 19:53:03 +010028 The pattern may contain simple shell-style wildcards a la
29 fnmatch. However, unlike fnmatch, filenames starting with a
30 dot are special cases that are not matched by '*' and '?'
31 patterns.
Johannes Gijsbers836f5432005-01-08 13:13:19 +000032
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030033 If recursive is true, the pattern '**' will match any files and
34 zero or more directories and subdirectories.
Johannes Gijsbers836f5432005-01-08 13:13:19 +000035 """
Serhiy Storchaka1d346992020-10-20 19:45:38 +030036 sys.audit("glob.glob", pathname, recursive)
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +030037 if root_dir is not None:
38 root_dir = os.fspath(root_dir)
39 else:
40 root_dir = pathname[:0]
41 it = _iglob(pathname, root_dir, dir_fd, recursive, False)
42 if not pathname or recursive and _isrecursive(pathname[:2]):
43 try:
44 s = next(it) # skip empty string
45 if s:
46 it = itertools.chain((s,), it)
47 except StopIteration:
48 pass
Serhiy Storchaka735b7902015-11-09 23:12:07 +020049 return it
50
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +030051def _iglob(pathname, root_dir, dir_fd, recursive, dironly):
Tim Golden9b3fb0c2012-11-06 15:33:30 +000052 dirname, basename = os.path.split(pathname)
Serhiy Storchaka6f201702014-08-12 12:55:12 +030053 if not has_magic(pathname):
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030054 assert not dironly
Serhiy Storchaka6f201702014-08-12 12:55:12 +030055 if basename:
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +030056 if _lexists(_join(root_dir, pathname), dir_fd):
Serhiy Storchaka6f201702014-08-12 12:55:12 +030057 yield pathname
58 else:
59 # Patterns ending with a slash should match only directories
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +030060 if _isdir(_join(root_dir, dirname), dir_fd):
Serhiy Storchaka6f201702014-08-12 12:55:12 +030061 yield pathname
62 return
Tim Golden9b3fb0c2012-11-06 15:33:30 +000063 if not dirname:
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030064 if recursive and _isrecursive(basename):
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +030065 yield from _glob2(root_dir, basename, dir_fd, dironly)
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030066 else:
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +030067 yield from _glob1(root_dir, basename, dir_fd, dironly)
Tim Golden9b3fb0c2012-11-06 15:33:30 +000068 return
Antoine Pitrou3d068b22012-12-16 13:49:37 +010069 # `os.path.split()` returns the argument itself as a dirname if it is a
70 # drive or UNC path. Prevent an infinite recursion if a drive or UNC path
71 # contains magic characters (i.e. r'\\?\C:').
72 if dirname != pathname and has_magic(dirname):
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +030073 dirs = _iglob(dirname, root_dir, dir_fd, recursive, True)
Tim Golden9b3fb0c2012-11-06 15:33:30 +000074 else:
75 dirs = [dirname]
76 if has_magic(basename):
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030077 if recursive and _isrecursive(basename):
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030078 glob_in_dir = _glob2
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030079 else:
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030080 glob_in_dir = _glob1
Tim Golden9b3fb0c2012-11-06 15:33:30 +000081 else:
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030082 glob_in_dir = _glob0
Tim Golden9b3fb0c2012-11-06 15:33:30 +000083 for dirname in dirs:
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +030084 for name in glob_in_dir(_join(root_dir, dirname), basename, dir_fd, dironly):
Tim Golden9b3fb0c2012-11-06 15:33:30 +000085 yield os.path.join(dirname, name)
Johannes Gijsbers836f5432005-01-08 13:13:19 +000086
87# These 2 helper functions non-recursively glob inside a literal directory.
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030088# They return a list of basenames. _glob1 accepts a pattern while _glob0
Johannes Gijsbers836f5432005-01-08 13:13:19 +000089# takes a literal basename (so it only has to check for its existence).
Guido van Rossum65a96201991-01-01 18:17:49 +000090
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +030091def _glob1(dirname, pattern, dir_fd, dironly):
92 names = list(_iterdir(dirname, dir_fd, dironly))
Hynek Schlawacke26568f2012-12-27 10:10:11 +010093 if not _ishidden(pattern):
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030094 names = (x for x in names if not _ishidden(x))
Guido van Rossumd8faa362007-04-27 19:54:29 +000095 return fnmatch.filter(names, pattern)
Guido van Rossum65a96201991-01-01 18:17:49 +000096
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +030097def _glob0(dirname, basename, dir_fd, dironly):
98 if basename:
99 if _lexists(_join(dirname, basename), dir_fd):
Johannes Gijsbers836f5432005-01-08 13:13:19 +0000100 return [basename]
101 else:
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +0300102 # `os.path.split()` returns an empty basename for paths ending with a
103 # directory separator. 'q*x/' should match only directories.
104 if _isdir(dirname, dir_fd):
Johannes Gijsbers836f5432005-01-08 13:13:19 +0000105 return [basename]
106 return []
107
Serhiy Storchaka28ab6342016-09-06 22:33:41 +0300108# Following functions are not public but can be used by third-party code.
109
110def glob0(dirname, pattern):
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +0300111 return _glob0(dirname, pattern, None, False)
Serhiy Storchaka28ab6342016-09-06 22:33:41 +0300112
113def glob1(dirname, pattern):
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +0300114 return _glob1(dirname, pattern, None, False)
Serhiy Storchaka28ab6342016-09-06 22:33:41 +0300115
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300116# This helper function recursively yields relative pathnames inside a literal
117# directory.
118
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +0300119def _glob2(dirname, pattern, dir_fd, dironly):
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300120 assert _isrecursive(pattern)
Serhiy Storchaka735b7902015-11-09 23:12:07 +0200121 yield pattern[:0]
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +0300122 yield from _rlistdir(dirname, dir_fd, dironly)
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300123
Serhiy Storchaka28ab6342016-09-06 22:33:41 +0300124# If dironly is false, yields all file names inside a directory.
125# If dironly is true, yields only directory names.
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +0300126def _iterdir(dirname, dir_fd, dironly):
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300127 try:
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +0300128 fd = None
129 fsencode = None
130 if dir_fd is not None:
131 if dirname:
132 fd = arg = os.open(dirname, _dir_open_flags, dir_fd=dir_fd)
133 else:
134 arg = dir_fd
135 if isinstance(dirname, bytes):
136 fsencode = os.fsencode
137 elif dirname:
138 arg = dirname
139 elif isinstance(dirname, bytes):
140 arg = bytes(os.curdir, 'ASCII')
141 else:
142 arg = os.curdir
143 try:
144 with os.scandir(arg) as it:
145 for entry in it:
146 try:
147 if not dironly or entry.is_dir():
148 if fsencode is not None:
149 yield fsencode(entry.name)
150 else:
151 yield entry.name
152 except OSError:
153 pass
154 finally:
155 if fd is not None:
156 os.close(fd)
Serhiy Storchaka28ab6342016-09-06 22:33:41 +0300157 except OSError:
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300158 return
Serhiy Storchaka28ab6342016-09-06 22:33:41 +0300159
160# Recursively yields relative pathnames inside a literal directory.
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +0300161def _rlistdir(dirname, dir_fd, dironly):
162 names = list(_iterdir(dirname, dir_fd, dironly))
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300163 for x in names:
164 if not _ishidden(x):
165 yield x
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +0300166 path = _join(dirname, x) if dirname else x
167 for y in _rlistdir(path, dir_fd, dironly):
168 yield _join(x, y)
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300169
Guido van Rossumc2ef5c21992-01-12 23:32:11 +0000170
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +0300171def _lexists(pathname, dir_fd):
172 # Same as os.path.lexists(), but with dir_fd
173 if dir_fd is None:
174 return os.path.lexists(pathname)
175 try:
176 os.lstat(pathname, dir_fd=dir_fd)
177 except (OSError, ValueError):
178 return False
179 else:
180 return True
181
182def _isdir(pathname, dir_fd):
183 # Same as os.path.isdir(), but with dir_fd
184 if dir_fd is None:
185 return os.path.isdir(pathname)
186 try:
187 st = os.stat(pathname, dir_fd=dir_fd)
188 except (OSError, ValueError):
189 return False
190 else:
191 return stat.S_ISDIR(st.st_mode)
192
193def _join(dirname, basename):
194 # It is common if dirname or basename is empty
195 if not dirname or not basename:
196 return dirname or basename
197 return os.path.join(dirname, basename)
198
Serhiy Storchakafd32fff2013-11-18 13:06:43 +0200199magic_check = re.compile('([*?[])')
200magic_check_bytes = re.compile(b'([*?[])')
Tim Golden9b3fb0c2012-11-06 15:33:30 +0000201
Guido van Rossum65a96201991-01-01 18:17:49 +0000202def has_magic(s):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000203 if isinstance(s, bytes):
204 match = magic_check_bytes.search(s)
205 else:
206 match = magic_check.search(s)
207 return match is not None
Hynek Schlawacke26568f2012-12-27 10:10:11 +0100208
209def _ishidden(path):
210 return path[0] in ('.', b'.'[0])
Serhiy Storchakafd32fff2013-11-18 13:06:43 +0200211
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300212def _isrecursive(pattern):
213 if isinstance(pattern, bytes):
214 return pattern == b'**'
215 else:
216 return pattern == '**'
217
Serhiy Storchakafd32fff2013-11-18 13:06:43 +0200218def escape(pathname):
219 """Escape all special characters.
220 """
221 # Escaping is done by wrapping any of "*?[" between square brackets.
222 # Metacharacters do not work in the drive part and shouldn't be escaped.
223 drive, pathname = os.path.splitdrive(pathname)
224 if isinstance(pathname, bytes):
225 pathname = magic_check_bytes.sub(br'[\1]', pathname)
226 else:
227 pathname = magic_check.sub(r'[\1]', pathname)
228 return drive + pathname
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +0300229
230
231_dir_open_flags = os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0)