blob: 599d41b5e12ccbf324cbf0284dac3e9b3a63188e [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
Guido van Rossumbba77af1992-01-12 23:26:24 +00007
Guido van Rossum65a96201991-01-01 18:17:49 +00008def glob(pathname):
Guido van Rossumab096c91997-04-02 05:47:11 +00009 """Return a list of paths matching a pathname pattern.
10
11 The pattern may contain simple shell-style wildcards a la fnmatch.
12
13 """
Guido van Rossumc2ef5c21992-01-12 23:32:11 +000014 if not has_magic(pathname):
15 if os.path.exists(pathname):
16 return [pathname]
17 else:
18 return []
Guido van Rossumbba77af1992-01-12 23:26:24 +000019 dirname, basename = os.path.split(pathname)
Guido van Rossum65a96201991-01-01 18:17:49 +000020 if has_magic(dirname):
21 list = glob(dirname)
22 else:
23 list = [dirname]
24 if not has_magic(basename):
25 result = []
26 for dirname in list:
Guido van Rossumbba77af1992-01-12 23:26:24 +000027 if basename or os.path.isdir(dirname):
28 name = os.path.join(dirname, basename)
29 if os.path.exists(name):
Guido van Rossum65a96201991-01-01 18:17:49 +000030 result.append(name)
31 else:
32 result = []
33 for dirname in list:
34 sublist = glob1(dirname, basename)
35 for name in sublist:
Guido van Rossumbba77af1992-01-12 23:26:24 +000036 result.append(os.path.join(dirname, name))
Guido van Rossum65a96201991-01-01 18:17:49 +000037 return result
38
39def glob1(dirname, pattern):
Guido van Rossumbba77af1992-01-12 23:26:24 +000040 if not dirname: dirname = os.curdir
Guido van Rossum65a96201991-01-01 18:17:49 +000041 try:
Guido van Rossumbba77af1992-01-12 23:26:24 +000042 names = os.listdir(dirname)
43 except os.error:
Guido van Rossum65a96201991-01-01 18:17:49 +000044 return []
45 result = []
46 for name in names:
Guido van Rossumc2ef5c21992-01-12 23:32:11 +000047 if name[0] != '.' or pattern[0] == '.':
48 if fnmatch.fnmatch(name, pattern):
49 result.append(name)
Guido van Rossum65a96201991-01-01 18:17:49 +000050 return result
51
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):
Guido van Rossum9694fca1997-10-22 21:00:49 +000056 return magic_check.search(s) is not None