markup, whitespace and PEP 8

Indent and variable name updates, also.
This commit is contained in:
BlauFeuer 2017-02-18 20:56:08 -05:00 committed by Griatch
parent ec11388531
commit 24bd3a6412

View file

@ -13,7 +13,7 @@ The property self.character can be used to access the character when
these commands are triggered with a connected character (such as the these commands are triggered with a connected character (such as the
case of the @ooc command), it is None if we are OOC. case of the @ooc command), it is None if we are OOC.
Note that under MULTISESSION_MODE > 2, Player- commands should use Note that under MULTISESSION_MODE > 2, Player commands should use
self.msg() and similar methods to reroute returns to the correct self.msg() and similar methods to reroute returns to the correct
method. Otherwise all text will be returned to all connected sessions. method. Otherwise all text will be returned to all connected sessions.
@ -44,7 +44,7 @@ class MuxPlayerLookCommand(COMMAND_DEFAULT_CLASS):
""" """
def parse(self): def parse(self):
"Custom parsing" """Custom parsing"""
super(MuxPlayerLookCommand, self).parse() super(MuxPlayerLookCommand, self).parse()
@ -97,11 +97,11 @@ class CmdOOCLook(MuxPlayerLookCommand):
player_caller = True player_caller = True
def func(self): def func(self):
"implement the ooc look command" """implement the ooc look command"""
if _MULTISESSION_MODE < 2: if _MULTISESSION_MODE < 2:
# only one character allowed # only one character allowed
self.msg("You are out-of-character (OOC).\nUse {w@ic{n to get back into the game.") self.msg("You are out-of-character (OOC).\nUse |w@ic|n to get back into the game.")
return return
# call on-player look helper method # call on-player look helper method
@ -128,7 +128,7 @@ class CmdCharCreate(COMMAND_DEFAULT_CLASS):
player_caller = True player_caller = True
def func(self): def func(self):
"create the new character" """create the new character"""
player = self.player player = self.player
if not self.args: if not self.args:
self.msg("Usage: @charcreate <charname> [= description]") self.msg("Usage: @charcreate <charname> [= description]")
@ -150,15 +150,13 @@ class CmdCharCreate(COMMAND_DEFAULT_CLASS):
# check if this Character already exists. Note that we are only # check if this Character already exists. Note that we are only
# searching the base character typeclass here, not any child # searching the base character typeclass here, not any child
# classes. # classes.
self.msg("{rA character named '{w%s{r' already exists.{n" % key) self.msg("|rA character named '|w%s|r' already exists.|n" % key)
return return
# create the character # create the character
start_location = ObjectDB.objects.get_id(settings.START_LOCATION) start_location = ObjectDB.objects.get_id(settings.START_LOCATION)
default_home = ObjectDB.objects.get_id(settings.DEFAULT_HOME) default_home = ObjectDB.objects.get_id(settings.DEFAULT_HOME)
permissions = settings.PERMISSION_PLAYER_DEFAULT permissions = settings.PERMISSION_PLAYER_DEFAULT
new_character = create.create_object(typeclass, key=key, new_character = create.create_object(typeclass, key=key,
location=start_location, location=start_location,
home=default_home, home=default_home,
@ -171,7 +169,8 @@ class CmdCharCreate(COMMAND_DEFAULT_CLASS):
new_character.db.desc = desc new_character.db.desc = desc
elif not new_character.db.desc: elif not new_character.db.desc:
new_character.db.desc = "This is a Player." new_character.db.desc = "This is a Player."
self.msg("Created new character %s. Use {w@ic %s{n to enter the game as this character." % (new_character.key, new_character.key)) self.msg("Created new character %s. Use |w@ic %s|n to enter the game as this character."
% (new_character.key, new_character.key))
class CmdCharDelete(COMMAND_DEFAULT_CLASS): class CmdCharDelete(COMMAND_DEFAULT_CLASS):
@ -188,7 +187,7 @@ class CmdCharDelete(COMMAND_DEFAULT_CLASS):
help_category = "General" help_category = "General"
def func(self): def func(self):
"delete the character" """delete the character"""
player = self.player player = self.player
if not self.args: if not self.args:
@ -196,7 +195,8 @@ class CmdCharDelete(COMMAND_DEFAULT_CLASS):
return return
# use the playable_characters list to search # use the playable_characters list to search
match = [char for char in utils.make_iter(player.db._playable_characters) if char.key.lower() == self.args.lower()] match = [char for char in utils.make_iter(player.db._playable_characters)
if char.key.lower() == self.args.lower()]
if not match: if not match:
self.msg("You have no such character to delete.") self.msg("You have no such character to delete.")
return return
@ -206,13 +206,12 @@ class CmdCharDelete(COMMAND_DEFAULT_CLASS):
else: # one match else: # one match
from evennia.utils.evmenu import get_input from evennia.utils.evmenu import get_input
def _callback(caller, prompt, result): def _callback(caller, callback_prompt, result):
if result.lower() == "yes": if result.lower() == "yes":
# only take action # only take action
delobj = caller.ndb._char_to_delete delobj = caller.ndb._char_to_delete
key = delobj.key key = delobj.key
caller.db._playable_characters = [char for char caller.db._playable_characters = [pc for pc in caller.db._playable_characters if pc != delobj]
in caller.db._playable_characters if char != delobj]
delobj.delete() delobj.delete()
self.msg("Character '%s' was permanently deleted." % key) self.msg("Character '%s' was permanently deleted." % key)
else: else:
@ -272,7 +271,8 @@ class CmdIC(COMMAND_DEFAULT_CLASS):
self.msg("That is not a valid character choice.") self.msg("That is not a valid character choice.")
return return
if len(new_character) > 1: if len(new_character) > 1:
self.msg("Multiple targets with the same name:\n %s" % ", ".join("%s(#%s)" % (obj.key, obj.id) for obj in new_character)) self.msg("Multiple targets with the same name:\n %s"
% ", ".join("%s(#%s)" % (obj.key, obj.id) for obj in new_character))
return return
else: else:
new_character = new_character[0] new_character = new_character[0]
@ -280,7 +280,7 @@ class CmdIC(COMMAND_DEFAULT_CLASS):
player.puppet_object(session, new_character) player.puppet_object(session, new_character)
player.db._last_puppet = new_character player.db._last_puppet = new_character
except RuntimeError as exc: except RuntimeError as exc:
self.msg("{rYou cannot become {C%s{n: %s" % (new_character.name, exc)) self.msg("|rYou cannot become |C%s|n: %s" % (new_character.name, exc))
# note that this is inheriting from MuxPlayerLookCommand, # note that this is inheriting from MuxPlayerLookCommand,
@ -306,7 +306,7 @@ class CmdOOC(MuxPlayerLookCommand):
player_caller = True player_caller = True
def func(self): def func(self):
"Implement function" """Implement function"""
player = self.player player = self.player
session = self.session session = self.session
@ -322,17 +322,18 @@ class CmdOOC(MuxPlayerLookCommand):
# disconnect # disconnect
try: try:
player.unpuppet_object(session) player.unpuppet_object(session)
self.msg("\n{GYou go OOC.{n\n") self.msg("\n|GYou go OOC.|n\n")
if _MULTISESSION_MODE < 2: if _MULTISESSION_MODE < 2:
# only one character allowed # only one character allowed
self.msg("You are out-of-character (OOC).\nUse {w@ic{n to get back into the game.") self.msg("You are out-of-character (OOC).\nUse |w@ic|n to get back into the game.")
return return
self.msg(player.at_look(target=self.playable, session=session)) self.msg(player.at_look(target=self.playable, session=session))
except RuntimeError as exc: except RuntimeError as exc:
self.msg("{rCould not unpuppet from {c%s{n: %s" % (old_char, exc)) self.msg("|rCould not unpuppet from |c%s|n: %s" % (old_char, exc))
class CmdSessions(COMMAND_DEFAULT_CLASS): class CmdSessions(COMMAND_DEFAULT_CLASS):
""" """
@ -352,22 +353,22 @@ class CmdSessions(COMMAND_DEFAULT_CLASS):
player_caller = True player_caller = True
def func(self): def func(self):
"Implement function" """Implement function"""
player = self.player player = self.player
sessions = player.sessions.all() sessions = player.sessions.all()
table = prettytable.PrettyTable(["{wsessid", table = prettytable.PrettyTable(["|wsessid",
"{wprotocol", "|wprotocol",
"{whost", "|whost",
"{wpuppet/character", "|wpuppet/character",
"{wlocation"]) "|wlocation"])
for sess in sorted(sessions, key=lambda x: x.sessid): for sess in sorted(sessions, key=lambda x: x.sessid):
char = player.get_puppet(sess) char = player.get_puppet(sess)
table.add_row([str(sess.sessid), str(sess.protocol_key), table.add_row([str(sess.sessid), str(sess.protocol_key),
type(sess.address) == tuple and sess.address[0] or sess.address, type(sess.address) == tuple and sess.address[0] or sess.address,
char and str(char) or "None", char and str(char) or "None",
char and str(char.location) or "N/A"]) char and str(char.location) or "N/A"])
string = "{wYour current session(s):{n\n%s" % table string = "|wYour current session(s):|n\n%s" % table
self.msg(string) self.msg(string)
@ -408,16 +409,17 @@ class CmdWho(COMMAND_DEFAULT_CLASS):
nplayers = (SESSIONS.player_count()) nplayers = (SESSIONS.player_count())
if show_session_data: if show_session_data:
# privileged info # privileged info
table = prettytable.PrettyTable(["{wPlayer Name", table = prettytable.PrettyTable(["|wPlayer Name",
"{wOn for", "|wOn for",
"{wIdle", "|wIdle",
"{wPuppeting", "|wPuppeting",
"{wRoom", "|wRoom",
"{wCmds", "|wCmds",
"{wProtocol", "|wProtocol",
"{wHost"]) "|wHost"])
for session in session_list: for session in session_list:
if not session.logged_in: continue if not session.logged_in:
continue
delta_cmd = time.time() - session.cmd_last_visible delta_cmd = time.time() - session.cmd_last_visible
delta_conn = time.time() - session.conn_time delta_conn = time.time() - session.conn_time
player = session.get_player() player = session.get_player()
@ -433,7 +435,7 @@ class CmdWho(COMMAND_DEFAULT_CLASS):
isinstance(session.address, tuple) and session.address[0] or session.address]) isinstance(session.address, tuple) and session.address[0] or session.address])
else: else:
# unprivileged # unprivileged
table = prettytable.PrettyTable(["{wPlayer name", "{wOn for", "{wIdle"]) table = prettytable.PrettyTable(["|wPlayer name", "|wOn for", "|wIdle"])
for session in session_list: for session in session_list:
if not session.logged_in: if not session.logged_in:
continue continue
@ -444,8 +446,9 @@ class CmdWho(COMMAND_DEFAULT_CLASS):
utils.time_format(delta_conn, 0), utils.time_format(delta_conn, 0),
utils.time_format(delta_cmd, 1)]) utils.time_format(delta_cmd, 1)])
isone = nplayers == 1 is_one = nplayers == 1
string = "{wPlayers:{n\n%s\n%s unique account%s logged in." % (table, "One" if isone else nplayers, "" if isone else "s") string = "|wPlayers:|n\n%s\n%s unique account%s logged in." \
% (table, "One" if is_one else nplayers, "" if is_one else "s")
self.msg(string) self.msg(string)
@ -489,11 +492,11 @@ class CmdOption(COMMAND_DEFAULT_CLASS):
if "save" in self.switches: if "save" in self.switches:
# save all options # save all options
self.caller.db._saved_protocol_flags = flags self.caller.db._saved_protocol_flags = flags
self.msg("{gSaved all options. Use @option/clear to remove.{n") self.msg("|gSaved all options. Use @option/clear to remove.|n")
if "clear" in self.switches: if "clear" in self.switches:
# clear all saves # clear all saves
self.caller.db._saved_protocol_flags = {} self.caller.db._saved_protocol_flags = {}
self.msg("{gCleared all saved options.") self.msg("|gCleared all saved options.")
options = dict(flags) # make a copy of the flag dict options = dict(flags) # make a copy of the flag dict
saved_options = dict(self.caller.attributes.get("_saved_protocol_flags", default={})) saved_options = dict(self.caller.attributes.get("_saved_protocol_flags", default={}))
@ -522,7 +525,7 @@ class CmdOption(COMMAND_DEFAULT_CLASS):
row.append("%s%s" % (saved, changed)) row.append("%s%s" % (saved, changed))
table.add_row(*row) table.add_row(*row)
self.msg("{wClient settings (%s):|n\n%s|n" % (self.session.protocol_key, table)) self.msg("|wClient settings (%s):|n\n%s|n" % (self.session.protocol_key, table))
return return
@ -532,30 +535,30 @@ class CmdOption(COMMAND_DEFAULT_CLASS):
# Try to assign new values # Try to assign new values
def validate_encoding(val): def validate_encoding(new_encoding):
# helper: change encoding # helper: change encoding
try: try:
utils.to_str(utils.to_unicode("test-string"), encoding=val) utils.to_str(utils.to_unicode("test-string"), encoding=new_encoding)
except LookupError: except LookupError:
raise RuntimeError("The encoding '|w%s|n' is invalid. " % val) raise RuntimeError("The encoding '|w%s|n' is invalid. " % new_encoding)
return val return val
def validate_size(val): def validate_size(new_size):
return {0: int(val)} return {0: int(new_size)}
def validate_bool(val): def validate_bool(new_bool):
return True if val.lower() in ("true", "on", "1") else False return True if new_bool.lower() in ("true", "on", "1") else False
def update(name, val, validator): def update(new_name, new_val, validator):
# helper: update property and report errors # helper: update property and report errors
try: try:
old_val = flags.get(name, False) old_val = flags.get(new_name, False)
new_val = validator(val) new_val = validator(new_val)
flags[name] = new_val flags[new_name] = new_val
self.msg("Option |w%s|n was changed from '|w%s|n' to '|w%s|n'." % (name, old_val, new_val)) self.msg("Option |w%s|n was changed from '|w%s|n' to '|w%s|n'." % (new_name, old_val, new_val))
return {name: new_val} return {new_name: new_val}
except Exception, err: except Exception, err:
self.msg("|rCould not set option |w%s|r:|n %s" % (name, err)) self.msg("|rCould not set option |w%s|r:|n %s" % (new_name, err))
return False return False
validators = {"ANSI": validate_bool, validators = {"ANSI": validate_bool,
@ -590,12 +593,12 @@ class CmdOption(COMMAND_DEFAULT_CLASS):
saved_options.update(optiondict) saved_options.update(optiondict)
self.player.attributes.add("_saved_protocol_flags", saved_options) self.player.attributes.add("_saved_protocol_flags", saved_options)
for key in optiondict: for key in optiondict:
self.msg("{gSaved option %s.{n" % key) self.msg("|gSaved option %s.|n" % key)
if "clear" in self.switches: if "clear" in self.switches:
# clear this save # clear this save
for key in optiondict: for key in optiondict:
self.player.attributes.get("_saved_protocol_flags", {}).pop(key, None) self.player.attributes.get("_saved_protocol_flags", {}).pop(key, None)
self.msg("{gCleared saved %s." % key) self.msg("|gCleared saved %s." % key)
self.session.update_flags(**optiondict) self.session.update_flags(**optiondict)
@ -616,14 +619,14 @@ class CmdPassword(COMMAND_DEFAULT_CLASS):
player_caller = True player_caller = True
def func(self): def func(self):
"hook function." """hook function."""
player = self.player player = self.player
if not self.rhs: if not self.rhs:
self.msg("Usage: @password <oldpass> = <newpass>") self.msg("Usage: @password <oldpass> = <newpass>")
return return
oldpass = self.lhslist[0] # this is already stripped by parse() oldpass = self.lhslist[0] # Both of these are
newpass = self.rhslist[0] # '' newpass = self.rhslist[0] # already stripped by parse()
if not player.check_password(oldpass): if not player.check_password(oldpass):
self.msg("The specified old password isn't correct.") self.msg("The specified old password isn't correct.")
elif len(newpass) < 3: elif len(newpass) < 3:
@ -655,11 +658,11 @@ class CmdQuit(COMMAND_DEFAULT_CLASS):
player_caller = True player_caller = True
def func(self): def func(self):
"hook function" """hook function"""
player = self.player player = self.player
if 'all' in self.switches: if 'all' in self.switches:
player.msg("{RQuitting{n all sessions. Hope to see you soon again.", session=self.session) player.msg("|RQuitting|n all sessions. Hope to see you soon again.", session=self.session)
for session in player.sessions.all(): for session in player.sessions.all():
player.disconnect_session_from_player(session) player.disconnect_session_from_player(session)
else: else:
@ -674,7 +677,6 @@ class CmdQuit(COMMAND_DEFAULT_CLASS):
player.disconnect_session_from_player(self.session) player.disconnect_session_from_player(self.session)
class CmdColorTest(COMMAND_DEFAULT_CLASS): class CmdColorTest(COMMAND_DEFAULT_CLASS):
""" """
testing which colors your client support testing which colors your client support
@ -708,12 +710,12 @@ class CmdColorTest(COMMAND_DEFAULT_CLASS):
max_widths = [max([len(str(val)) for val in col]) for col in table] max_widths = [max([len(str(val)) for val in col]) for col in table]
ftable = [] ftable = []
for irow in range(len(table[0])): for irow in range(len(table[0])):
ftable.append([str(col[irow]).ljust(max_widths[icol]) + " " * extra_space ftable.append([str(col[irow]).ljust(max_widths[icol]) + " " *
for icol, col in enumerate(table)]) extra_space for icol, col in enumerate(table)])
return ftable return ftable
def func(self): def func(self):
"Show color tables" """Show color tables"""
if self.args.startswith("a"): if self.args.startswith("a"):
# show ansi 16-color table # show ansi 16-color table
@ -723,9 +725,11 @@ class CmdColorTest(COMMAND_DEFAULT_CLASS):
# show all ansi color-related codes # show all ansi color-related codes
col1 = ["%s%s|n" % (code, code.replace("|", "||")) for code, _ in ap.ext_ansi_map[48:56]] col1 = ["%s%s|n" % (code, code.replace("|", "||")) for code, _ in ap.ext_ansi_map[48:56]]
col2 = ["%s%s|n" % (code, code.replace("|", "||")) for code, _ in ap.ext_ansi_map[56:64]] col2 = ["%s%s|n" % (code, code.replace("|", "||")) for code, _ in ap.ext_ansi_map[56:64]]
col3 = ["%s%s|n" % (code.replace("\\",""), code.replace("|", "||").replace("\\", "")) for code, _ in ap.ext_ansi_map[-8:]] col3 = ["%s%s|n" % (code.replace("\\", ""), code.replace("|", "||").replace("\\", ""))
col4 = ["%s%s|n" % (code.replace("\\",""), code.replace("|", "||").replace("\\", "")) for code, _ in ap.ansi_bright_bgs[-8:]] for code, _ in ap.ext_ansi_map[-8:]]
col2.extend(["" for i in range(len(col1)-len(col2))]) col4 = ["%s%s|n" % (code.replace("\\", ""), code.replace("|", "||").replace("\\", ""))
for code, _ in ap.ansi_bright_bgs[-8:]]
col2.extend(["" for _ in range(len(col1)-len(col2))])
table = utils.format_table([col1, col2, col4, col3]) table = utils.format_table([col1, col2, col4, col3])
string = "ANSI colors:" string = "ANSI colors:"
for row in table: for row in table:
@ -744,9 +748,8 @@ class CmdColorTest(COMMAND_DEFAULT_CLASS):
# foreground table # foreground table
table[ir].append("|%i%i%i%s|n" % (ir, ig, ib, "||%i%i%i" % (ir, ig, ib))) table[ir].append("|%i%i%i%s|n" % (ir, ig, ib, "||%i%i%i" % (ir, ig, ib)))
# background table # background table
table[6+ir].append("|%i%i%i|[%i%i%i%s|n" % (5 - ir, 5 - ig, 5 - ib, table[6+ir].append("|%i%i%i|[%i%i%i%s|n"
ir, ig, ib, % (5 - ir, 5 - ig, 5 - ib, ir, ig, ib, "||[%i%i%i" % (ir, ig, ib)))
"||[%i%i%i" % (ir, ig, ib)))
table = self.table_format(table) table = self.table_format(table)
string = "Xterm256 colors (if not all hues show, your client might not report that it can handle xterm256):" string = "Xterm256 colors (if not all hues show, your client might not report that it can handle xterm256):"
string += "\n" + "\n".join("".join(row) for row in table) string += "\n" + "\n".join("".join(row) for row in table)
@ -755,15 +758,15 @@ class CmdColorTest(COMMAND_DEFAULT_CLASS):
for igray in range(6): for igray in range(6):
letter = chr(97 + (ibatch*6 + igray)) letter = chr(97 + (ibatch*6 + igray))
inverse = chr(122 - (ibatch*6 + igray)) inverse = chr(122 - (ibatch*6 + igray))
table[0 + igray].append("|=%s%s |n" % (letter, "||=%s" % (letter))) table[0 + igray].append("|=%s%s |n" % (letter, "||=%s" % letter))
table[6 + igray].append("|=%s|[=%s%s |n" % (inverse, letter, "||[=%s" % (letter))) table[6 + igray].append("|=%s|[=%s%s |n" % (inverse, letter, "||[=%s" % letter))
for igray in range(6): for igray in range(6):
# the last row (y, z) has empty columns # the last row (y, z) has empty columns
if igray < 2: if igray < 2:
letter = chr(121 + igray) letter = chr(121 + igray)
inverse = chr(98 - igray) inverse = chr(98 - igray)
fg = "|=%s%s |n" % (letter, "||=%s" % (letter)) fg = "|=%s%s |n" % (letter, "||=%s" % letter)
bg = "|=%s|[=%s%s |n" % (inverse, letter, "||[=%s" % (letter)) bg = "|=%s|[=%s%s |n" % (inverse, letter, "||[=%s" % letter)
else: else:
fg, bg = " ", " " fg, bg = " ", " "
table[0 + igray].append(fg) table[0 + igray].append(fg)
@ -802,7 +805,7 @@ class CmdQuell(COMMAND_DEFAULT_CLASS):
player_caller = True player_caller = True
def _recache_locks(self, player): def _recache_locks(self, player):
"Helper method to reset the lockhandler on an already puppeted object" """Helper method to reset the lockhandler on an already puppeted object"""
if self.session: if self.session:
char = self.session.puppet char = self.session.puppet
if char: if char:
@ -813,7 +816,7 @@ class CmdQuell(COMMAND_DEFAULT_CLASS):
player.locks.reset() player.locks.reset()
def func(self): def func(self):
"Perform the command" """Perform the command"""
player = self.player player = self.player
permstr = player.is_superuser and " (superuser)" or " (%s)" % (", ".join(player.permissions.all())) permstr = player.is_superuser and " (superuser)" or " (%s)" % (", ".join(player.permissions.all()))
if self.cmdstring == '@unquell': if self.cmdstring == '@unquell':
@ -831,7 +834,8 @@ class CmdQuell(COMMAND_DEFAULT_CLASS):
if puppet: if puppet:
cpermstr = "(%s)" % ", ".join(puppet.permissions.all()) cpermstr = "(%s)" % ", ".join(puppet.permissions.all())
cpermstr = "Quelling to current puppet's permissions%s." % cpermstr cpermstr = "Quelling to current puppet's permissions%s." % cpermstr
cpermstr += "\n(Note: If this is higher than Player permissions%s, the lowest of the two will be used.)" % permstr cpermstr += "\n(Note: If this is higher than Player permissions %s," \
" the lowest of the two will be used.)" % permstr
cpermstr += "\nUse @unquell to return to normal permission usage." cpermstr += "\nUse @unquell to return to normal permission usage."
self.msg(cpermstr) self.msg(cpermstr)
else: else: