Back to index

enigmail  1.4.3
globrelative.py
Go to the documentation of this file.
00001 """
00002 Filename globbing like the python glob module with minor differences:
00003 
00004 * glob relative to an arbitrary directory
00005 * include . and ..
00006 * check that link targets exist, not just links
00007 """
00008 
00009 import os, re, fnmatch
00010 import util
00011 
00012 _globcheck = re.compile('[[*?]')
00013 
00014 def hasglob(p):
00015     return _globcheck.search(p) is not None
00016 
00017 def glob(fsdir, path):
00018     """
00019     Yield paths matching the path glob. Sorts as a bonus. Excludes '.' and '..'
00020     """
00021 
00022     dir, leaf = os.path.split(path)
00023     if dir == '':
00024         return globpattern(fsdir, leaf)
00025 
00026     if hasglob(dir):
00027         dirsfound = glob(fsdir, dir)
00028     else:
00029         dirsfound = [dir]
00030 
00031     r = []
00032 
00033     for dir in dirsfound:
00034         fspath = util.normaljoin(fsdir, dir)
00035         if not os.path.isdir(fspath):
00036             continue
00037 
00038         r.extend((util.normaljoin(dir, found) for found in globpattern(fspath, leaf)))
00039 
00040     return r
00041 
00042 def globpattern(dir, pattern):
00043     """
00044     Return leaf names in the specified directory which match the pattern.
00045     """
00046 
00047     if not hasglob(pattern):
00048         if pattern == '':
00049             if os.path.isdir(dir):
00050                 return ['']
00051             return []
00052 
00053         if os.path.exists(util.normaljoin(dir, pattern)):
00054             return [pattern]
00055         return []
00056 
00057     leaves = os.listdir(dir) + ['.', '..']
00058 
00059     # "hidden" filenames are a bit special
00060     if not pattern.startswith('.'):
00061         leaves = [leaf for leaf in leaves
00062                   if not leaf.startswith('.')]
00063 
00064     leaves = fnmatch.filter(leaves, pattern)
00065     leaves = filter(lambda l: os.path.exists(util.normaljoin(dir, l)), leaves)
00066 
00067     leaves.sort()
00068     return leaves