]> jfr.im git - erebus.git/blob - ctlmod.py
cleanup (remove excess whitespace)
[erebus.git] / ctlmod.py
1 # Erebus IRC bot - Author: John Runyon
2 # module loading/unloading/tracking code
3
4 import sys
5 import modlib
6
7 modules = {}
8 dependents = {}
9
10 def isloaded(modname): return modname in modules
11 def modhas(modname, attname): return getattr(modules[modname], attname, None) is not None
12
13 def load(parent, modname):
14 if not isloaded(modname):
15 sys.path.insert(0, 'modules')
16 try:
17 mod = __import__(modname)
18 reload(mod) #in case it's been previously loaded.
19 except BaseException as e: #we don't want even sys.exit() to crash us (in case of malicious module) so use BaseException
20 return modlib.error(e)
21 finally:
22 del sys.path[0] #remove ./modules from path, in case there's a name conflict
23
24
25 if not hasattr(mod, 'modinfo'):
26 return modlib.error('no modinfo')
27
28 if parent.APIVERSION not in mod.modinfo['compatible']:
29 return modlib.error('API-incompatible')
30
31 modules[modname] = mod
32 dependents[modname] = []
33
34 for dep in mod.modinfo['depends']:
35 if dep not in modules:
36 depret = load(parent, dep)
37 if not depret:
38 return
39 dependents[dep].append(modname)
40
41
42 ret = mod.modstart(parent)
43 if ret is not None and not ret:
44 del modules[modname]
45 del dependents[modname]
46 for dep in mod.modinfo['depends']:
47 dependents[dep].remove(modname)
48 return ret
49 else: #if not isloaded...else:
50 return modlib.error('already loaded')
51
52 def unload(parent, modname):
53 if isloaded(modname):
54 for dependent in dependents[modname]:
55 unload(parent, dependent)
56 for dep in dependents[modname]:
57 dependents[dep].remove(modname)
58 ret = modules[modname].modstop(parent)
59 del modules[modname]
60 return ret
61 else:
62 return modlib.error('already unloaded')
63
64 def reloadmod(parent, modname):
65 if isloaded(modname):
66 if modhas(modname, 'modrestart'): modules[modname].modrestart(parent)
67 else: modules[modname].modstop(parent)
68
69 try:
70 reload(modules[modname])
71 except BaseException as e:
72 return modlib.error(e)
73
74 if modhas(modname, 'modrestarted'): ret = modules[modname].modrestarted(parent)
75 else: ret = modules[modname].modstart(parent)
76
77 return ret
78 else:
79 return load(parent, modname)
80
81
82 def loadall(parent, modlist):
83 for m in modlist: load(parent, m)
84 def unloadall(parent, modlist):
85 for m in modlist: unload(parent, m)
86 def reloadall(parent, modlist):
87 for m in modlist: reloadmod(parent, m)
88
89 sys.path.append('modules')