--- /dev/null
+"""Filename globbing utility."""\r
+\r
+import sys\r
+import os\r
+import re\r
+import fnmatch\r
+\r
+__all__ = ["glob", "iglob"]\r
+\r
+def glob(pathname):\r
+ """Return a list of paths matching a pathname pattern.\r
+\r
+ The pattern may contain simple shell-style wildcards a la fnmatch.\r
+\r
+ """\r
+ return list(iglob(pathname))\r
+\r
+def iglob(pathname):\r
+ """Return an iterator which yields the paths matching a pathname pattern.\r
+\r
+ The pattern may contain simple shell-style wildcards a la fnmatch.\r
+\r
+ """\r
+ if not has_magic(pathname):\r
+ if os.path.lexists(pathname):\r
+ yield pathname\r
+ return\r
+ dirname, basename = os.path.split(pathname)\r
+ if not dirname:\r
+ for name in glob1(os.curdir, basename):\r
+ yield name\r
+ return\r
+ if has_magic(dirname):\r
+ dirs = iglob(dirname)\r
+ else:\r
+ dirs = [dirname]\r
+ if has_magic(basename):\r
+ glob_in_dir = glob1\r
+ else:\r
+ glob_in_dir = glob0\r
+ for dirname in dirs:\r
+ for name in glob_in_dir(dirname, basename):\r
+ yield os.path.join(dirname, name)\r
+\r
+# These 2 helper functions non-recursively glob inside a literal directory.\r
+# They return a list of basenames. `glob1` accepts a pattern while `glob0`\r
+# takes a literal basename (so it only has to check for its existence).\r
+\r
+def glob1(dirname, pattern):\r
+ if not dirname:\r
+ dirname = os.curdir\r
+ if isinstance(pattern, unicode) and not isinstance(dirname, unicode):\r
+ dirname = unicode(dirname, sys.getfilesystemencoding() or\r
+ sys.getdefaultencoding())\r
+ try:\r
+ names = os.listdir(dirname)\r
+ except os.error:\r
+ return []\r
+ if pattern[0] != '.':\r
+ names = filter(lambda x: x[0] != '.', names)\r
+ return fnmatch.filter(names, pattern)\r
+\r
+def glob0(dirname, basename):\r
+ if basename == '':\r
+ # `os.path.split()` returns an empty basename for paths ending with a\r
+ # directory separator. 'q*x/' should match only directories.\r
+ if os.path.isdir(dirname):\r
+ return [basename]\r
+ else:\r
+ if os.path.lexists(os.path.join(dirname, basename)):\r
+ return [basename]\r
+ return []\r
+\r
+\r
+magic_check = re.compile('[*?[]')\r
+\r
+def has_magic(s):\r
+ return magic_check.search(s) is not None\r