3 __author__ = "Gustavo Sverzut Barbieri / Artur Duque de Souza"
4 __author_email__ = "barbieri@gmail.com / artur.souza@indt.org.br"
16 log = logging.getLogger("gms.utils")
18 __all__ = ("which", "load_plugins", "PluginSet")
21 """function to implement which(1) unix command"""
22 pl = os.environ["PATH"].split(os.pathsep)
24 path = os.path.join(p, app)
25 if os.path.isfile(path):
27 if st[stat.ST_MODE] & 0111:
33 def _load_module(pathlist, name):
34 fp, path, desc = imp.find_module(name, pathlist)
36 module = imp.load_module(name, fp, path, desc)
44 class PluginSet(object):
45 def __init__(self, basetype, *items):
46 self.basetype = basetype
57 self.map[item.name] = item
58 self.list.append(item)
68 def __getitem__(self, spec):
69 if isinstance(spec, basestring):
72 return self.list[spec]
76 def get(self, name, default=None):
77 return self.map.get(name, default)
82 return self.list.__iter__()
92 self.list.sort(lambda a, b: cmp(a.priority, b.priority))
96 def update(self, pluginset):
97 self.map.update(pluginset.map)
98 self.list.extend(pluginset.list)
103 def load_from_directory(self, directory):
104 for i in load_plugins(directory, self.basetype):
107 # load_from_directory()
113 lst.append('"%s" (%s)' % (o.name, o.__name__))
115 return "%s(basetype=%s, items=[%s])" % \
116 (self.__class__.__name__,
117 self.basetype.__name__,
123 def load_plugins(directory, basetype):
124 tn = basetype.__name__
125 log.debug("Loading plugins from %s, type=%s" % (directory, tn))
129 for d in os.listdir(directory):
130 if not d.endswith(".py"):
134 if name == "__init__":
137 directory.replace(os.path.sep, ".")
138 mod = _load_module([directory], name)
140 cls = getattr(mod, sym)
141 if isinstance(cls, type) and issubclass(cls, basetype) and \
144 log.info("Loaded %s (%s) from %s" % \
145 (cls.__name__, tn, os.path.join(directory, d)))