glob.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. """Filename globbing utility."""
  2. import contextlib
  3. import os
  4. import re
  5. import fnmatch
  6. import itertools
  7. import stat
  8. import sys
  9. __all__ = ["glob", "iglob", "escape"]
  10. def glob(pathname, *, root_dir=None, dir_fd=None, recursive=False,
  11. include_hidden=False):
  12. """Return a list of paths matching a pathname pattern.
  13. The pattern may contain simple shell-style wildcards a la
  14. fnmatch. Unlike fnmatch, filenames starting with a
  15. dot are special cases that are not matched by '*' and '?'
  16. patterns by default.
  17. If `include_hidden` is true, the patterns '*', '?', '**' will match hidden
  18. directories.
  19. If `recursive` is true, the pattern '**' will match any files and
  20. zero or more directories and subdirectories.
  21. """
  22. return list(iglob(pathname, root_dir=root_dir, dir_fd=dir_fd, recursive=recursive,
  23. include_hidden=include_hidden))
  24. def iglob(pathname, *, root_dir=None, dir_fd=None, recursive=False,
  25. include_hidden=False):
  26. """Return an iterator which yields the paths matching a pathname pattern.
  27. The pattern may contain simple shell-style wildcards a la
  28. fnmatch. However, unlike fnmatch, filenames starting with a
  29. dot are special cases that are not matched by '*' and '?'
  30. patterns.
  31. If recursive is true, the pattern '**' will match any files and
  32. zero or more directories and subdirectories.
  33. """
  34. sys.audit("glob.glob", pathname, recursive)
  35. sys.audit("glob.glob/2", pathname, recursive, root_dir, dir_fd)
  36. if root_dir is not None:
  37. root_dir = os.fspath(root_dir)
  38. else:
  39. root_dir = pathname[:0]
  40. it = _iglob(pathname, root_dir, dir_fd, recursive, False,
  41. include_hidden=include_hidden)
  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
  49. return it
  50. def _iglob(pathname, root_dir, dir_fd, recursive, dironly,
  51. include_hidden=False):
  52. dirname, basename = os.path.split(pathname)
  53. if not has_magic(pathname):
  54. assert not dironly
  55. if basename:
  56. if _lexists(_join(root_dir, pathname), dir_fd):
  57. yield pathname
  58. else:
  59. # Patterns ending with a slash should match only directories
  60. if _isdir(_join(root_dir, dirname), dir_fd):
  61. yield pathname
  62. return
  63. if not dirname:
  64. if recursive and _isrecursive(basename):
  65. yield from _glob2(root_dir, basename, dir_fd, dironly,
  66. include_hidden=include_hidden)
  67. else:
  68. yield from _glob1(root_dir, basename, dir_fd, dironly,
  69. include_hidden=include_hidden)
  70. return
  71. # `os.path.split()` returns the argument itself as a dirname if it is a
  72. # drive or UNC path. Prevent an infinite recursion if a drive or UNC path
  73. # contains magic characters (i.e. r'\\?\C:').
  74. if dirname != pathname and has_magic(dirname):
  75. dirs = _iglob(dirname, root_dir, dir_fd, recursive, True,
  76. include_hidden=include_hidden)
  77. else:
  78. dirs = [dirname]
  79. if has_magic(basename):
  80. if recursive and _isrecursive(basename):
  81. glob_in_dir = _glob2
  82. else:
  83. glob_in_dir = _glob1
  84. else:
  85. glob_in_dir = _glob0
  86. for dirname in dirs:
  87. for name in glob_in_dir(_join(root_dir, dirname), basename, dir_fd, dironly,
  88. include_hidden=include_hidden):
  89. yield os.path.join(dirname, name)
  90. # These 2 helper functions non-recursively glob inside a literal directory.
  91. # They return a list of basenames. _glob1 accepts a pattern while _glob0
  92. # takes a literal basename (so it only has to check for its existence).
  93. def _glob1(dirname, pattern, dir_fd, dironly, include_hidden=False):
  94. names = _listdir(dirname, dir_fd, dironly)
  95. if include_hidden or not _ishidden(pattern):
  96. names = (x for x in names if include_hidden or not _ishidden(x))
  97. return fnmatch.filter(names, pattern)
  98. def _glob0(dirname, basename, dir_fd, dironly, include_hidden=False):
  99. if basename:
  100. if _lexists(_join(dirname, basename), dir_fd):
  101. return [basename]
  102. else:
  103. # `os.path.split()` returns an empty basename for paths ending with a
  104. # directory separator. 'q*x/' should match only directories.
  105. if _isdir(dirname, dir_fd):
  106. return [basename]
  107. return []
  108. # Following functions are not public but can be used by third-party code.
  109. def glob0(dirname, pattern):
  110. return _glob0(dirname, pattern, None, False)
  111. def glob1(dirname, pattern):
  112. return _glob1(dirname, pattern, None, False)
  113. # This helper function recursively yields relative pathnames inside a literal
  114. # directory.
  115. def _glob2(dirname, pattern, dir_fd, dironly, include_hidden=False):
  116. assert _isrecursive(pattern)
  117. if not dirname or _isdir(dirname, dir_fd):
  118. yield pattern[:0]
  119. yield from _rlistdir(dirname, dir_fd, dironly,
  120. include_hidden=include_hidden)
  121. # If dironly is false, yields all file names inside a directory.
  122. # If dironly is true, yields only directory names.
  123. def _iterdir(dirname, dir_fd, dironly):
  124. try:
  125. fd = None
  126. fsencode = None
  127. if dir_fd is not None:
  128. if dirname:
  129. fd = arg = os.open(dirname, _dir_open_flags, dir_fd=dir_fd)
  130. else:
  131. arg = dir_fd
  132. if isinstance(dirname, bytes):
  133. fsencode = os.fsencode
  134. elif dirname:
  135. arg = dirname
  136. elif isinstance(dirname, bytes):
  137. arg = bytes(os.curdir, 'ASCII')
  138. else:
  139. arg = os.curdir
  140. try:
  141. with os.scandir(arg) as it:
  142. for entry in it:
  143. try:
  144. if not dironly or entry.is_dir():
  145. if fsencode is not None:
  146. yield fsencode(entry.name)
  147. else:
  148. yield entry.name
  149. except OSError:
  150. pass
  151. finally:
  152. if fd is not None:
  153. os.close(fd)
  154. except OSError:
  155. return
  156. def _listdir(dirname, dir_fd, dironly):
  157. with contextlib.closing(_iterdir(dirname, dir_fd, dironly)) as it:
  158. return list(it)
  159. # Recursively yields relative pathnames inside a literal directory.
  160. def _rlistdir(dirname, dir_fd, dironly, include_hidden=False):
  161. names = _listdir(dirname, dir_fd, dironly)
  162. for x in names:
  163. if include_hidden or not _ishidden(x):
  164. yield x
  165. path = _join(dirname, x) if dirname else x
  166. for y in _rlistdir(path, dir_fd, dironly,
  167. include_hidden=include_hidden):
  168. yield _join(x, y)
  169. def _lexists(pathname, dir_fd):
  170. # Same as os.path.lexists(), but with dir_fd
  171. if dir_fd is None:
  172. return os.path.lexists(pathname)
  173. try:
  174. os.lstat(pathname, dir_fd=dir_fd)
  175. except (OSError, ValueError):
  176. return False
  177. else:
  178. return True
  179. def _isdir(pathname, dir_fd):
  180. # Same as os.path.isdir(), but with dir_fd
  181. if dir_fd is None:
  182. return os.path.isdir(pathname)
  183. try:
  184. st = os.stat(pathname, dir_fd=dir_fd)
  185. except (OSError, ValueError):
  186. return False
  187. else:
  188. return stat.S_ISDIR(st.st_mode)
  189. def _join(dirname, basename):
  190. # It is common if dirname or basename is empty
  191. if not dirname or not basename:
  192. return dirname or basename
  193. return os.path.join(dirname, basename)
  194. magic_check = re.compile('([*?[])')
  195. magic_check_bytes = re.compile(b'([*?[])')
  196. def has_magic(s):
  197. if isinstance(s, bytes):
  198. match = magic_check_bytes.search(s)
  199. else:
  200. match = magic_check.search(s)
  201. return match is not None
  202. def _ishidden(path):
  203. return path[0] in ('.', b'.'[0])
  204. def _isrecursive(pattern):
  205. if isinstance(pattern, bytes):
  206. return pattern == b'**'
  207. else:
  208. return pattern == '**'
  209. def escape(pathname):
  210. """Escape all special characters.
  211. """
  212. # Escaping is done by wrapping any of "*?[" between square brackets.
  213. # Metacharacters do not work in the drive part and shouldn't be escaped.
  214. drive, pathname = os.path.splitdrive(pathname)
  215. if isinstance(pathname, bytes):
  216. pathname = magic_check_bytes.sub(br'[\1]', pathname)
  217. else:
  218. pathname = magic_check.sub(r'[\1]', pathname)
  219. return drive + pathname
  220. _dir_open_flags = os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0)