blob: 002cd920190da76adb907aa6bad8763951a55eb7 [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
Guido van Rossum65a96201991-01-01 18:17:49 +00006
Serhiy Storchaka04b57002015-11-09 23:18:19 +02007__all__ = ["glob", "iglob", "escape"]
Guido van Rossumbba77af1992-01-12 23:26:24 +00008
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +03009def glob(pathname, *, recursive=False):
Tim Peters07e99cb2001-01-14 23:47:14 +000010 """Return a list of paths matching a pathname pattern.
Guido van Rossumab096c91997-04-02 05:47:11 +000011
Petri Lehtinenee4a20b2013-02-23 19:53:03 +010012 The pattern may contain simple shell-style wildcards a la
13 fnmatch. However, unlike fnmatch, filenames starting with a
14 dot are special cases that are not matched by '*' and '?'
15 patterns.
Guido van Rossumab096c91997-04-02 05:47:11 +000016
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030017 If recursive is true, the pattern '**' will match any files and
18 zero or more directories and subdirectories.
Tim Peters07e99cb2001-01-14 23:47:14 +000019 """
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030020 return list(iglob(pathname, recursive=recursive))
Johannes Gijsbers836f5432005-01-08 13:13:19 +000021
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030022def iglob(pathname, *, recursive=False):
Benjamin Petersond23f8222009-04-05 19:13:16 +000023 """Return an iterator which yields the paths matching a pathname pattern.
Johannes Gijsbers836f5432005-01-08 13:13:19 +000024
Petri Lehtinenee4a20b2013-02-23 19:53:03 +010025 The pattern may contain simple shell-style wildcards a la
26 fnmatch. However, unlike fnmatch, filenames starting with a
27 dot are special cases that are not matched by '*' and '?'
28 patterns.
Johannes Gijsbers836f5432005-01-08 13:13:19 +000029
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030030 If recursive is true, the pattern '**' will match any files and
31 zero or more directories and subdirectories.
Johannes Gijsbers836f5432005-01-08 13:13:19 +000032 """
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030033 it = _iglob(pathname, recursive, False)
Serhiy Storchaka735b7902015-11-09 23:12:07 +020034 if recursive and _isrecursive(pathname):
35 s = next(it) # skip empty string
36 assert not s
37 return it
38
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030039def _iglob(pathname, recursive, dironly):
Tim Golden9b3fb0c2012-11-06 15:33:30 +000040 dirname, basename = os.path.split(pathname)
Serhiy Storchaka6f201702014-08-12 12:55:12 +030041 if not has_magic(pathname):
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030042 assert not dironly
Serhiy Storchaka6f201702014-08-12 12:55:12 +030043 if basename:
44 if os.path.lexists(pathname):
45 yield pathname
46 else:
47 # Patterns ending with a slash should match only directories
48 if os.path.isdir(dirname):
49 yield pathname
50 return
Tim Golden9b3fb0c2012-11-06 15:33:30 +000051 if not dirname:
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030052 if recursive and _isrecursive(basename):
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030053 yield from _glob2(dirname, basename, dironly)
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030054 else:
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030055 yield from _glob1(dirname, basename, dironly)
Tim Golden9b3fb0c2012-11-06 15:33:30 +000056 return
Antoine Pitrou3d068b22012-12-16 13:49:37 +010057 # `os.path.split()` returns the argument itself as a dirname if it is a
58 # drive or UNC path. Prevent an infinite recursion if a drive or UNC path
59 # contains magic characters (i.e. r'\\?\C:').
60 if dirname != pathname and has_magic(dirname):
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030061 dirs = _iglob(dirname, recursive, True)
Tim Golden9b3fb0c2012-11-06 15:33:30 +000062 else:
63 dirs = [dirname]
64 if has_magic(basename):
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030065 if recursive and _isrecursive(basename):
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030066 glob_in_dir = _glob2
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030067 else:
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030068 glob_in_dir = _glob1
Tim Golden9b3fb0c2012-11-06 15:33:30 +000069 else:
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030070 glob_in_dir = _glob0
Tim Golden9b3fb0c2012-11-06 15:33:30 +000071 for dirname in dirs:
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030072 for name in glob_in_dir(dirname, basename, dironly):
Tim Golden9b3fb0c2012-11-06 15:33:30 +000073 yield os.path.join(dirname, name)
Johannes Gijsbers836f5432005-01-08 13:13:19 +000074
75# These 2 helper functions non-recursively glob inside a literal directory.
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030076# They return a list of basenames. _glob1 accepts a pattern while _glob0
Johannes Gijsbers836f5432005-01-08 13:13:19 +000077# takes a literal basename (so it only has to check for its existence).
Guido van Rossum65a96201991-01-01 18:17:49 +000078
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030079def _glob1(dirname, pattern, dironly):
80 names = list(_iterdir(dirname, dironly))
Hynek Schlawacke26568f2012-12-27 10:10:11 +010081 if not _ishidden(pattern):
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030082 names = (x for x in names if not _ishidden(x))
Guido van Rossumd8faa362007-04-27 19:54:29 +000083 return fnmatch.filter(names, pattern)
Guido van Rossum65a96201991-01-01 18:17:49 +000084
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030085def _glob0(dirname, basename, dironly):
Antoine Pitrou54615582012-12-16 16:03:01 +010086 if not basename:
Johannes Gijsbers836f5432005-01-08 13:13:19 +000087 # `os.path.split()` returns an empty basename for paths ending with a
88 # directory separator. 'q*x/' should match only directories.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000089 if os.path.isdir(dirname):
Johannes Gijsbers836f5432005-01-08 13:13:19 +000090 return [basename]
91 else:
92 if os.path.lexists(os.path.join(dirname, basename)):
93 return [basename]
94 return []
95
Serhiy Storchaka28ab6342016-09-06 22:33:41 +030096# Following functions are not public but can be used by third-party code.
97
98def glob0(dirname, pattern):
99 return _glob0(dirname, pattern, False)
100
101def glob1(dirname, pattern):
102 return _glob1(dirname, pattern, False)
103
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300104# This helper function recursively yields relative pathnames inside a literal
105# directory.
106
Serhiy Storchaka28ab6342016-09-06 22:33:41 +0300107def _glob2(dirname, pattern, dironly):
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300108 assert _isrecursive(pattern)
Serhiy Storchaka735b7902015-11-09 23:12:07 +0200109 yield pattern[:0]
Serhiy Storchaka28ab6342016-09-06 22:33:41 +0300110 yield from _rlistdir(dirname, dironly)
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300111
Serhiy Storchaka28ab6342016-09-06 22:33:41 +0300112# If dironly is false, yields all file names inside a directory.
113# If dironly is true, yields only directory names.
114def _iterdir(dirname, dironly):
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300115 if not dirname:
116 if isinstance(dirname, bytes):
117 dirname = bytes(os.curdir, 'ASCII')
118 else:
119 dirname = os.curdir
120 try:
Serhiy Storchaka3ae41552016-10-05 23:17:10 +0300121 with os.scandir(dirname) as it:
122 for entry in it:
123 try:
124 if not dironly or entry.is_dir():
125 yield entry.name
126 except OSError:
127 pass
Serhiy Storchaka28ab6342016-09-06 22:33:41 +0300128 except OSError:
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300129 return
Serhiy Storchaka28ab6342016-09-06 22:33:41 +0300130
131# Recursively yields relative pathnames inside a literal directory.
132def _rlistdir(dirname, dironly):
133 names = list(_iterdir(dirname, dironly))
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300134 for x in names:
135 if not _ishidden(x):
136 yield x
137 path = os.path.join(dirname, x) if dirname else x
Serhiy Storchaka28ab6342016-09-06 22:33:41 +0300138 for y in _rlistdir(path, dironly):
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300139 yield os.path.join(x, y)
140
Guido van Rossumc2ef5c21992-01-12 23:32:11 +0000141
Serhiy Storchakafd32fff2013-11-18 13:06:43 +0200142magic_check = re.compile('([*?[])')
143magic_check_bytes = re.compile(b'([*?[])')
Tim Golden9b3fb0c2012-11-06 15:33:30 +0000144
Guido van Rossum65a96201991-01-01 18:17:49 +0000145def has_magic(s):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000146 if isinstance(s, bytes):
147 match = magic_check_bytes.search(s)
148 else:
149 match = magic_check.search(s)
150 return match is not None
Hynek Schlawacke26568f2012-12-27 10:10:11 +0100151
152def _ishidden(path):
153 return path[0] in ('.', b'.'[0])
Serhiy Storchakafd32fff2013-11-18 13:06:43 +0200154
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300155def _isrecursive(pattern):
156 if isinstance(pattern, bytes):
157 return pattern == b'**'
158 else:
159 return pattern == '**'
160
Serhiy Storchakafd32fff2013-11-18 13:06:43 +0200161def escape(pathname):
162 """Escape all special characters.
163 """
164 # Escaping is done by wrapping any of "*?[" between square brackets.
165 # Metacharacters do not work in the drive part and shouldn't be escaped.
166 drive, pathname = os.path.splitdrive(pathname)
167 if isinstance(pathname, bytes):
168 pathname = magic_check_bytes.sub(br'[\1]', pathname)
169 else:
170 pathname = magic_check.sub(r'[\1]', pathname)
171 return drive + pathname