blob: 4ba41382aa8cd85e9dd8e546336ed9ff55c0471c [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 Rossum65a96201991-01-01 18:17:49 +00004import fnmatch
Guido van Rossum9694fca1997-10-22 21:00:49 +00005import re
Guido van Rossum65a96201991-01-01 18:17:49 +00006
Skip Montanaroeccd02a2001-01-20 23:34:12 +00007__all__ = ["glob"]
Guido van Rossumbba77af1992-01-12 23:26:24 +00008
Guido van Rossum65a96201991-01-01 18:17:49 +00009def glob(pathname):
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
Tim Peters07e99cb2001-01-14 23:47:14 +000012 The pattern may contain simple shell-style wildcards a la fnmatch.
Guido van Rossumab096c91997-04-02 05:47:11 +000013
Tim Peters07e99cb2001-01-14 23:47:14 +000014 """
15 if not has_magic(pathname):
Johannes Gijsbersae882f72004-08-30 10:19:56 +000016 if os.path.lexists(pathname):
Tim Peters07e99cb2001-01-14 23:47:14 +000017 return [pathname]
18 else:
19 return []
20 dirname, basename = os.path.split(pathname)
Martin v. Löwisb5d4d2a2001-06-06 06:24:38 +000021 if not dirname:
22 return glob1(os.curdir, basename)
23 elif has_magic(dirname):
Tim Peters07e99cb2001-01-14 23:47:14 +000024 list = glob(dirname)
25 else:
26 list = [dirname]
27 if not has_magic(basename):
28 result = []
29 for dirname in list:
30 if basename or os.path.isdir(dirname):
31 name = os.path.join(dirname, basename)
Johannes Gijsbersae882f72004-08-30 10:19:56 +000032 if os.path.lexists(name):
Tim Peters07e99cb2001-01-14 23:47:14 +000033 result.append(name)
34 else:
35 result = []
36 for dirname in list:
37 sublist = glob1(dirname, basename)
38 for name in sublist:
39 result.append(os.path.join(dirname, name))
40 return result
Guido van Rossum65a96201991-01-01 18:17:49 +000041
42def glob1(dirname, pattern):
Tim Peters07e99cb2001-01-14 23:47:14 +000043 if not dirname: dirname = os.curdir
44 try:
45 names = os.listdir(dirname)
46 except os.error:
47 return []
Martin v. Löwisb5d4d2a2001-06-06 06:24:38 +000048 if pattern[0]!='.':
49 names=filter(lambda x: x[0]!='.',names)
50 return fnmatch.filter(names,pattern)
Guido van Rossum65a96201991-01-01 18:17:49 +000051
Guido van Rossumc2ef5c21992-01-12 23:32:11 +000052
Guido van Rossum9694fca1997-10-22 21:00:49 +000053magic_check = re.compile('[*?[]')
Guido van Rossumc2ef5c21992-01-12 23:32:11 +000054
Guido van Rossum65a96201991-01-01 18:17:49 +000055def has_magic(s):
Tim Peters07e99cb2001-01-14 23:47:14 +000056 return magic_check.search(s) is not None