Refactor code for readability and compatibility.

This commit is contained in:
Griatch 2017-01-27 00:19:27 +01:00
parent a09835049b
commit c6d9c0619e
43 changed files with 129 additions and 112 deletions

View file

@ -103,6 +103,7 @@ def _create_version():
try: try:
version = "%s (rev %s)" % (version, check_output("git rev-parse --short HEAD", shell=True, cwd=root, stderr=STDOUT).strip()) version = "%s (rev %s)" % (version, check_output("git rev-parse --short HEAD", shell=True, cwd=root, stderr=STDOUT).strip())
except (IOError, CalledProcessError): except (IOError, CalledProcessError):
# ignore if we cannot get to git
pass pass
return version return version

View file

@ -383,7 +383,7 @@ def get_and_merge_cmdsets(caller, session, player, obj, callertype):
except Exception: except Exception:
_msg_err(caller, _ERROR_CMDSETS) _msg_err(caller, _ERROR_CMDSETS)
raise raise
raise ErrorReported #raise ErrorReported
# Main command-handler function # Main command-handler function
@ -565,7 +565,7 @@ def cmdhandler(called_by, raw_string, _testing=False, callertype="session", sess
syscmd.matches = matches syscmd.matches = matches
else: else:
# fall back to default error handling # fall back to default error handling
sysarg = yield _SEARCH_AT_RESULT([match[2] for match in matches], caller, query=match[0]) sysarg = yield _SEARCH_AT_RESULT([match[2] for match in matches], caller, query=matches[0][0])
raise ExecSystemCommand(syscmd, sysarg) raise ExecSystemCommand(syscmd, sysarg)
if len(matches) == 1: if len(matches) == 1:

View file

@ -40,21 +40,21 @@ class _CmdSetMeta(type):
the cmdset class. the cmdset class.
""" """
def __init__(mcs, *args, **kwargs): def __init__(cls, *args, **kwargs):
""" """
Fixes some things in the cmdclass Fixes some things in the cmdclass
""" """
# by default we key the cmdset the same as the # by default we key the cmdset the same as the
# name of its class. # name of its class.
if not hasattr(mcs, 'key') or not mcs.key: if not hasattr(cls, 'key') or not cls.key:
mcs.key = mcs.__name__ cls.key = cls.__name__
mcs.path = "%s.%s" % (mcs.__module__, mcs.__name__) cls.path = "%s.%s" % (cls.__module__, cls.__name__)
if not type(mcs.key_mergetypes) == dict: if not type(cls.key_mergetypes) == dict:
mcs.key_mergetypes = {} cls.key_mergetypes = {}
super(_CmdSetMeta, mcs).__init__(*args, **kwargs) super(_CmdSetMeta, cls).__init__(*args, **kwargs)
class CmdSet(with_metaclass(_CmdSetMeta, object)): class CmdSet(with_metaclass(_CmdSetMeta, object)):
@ -511,6 +511,7 @@ class CmdSet(with_metaclass(_CmdSetMeta, object)):
ic = self.system_commands.index(cmd) ic = self.system_commands.index(cmd)
del self.system_commands[ic] del self.system_commands[ic]
except ValueError: except ValueError:
# ignore error
pass pass
else: else:
self.commands = [oldcmd for oldcmd in self.commands if oldcmd != cmd] self.commands = [oldcmd for oldcmd in self.commands if oldcmd != cmd]

View file

@ -490,6 +490,7 @@ class CmdSetHandler(object):
storage.remove(cset.path) storage.remove(cset.path)
updated = True updated = True
except ValueError: except ValueError:
# nothing to remove
pass pass
if updated: if updated:
self.obj.cmdset_storage = storage self.obj.cmdset_storage = storage
@ -498,6 +499,7 @@ class CmdSetHandler(object):
try: try:
self.cmdset_stack.remove(cset) self.cmdset_stack.remove(cset)
except ValueError: except ValueError:
# nothing to remove
pass pass
# re-sync the cmdsethandler. # re-sync the cmdsethandler.
self.update() self.update()

View file

@ -12,7 +12,7 @@ from evennia.utils.utils import is_iter, fill, lazy_property, make_iter
from future.utils import with_metaclass from future.utils import with_metaclass
def _init_command(mcs, **kwargs): def _init_command(cls, **kwargs):
""" """
Helper command. Helper command.
Makes sure all data are stored as lowercase and Makes sure all data are stored as lowercase and
@ -26,60 +26,60 @@ def _init_command(mcs, **kwargs):
for i in range(len(kwargs)): for i in range(len(kwargs)):
# used for dynamic creation of commands # used for dynamic creation of commands
key, value = kwargs.popitem() key, value = kwargs.popitem()
setattr(mcs, key, value) setattr(cls, key, value)
mcs.key = mcs.key.lower() cls.key = cls.key.lower()
if mcs.aliases and not is_iter(mcs.aliases): if cls.aliases and not is_iter(cls.aliases):
try: try:
mcs.aliases = [str(alias).strip().lower() cls.aliases = [str(alias).strip().lower()
for alias in mcs.aliases.split(',')] for alias in cls.aliases.split(',')]
except Exception: except Exception:
mcs.aliases = [] cls.aliases = []
mcs.aliases = list(set(alias for alias in mcs.aliases cls.aliases = list(set(alias for alias in cls.aliases
if alias and alias != mcs.key)) if alias and alias != cls.key))
# optimization - a set is much faster to match against than a list # optimization - a set is much faster to match against than a list
mcs._matchset = set([mcs.key] + mcs.aliases) cls._matchset = set([cls.key] + cls.aliases)
# optimization for looping over keys+aliases # optimization for looping over keys+aliases
mcs._keyaliases = tuple(mcs._matchset) cls._keyaliases = tuple(cls._matchset)
# by default we don't save the command between runs # by default we don't save the command between runs
if not hasattr(mcs, "save_for_next"): if not hasattr(cls, "save_for_next"):
mcs.save_for_next = False cls.save_for_next = False
# pre-process locks as defined in class definition # pre-process locks as defined in class definition
temp = [] temp = []
if hasattr(mcs, 'permissions'): if hasattr(cls, 'permissions'):
mcs.locks = mcs.permissions cls.locks = cls.permissions
if not hasattr(mcs, 'locks'): if not hasattr(cls, 'locks'):
# default if one forgets to define completely # default if one forgets to define completely
mcs.locks = "cmd:all()" cls.locks = "cmd:all()"
if not "cmd:" in mcs.locks: if not "cmd:" in cls.locks:
mcs.locks = "cmd:all();" + mcs.locks cls.locks = "cmd:all();" + cls.locks
for lockstring in mcs.locks.split(';'): for lockstring in cls.locks.split(';'):
if lockstring and not ':' in lockstring: if lockstring and not ':' in lockstring:
lockstring = "cmd:%s" % lockstring lockstring = "cmd:%s" % lockstring
temp.append(lockstring) temp.append(lockstring)
mcs.lock_storage = ";".join(temp) cls.lock_storage = ";".join(temp)
if hasattr(mcs, 'arg_regex') and isinstance(mcs.arg_regex, basestring): if hasattr(cls, 'arg_regex') and isinstance(cls.arg_regex, basestring):
mcs.arg_regex = re.compile(r"%s" % mcs.arg_regex, re.I + re.UNICODE) cls.arg_regex = re.compile(r"%s" % cls.arg_regex, re.I + re.UNICODE)
if not hasattr(mcs, "auto_help"): if not hasattr(cls, "auto_help"):
mcs.auto_help = True cls.auto_help = True
if not hasattr(mcs, 'is_exit'): if not hasattr(cls, 'is_exit'):
mcs.is_exit = False cls.is_exit = False
if not hasattr(mcs, "help_category"): if not hasattr(cls, "help_category"):
mcs.help_category = "general" cls.help_category = "general"
mcs.help_category = mcs.help_category.lower() cls.help_category = cls.help_category.lower()
class CommandMeta(type): class CommandMeta(type):
""" """
The metaclass cleans up all properties on the class The metaclass cleans up all properties on the class
""" """
def __init__(mcs, *args, **kwargs): def __init__(cls, *args, **kwargs):
_init_command(mcs, **kwargs) _init_command(cls, **kwargs)
super(CommandMeta, mcs).__init__(*args, **kwargs) super(CommandMeta, cls).__init__(*args, **kwargs)
# The Command class is the basic unit of an Evennia command; when # The Command class is the basic unit of an Evennia command; when
# defining new commands, the admin subclass this class and # defining new commands, the admin subclass this class and

View file

@ -203,7 +203,8 @@ def purge_processor(caller):
del caller.ndb.batch_stackptr del caller.ndb.batch_stackptr
del caller.ndb.batch_pythonpath del caller.ndb.batch_pythonpath
del caller.ndb.batch_batchmode del caller.ndb.batch_batchmode
except: except Exception:
# something might have already been erased; it's not critical
pass pass
# clear everything back to the state before the batch call # clear everything back to the state before the batch call
if caller.ndb.batch_cmdset_backup: if caller.ndb.batch_cmdset_backup:

View file

@ -1355,10 +1355,12 @@ def _convert_from_string(cmd, strobj):
try: try:
return int(obj) return int(obj)
except ValueError: except ValueError:
# obj cannot be converted to int - that's fine
pass pass
try: try:
return float(obj) return float(obj)
except ValueError: except ValueError:
# obj cannot be converted to float - that's fine
pass pass
# iterables # iterables
if obj.startswith('[') and obj.endswith(']'): if obj.startswith('[') and obj.endswith(']'):
@ -1983,6 +1985,7 @@ class CmdExamine(ObjManipCommand):
# we have to protect this since many objects don't have sessions. # we have to protect this since many objects don't have sessions.
all_cmdsets.extend([(cmdset.key, cmdset) for cmdset in obj.get_session(obj.sessions.get()).cmdset.all()]) all_cmdsets.extend([(cmdset.key, cmdset) for cmdset in obj.get_session(obj.sessions.get()).cmdset.all()])
except (TypeError, AttributeError): except (TypeError, AttributeError):
# an error means we are merging an object without a session
pass pass
all_cmdsets = [cmdset for cmdset in dict(all_cmdsets).values()] all_cmdsets = [cmdset for cmdset in dict(all_cmdsets).values()]
all_cmdsets.sort(key=lambda x: x.priority, reverse=True) all_cmdsets.sort(key=lambda x: x.priority, reverse=True)

View file

@ -316,10 +316,7 @@ class CmdScripts(COMMAND_DEFAULT_CLASS):
if self.switches and self.switches[0] in ('stop', 'del', 'delete', 'kill'): if self.switches and self.switches[0] in ('stop', 'del', 'delete', 'kill'):
# we want to delete something # we want to delete something
if not scripts: if len(scripts) == 1:
string = "No scripts/objects matching '%s'. " % args
string += "Be more specific."
elif len(scripts) == 1:
# we have a unique match! # we have a unique match!
if 'kill' in self.switches: if 'kill' in self.switches:
string = "Killing script '%s'" % scripts[0].key string = "Killing script '%s'" % scripts[0].key

View file

@ -105,7 +105,7 @@ def create_guest_player(session):
if not PlayerDB.objects.filter(username__iexact=playername): if not PlayerDB.objects.filter(username__iexact=playername):
break break
playername = None playername = None
if playername == None: if playername is None:
session.msg("All guest accounts are in use. Please try again later.") session.msg("All guest accounts are in use. Please try again later.")
return True, None return True, None
@ -126,8 +126,7 @@ def create_guest_player(session):
# we won't see any errors at all. # we won't see any errors at all.
session.msg("An error occurred. Please e-mail an admin if the problem persists.") session.msg("An error occurred. Please e-mail an admin if the problem persists.")
logger.log_trace() logger.log_trace()
finally: raise
return True, new_player
def create_normal_player(session, name, password): def create_normal_player(session, name, password):

View file

@ -79,6 +79,7 @@ class ChannelCommand(command.Command):
try: try:
self.history_start = int(arg) if arg else 0 self.history_start = int(arg) if arg else 0
except ValueError: except ValueError:
# if no valid number was given, ignore it
pass pass
self.args = (channelname.strip(), msg.strip()) self.args = (channelname.strip(), msg.strip())

View file

@ -401,6 +401,7 @@ class ChannelDBManager(TypedObjectManager):
dbref = int(ostring.strip('#')) dbref = int(ostring.strip('#'))
channels = self.filter(id=dbref) channels = self.filter(id=dbref)
except Exception: except Exception:
# Usually because we couldn't convert to int - not a dbref
pass pass
if not channels: if not channels:
# no id match. Search on the key. # no id match. Search on the key.

View file

@ -612,6 +612,7 @@ class CmdEvaluate(CmdTradeBase):
ind = int(self.args) ind = int(self.args)
self.args = ind - 1 self.args = ind - 1
except Exception: except Exception:
# not a valid index - ignore
pass pass
offer = self.tradehandler.search(self.args) offer = self.tradehandler.search(self.args)

View file

@ -51,6 +51,7 @@ CONNECTION_SCREEN = ""
try: try:
CONNECTION_SCREEN = ansi.parse_ansi(utils.random_string_from_module(CONNECTION_SCREEN_MODULE)) CONNECTION_SCREEN = ansi.parse_ansi(utils.random_string_from_module(CONNECTION_SCREEN_MODULE))
except Exception: except Exception:
# malformed connection screen or no screen given
pass pass
if not CONNECTION_SCREEN: if not CONNECTION_SCREEN:
CONNECTION_SCREEN = "\nEvennia: Error in CONNECTION_SCREEN MODULE (randomly picked connection screen variable is not a string). \nEnter 'help' for aid." CONNECTION_SCREEN = "\nEvennia: Error in CONNECTION_SCREEN MODULE (randomly picked connection screen variable is not a string). \nEnter 'help' for aid."

View file

@ -39,7 +39,7 @@ class CmdNudge(Command):
rand = random.random() rand = random.random()
if rand < 0.5: if rand < 0.5:
self.caller.msg("You nudge at the lid. It seems stuck.") self.caller.msg("You nudge at the lid. It seems stuck.")
elif 0.5 <= rand < 0.7: elif rand < 0.7:
self.caller.msg("You move the lid back and forth. It won't budge.") self.caller.msg("You move the lid back and forth. It won't budge.")
else: else:
self.caller.msg("You manage to get a nail under the lid.") self.caller.msg("You manage to get a nail under the lid.")

View file

@ -344,6 +344,7 @@ class LightSource(TutorialObject):
self.location.msg_contents("A %s on the floor flickers and dies." % self.key) self.location.msg_contents("A %s on the floor flickers and dies." % self.key)
self.location.location.check_light_state() self.location.location.check_light_state()
except AttributeError: except AttributeError:
# Mainly happens if we happen to be in a None location
pass pass
self.delete() self.delete()
@ -364,6 +365,7 @@ class LightSource(TutorialObject):
# maybe we are directly in the room # maybe we are directly in the room
self.location.check_light_state() self.location.check_light_state()
except AttributeError: except AttributeError:
# we are in a None location
pass pass
finally: finally:
# start the burn timer. When it runs out, self._burnout # start the burn timer. When it runs out, self._burnout

View file

@ -62,15 +62,18 @@ MSSPTable = {
# Protocols set to 1 or 0) # Protocols set to 1 or 0)
"ANSI": "1", "ANSI": "1",
"GMCP": "0", "GMCP": "1",
"ATCP": "0",
"MCCP": "0", "MCCP": "0",
"MCP": "0", "MCP": "0",
"MSDP": "0", "MSDP": "0",
"MSP": "0", "MSP": "0",
"MXP": "0", "MXP": "0",
"PUEBLO": "0", "PUEBLO": "0",
"SSL": "1",
"UTF-8": "1", "UTF-8": "1",
"VT100": "0", "VT100": "0",
"ZMP": "0",
"XTERM 256 COLORS": "0", "XTERM 256 COLORS": "0",
# Commercial set to 1 or 0) # Commercial set to 1 or 0)
@ -111,12 +114,4 @@ MSSPTable = {
"TRAINING SYSTEM": "None", # "None", "Level", "Skill", "Both" "TRAINING SYSTEM": "None", # "None", "Level", "Skill", "Both"
"WORLD ORIGINALITY": "None", # "All Stock", "Mostly Stock", "Mostly Original", "All Original" "WORLD ORIGINALITY": "None", # "All Stock", "Mostly Stock", "Mostly Original", "All Original"
# Protocols (only change if you added/removed something manually) }
"ATCP": "0",
"MSDP": "0",
"MCCP": "1",
"SSL": "1",
"UTF-8": "1",
"ZMP": "0",
"XTERM 256 COLORS": "0"}

View file

@ -539,6 +539,7 @@ def holds(accessing_obj, accessed_obj, *args, **kwargs):
if check_holds(accessed_obj.dbid): if check_holds(accessed_obj.dbid):
return True return True
except Exception: except Exception:
# we need to catch any trouble here
pass pass
return hasattr(accessed_obj, "obj") and check_holds(accessed_obj.obj.dbid) return hasattr(accessed_obj, "obj") and check_holds(accessed_obj.obj.dbid)
if len(args) == 1: if len(args) == 1:

View file

@ -409,6 +409,7 @@ class ObjectDBManager(TypedObjectManager):
try: try:
matches = [matches[match_number]] matches = [matches[match_number]]
except IndexError: except IndexError:
# match number not matching anything
pass pass
# return a list (possibly empty) # return a list (possibly empty)
return matches return matches

View file

@ -242,12 +242,14 @@ class ObjectDB(TypedObject):
return return
elif loc == self: elif loc == self:
raise RuntimeError raise RuntimeError
elif loc == None: elif loc is None:
raise RuntimeWarning raise RuntimeWarning
return is_loc_loop(loc.db_location, depth + 1) return is_loc_loop(loc.db_location, depth + 1)
try: try:
is_loc_loop(location) is_loc_loop(location)
except RuntimeWarning: except RuntimeWarning:
# we caught a infitite location loop!
# (location1 is in location2 which is in location1 ...)
pass pass
# if we get to this point we are ready to change location # if we get to this point we are ready to change location

View file

@ -83,7 +83,7 @@ class ObjectSessionHandler(object):
if sessid: if sessid:
sessions = [_SESSIONS[sessid] if sessid in _SESSIONS else None] if sessid in self._sessid_cache else [] sessions = [_SESSIONS[sessid] if sessid in _SESSIONS else None] if sessid in self._sessid_cache else []
else: else:
sessions = [_SESSIONS[sessid] if sessid in _SESSIONS else None for sessid in self._sessid_cache] sessions = [_SESSIONS[ssid] if ssid in _SESSIONS else None for ssid in self._sessid_cache]
if None in sessions: if None in sessions:
# this happens only if our cache has gone out of sync with the SessionHandler. # this happens only if our cache has gone out of sync with the SessionHandler.
self._recache() self._recache()

View file

@ -409,12 +409,14 @@ class DefaultPlayer(with_metaclass(TypeclassBase, PlayerDB)):
try: try:
from_obj.at_msg_send(text=text, to_obj=self, **kwargs) from_obj.at_msg_send(text=text, to_obj=self, **kwargs)
except Exception: except Exception:
# this may not be assigned.
pass pass
try: try:
if not self.at_msg_receive(text=text, **kwargs): if not self.at_msg_receive(text=text, **kwargs):
# abort message to this player # abort message to this player
return return
except Exception: except Exception:
# this may not be assigned.
pass pass
kwargs["options"] = options kwargs["options"] = options

View file

@ -139,6 +139,7 @@ class ScriptDB(TypedObject):
try: try:
value = _GA(value, "dbobj") value = _GA(value, "dbobj")
except AttributeError: except AttributeError:
# deprecated ...
pass pass
if isinstance(value, (basestring, int)): if isinstance(value, (basestring, int)):
from evennia.objects.models import ObjectDB from evennia.objects.models import ObjectDB

View file

@ -46,7 +46,7 @@ class ScriptHandler(object):
repeats = script.repeats repeats = script.repeats
try: try:
next_repeat = script.time_until_next_repeat() next_repeat = script.time_until_next_repeat()
except: except Exception:
next_repeat = "?" next_repeat = "?"
string += _("\n '%(key)s' (%(next_repeat)s/%(interval)s, %(repeats)s repeats): %(desc)s") % \ string += _("\n '%(key)s' (%(next_repeat)s/%(interval)s, %(repeats)s repeats): %(desc)s") % \
{"key": script.key, "next_repeat": next_repeat, {"key": script.key, "next_repeat": next_repeat,

View file

@ -100,7 +100,7 @@ class ExtendedLoopingCall(LoopingCall):
if self.start_delay: if self.start_delay:
self.start_delay = None self.start_delay = None
self.starttime = self.clock.seconds() self.starttime = self.clock.seconds()
super(ExtendedLoopingCall, self).__call__() LoopingCall.__call__(self)
def force_repeat(self): def force_repeat(self):
""" """
@ -210,6 +210,7 @@ class DefaultScript(ScriptBase):
try: try:
self.db_obj.msg(estring) self.db_obj.msg(estring)
except Exception: except Exception:
# we must not crash inside the errback, even if db_obj is None.
pass pass
logger.log_err(estring) logger.log_err(estring)

View file

@ -405,6 +405,7 @@ def evennia_version():
import evennia import evennia
version = evennia.__version__ version = evennia.__version__
except ImportError: except ImportError:
# even if evennia is not found, we should not crash here.
pass pass
try: try:
rev = check_output( rev = check_output(
@ -412,6 +413,7 @@ def evennia_version():
shell=True, cwd=EVENNIA_ROOT, stderr=STDOUT).strip() shell=True, cwd=EVENNIA_ROOT, stderr=STDOUT).strip()
version = "%s (rev %s)" % (version, rev) version = "%s (rev %s)" % (version, rev)
except (IOError, CalledProcessError): except (IOError, CalledProcessError):
# move on if git is not answering
pass pass
return version return version
@ -520,7 +522,7 @@ def create_settings_file(init=True):
if not init: if not init:
# if not --init mode, settings file may already exist from before # if not --init mode, settings file may already exist from before
if os.path.exists(settings_path): if os.path.exists(settings_path):
inp = raw_input("server/conf/settings.py already exists. " inp = input("server/conf/settings.py already exists. "
"Do you want to reset it? y/[N]> ") "Do you want to reset it? y/[N]> ")
if not inp.lower() == 'y': if not inp.lower() == 'y':
print ("Aborted.") print ("Aborted.")
@ -659,14 +661,13 @@ def get_pid(pidfile):
pidfile (str): The path of the pid file. pidfile (str): The path of the pid file.
Returns: Returns:
pid (str): The process id. pid (str or None): The process id.
""" """
pid = None
if os.path.exists(pidfile): if os.path.exists(pidfile):
f = open(pidfile, 'r') with open(pidfile, 'r') as f:
pid = f.read() pid = f.read()
return pid return pid
def del_pid(pidfile): def del_pid(pidfile):
@ -722,6 +723,7 @@ def kill(pidfile, signal=SIG, succmsg="", errmsg="",
SetConsoleCtrlHandler(None, True) SetConsoleCtrlHandler(None, True)
GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0) GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0)
except KeyboardInterrupt: except KeyboardInterrupt:
# We must catch and ignore the interrupt sent.
pass pass
else: else:
# Linux can send the SIGINT signal directly # Linux can send the SIGINT signal directly
@ -986,6 +988,8 @@ def run_dummyrunner(number_of_dummies):
try: try:
call(cmdstr, env=getenv()) call(cmdstr, env=getenv())
except KeyboardInterrupt: except KeyboardInterrupt:
# this signals the dummyrunner to stop cleanly and should
# not lead to a traceback here.
pass pass

View file

@ -133,13 +133,16 @@ class Mssp(object):
"ANSI": "1", "ANSI": "1",
"GMCP": "0", "GMCP": "0",
"ATCP": "0",
"MCCP": "0", "MCCP": "0",
"MCP": "0", "MCP": "0",
"MSDP": "0", "MSDP": "0",
"MSP": "0", "MSP": "0",
"MXP": "0", "MXP": "0",
"PUEBLO": "0", "PUEBLO": "0",
"SSL": "1",
"UTF-8": "1", "UTF-8": "1",
"ZMP": "0",
"VT100": "0", "VT100": "0",
"XTERM 256 COLORS": "0", "XTERM 256 COLORS": "0",
@ -180,16 +183,7 @@ class Mssp(object):
"ROLEPLAYING": "None", # "None", "Accepted", "Encouraged", "Enforced" "ROLEPLAYING": "None", # "None", "Accepted", "Encouraged", "Enforced"
"TRAINING SYSTEM": "None", # "None", "Level", "Skill", "Both" "TRAINING SYSTEM": "None", # "None", "Level", "Skill", "Both"
"WORLD ORIGINALITY": "None", # "All Stock", "Mostly Stock", "Mostly Original", "All Original" "WORLD ORIGINALITY": "None", # "All Stock", "Mostly Stock", "Mostly Original", "All Original"
}
# Protocols (only change if you added/removed something manually)
"ATCP": "0",
"MSDP": "0",
"MCCP": "1",
"SSL": "1",
"UTF-8": "1",
"ZMP": "0",
"XTERM 256 COLORS": "0"}
# update the static table with the custom one # update the static table with the custom one
if MSSPTable_CUSTOM: if MSSPTable_CUSTOM:

View file

@ -364,6 +364,7 @@ class PortalSessionHandler(SessionHandler):
self.data_out(session, text=[[_ERROR_MAX_CHAR], {}]) self.data_out(session, text=[[_ERROR_MAX_CHAR], {}])
return return
except Exception: except Exception:
# if there is a problem to send, we continue
pass pass
if session: if session:
now = time() now = time()

View file

@ -364,6 +364,7 @@ class TelnetOOB(object):
try: try:
structure = json.loads(structure) structure = json.loads(structure)
except ValueError: except ValueError:
# maybe the structure is not json-serialized at all
pass pass
args, kwargs = [], {} args, kwargs = [], {}
if hasattr(structure, "__iter__"): if hasattr(structure, "__iter__"):

View file

@ -89,6 +89,7 @@ class Ttype(object):
try: try:
option = "".join(option).lstrip(IS) option = "".join(option).lstrip(IS)
except TypeError: except TypeError:
# option is not on a suitable form for joining
pass pass
if self.ttype_step == 0: if self.ttype_step == 0:

View file

@ -204,7 +204,7 @@ class WebSocketClient(Protocol, Session):
kwargs["options"].update({"send_prompt": True}) kwargs["options"].update({"send_prompt": True})
self.send_text(*args, **kwargs) self.send_text(*args, **kwargs)
def send_default(session, cmdname, *args, **kwargs): def send_default(self, cmdname, *args, **kwargs):
""" """
Data Evennia -> User. Data Evennia -> User.
@ -219,4 +219,4 @@ class WebSocketClient(Protocol, Session):
""" """
if not cmdname == "options": if not cmdname == "options":
session.sendLine(json.dumps([cmdname, args, kwargs])) self.sendLine(json.dumps([cmdname, args, kwargs]))

View file

@ -76,6 +76,7 @@ class WebClient(resource.Resource):
try: try:
del self.requests[csessid] del self.requests[csessid]
except KeyError: except KeyError:
# nothing left to delete
pass pass
def _keepalive(self): def _keepalive(self):

View file

@ -310,7 +310,7 @@ class ServerSession(Session):
cchan = ChannelDB.objects.get_channel(cchan[0]) cchan = ChannelDB.objects.get_channel(cchan[0])
cchan.msg("[%s]: %s" % (cchan.key, message)) cchan.msg("[%s]: %s" % (cchan.key, message))
except Exception: except Exception:
pass logger.log_trace()
logger.log_info(message) logger.log_info(message)
def get_client_size(self): def get_client_size(self):

View file

@ -696,6 +696,7 @@ try:
import django_extensions import django_extensions
INSTALLED_APPS = INSTALLED_APPS + ('django_extensions',) INSTALLED_APPS = INSTALLED_APPS + ('django_extensions',)
except ImportError: except ImportError:
# Django extensions are not installed in all distros.
pass pass
####################################################################### #######################################################################

View file

@ -286,7 +286,7 @@ class TagHandler(object):
for keystr in make_iter(key): for keystr in make_iter(key):
# note - the _getcache call removes case sensitivity for us # note - the _getcache call removes case sensitivity for us
ret.extend([tag if return_tagobj else to_str(tag.db_key) ret.extend([tag if return_tagobj else to_str(tag.db_key)
for tag in self._getcache(key, category)]) for tag in self._getcache(keystr, category)])
return ret[0] if len(ret) == 1 else (ret if ret else default) return ret[0] if len(ret) == 1 else (ret if ret else default)
def remove(self, key, category=None): def remove(self, key, category=None):
@ -355,7 +355,6 @@ class TagHandler(object):
return [(to_str(tag.db_key), to_str(tag.db_category)) for tag in tags] return [(to_str(tag.db_key), to_str(tag.db_category)) for tag in tags]
else: else:
return [to_str(tag.db_key) for tag in tags] return [to_str(tag.db_key) for tag in tags]
return []
def __str__(self): def __str__(self):
return ",".join(self.all()) return ",".join(self.all())

View file

@ -575,6 +575,7 @@ def _on_raw(func_name):
else: else:
args.insert(0, string) args.insert(0, string)
except IndexError: except IndexError:
# just skip out if there are no more strings
pass pass
result = getattr(self._raw_string, func_name)(*args, **kwargs) result = getattr(self._raw_string, func_name)(*args, **kwargs)
if isinstance(result, basestring): if isinstance(result, basestring):
@ -850,6 +851,7 @@ class ANSIString(with_metaclass(ANSIMeta, unicode)):
try: try:
string += self._raw_string[i] string += self._raw_string[i]
except IndexError: except IndexError:
# raw_string not long enough
pass pass
if i is not None: if i is not None:
append_tail = self._get_interleving(self._char_indexes.index(i) + 1) append_tail = self._get_interleving(self._char_indexes.index(i) + 1)

View file

@ -115,7 +115,7 @@ def create_object(typeclass=None, key=None, location=None,
# store the call signature for the signal # store the call signature for the signal
new_object._createdict = {"key":key, "location":location, "destination":destination, new_object._createdict = {"key":key, "location":location, "destination":destination,
"home":home, "typeclass":typeclass.path, "permissions":permissions, "home":home, "typeclass":typeclass.path, "permissions":permissions,
"locks":locks, "aliases":aliases, "tags": tags, "destination":destination, "locks":locks, "aliases":aliases, "tags": tags,
"report_to":report_to, "nohome":nohome} "report_to":report_to, "nohome":nohome}
# this will trigger the save signal which in turn calls the # this will trigger the save signal which in turn calls the
# at_first_save hook on the typeclass, where the _createdict can be # at_first_save hook on the typeclass, where the _createdict can be

View file

@ -809,7 +809,7 @@ class EvEditor(object):
formatting information. formatting information.
""" """
if buf == None: if buf is None:
buf = self._buffer buf = self._buffer
if is_iter(buf): if is_iter(buf):
buf = "\n".join(buf) buf = "\n".join(buf)

View file

@ -159,14 +159,14 @@ class ANSITextWrapper(TextWrapper):
""" """
# ignore expand_tabs/replace_whitespace until ANSISTring handles them # ignore expand_tabs/replace_whitespace until ANSISTring handles them
return text return text
if self.expand_tabs: # if self.expand_tabs:
text = text.expandtabs() # text = text.expandtabs()
if self.replace_whitespace: # if self.replace_whitespace:
if isinstance(text, str): # if isinstance(text, str):
text = text.translate(self.whitespace_trans) # text = text.translate(self.whitespace_trans)
elif isinstance(text, _unicode): # elif isinstance(text, _unicode):
text = text.translate(self.unicode_whitespace_trans) # text = text.translate(self.unicode_whitespace_trans)
return text # return text
def _split(self, text): def _split(self, text):

View file

@ -134,10 +134,6 @@ class SharedMemoryModelBase(ModelBase):
"Setter only used on foreign key relations, allows setting with #dbref" "Setter only used on foreign key relations, allows setting with #dbref"
if _GA(cls, "_is_deleted"): if _GA(cls, "_is_deleted"):
raise ObjectDoesNotExist("Cannot set %s to %s: Hosting object was already deleted!" % (fname, value)) raise ObjectDoesNotExist("Cannot set %s to %s: Hosting object was already deleted!" % (fname, value))
try:
value = _GA(value, "dbobj")
except AttributeError:
pass
if isinstance(value, (basestring, int)): if isinstance(value, (basestring, int)):
value = to_str(value, force_string=True) value = to_str(value, force_string=True)
if (value.isdigit() or value.startswith("#")): if (value.isdigit() or value.startswith("#")):
@ -273,6 +269,7 @@ class SharedMemoryModel(with_metaclass(SharedMemoryModelBase, Model)):
# at first initialization # at first initialization
instance.at_init() instance.at_init()
except AttributeError: except AttributeError:
# The at_init hook is not assigned to all entities
pass pass
@classmethod @classmethod

View file

@ -212,7 +212,7 @@ class PickledObjectField(models.Field):
if value is not None: if value is not None:
try: try:
value = dbsafe_decode(value, self.compress) value = dbsafe_decode(value, self.compress)
except: except Exception:
# If the value is a definite pickle; and an error is raised in # If the value is a definite pickle; and an error is raised in
# de-pickling it should be allowed to propogate. # de-pickling it should be allowed to propogate.
if isinstance(value, PickledObject): if isinstance(value, PickledObject):

View file

@ -430,12 +430,12 @@ class PrettyTable(object):
############################## ##############################
def _get_field_names(self): def _get_field_names(self):
return self._field_names
"""The names of the fields """The names of the fields
Arguments: Arguments:
fields - list or tuple of field names""" fields - list or tuple of field names"""
return self._field_names
def _set_field_names(self, val): def _set_field_names(self, val):
val = [self._unicode(x) for x in val] val = [self._unicode(x) for x in val]
self._validate_option("field_names", val) self._validate_option("field_names", val)

View file

@ -99,6 +99,7 @@ def http_headers(s):
key, value = [i.strip() for i in line.split(":", 1)] key, value = [i.strip() for i in line.split(":", 1)]
d[key] = value d[key] = value
except ValueError: except ValueError:
# malformed header, skip it
pass pass
return d return d
@ -257,8 +258,8 @@ def parse_hybi07_frames(buf):
if header & 0x70: if header & 0x70:
# At least one of the reserved flags is set. Pork chop sandwiches! # At least one of the reserved flags is set. Pork chop sandwiches!
raise WSException("Reserved flag in HyBi-07 frame (%d)" % header) raise WSException("Reserved flag in HyBi-07 frame (%d)" % header)
frames.append(("", CLOSE)) #frames.append(("", CLOSE))
return frames, buf #return frames, buf
# Get the opcode, and translate it to a local enum which we actually # Get the opcode, and translate it to a local enum which we actually
# care about. # care about.

View file

@ -703,6 +703,7 @@ def to_unicode(obj, encoding='utf-8', force_string=False):
obj = unicode(obj, alt_encoding) obj = unicode(obj, alt_encoding)
return obj return obj
except UnicodeDecodeError: except UnicodeDecodeError:
# if we still have an error, give up
pass pass
raise Exception("Error: '%s' contains invalid character(s) not in %s." % (obj, encoding)) raise Exception("Error: '%s' contains invalid character(s) not in %s." % (obj, encoding))
return obj return obj
@ -744,6 +745,7 @@ def to_str(obj, encoding='utf-8', force_string=False):
obj = obj.encode(alt_encoding) obj = obj.encode(alt_encoding)
return obj return obj
except UnicodeEncodeError: except UnicodeEncodeError:
# if we still have an error, give up
pass pass
# if we get to this point we have not found any way to convert this string. Try to parse it manually, # if we get to this point we have not found any way to convert this string. Try to parse it manually,
@ -926,6 +928,7 @@ def clean_object_caches(obj):
try: try:
_SA(obj, "_contents_cache", None) _SA(obj, "_contents_cache", None)
except AttributeError: except AttributeError:
# if the cache cannot be reached, move on anyway
pass pass
# on-object property cache # on-object property cache
@ -935,6 +938,7 @@ def clean_object_caches(obj):
hashid = _GA(obj, "hashid") hashid = _GA(obj, "hashid")
_TYPECLASSMODELS._ATTRIBUTE_CACHE[hashid] = {} _TYPECLASSMODELS._ATTRIBUTE_CACHE[hashid] = {}
except AttributeError: except AttributeError:
# skip caching
pass pass
@ -1273,9 +1277,9 @@ def fuzzy_import_from_module(path, variable, default=None, defaultpaths=None):
paths = [path] + make_iter(defaultpaths) paths = [path] + make_iter(defaultpaths)
for modpath in paths: for modpath in paths:
try: try:
mod = import_module(path) mod = import_module(modpath)
except ImportError as ex: except ImportError as ex:
if not str(ex).startswith ("No module named %s" % path): if not str(ex).startswith ("No module named %s" % modpath):
# this means the module was found but it # this means the module was found but it
# triggers an ImportError on import. # triggers an ImportError on import.
raise ex raise ex
@ -1521,13 +1525,11 @@ def get_evennia_pids():
portal_pidfile = os.path.join(settings.GAME_DIR, 'portal.pid') portal_pidfile = os.path.join(settings.GAME_DIR, 'portal.pid')
server_pid, portal_pid = None, None server_pid, portal_pid = None, None
if os.path.exists(server_pidfile): if os.path.exists(server_pidfile):
f = open(server_pidfile, 'r') with open(server_pidfile, 'r') as f:
server_pid = f.read() server_pid = f.read()
f.close()
if os.path.exists(portal_pidfile): if os.path.exists(portal_pidfile):
f = open(portal_pidfile, 'r') with open(portal_pidfile, 'r') as f:
portal_pid = f.read() portal_pid = f.read()
f.close()
if server_pid and portal_pid: if server_pid and portal_pid:
return int(server_pid), int(portal_pid) return int(server_pid), int(portal_pid)
return None, None return None, None