self.dirs = [abspath(expanduser(s)) for s in dirs]
self.build_filelist ()
self.watcher.add(self.dirs)
else:
self.dirs = None
self.filelist = []
def _on_handler_file_changed(self, watcher, f):
if f in self.filelist or not self.is_module(f):
return
self.load(f)
self.filelist.append(f)
def build_filelist (self):
"""Returns a list containing the filenames of all qualified modules.
This method is automatically invoked by the constructor.
"""
res = []
for d in self.dirs:
try:
if not os.path.exists(d):
continue
for i in [join(d, m) for m in os.listdir (d) if self.is_module(m)]:
if basename(i) not in [basename(j) for j in res]:
res.append(i)
except OSError, err:
print >> sys.stderr, "Error reading directory %s, skipping." % d
traceback.print_exc()
self.filelist = res
def is_module (self, filename):
"""Tests whether the filename has the appropriate extension."""
return (filename[-len(self.ext):] == self.ext)
def import_module (self, filename):
"""Tries to import the specified file. Returns the python module on succes.
Primarily for internal use."""
try:
mod = pydoc.importfile (filename)
except Exception:
print >> sys.stderr, "Error loading the file: %s." % filename
traceback.print_exc()
return
try:
if (mod.HANDLERS): pass
except AttributeError:
print >> sys.stderr, "The file %s is not a valid module. Skipping." %filename
print >> sys.stderr, "A module must have the variable HANDLERS defined as a dictionary."
traceback.print_exc()
return
if mod.HANDLERS == None:
if not hasattr(mod, "ERROR"):
mod.ERROR = "Unspecified Reason"
print >> sys.stderr, "*** The file %s decided to not load itself: %s" % (filename, mod.ERROR)
return
for handler, infos in mod.HANDLERS.items():
if hasattr(getattr(mod, handler), "initialize") and "name" in infos:
pass
else:
print >> sys.stderr, "Class %s in file %s does not have an initialize(self) method or does not define a 'name' attribute. Skipping." % (handler, filename)
return
if "requirements" in infos:
status, msg, callback = infos["requirements"]()
if status == deskbar.Handler.HANDLER_IS_NOT_APPLICABLE:
print >> sys.stderr, "***"
print >> sys.stderr, "*** The file %s (%s) decided to not load itself: %s" % (filename, handler, msg)
print >> sys.stderr, "***"
return
return mod
def load (self, filename):
"""Loads the given file as a module and emits a 'module-loaded' signal
passing a corresponding ModuleContext as argument.
"""
mod = self.import_module (filename)
if mod is None:
return
for handler, infos in mod.HANDLERS.items():
print "Loading module '%s' from file %s." % (infos["name"], filename)