added an untested module requirement system.

This commit is contained in:
jesopo 2016-04-04 12:36:59 +01:00
parent 9567ad4784
commit 80818fad66
No known key found for this signature in database
GPG key ID: 0BBDEB2AEFCFFCB3

View file

@ -5,10 +5,15 @@ class ModuleManager(object):
self.bot = bot
self.directory = directory
self.modules = {}
self.waiting_requirement = {}
def list_modules(self):
return sorted(glob.glob(os.path.join(self.directory, "*.py")))
def load_module(self, filename):
name = os.path.basename(filename).rsplit(".py", 1)[0]
def module_name(self, filename):
return os.path.basename(filename).rsplit(".py", 1)[0].lower()
def _load_module(self, filename):
name = self.module_name(filename)
with open(filename) as module_file:
while True:
line = module_file.readline().strip()
@ -23,6 +28,13 @@ class ModuleManager(object):
if not line_split[1].lower() in self.bot.config:
# nope, required config option not present.
return None
elif line_split[0] == "#--require-module" and len(
line_split) > 1:
if not "bitbot_%s" % line_split[1].lower() in sys.modules:
if not line_split[1].lower() in self.waiting_requirement:
self.waiting_requirement[line_split[1].lower()] = set([])
self.waiting_requirement[line_split[1].lower()].add(filename)
return None
else:
break
module = imp.load_source("bitbot_%s" % name, filename)
@ -33,13 +45,21 @@ class ModuleManager(object):
module_object = module.Module(self.bot)
if not hasattr(module_object, "_name"):
module_object._name = name.title()
return module_object
def load_modules(self):
for filename in self.list_modules():
module = self.load_module(filename)
if module:
assert not module._name in self.modules, (
assert not module_object._name in self.modules, (
"module name '%s' attempted to be used twice.")
return module_object
def load_module(self, filename):
name = self.module_name(filename)
module = self._load_module(filename)
if module:
self.modules[module._name] = module
if name in self.waiting_requirement:
for filename in self.waiting_requirement:
self.load_module(filename)
else:
sys.stderr.write("module '%s' not loaded.\n" % filename)
def load_modules(self):
for filename in self.list_modules():
self.load_module(filename)