glob.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. yield pattern[:0]
  118. yield from _rlistdir(dirname, dir_fd, dironly,
  119. include_hidden=include_hidden)
  120. # If dironly is false, yields all file names inside a directory.
  121. # If dironly is true, yields only directory names.
  122. def _iterdir(dirname, dir_fd, dironly):
  123. try:
  124. fd = None
  125. fsencode = None
  126. if dir_fd is not None:
  127. if dirname:
  128. fd = arg = os.open(dirname, _dir_open_flags, dir_fd=dir_fd)
  129. else:
  130. arg = dir_fd
  131. if isinstance(dirname, bytes):
  132. fsencode = os.fsencode
  133. elif dirname:
  134. arg = dirname
  135. elif isinstance(dirname, bytes):
  136. arg = bytes(os.curdir, 'ASCII')
  137. else:
  138. arg = os.curdir
  139. try:
  140. with os.scandir(arg) as it:
  141. for entry in it:
  142. try:
  143. if not dironly or entry.is_dir():
  144. if fsencode is not None:
  145. yield fsencode(entry.name)
  146. else:
  147. yield entry.name
  148. except OSError:
  149. pass
  150. finally:
  151. if fd is not None:
  152. os.close(fd)
  153. except OSError:
  154. return
  155. def _listdir(dirname, dir_fd, dironly):
  156. with contextlib.closing(_iterdir(dirname, dir_fd, dironly)) as it:
  157. return list(it)
  158. # Recursively yields relative pathnames inside a literal directory.
  159. def _rlistdir(dirname, dir_fd, dironly, include_hidden=False):
  160. names = _listdir(dirname, dir_fd, dironly)
  161. for x in names:
  162. if include_hidden or not _ishidden(x):
  163. yield x
  164. path = _join(dirname, x) if dirname else x
  165. for y in _rlistdir(path, dir_fd, dironly,
  166. include_hidden=include_hidden):
  167. yield _join(x, y)
  168. def _lexists(pathname, dir_fd):
  169. # Same as os.path.lexists(), but with dir_fd
  170. if dir_fd is None:
  171. return os.path.lexists(pathname)
  172. try:
  173. os.lstat(pathname, dir_fd=dir_fd)
  174. except (OSError, ValueError):
  175. return False
  176. else:
  177. return True
  178. def _isdir(pathname, dir_fd):
  179. # Same as os.path.isdir(), but with dir_fd
  180. if dir_fd is None:
  181. return os.path.isdir(pathname)
  182. try:
  183. st = os.stat(pathname, dir_fd=dir_fd)
  184. except (OSError, ValueError):
  185. return False
  186. else:
  187. return stat.S_ISDIR(st.st_mode)
  188. def _join(dirname, basename):
  189. # It is common if dirname or basename is empty
  190. if not dirname or not basename:
  191. return dirname or basename
  192. return os.path.join(dirname, basename)
  193. magic_check = re.compile('([*?[])')
  194. magic_check_bytes = re.compile(b'([*?[])')
  195. def has_magic(s):
  196. if isinstance(s, bytes):
  197. match = magic_check_bytes.search(s)
  198. else:
  199. match = magic_check.search(s)
  200. return match is not None
  201. def _ishidden(path):
  202. return path[0] in ('.', b'.'[0])
  203. def _isrecursive(pattern):
  204. if isinstance(pattern, bytes):
  205. return pattern == b'**'
  206. else:
  207. return pattern == '**'
  208. def escape(pathname):
  209. """Escape all special characters.
  210. """
  211. # Escaping is done by wrapping any of "*?[" between square brackets.
  212. # Metacharacters do not work in the drive part and shouldn't be escaped.
  213. drive, pathname = os.path.splitdrive(pathname)
  214. if isinstance(pathname, bytes):
  215. pathname = magic_check_bytes.sub(br'[\1]', pathname)
  216. else:
  217. pathname = magic_check.sub(r'[\1]', pathname)
  218. return drive + pathname
  219. _dir_open_flags = os.O_RDONLY | getattr(os, 'O_DIRECTORY', 0)