3
0
mirror of https://github.com/jlu5/PyLink.git synced 2024-11-30 14:49:28 +01:00

Modularize our import hacks, make Irc() take a conf object again

This commit is contained in:
James Lu 2015-09-28 19:12:45 -07:00
parent 9e07949730
commit e84a2d1025
6 changed files with 26 additions and 23 deletions

View File

@ -9,7 +9,6 @@ import hashlib
from copy import deepcopy from copy import deepcopy
from log import log from log import log
from conf import conf
import world import world
import utils import utils
@ -63,7 +62,7 @@ class Irc():
self.uplink = None self.uplink = None
self.start_ts = int(time.time()) self.start_ts = int(time.time())
def __init__(self, netname, proto): def __init__(self, netname, proto, conf):
# Initialize some variables # Initialize some variables
self.name = netname.lower() self.name = netname.lower()
self.conf = conf self.conf = conf

View File

@ -60,6 +60,7 @@ def loadConf(fname):
if world.testing: if world.testing:
conf = testconf conf = testconf
confname = 'testconf' confname = 'testconf'
fname = None
else: else:
try: try:
# Get the config name from the command line, falling back to config.yml # Get the config name from the command line, falling back to config.yml

View File

@ -7,9 +7,10 @@ import gc
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import utils import utils
from conf import conf import conf
from log import log from log import log
import world import world
import classes
@utils.add_cmd @utils.add_cmd
def status(irc, source, args): def status(irc, source, args):
@ -37,8 +38,8 @@ def identify(irc, source, args):
irc.msg(source, 'Error: Not enough arguments.') irc.msg(source, 'Error: Not enough arguments.')
return return
# Usernames are case-insensitive, passwords are NOT. # Usernames are case-insensitive, passwords are NOT.
if username.lower() == conf['login']['user'].lower() and password == conf['login']['password']: if username.lower() == irc.conf['login']['user'].lower() and password == irc.conf['login']['password']:
realuser = conf['login']['user'] realuser = irc.conf['login']['user']
irc.users[source].identified = realuser irc.users[source].identified = realuser
irc.msg(source, 'Successfully logged in as %s.' % realuser) irc.msg(source, 'Successfully logged in as %s.' % realuser)
log.info("(%s) Successful login to %r by %s.", log.info("(%s) Successful login to %r by %s.",
@ -220,7 +221,7 @@ def load(irc, source, args):
irc.msg(irc.called_by, "Error: %r is already loaded." % name) irc.msg(irc.called_by, "Error: %r is already loaded." % name)
return return
try: try:
world.plugins[name] = pl = __import__(name) world.plugins[name] = pl = utils.loadModuleFromFolder(name, world.plugins_folder)
except ImportError as e: except ImportError as e:
if str(e) == ('No module named %r' % name): if str(e) == ('No module named %r' % name):
log.exception('Failed to load plugin %r: The plugin could not be found.', name) log.exception('Failed to load plugin %r: The plugin could not be found.', name)

21
pylink
View File

@ -12,11 +12,11 @@ world.testing = False
import conf import conf
from log import log from log import log
import classes import classes
import utils
import coreplugin import coreplugin
if __name__ == '__main__': if __name__ == '__main__':
log.info('PyLink %s starting...', world.version) log.info('PyLink %s starting...', world.version)
protocols_folder = [os.path.join(os.getcwd(), 'protocols')]
# Write a PID file. # Write a PID file.
with open('%s.pid' % conf.confname, 'w') as f: with open('%s.pid' % conf.confname, 'w') as f:
@ -25,14 +25,11 @@ if __name__ == '__main__':
# Import plugins first globally, because they can listen for events # Import plugins first globally, because they can listen for events
# that happen before the connection phase. # that happen before the connection phase.
to_load = conf.conf['plugins'] to_load = conf.conf['plugins']
plugins_folder = [os.path.join(os.getcwd(), 'plugins')]
# Here, we override the module lookup and import the plugins # Here, we override the module lookup and import the plugins
# dynamically depending on which were configured. # dynamically depending on which were configured.
for plugin in to_load: for plugin in to_load:
try: try:
moduleinfo = imp.find_module(plugin, plugins_folder) world.plugins[plugin] = pl = utils.loadModuleFromFolder(plugin, world.plugins_folder)
pl = imp.load_source(plugin, moduleinfo[1])
world.plugins[plugin] = pl
except ImportError as e: except ImportError as e:
if str(e) == ('No module named %r' % plugin): if str(e) == ('No module named %r' % plugin):
log.error('Failed to load plugin %r: The plugin could not be found.', plugin) log.error('Failed to load plugin %r: The plugin could not be found.', plugin)
@ -44,17 +41,7 @@ if __name__ == '__main__':
pl.main() pl.main()
for network in conf.conf['servers']: for network in conf.conf['servers']:
protoname = conf.conf['servers'][network]['protocol'] proto = utils.getProtoModule(conf.conf['servers'][network]['protocol'])
try: world.networkobjects[network] = classes.Irc(network, proto, conf.conf)
moduleinfo = imp.find_module(protoname, protocols_folder)
proto = imp.load_source(protoname, moduleinfo[1])
except ImportError as e:
if str(e) == ('No module named %r' % protoname):
log.critical('Failed to load protocol module %r: The file could not be found.', protoname)
else:
log.critical('Failed to load protocol module: ImportError: %s', protoname, str(e))
sys.exit(2)
else:
world.networkobjects[network] = classes.Irc(network, proto)
world.started.set() world.started.set()
log.info("loaded plugins: %s", world.plugins) log.info("loaded plugins: %s", world.plugins)

View File

@ -1,6 +1,7 @@
import string import string
import re import re
import inspect import inspect
import imp
from log import log from log import log
import world import world
@ -497,3 +498,13 @@ def getHostmask(irc, user):
except AttributeError: except AttributeError:
host = '<unknown host>' host = '<unknown host>'
return '%s!%s@%s' % (nick, ident, host) return '%s!%s@%s' % (nick, ident, host)
def loadModuleFromFolder(name, folder):
"""Attempts an import of name from a specific folder, returning the resulting module."""
moduleinfo = imp.find_module(name, folder)
m = imp.load_source(name, moduleinfo[1])
return m
def getProtoModule(protoname):
"""Imports and returns the protocol module requested."""
return loadModuleFromFolder(protoname, world.protocols_folder)

View File

@ -3,6 +3,7 @@
from collections import defaultdict from collections import defaultdict
import threading import threading
import subprocess import subprocess
import os
# Global variable to indicate whether we're being ran directly, or imported # Global variable to indicate whether we're being ran directly, or imported
# for a testcase. # for a testcase.
@ -18,6 +19,9 @@ plugins = {}
whois_handlers = [] whois_handlers = []
started = threading.Event() started = threading.Event()
plugins_folder = [os.path.join(os.getcwd(), 'plugins')]
protocols_folder = [os.path.join(os.getcwd(), 'protocols')]
version = "<unknown>" version = "<unknown>"
source = "https://github.com/GLolol/PyLink" # CHANGE THIS IF YOU'RE FORKING!! source = "https://github.com/GLolol/PyLink" # CHANGE THIS IF YOU'RE FORKING!!