blob: 56d670419a682719672cd619c6382d0e6c4ea244 [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
Johannes Gijsbers836f5432005-01-08 13:13:19 +00007__all__ = ["glob", "iglob"]
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 """
Tim Golden9b3fb0c2012-11-06 15:33:30 +000033 dirname, basename = os.path.split(pathname)
Serhiy Storchaka6f201702014-08-12 12:55:12 +030034 if not has_magic(pathname):
35 if basename:
36 if os.path.lexists(pathname):
37 yield pathname
38 else:
39 # Patterns ending with a slash should match only directories
40 if os.path.isdir(dirname):
41 yield pathname
42 return
Tim Golden9b3fb0c2012-11-06 15:33:30 +000043 if not dirname:
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030044 if recursive and _isrecursive(basename):
45 yield from glob2(dirname, basename)
46 else:
47 yield from glob1(dirname, basename)
Tim Golden9b3fb0c2012-11-06 15:33:30 +000048 return
Antoine Pitrou3d068b22012-12-16 13:49:37 +010049 # `os.path.split()` returns the argument itself as a dirname if it is a
50 # drive or UNC path. Prevent an infinite recursion if a drive or UNC path
51 # contains magic characters (i.e. r'\\?\C:').
52 if dirname != pathname and has_magic(dirname):
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030053 dirs = iglob(dirname, recursive=recursive)
Tim Golden9b3fb0c2012-11-06 15:33:30 +000054 else:
55 dirs = [dirname]
56 if has_magic(basename):
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +030057 if recursive and _isrecursive(basename):
58 glob_in_dir = glob2
59 else:
60 glob_in_dir = glob1
Tim Golden9b3fb0c2012-11-06 15:33:30 +000061 else:
62 glob_in_dir = glob0
63 for dirname in dirs:
64 for name in glob_in_dir(dirname, basename):
65 yield os.path.join(dirname, name)
Johannes Gijsbers836f5432005-01-08 13:13:19 +000066
67# These 2 helper functions non-recursively glob inside a literal directory.
68# They return a list of basenames. `glob1` accepts a pattern while `glob0`
69# takes a literal basename (so it only has to check for its existence).
Guido van Rossum65a96201991-01-01 18:17:49 +000070
71def glob1(dirname, pattern):
Johannes Gijsbers836f5432005-01-08 13:13:19 +000072 if not dirname:
Guido van Rossumf0af3e32008-10-02 18:55:37 +000073 if isinstance(pattern, bytes):
74 dirname = bytes(os.curdir, 'ASCII')
75 else:
76 dirname = os.curdir
Tim Peters07e99cb2001-01-14 23:47:14 +000077 try:
78 names = os.listdir(dirname)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +020079 except OSError:
Tim Peters07e99cb2001-01-14 23:47:14 +000080 return []
Hynek Schlawacke26568f2012-12-27 10:10:11 +010081 if not _ishidden(pattern):
82 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
Johannes Gijsbers836f5432005-01-08 13:13:19 +000085def glob0(dirname, basename):
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 Storchakac2edcdd2014-09-11 12:17:37 +030096# This helper function recursively yields relative pathnames inside a literal
97# directory.
98
99def glob2(dirname, pattern):
100 assert _isrecursive(pattern)
101 if dirname:
102 yield pattern[:0]
103 yield from _rlistdir(dirname)
104
105# Recursively yields relative pathnames inside a literal directory.
106
107def _rlistdir(dirname):
108 if not dirname:
109 if isinstance(dirname, bytes):
110 dirname = bytes(os.curdir, 'ASCII')
111 else:
112 dirname = os.curdir
113 try:
114 names = os.listdir(dirname)
115 except os.error:
116 return
117 for x in names:
118 if not _ishidden(x):
119 yield x
120 path = os.path.join(dirname, x) if dirname else x
121 for y in _rlistdir(path):
122 yield os.path.join(x, y)
123
Guido van Rossumc2ef5c21992-01-12 23:32:11 +0000124
Serhiy Storchakafd32fff2013-11-18 13:06:43 +0200125magic_check = re.compile('([*?[])')
126magic_check_bytes = re.compile(b'([*?[])')
Tim Golden9b3fb0c2012-11-06 15:33:30 +0000127
Guido van Rossum65a96201991-01-01 18:17:49 +0000128def has_magic(s):
Guido van Rossumf0af3e32008-10-02 18:55:37 +0000129 if isinstance(s, bytes):
130 match = magic_check_bytes.search(s)
131 else:
132 match = magic_check.search(s)
133 return match is not None
Hynek Schlawacke26568f2012-12-27 10:10:11 +0100134
135def _ishidden(path):
136 return path[0] in ('.', b'.'[0])
Serhiy Storchakafd32fff2013-11-18 13:06:43 +0200137
Serhiy Storchakac2edcdd2014-09-11 12:17:37 +0300138def _isrecursive(pattern):
139 if isinstance(pattern, bytes):
140 return pattern == b'**'
141 else:
142 return pattern == '**'
143
Serhiy Storchakafd32fff2013-11-18 13:06:43 +0200144def escape(pathname):
145 """Escape all special characters.
146 """
147 # Escaping is done by wrapping any of "*?[" between square brackets.
148 # Metacharacters do not work in the drive part and shouldn't be escaped.
149 drive, pathname = os.path.splitdrive(pathname)
150 if isinstance(pathname, bytes):
151 pathname = magic_check_bytes.sub(br'[\1]', pathname)
152 else:
153 pathname = magic_check.sub(r'[\1]', pathname)
154 return drive + pathname