From c6d9c0619e1584181c281e16c6785b51a99e0eed Mon Sep 17 00:00:00 2001 From: Griatch Date: Fri, 27 Jan 2017 00:19:27 +0100 Subject: [PATCH] Refactor code for readability and compatibility. --- evennia/__init__.py | 1 + evennia/commands/cmdhandler.py | 4 +- evennia/commands/cmdset.py | 15 +++-- evennia/commands/cmdsethandler.py | 2 + evennia/commands/command.py | 66 +++++++++---------- evennia/commands/default/batchprocess.py | 3 +- evennia/commands/default/building.py | 3 + evennia/commands/default/system.py | 5 +- evennia/commands/default/unloggedin.py | 5 +- evennia/comms/channelhandler.py | 1 + evennia/comms/managers.py | 1 + evennia/contrib/barter.py | 1 + evennia/contrib/email_login.py | 1 + .../tutorial_examples/cmdset_red_button.py | 2 +- evennia/contrib/tutorial_world/objects.py | 2 + evennia/game_template/server/conf/mssp.py | 15 ++--- evennia/locks/lockfuncs.py | 1 + evennia/objects/manager.py | 1 + evennia/objects/models.py | 4 +- evennia/objects/objects.py | 2 +- evennia/players/players.py | 2 + evennia/scripts/models.py | 1 + evennia/scripts/scripthandler.py | 2 +- evennia/scripts/scripts.py | 3 +- evennia/server/evennia_launcher.py | 16 +++-- evennia/server/portal/mssp.py | 14 ++-- evennia/server/portal/portalsessionhandler.py | 1 + evennia/server/portal/telnet_oob.py | 1 + evennia/server/portal/ttype.py | 1 + evennia/server/portal/webclient.py | 4 +- evennia/server/portal/webclient_ajax.py | 1 + evennia/server/serversession.py | 2 +- evennia/settings_default.py | 1 + evennia/typeclasses/tags.py | 3 +- evennia/utils/ansi.py | 2 + evennia/utils/create.py | 2 +- evennia/utils/eveditor.py | 2 +- evennia/utils/evtable.py | 16 ++--- evennia/utils/idmapper/models.py | 5 +- evennia/utils/picklefield.py | 2 +- evennia/utils/prettytable.py | 2 +- evennia/utils/txws.py | 5 +- evennia/utils/utils.py | 18 ++--- 43 files changed, 129 insertions(+), 112 deletions(-) diff --git a/evennia/__init__.py b/evennia/__init__.py index dd0d0a406..865b547b7 100644 --- a/evennia/__init__.py +++ b/evennia/__init__.py @@ -103,6 +103,7 @@ def _create_version(): try: version = "%s (rev %s)" % (version, check_output("git rev-parse --short HEAD", shell=True, cwd=root, stderr=STDOUT).strip()) except (IOError, CalledProcessError): + # ignore if we cannot get to git pass return version diff --git a/evennia/commands/cmdhandler.py b/evennia/commands/cmdhandler.py index bbe0aec9e..ae87b62b6 100644 --- a/evennia/commands/cmdhandler.py +++ b/evennia/commands/cmdhandler.py @@ -383,7 +383,7 @@ def get_and_merge_cmdsets(caller, session, player, obj, callertype): except Exception: _msg_err(caller, _ERROR_CMDSETS) raise - raise ErrorReported + #raise ErrorReported # Main command-handler function @@ -565,7 +565,7 @@ def cmdhandler(called_by, raw_string, _testing=False, callertype="session", sess syscmd.matches = matches else: # 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) if len(matches) == 1: diff --git a/evennia/commands/cmdset.py b/evennia/commands/cmdset.py index 49a287572..ca0c9df51 100644 --- a/evennia/commands/cmdset.py +++ b/evennia/commands/cmdset.py @@ -40,21 +40,21 @@ class _CmdSetMeta(type): the cmdset class. """ - def __init__(mcs, *args, **kwargs): + def __init__(cls, *args, **kwargs): """ Fixes some things in the cmdclass """ # by default we key the cmdset the same as the # name of its class. - if not hasattr(mcs, 'key') or not mcs.key: - mcs.key = mcs.__name__ - mcs.path = "%s.%s" % (mcs.__module__, mcs.__name__) + if not hasattr(cls, 'key') or not cls.key: + cls.key = cls.__name__ + cls.path = "%s.%s" % (cls.__module__, cls.__name__) - if not type(mcs.key_mergetypes) == dict: - mcs.key_mergetypes = {} + if not type(cls.key_mergetypes) == dict: + cls.key_mergetypes = {} - super(_CmdSetMeta, mcs).__init__(*args, **kwargs) + super(_CmdSetMeta, cls).__init__(*args, **kwargs) class CmdSet(with_metaclass(_CmdSetMeta, object)): @@ -511,6 +511,7 @@ class CmdSet(with_metaclass(_CmdSetMeta, object)): ic = self.system_commands.index(cmd) del self.system_commands[ic] except ValueError: + # ignore error pass else: self.commands = [oldcmd for oldcmd in self.commands if oldcmd != cmd] diff --git a/evennia/commands/cmdsethandler.py b/evennia/commands/cmdsethandler.py index 656d94ab4..a77243a1c 100644 --- a/evennia/commands/cmdsethandler.py +++ b/evennia/commands/cmdsethandler.py @@ -490,6 +490,7 @@ class CmdSetHandler(object): storage.remove(cset.path) updated = True except ValueError: + # nothing to remove pass if updated: self.obj.cmdset_storage = storage @@ -498,6 +499,7 @@ class CmdSetHandler(object): try: self.cmdset_stack.remove(cset) except ValueError: + # nothing to remove pass # re-sync the cmdsethandler. self.update() diff --git a/evennia/commands/command.py b/evennia/commands/command.py index bf7202f47..d00074f20 100644 --- a/evennia/commands/command.py +++ b/evennia/commands/command.py @@ -12,7 +12,7 @@ from evennia.utils.utils import is_iter, fill, lazy_property, make_iter from future.utils import with_metaclass -def _init_command(mcs, **kwargs): +def _init_command(cls, **kwargs): """ Helper command. Makes sure all data are stored as lowercase and @@ -26,60 +26,60 @@ def _init_command(mcs, **kwargs): for i in range(len(kwargs)): # used for dynamic creation of commands key, value = kwargs.popitem() - setattr(mcs, key, value) + setattr(cls, key, value) - mcs.key = mcs.key.lower() - if mcs.aliases and not is_iter(mcs.aliases): + cls.key = cls.key.lower() + if cls.aliases and not is_iter(cls.aliases): try: - mcs.aliases = [str(alias).strip().lower() - for alias in mcs.aliases.split(',')] + cls.aliases = [str(alias).strip().lower() + for alias in cls.aliases.split(',')] except Exception: - mcs.aliases = [] - mcs.aliases = list(set(alias for alias in mcs.aliases - if alias and alias != mcs.key)) + cls.aliases = [] + cls.aliases = list(set(alias for alias in cls.aliases + if alias and alias != cls.key)) # 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 - mcs._keyaliases = tuple(mcs._matchset) + cls._keyaliases = tuple(cls._matchset) # by default we don't save the command between runs - if not hasattr(mcs, "save_for_next"): - mcs.save_for_next = False + if not hasattr(cls, "save_for_next"): + cls.save_for_next = False # pre-process locks as defined in class definition temp = [] - if hasattr(mcs, 'permissions'): - mcs.locks = mcs.permissions - if not hasattr(mcs, 'locks'): + if hasattr(cls, 'permissions'): + cls.locks = cls.permissions + if not hasattr(cls, 'locks'): # default if one forgets to define completely - mcs.locks = "cmd:all()" - if not "cmd:" in mcs.locks: - mcs.locks = "cmd:all();" + mcs.locks - for lockstring in mcs.locks.split(';'): + cls.locks = "cmd:all()" + if not "cmd:" in cls.locks: + cls.locks = "cmd:all();" + cls.locks + for lockstring in cls.locks.split(';'): if lockstring and not ':' in lockstring: lockstring = "cmd:%s" % 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): - mcs.arg_regex = re.compile(r"%s" % mcs.arg_regex, re.I + re.UNICODE) - if not hasattr(mcs, "auto_help"): - mcs.auto_help = True - if not hasattr(mcs, 'is_exit'): - mcs.is_exit = False - if not hasattr(mcs, "help_category"): - mcs.help_category = "general" - mcs.help_category = mcs.help_category.lower() + if hasattr(cls, 'arg_regex') and isinstance(cls.arg_regex, basestring): + cls.arg_regex = re.compile(r"%s" % cls.arg_regex, re.I + re.UNICODE) + if not hasattr(cls, "auto_help"): + cls.auto_help = True + if not hasattr(cls, 'is_exit'): + cls.is_exit = False + if not hasattr(cls, "help_category"): + cls.help_category = "general" + cls.help_category = cls.help_category.lower() class CommandMeta(type): """ The metaclass cleans up all properties on the class """ - def __init__(mcs, *args, **kwargs): - _init_command(mcs, **kwargs) - super(CommandMeta, mcs).__init__(*args, **kwargs) + def __init__(cls, *args, **kwargs): + _init_command(cls, **kwargs) + super(CommandMeta, cls).__init__(*args, **kwargs) # The Command class is the basic unit of an Evennia command; when # defining new commands, the admin subclass this class and diff --git a/evennia/commands/default/batchprocess.py b/evennia/commands/default/batchprocess.py index 38518e837..cefeba6ba 100644 --- a/evennia/commands/default/batchprocess.py +++ b/evennia/commands/default/batchprocess.py @@ -203,7 +203,8 @@ def purge_processor(caller): del caller.ndb.batch_stackptr del caller.ndb.batch_pythonpath del caller.ndb.batch_batchmode - except: + except Exception: + # something might have already been erased; it's not critical pass # clear everything back to the state before the batch call if caller.ndb.batch_cmdset_backup: diff --git a/evennia/commands/default/building.py b/evennia/commands/default/building.py index 7b77be2c0..2f8597967 100644 --- a/evennia/commands/default/building.py +++ b/evennia/commands/default/building.py @@ -1355,10 +1355,12 @@ def _convert_from_string(cmd, strobj): try: return int(obj) except ValueError: + # obj cannot be converted to int - that's fine pass try: return float(obj) except ValueError: + # obj cannot be converted to float - that's fine pass # iterables 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. all_cmdsets.extend([(cmdset.key, cmdset) for cmdset in obj.get_session(obj.sessions.get()).cmdset.all()]) except (TypeError, AttributeError): + # an error means we are merging an object without a session pass all_cmdsets = [cmdset for cmdset in dict(all_cmdsets).values()] all_cmdsets.sort(key=lambda x: x.priority, reverse=True) diff --git a/evennia/commands/default/system.py b/evennia/commands/default/system.py index 594c615f5..a73a06498 100644 --- a/evennia/commands/default/system.py +++ b/evennia/commands/default/system.py @@ -316,10 +316,7 @@ class CmdScripts(COMMAND_DEFAULT_CLASS): if self.switches and self.switches[0] in ('stop', 'del', 'delete', 'kill'): # we want to delete something - if not scripts: - string = "No scripts/objects matching '%s'. " % args - string += "Be more specific." - elif len(scripts) == 1: + if len(scripts) == 1: # we have a unique match! if 'kill' in self.switches: string = "Killing script '%s'" % scripts[0].key diff --git a/evennia/commands/default/unloggedin.py b/evennia/commands/default/unloggedin.py index d58dba1a1..86a143ab2 100644 --- a/evennia/commands/default/unloggedin.py +++ b/evennia/commands/default/unloggedin.py @@ -105,7 +105,7 @@ def create_guest_player(session): if not PlayerDB.objects.filter(username__iexact=playername): break playername = None - if playername == None: + if playername is None: session.msg("All guest accounts are in use. Please try again later.") return True, None @@ -126,8 +126,7 @@ def create_guest_player(session): # we won't see any errors at all. session.msg("An error occurred. Please e-mail an admin if the problem persists.") logger.log_trace() - finally: - return True, new_player + raise def create_normal_player(session, name, password): diff --git a/evennia/comms/channelhandler.py b/evennia/comms/channelhandler.py index 3506d6aec..da72bba5e 100644 --- a/evennia/comms/channelhandler.py +++ b/evennia/comms/channelhandler.py @@ -79,6 +79,7 @@ class ChannelCommand(command.Command): try: self.history_start = int(arg) if arg else 0 except ValueError: + # if no valid number was given, ignore it pass self.args = (channelname.strip(), msg.strip()) diff --git a/evennia/comms/managers.py b/evennia/comms/managers.py index f58a2b8b1..bd13ef72a 100644 --- a/evennia/comms/managers.py +++ b/evennia/comms/managers.py @@ -401,6 +401,7 @@ class ChannelDBManager(TypedObjectManager): dbref = int(ostring.strip('#')) channels = self.filter(id=dbref) except Exception: + # Usually because we couldn't convert to int - not a dbref pass if not channels: # no id match. Search on the key. diff --git a/evennia/contrib/barter.py b/evennia/contrib/barter.py index 6c472da8a..36146387b 100644 --- a/evennia/contrib/barter.py +++ b/evennia/contrib/barter.py @@ -612,6 +612,7 @@ class CmdEvaluate(CmdTradeBase): ind = int(self.args) self.args = ind - 1 except Exception: + # not a valid index - ignore pass offer = self.tradehandler.search(self.args) diff --git a/evennia/contrib/email_login.py b/evennia/contrib/email_login.py index 5d30b67e3..6ec544f66 100644 --- a/evennia/contrib/email_login.py +++ b/evennia/contrib/email_login.py @@ -51,6 +51,7 @@ CONNECTION_SCREEN = "" try: CONNECTION_SCREEN = ansi.parse_ansi(utils.random_string_from_module(CONNECTION_SCREEN_MODULE)) except Exception: + # malformed connection screen or no screen given pass 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." diff --git a/evennia/contrib/tutorial_examples/cmdset_red_button.py b/evennia/contrib/tutorial_examples/cmdset_red_button.py index 5ce0ba37a..5f4c8d7fd 100644 --- a/evennia/contrib/tutorial_examples/cmdset_red_button.py +++ b/evennia/contrib/tutorial_examples/cmdset_red_button.py @@ -39,7 +39,7 @@ class CmdNudge(Command): rand = random.random() if rand < 0.5: 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.") else: self.caller.msg("You manage to get a nail under the lid.") diff --git a/evennia/contrib/tutorial_world/objects.py b/evennia/contrib/tutorial_world/objects.py index 54d0c31d0..31be8824c 100644 --- a/evennia/contrib/tutorial_world/objects.py +++ b/evennia/contrib/tutorial_world/objects.py @@ -344,6 +344,7 @@ class LightSource(TutorialObject): self.location.msg_contents("A %s on the floor flickers and dies." % self.key) self.location.location.check_light_state() except AttributeError: + # Mainly happens if we happen to be in a None location pass self.delete() @@ -364,6 +365,7 @@ class LightSource(TutorialObject): # maybe we are directly in the room self.location.check_light_state() except AttributeError: + # we are in a None location pass finally: # start the burn timer. When it runs out, self._burnout diff --git a/evennia/game_template/server/conf/mssp.py b/evennia/game_template/server/conf/mssp.py index 47f0f3094..e00aad631 100644 --- a/evennia/game_template/server/conf/mssp.py +++ b/evennia/game_template/server/conf/mssp.py @@ -62,15 +62,18 @@ MSSPTable = { # Protocols set to 1 or 0) "ANSI": "1", - "GMCP": "0", + "GMCP": "1", + "ATCP": "0", "MCCP": "0", "MCP": "0", "MSDP": "0", "MSP": "0", "MXP": "0", "PUEBLO": "0", + "SSL": "1", "UTF-8": "1", "VT100": "0", + "ZMP": "0", "XTERM 256 COLORS": "0", # Commercial set to 1 or 0) @@ -111,12 +114,4 @@ MSSPTable = { "TRAINING SYSTEM": "None", # "None", "Level", "Skill", "Both" "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"} + } diff --git a/evennia/locks/lockfuncs.py b/evennia/locks/lockfuncs.py index 23ae3b783..138d31f2f 100644 --- a/evennia/locks/lockfuncs.py +++ b/evennia/locks/lockfuncs.py @@ -539,6 +539,7 @@ def holds(accessing_obj, accessed_obj, *args, **kwargs): if check_holds(accessed_obj.dbid): return True except Exception: + # we need to catch any trouble here pass return hasattr(accessed_obj, "obj") and check_holds(accessed_obj.obj.dbid) if len(args) == 1: diff --git a/evennia/objects/manager.py b/evennia/objects/manager.py index 0127b6e0e..9bbd847f8 100644 --- a/evennia/objects/manager.py +++ b/evennia/objects/manager.py @@ -409,6 +409,7 @@ class ObjectDBManager(TypedObjectManager): try: matches = [matches[match_number]] except IndexError: + # match number not matching anything pass # return a list (possibly empty) return matches diff --git a/evennia/objects/models.py b/evennia/objects/models.py index 523fdfab4..0d5c55317 100644 --- a/evennia/objects/models.py +++ b/evennia/objects/models.py @@ -242,12 +242,14 @@ class ObjectDB(TypedObject): return elif loc == self: raise RuntimeError - elif loc == None: + elif loc is None: raise RuntimeWarning return is_loc_loop(loc.db_location, depth + 1) try: is_loc_loop(location) except RuntimeWarning: + # we caught a infitite location loop! + # (location1 is in location2 which is in location1 ...) pass # if we get to this point we are ready to change location diff --git a/evennia/objects/objects.py b/evennia/objects/objects.py index c7121e8b8..4fe8143a8 100644 --- a/evennia/objects/objects.py +++ b/evennia/objects/objects.py @@ -83,7 +83,7 @@ class ObjectSessionHandler(object): if sessid: sessions = [_SESSIONS[sessid] if sessid in _SESSIONS else None] if sessid in self._sessid_cache 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: # this happens only if our cache has gone out of sync with the SessionHandler. self._recache() diff --git a/evennia/players/players.py b/evennia/players/players.py index e9947e577..10ce498c3 100644 --- a/evennia/players/players.py +++ b/evennia/players/players.py @@ -409,12 +409,14 @@ class DefaultPlayer(with_metaclass(TypeclassBase, PlayerDB)): try: from_obj.at_msg_send(text=text, to_obj=self, **kwargs) except Exception: + # this may not be assigned. pass try: if not self.at_msg_receive(text=text, **kwargs): # abort message to this player return except Exception: + # this may not be assigned. pass kwargs["options"] = options diff --git a/evennia/scripts/models.py b/evennia/scripts/models.py index 5d9560b30..afeff10b5 100644 --- a/evennia/scripts/models.py +++ b/evennia/scripts/models.py @@ -139,6 +139,7 @@ class ScriptDB(TypedObject): try: value = _GA(value, "dbobj") except AttributeError: + # deprecated ... pass if isinstance(value, (basestring, int)): from evennia.objects.models import ObjectDB diff --git a/evennia/scripts/scripthandler.py b/evennia/scripts/scripthandler.py index 474c3c669..1106d1a95 100644 --- a/evennia/scripts/scripthandler.py +++ b/evennia/scripts/scripthandler.py @@ -46,7 +46,7 @@ class ScriptHandler(object): repeats = script.repeats try: next_repeat = script.time_until_next_repeat() - except: + except Exception: next_repeat = "?" string += _("\n '%(key)s' (%(next_repeat)s/%(interval)s, %(repeats)s repeats): %(desc)s") % \ {"key": script.key, "next_repeat": next_repeat, diff --git a/evennia/scripts/scripts.py b/evennia/scripts/scripts.py index 308261b14..2ef5930cf 100644 --- a/evennia/scripts/scripts.py +++ b/evennia/scripts/scripts.py @@ -100,7 +100,7 @@ class ExtendedLoopingCall(LoopingCall): if self.start_delay: self.start_delay = None self.starttime = self.clock.seconds() - super(ExtendedLoopingCall, self).__call__() + LoopingCall.__call__(self) def force_repeat(self): """ @@ -210,6 +210,7 @@ class DefaultScript(ScriptBase): try: self.db_obj.msg(estring) except Exception: + # we must not crash inside the errback, even if db_obj is None. pass logger.log_err(estring) diff --git a/evennia/server/evennia_launcher.py b/evennia/server/evennia_launcher.py index 36aa64f16..06989b66d 100644 --- a/evennia/server/evennia_launcher.py +++ b/evennia/server/evennia_launcher.py @@ -405,6 +405,7 @@ def evennia_version(): import evennia version = evennia.__version__ except ImportError: + # even if evennia is not found, we should not crash here. pass try: rev = check_output( @@ -412,6 +413,7 @@ def evennia_version(): shell=True, cwd=EVENNIA_ROOT, stderr=STDOUT).strip() version = "%s (rev %s)" % (version, rev) except (IOError, CalledProcessError): + # move on if git is not answering pass return version @@ -520,7 +522,7 @@ def create_settings_file(init=True): if not init: # if not --init mode, settings file may already exist from before 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]> ") if not inp.lower() == 'y': print ("Aborted.") @@ -659,14 +661,13 @@ def get_pid(pidfile): pidfile (str): The path of the pid file. Returns: - pid (str): The process id. + pid (str or None): The process id. """ - pid = None if os.path.exists(pidfile): - f = open(pidfile, 'r') - pid = f.read() - return pid + with open(pidfile, 'r') as f: + pid = f.read() + return pid def del_pid(pidfile): @@ -722,6 +723,7 @@ def kill(pidfile, signal=SIG, succmsg="", errmsg="", SetConsoleCtrlHandler(None, True) GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0) except KeyboardInterrupt: + # We must catch and ignore the interrupt sent. pass else: # Linux can send the SIGINT signal directly @@ -986,6 +988,8 @@ def run_dummyrunner(number_of_dummies): try: call(cmdstr, env=getenv()) except KeyboardInterrupt: + # this signals the dummyrunner to stop cleanly and should + # not lead to a traceback here. pass diff --git a/evennia/server/portal/mssp.py b/evennia/server/portal/mssp.py index d8c699cfe..c95325408 100644 --- a/evennia/server/portal/mssp.py +++ b/evennia/server/portal/mssp.py @@ -133,13 +133,16 @@ class Mssp(object): "ANSI": "1", "GMCP": "0", + "ATCP": "0", "MCCP": "0", "MCP": "0", "MSDP": "0", "MSP": "0", "MXP": "0", "PUEBLO": "0", + "SSL": "1", "UTF-8": "1", + "ZMP": "0", "VT100": "0", "XTERM 256 COLORS": "0", @@ -180,16 +183,7 @@ class Mssp(object): "ROLEPLAYING": "None", # "None", "Accepted", "Encouraged", "Enforced" "TRAINING SYSTEM": "None", # "None", "Level", "Skill", "Both" "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 if MSSPTable_CUSTOM: diff --git a/evennia/server/portal/portalsessionhandler.py b/evennia/server/portal/portalsessionhandler.py index ea4587f15..e9fe64dcb 100644 --- a/evennia/server/portal/portalsessionhandler.py +++ b/evennia/server/portal/portalsessionhandler.py @@ -364,6 +364,7 @@ class PortalSessionHandler(SessionHandler): self.data_out(session, text=[[_ERROR_MAX_CHAR], {}]) return except Exception: + # if there is a problem to send, we continue pass if session: now = time() diff --git a/evennia/server/portal/telnet_oob.py b/evennia/server/portal/telnet_oob.py index eb5071b3a..3b0f335a3 100644 --- a/evennia/server/portal/telnet_oob.py +++ b/evennia/server/portal/telnet_oob.py @@ -364,6 +364,7 @@ class TelnetOOB(object): try: structure = json.loads(structure) except ValueError: + # maybe the structure is not json-serialized at all pass args, kwargs = [], {} if hasattr(structure, "__iter__"): diff --git a/evennia/server/portal/ttype.py b/evennia/server/portal/ttype.py index b60c4e8e4..de7d1b4c1 100644 --- a/evennia/server/portal/ttype.py +++ b/evennia/server/portal/ttype.py @@ -89,6 +89,7 @@ class Ttype(object): try: option = "".join(option).lstrip(IS) except TypeError: + # option is not on a suitable form for joining pass if self.ttype_step == 0: diff --git a/evennia/server/portal/webclient.py b/evennia/server/portal/webclient.py index df675aa0d..8c4266f13 100644 --- a/evennia/server/portal/webclient.py +++ b/evennia/server/portal/webclient.py @@ -204,7 +204,7 @@ class WebSocketClient(Protocol, Session): kwargs["options"].update({"send_prompt": True}) self.send_text(*args, **kwargs) - def send_default(session, cmdname, *args, **kwargs): + def send_default(self, cmdname, *args, **kwargs): """ Data Evennia -> User. @@ -219,4 +219,4 @@ class WebSocketClient(Protocol, Session): """ if not cmdname == "options": - session.sendLine(json.dumps([cmdname, args, kwargs])) + self.sendLine(json.dumps([cmdname, args, kwargs])) diff --git a/evennia/server/portal/webclient_ajax.py b/evennia/server/portal/webclient_ajax.py index 7b38002e4..9ca246286 100644 --- a/evennia/server/portal/webclient_ajax.py +++ b/evennia/server/portal/webclient_ajax.py @@ -76,6 +76,7 @@ class WebClient(resource.Resource): try: del self.requests[csessid] except KeyError: + # nothing left to delete pass def _keepalive(self): diff --git a/evennia/server/serversession.py b/evennia/server/serversession.py index 79f1213ee..e40fb1274 100644 --- a/evennia/server/serversession.py +++ b/evennia/server/serversession.py @@ -310,7 +310,7 @@ class ServerSession(Session): cchan = ChannelDB.objects.get_channel(cchan[0]) cchan.msg("[%s]: %s" % (cchan.key, message)) except Exception: - pass + logger.log_trace() logger.log_info(message) def get_client_size(self): diff --git a/evennia/settings_default.py b/evennia/settings_default.py index 986110c89..bdea92178 100644 --- a/evennia/settings_default.py +++ b/evennia/settings_default.py @@ -696,6 +696,7 @@ try: import django_extensions INSTALLED_APPS = INSTALLED_APPS + ('django_extensions',) except ImportError: + # Django extensions are not installed in all distros. pass ####################################################################### diff --git a/evennia/typeclasses/tags.py b/evennia/typeclasses/tags.py index a88e68e30..f328351c1 100644 --- a/evennia/typeclasses/tags.py +++ b/evennia/typeclasses/tags.py @@ -286,7 +286,7 @@ class TagHandler(object): for keystr in make_iter(key): # note - the _getcache call removes case sensitivity for us 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) 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] else: return [to_str(tag.db_key) for tag in tags] - return [] def __str__(self): return ",".join(self.all()) diff --git a/evennia/utils/ansi.py b/evennia/utils/ansi.py index c17661992..7ae229421 100644 --- a/evennia/utils/ansi.py +++ b/evennia/utils/ansi.py @@ -575,6 +575,7 @@ def _on_raw(func_name): else: args.insert(0, string) except IndexError: + # just skip out if there are no more strings pass result = getattr(self._raw_string, func_name)(*args, **kwargs) if isinstance(result, basestring): @@ -850,6 +851,7 @@ class ANSIString(with_metaclass(ANSIMeta, unicode)): try: string += self._raw_string[i] except IndexError: + # raw_string not long enough pass if i is not None: append_tail = self._get_interleving(self._char_indexes.index(i) + 1) diff --git a/evennia/utils/create.py b/evennia/utils/create.py index 58e717e5c..34aa1e06b 100644 --- a/evennia/utils/create.py +++ b/evennia/utils/create.py @@ -115,7 +115,7 @@ def create_object(typeclass=None, key=None, location=None, # store the call signature for the signal new_object._createdict = {"key":key, "location":location, "destination":destination, "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} # this will trigger the save signal which in turn calls the # at_first_save hook on the typeclass, where the _createdict can be diff --git a/evennia/utils/eveditor.py b/evennia/utils/eveditor.py index 9bd553796..657bc9895 100644 --- a/evennia/utils/eveditor.py +++ b/evennia/utils/eveditor.py @@ -809,7 +809,7 @@ class EvEditor(object): formatting information. """ - if buf == None: + if buf is None: buf = self._buffer if is_iter(buf): buf = "\n".join(buf) diff --git a/evennia/utils/evtable.py b/evennia/utils/evtable.py index b27eb6c3b..3648df0dd 100644 --- a/evennia/utils/evtable.py +++ b/evennia/utils/evtable.py @@ -159,14 +159,14 @@ class ANSITextWrapper(TextWrapper): """ # ignore expand_tabs/replace_whitespace until ANSISTring handles them return text - if self.expand_tabs: - text = text.expandtabs() - if self.replace_whitespace: - if isinstance(text, str): - text = text.translate(self.whitespace_trans) - elif isinstance(text, _unicode): - text = text.translate(self.unicode_whitespace_trans) - return text +# if self.expand_tabs: +# text = text.expandtabs() +# if self.replace_whitespace: +# if isinstance(text, str): +# text = text.translate(self.whitespace_trans) +# elif isinstance(text, _unicode): +# text = text.translate(self.unicode_whitespace_trans) +# return text def _split(self, text): diff --git a/evennia/utils/idmapper/models.py b/evennia/utils/idmapper/models.py index b74a05eb4..4ecbd3e99 100644 --- a/evennia/utils/idmapper/models.py +++ b/evennia/utils/idmapper/models.py @@ -134,10 +134,6 @@ class SharedMemoryModelBase(ModelBase): "Setter only used on foreign key relations, allows setting with #dbref" if _GA(cls, "_is_deleted"): 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)): value = to_str(value, force_string=True) if (value.isdigit() or value.startswith("#")): @@ -273,6 +269,7 @@ class SharedMemoryModel(with_metaclass(SharedMemoryModelBase, Model)): # at first initialization instance.at_init() except AttributeError: + # The at_init hook is not assigned to all entities pass @classmethod diff --git a/evennia/utils/picklefield.py b/evennia/utils/picklefield.py index 45a983577..5adedc94e 100644 --- a/evennia/utils/picklefield.py +++ b/evennia/utils/picklefield.py @@ -212,7 +212,7 @@ class PickledObjectField(models.Field): if value is not None: try: value = dbsafe_decode(value, self.compress) - except: + except Exception: # If the value is a definite pickle; and an error is raised in # de-pickling it should be allowed to propogate. if isinstance(value, PickledObject): diff --git a/evennia/utils/prettytable.py b/evennia/utils/prettytable.py index 04eb56b60..b3fdc3eb9 100644 --- a/evennia/utils/prettytable.py +++ b/evennia/utils/prettytable.py @@ -430,12 +430,12 @@ class PrettyTable(object): ############################## def _get_field_names(self): - return self._field_names """The names of the fields Arguments: fields - list or tuple of field names""" + return self._field_names def _set_field_names(self, val): val = [self._unicode(x) for x in val] self._validate_option("field_names", val) diff --git a/evennia/utils/txws.py b/evennia/utils/txws.py index 52a718ab6..dc16a93ce 100644 --- a/evennia/utils/txws.py +++ b/evennia/utils/txws.py @@ -99,6 +99,7 @@ def http_headers(s): key, value = [i.strip() for i in line.split(":", 1)] d[key] = value except ValueError: + # malformed header, skip it pass return d @@ -257,8 +258,8 @@ def parse_hybi07_frames(buf): if header & 0x70: # At least one of the reserved flags is set. Pork chop sandwiches! raise WSException("Reserved flag in HyBi-07 frame (%d)" % header) - frames.append(("", CLOSE)) - return frames, buf + #frames.append(("", CLOSE)) + #return frames, buf # Get the opcode, and translate it to a local enum which we actually # care about. diff --git a/evennia/utils/utils.py b/evennia/utils/utils.py index e4328d492..135df9bde 100644 --- a/evennia/utils/utils.py +++ b/evennia/utils/utils.py @@ -703,6 +703,7 @@ def to_unicode(obj, encoding='utf-8', force_string=False): obj = unicode(obj, alt_encoding) return obj except UnicodeDecodeError: + # if we still have an error, give up pass raise Exception("Error: '%s' contains invalid character(s) not in %s." % (obj, encoding)) return obj @@ -744,6 +745,7 @@ def to_str(obj, encoding='utf-8', force_string=False): obj = obj.encode(alt_encoding) return obj except UnicodeEncodeError: + # if we still have an error, give up pass # 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: _SA(obj, "_contents_cache", None) except AttributeError: + # if the cache cannot be reached, move on anyway pass # on-object property cache @@ -935,6 +938,7 @@ def clean_object_caches(obj): hashid = _GA(obj, "hashid") _TYPECLASSMODELS._ATTRIBUTE_CACHE[hashid] = {} except AttributeError: + # skip caching pass @@ -1273,9 +1277,9 @@ def fuzzy_import_from_module(path, variable, default=None, defaultpaths=None): paths = [path] + make_iter(defaultpaths) for modpath in paths: try: - mod = import_module(path) + mod = import_module(modpath) 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 # triggers an ImportError on import. raise ex @@ -1521,13 +1525,11 @@ def get_evennia_pids(): portal_pidfile = os.path.join(settings.GAME_DIR, 'portal.pid') server_pid, portal_pid = None, None if os.path.exists(server_pidfile): - f = open(server_pidfile, 'r') - server_pid = f.read() - f.close() + with open(server_pidfile, 'r') as f: + server_pid = f.read() if os.path.exists(portal_pidfile): - f = open(portal_pidfile, 'r') - portal_pid = f.read() - f.close() + with open(portal_pidfile, 'r') as f: + portal_pid = f.read() if server_pid and portal_pid: return int(server_pid), int(portal_pid) return None, None