PageRenderTime 35ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/glob.py

https://bitbucket.org/bwesterb/pypy
Python | 78 lines | 57 code | 7 blank | 14 comment | 17 complexity | 6d3ac906ba8cd3f97a569f3f6279cfd8 MD5 | raw file
  1. """Filename globbing utility."""
  2. import sys
  3. import os
  4. import re
  5. import fnmatch
  6. __all__ = ["glob", "iglob"]
  7. def glob(pathname):
  8. """Return a list of paths matching a pathname pattern.
  9. The pattern may contain simple shell-style wildcards a la fnmatch.
  10. """
  11. return list(iglob(pathname))
  12. def iglob(pathname):
  13. """Return an iterator which yields the paths matching a pathname pattern.
  14. The pattern may contain simple shell-style wildcards a la fnmatch.
  15. """
  16. if not has_magic(pathname):
  17. if os.path.lexists(pathname):
  18. yield pathname
  19. return
  20. dirname, basename = os.path.split(pathname)
  21. if not dirname:
  22. for name in glob1(os.curdir, basename):
  23. yield name
  24. return
  25. if has_magic(dirname):
  26. dirs = iglob(dirname)
  27. else:
  28. dirs = [dirname]
  29. if has_magic(basename):
  30. glob_in_dir = glob1
  31. else:
  32. glob_in_dir = glob0
  33. for dirname in dirs:
  34. for name in glob_in_dir(dirname, basename):
  35. yield os.path.join(dirname, name)
  36. # These 2 helper functions non-recursively glob inside a literal directory.
  37. # They return a list of basenames. `glob1` accepts a pattern while `glob0`
  38. # takes a literal basename (so it only has to check for its existence).
  39. def glob1(dirname, pattern):
  40. if not dirname:
  41. dirname = os.curdir
  42. if isinstance(pattern, unicode) and not isinstance(dirname, unicode):
  43. dirname = unicode(dirname, sys.getfilesystemencoding() or
  44. sys.getdefaultencoding())
  45. try:
  46. names = os.listdir(dirname)
  47. except os.error:
  48. return []
  49. if pattern[0] != '.':
  50. names = filter(lambda x: x[0] != '.', names)
  51. return fnmatch.filter(names, pattern)
  52. def glob0(dirname, basename):
  53. if basename == '':
  54. # `os.path.split()` returns an empty basename for paths ending with a
  55. # directory separator. 'q*x/' should match only directories.
  56. if os.path.isdir(dirname):
  57. return [basename]
  58. else:
  59. if os.path.lexists(os.path.join(dirname, basename)):
  60. return [basename]
  61. return []
  62. magic_check = re.compile('[*?[]')
  63. def has_magic(s):
  64. return magic_check.search(s) is not None