Move commands into a separate command module
[mudpy.git] / mudpy / misc.py
index 2da1b40..930d4d7 100644 (file)
@@ -1,8 +1,8 @@
 """Miscellaneous functions for the mudpy engine."""
 
-# Copyright (c) 2004-2017 Jeremy Stanley <fungi@yuggoth.org>. Permission
-# to use, copy, modify, and distribute this software is granted under
-# terms provided in the LICENSE file distributed with this software.
+# Copyright (c) 2004-2018 mudpy authors. Permission to use, copy,
+# modify, and distribute this software is granted under terms
+# provided in the LICENSE file distributed with this software.
 
 import codecs
 import os
@@ -64,8 +64,9 @@ class Element:
 
     def reload(self):
         """Create a new element and replace this one."""
-        Element(self.key, self.universe, self.origin)
-        del(self)
+        args = (self.key, self.universe, self.origin)
+        self.destroy()
+        Element(*args)
 
     def destroy(self):
         """Remove an element from the universe and destroy it."""
@@ -129,16 +130,25 @@ class Element:
             # updated data from files
             raise PermissionError("Altering elements in read-only files is "
                                   "disallowed")
+        # Coerce some values to appropriate data types
+        # TODO(fungi) Move these to a separate validation mechanism
         if facet in ["loglevel"]:
             value = int(value)
         elif facet in ["administrator"]:
             value = bool(value)
-        if not self.has_facet(facet) or not self.get(facet) == value:
-            node = ".".join((self.key, facet))
+
+        # The canonical node for this facet within its origin
+        node = ".".join((self.key, facet))
+
+        if node not in self.origin.data or self.origin.data[node] != value:
+            # Be careful to only update the origin's contents when required,
+            # since that affects whether the backing file gets written
             self.origin.data[node] = value
-            self.facethash[facet] = self.origin.data[node]
             self.origin.modified = True
 
+        # Make sure this facet is included in the element's facets
+        self.facethash[facet] = self.origin.data[node]
+
     def append(self, facet, value):
         """Append value to a list."""
         newlist = self.get(facet)
@@ -326,6 +336,7 @@ class Universe:
         self.startdir = os.getcwd()
         self.terminate_flag = False
         self.userlist = []
+        self.versions = None
         if not filename:
             possible_filenames = [
                 "etc/mudpy.yaml",
@@ -353,23 +364,9 @@ class Universe:
         # it's possible for this to enter before logging configuration is read
         pending_loglines = []
 
-        # the files dict must exist and filename needs to be read-only
-        if not hasattr(
-           self, "files"
-           ) or not (
-            self.filename in self.files and self.files[
-                self.filename
-            ].is_writeable()
-        ):
-
-            # clear out all read-only files
-            if hasattr(self, "files"):
-                for data_filename in list(self.files.keys()):
-                    if not self.files[data_filename].is_writeable():
-                        del self.files[data_filename]
-
-            # start loading from the initial file
-            mudpy.data.Data(self.filename, self)
+        # start populating the (re)files dict from the base config
+        self.files = {}
+        mudpy.data.Data(self.filename, self)
 
         # load default storage locations for groups
         if hasattr(self, "contents") and "mudpy.filing" in self.contents:
@@ -394,17 +391,6 @@ class Universe:
             if user.avatar in inactive_avatars:
                 inactive_avatars.remove(user.avatar)
 
-        # go through all elements to clear out inactive avatar locations
-        for element in self.contents.values():
-            area = element.get("location")
-            if element in inactive_avatars and area:
-                if area in self.contents and element.key in self.contents[
-                   area
-                   ].contents:
-                    del self.contents[area].contents[element.key]
-                element.set("default_location", area)
-                element.remove_facet("location")
-
         # another pass to straighten out all the element contents
         for element in self.contents.values():
             element.update_location()
@@ -515,21 +501,17 @@ class User:
         self.output_queue = []
         self.partial_input = b""
         self.password_tries = 0
-        self.state = "initial"
+        self.state = "telopt_negotiation"
         self.telopts = {}
+        self.universe = universe
 
     def quit(self):
         """Log, close the connection and remove."""
         if self.account:
-            name = self.account.get("name")
-        else:
-            name = ""
-        if name:
-            message = "User " + name
+            name = self.account.get("name", self)
         else:
-            message = "An unnamed user"
-        message += " logged out."
-        log(message, 2)
+            name = self
+        log("Logging out %s" % name, 2)
         self.deactivate_avatar()
         self.connection.close()
         self.remove()
@@ -574,26 +556,30 @@ class User:
     def reload(self):
         """Save, load a new user and relocate the connection."""
 
+        # copy old attributes
+        attributes = self.__dict__
+
         # get out of the list
         self.remove()
 
+        # get rid of the old user object
+        del(self)
+
         # create a new user object
         new_user = User()
 
         # set everything equivalent
-        for attribute in vars(self).keys():
-            exec("new_user." + attribute + " = self." + attribute)
+        new_user.__dict__ = attributes
 
         # the avatar needs a new owner
         if new_user.avatar:
+            new_user.account = universe.contents[new_user.account.key]
+            new_user.avatar = universe.contents[new_user.avatar.key]
             new_user.avatar.owner = new_user
 
         # add it to the list
         universe.userlist.append(new_user)
 
-        # get rid of the old user object
-        del(self)
-
     def replace_old_connections(self):
         """Disconnect active users with the same name."""
 
@@ -658,8 +644,8 @@ class User:
                 log("Administrator %s authenticated." %
                     self.account.get("name"), 2)
             else:
-                # log("User %s authenticated." % self.account.get("name"), 2)
-                log("User %s authenticated." % self.account.subkey, 2)
+                log("User %s authenticated for account %s." % (
+                        self, self.account.subkey), 2)
 
     def show_menu(self):
         """Send the user their current menu."""
@@ -687,6 +673,7 @@ class User:
 
     def remove(self):
         """Remove a user from the list of connected users."""
+        log("Disconnecting account %s." % self, 0)
         universe.userlist.remove(self)
 
     def send(
@@ -796,7 +783,7 @@ class User:
             self.check_idle()
 
         # if output is paused, decrement the counter
-        if self.state == "initial":
+        if self.state == "telopt_negotiation":
             if self.negotiation_pause:
                 self.negotiation_pause -= 1
             else:
@@ -825,13 +812,13 @@ class User:
         if self.output_queue:
             try:
                 self.connection.send(self.output_queue[0])
-            except BrokenPipeError:
+            except (BrokenPipeError, ConnectionResetError):
                 if self.account and self.account.get("name"):
                     account = self.account.get("name")
                 else:
                     account = "an unknown user"
                 self.state = "disconnecting"
-                log("Broken pipe sending to %s." % account, 7)
+                log("Disconnected while sending to %s." % account, 7)
             del self.output_queue[0]
 
     def enqueue_input(self):
@@ -853,11 +840,15 @@ class User:
             mudpy.telnet.negotiate_telnet_options(self)
 
             # separate multiple input lines
-            new_input_lines = self.partial_input.split(b"\n")
+            new_input_lines = self.partial_input.split(b"\r\0")
+            if len(new_input_lines) == 1:
+                new_input_lines = new_input_lines[0].split(b"\r\n")
 
             # if input doesn't end in a newline, replace the
             # held partial input with the last line of it
-            if not self.partial_input.endswith(b"\n"):
+            if not (
+                    self.partial_input.endswith(b"\r\0") or
+                    self.partial_input.endswith(b"\r\n")):
                 self.partial_input = new_input_lines.pop()
 
             # otherwise, chop off the extra null input and reset
@@ -873,8 +864,8 @@ class User:
                 line = line.strip()
 
                 # log non-printable characters remaining
-                if mudpy.telnet.is_enabled(self, mudpy.telnet.TELOPT_BINARY,
-                                           mudpy.telnet.HIM):
+                if not mudpy.telnet.is_enabled(
+                        self, mudpy.telnet.TELOPT_BINARY, mudpy.telnet.HIM):
                     asciiline = bytes([x for x in line if 32 <= x <= 126])
                     if line != asciiline:
                         logline = "Non-ASCII characters from "
@@ -889,7 +880,7 @@ class User:
                 try:
                     line = line.decode("utf-8")
                 except UnicodeDecodeError:
-                    logline = "Non-UTF-8 characters from "
+                    logline = "Non-UTF-8 sequence from "
                     if self.account and self.account.get("name"):
                         logline += self.account.get("name") + ": "
                     else:
@@ -914,11 +905,15 @@ class User:
             universe)
         self.avatar.append("inherit", "archetype.avatar")
         self.account.append("avatars", self.avatar.key)
+        log("Created new avatar %s for user %s." % (
+                self.avatar.key, self.account.get("name")), 0)
 
     def delete_avatar(self, avatar):
         """Remove an avatar from the world and from the user's list."""
         if self.avatar is universe.contents[avatar]:
             self.avatar = None
+        log("Deleting avatar %s for user %s." % (
+                avatar, self.account.get("name")), 0)
         universe.contents[avatar].destroy()
         avatars = self.account.get("avatars")
         avatars.remove(avatar)
@@ -930,11 +925,16 @@ class User:
             self.account.get("avatars")[index]]
         self.avatar.owner = self
         self.state = "active"
+        log("Activated avatar %s (%s)." % (
+                self.avatar.get("name"), self.avatar.key), 0)
         self.avatar.go_home()
 
     def deactivate_avatar(self):
         """Have the active avatar leave the world."""
         if self.avatar:
+            log("Deactivating avatar %s (%s) for user %s." % (
+                    self.avatar.get("name"), self.avatar.key,
+                    self.account.get("name")), 0)
             current = self.avatar.get("location")
             if current:
                 self.avatar.set("default_location", current)
@@ -952,6 +952,8 @@ class User:
         """Destroy the user and associated avatars."""
         for avatar in self.account.get("avatars"):
             self.delete_avatar(avatar)
+        log("Destroying account %s for user %s." % (
+                self.account.get("name"), self), 0)
         self.account.destroy()
 
     def list_avatar_names(self):
@@ -993,6 +995,7 @@ def log(message, level=0):
     if file_name:
         if not os.path.isabs(file_name):
             file_name = os.path.join(universe.startdir, file_name)
+        os.makedirs(os.path.dirname(file_name), exist_ok=True)
         file_descriptor = codecs.open(file_name, "a", "utf-8")
         for line in lines:
             file_descriptor.write(timestamp + " " + line + "\n")
@@ -1106,8 +1109,10 @@ def wrap_ansi_text(text, width):
     # ignoring color escape sequences
     rel_pos = 0
 
-    # the absolute position of the most recent whitespace character
-    last_whitespace = 0
+    # the absolute and relative positions of the most recent whitespace
+    # character
+    last_abs_whitespace = 0
+    last_rel_whitespace = 0
 
     # whether the current character is part of a color escape sequence
     escape = False
@@ -1121,39 +1126,37 @@ def wrap_ansi_text(text, width):
         # the current character is the escape character
         if each_character == "\x1b" and not escape:
             escape = True
+            rel_pos -= 1
 
         # the current character is within an escape sequence
         elif escape:
-
-            # the current character is m, which terminates the
-            # escape sequence
+            rel_pos -= 1
             if each_character == "m":
+                # the current character is m, which terminates the
+                # escape sequence
                 escape = False
 
+        # the current character is a space
+        elif each_character == " ":
+            last_abs_whitespace = abs_pos
+            last_rel_whitespace = rel_pos
+
         # the current character is a newline, so reset the relative
-        # position (start a new line)
+        # position too (start a new line)
         elif each_character == "\n":
             rel_pos = 0
-            last_whitespace = abs_pos
-
-        # the current character meets the requested maximum line width,
-        # so we need to backtrack and find a space at which to wrap;
-        # special care is taken to avoid an off-by-one in case the
-        # current character is a double-width glyph
-        elif each_character != "\r" and (
-            rel_pos >= width or (
-                rel_pos >= width - 1 and glyph_columns(
-                    each_character
-                ) == 2
-            )
-        ):
+            last_abs_whitespace = abs_pos
+            last_rel_whitespace = rel_pos
 
-            # it's always possible we landed on whitespace
-            if unicodedata.category(each_character) in ("Cc", "Zs"):
-                last_whitespace = abs_pos
+        # the current character meets the requested maximum line width, so we
+        # need to wrap unless the current word is wider than the terminal (in
+        # which case we let it do the wrapping instead)
+        if last_rel_whitespace != 0 and (rel_pos > width or (
+                rel_pos > width - 1 and glyph_columns(each_character) == 2)):
 
-            # insert an eol in place of the space
-            text = text[:last_whitespace] + "\r\n" + text[last_whitespace + 1:]
+            # insert an eol in place of the last space
+            text = (text[:last_abs_whitespace] + "\r\n" +
+                    text[last_abs_whitespace + 1:])
 
             # increase the absolute position because an eol is two
             # characters but the space it replaced was only one
@@ -1161,17 +1164,17 @@ def wrap_ansi_text(text, width):
 
             # now we're at the begining of a new line, plus the
             # number of characters wrapped from the previous line
-            rel_pos = 0
-            for remaining_characters in text[last_whitespace:abs_pos]:
-                rel_pos += glyph_columns(remaining_characters)
+            rel_pos -= last_rel_whitespace
+            last_rel_whitespace = 0
 
         # as long as the character is not a carriage return and the
         # other above conditions haven't been met, count it as a
         # printable character
         elif each_character != "\r":
             rel_pos += glyph_columns(each_character)
-            if unicodedata.category(each_character) in ("Cc", "Zs"):
-                last_whitespace = abs_pos
+            if each_character in (" ", "\n"):
+                last_abs_whitespace = abs_pos
+                last_rel_whitespace = rel_pos
 
         # increase the absolute position for every character
         abs_pos += 1
@@ -1404,12 +1407,13 @@ def on_pulse():
 
 def reload_data():
     """Reload all relevant objects."""
-    for user in universe.userlist[:]:
-        user.reload()
-    for element in universe.contents.values():
-        if element.origin.is_writeable():
-            element.reload()
+    universe.save()
+    old_userlist = universe.userlist[:]
+    for element in list(universe.contents.values()):
+        element.destroy()
     universe.load()
+    for user in old_userlist:
+        user.reload()
 
 
 def check_for_connection(listening_socket):
@@ -1422,13 +1426,14 @@ def check_for_connection(listening_socket):
         return None
 
     # note that we got one
-    log("Connection from " + address[0], 2)
+    log("New connection from %s." % address[0], 2)
 
     # disable blocking so we can proceed whether or not we can send/receive
     connection.setblocking(0)
 
     # create a new user object
     user = User()
+    log("Instantiated %s for %s." % (user, address[0]), 0)
 
     # associate this connection with it
     user.connection = connection
@@ -1849,492 +1854,13 @@ def handler_active(user):
 
         # otherwise, give an error
         elif command_name:
-            command_error(actor, input_data)
+            mudpy.command.error(actor, input_data)
 
     # if no input, just idle back with a prompt
     else:
         user.send("", just_prompt=True)
 
 
-def command_halt(actor, parameters):
-    """Halt the world."""
-    if actor.owner:
-
-        # see if there's a message or use a generic one
-        if parameters:
-            message = "Halting: " + parameters
-        else:
-            message = "User " + actor.owner.account.get(
-                "name"
-            ) + " halted the world."
-
-        # let everyone know
-        broadcast(message, add_prompt=False)
-        log(message, 8)
-
-        # set a flag to terminate the world
-        universe.terminate_flag = True
-
-
-def command_reload(actor):
-    """Reload all code modules, configs and data."""
-    if actor.owner:
-
-        # let the user know and log
-        actor.send("Reloading all code modules, configs and data.")
-        log(
-            "User " +
-            actor.owner.account.get("name") + " reloaded the world.",
-            6
-        )
-
-        # set a flag to reload
-        universe.reload_flag = True
-
-
-def command_quit(actor):
-    """Leave the world and go back to the main menu."""
-    if actor.owner:
-        actor.owner.state = "main_utility"
-        actor.owner.deactivate_avatar()
-
-
-def command_help(actor, parameters):
-    """List available commands and provide help for commands."""
-
-    # did the user ask for help on a specific command word?
-    if parameters and actor.owner:
-
-        # is the command word one for which we have data?
-        if parameters in universe.groups["command"]:
-            command = universe.groups["command"][parameters]
-        else:
-            command = None
-
-        # only for allowed commands
-        if actor.can_run(command):
-
-            # add a description if provided
-            description = command.get("description")
-            if not description:
-                description = "(no short description provided)"
-            if command.get("administrative"):
-                output = "$(red)"
-            else:
-                output = "$(grn)"
-            output += parameters + "$(nrm) - " + description + "$(eol)$(eol)"
-
-            # add the help text if provided
-            help_text = command.get("help")
-            if not help_text:
-                help_text = "No help is provided for this command."
-            output += help_text
-
-            # list related commands
-            see_also = command.get("see_also")
-            if see_also:
-                really_see_also = ""
-                for item in see_also:
-                    if item in universe.groups["command"]:
-                        command = universe.groups["command"][item]
-                        if actor.can_run(command):
-                            if really_see_also:
-                                really_see_also += ", "
-                            if command.get("administrative"):
-                                really_see_also += "$(red)"
-                            else:
-                                really_see_also += "$(grn)"
-                            really_see_also += item + "$(nrm)"
-                if really_see_also:
-                    output += "$(eol)$(eol)See also: " + really_see_also
-
-        # no data for the requested command word
-        else:
-            output = "That is not an available command."
-
-    # no specific command word was indicated
-    else:
-
-        # give a sorted list of commands with descriptions if provided
-        output = "These are the commands available to you:$(eol)$(eol)"
-        sorted_commands = list(universe.groups["command"].keys())
-        sorted_commands.sort()
-        for item in sorted_commands:
-            command = universe.groups["command"][item]
-            if actor.can_run(command):
-                description = command.get("description")
-                if not description:
-                    description = "(no short description provided)"
-                if command.get("administrative"):
-                    output += "   $(red)"
-                else:
-                    output += "   $(grn)"
-                output += item + "$(nrm) - " + description + "$(eol)"
-        output += ('$(eol)Enter "help COMMAND" for help on a command '
-                   'named "COMMAND".')
-
-    # send the accumulated output to the user
-    actor.send(output)
-
-
-def command_move(actor, parameters):
-    """Move the avatar in a given direction."""
-    if parameters in universe.contents[actor.get("location")].portals():
-        actor.move_direction(parameters)
-    else:
-        actor.send("You cannot go that way.")
-
-
-def command_look(actor, parameters):
-    """Look around."""
-    if parameters:
-        actor.send("You can't look at or in anything yet.")
-    else:
-        actor.look_at(actor.get("location"))
-
-
-def command_say(actor, parameters):
-    """Speak to others in the same area."""
-
-    # check for replacement macros and escape them
-    parameters = escape_macros(parameters)
-
-    # if the message is wrapped in quotes, remove them and leave contents
-    # intact
-    if parameters.startswith('"') and parameters.endswith('"'):
-        message = parameters[1:-1]
-        literal = True
-
-    # otherwise, get rid of stray quote marks on the ends of the message
-    else:
-        message = parameters.strip('''"'`''')
-        literal = False
-
-    # the user entered a message
-    if message:
-
-        # match the punctuation used, if any, to an action
-        if "mudpy.linguistic" in universe.contents:
-            actions = universe.contents["mudpy.linguistic"].get("actions", {})
-            default_punctuation = (universe.contents["mudpy.linguistic"].get(
-                "default_punctuation", "."))
-        else:
-            actions = {}
-            default_punctuation = "."
-        action = ""
-
-        # reverse sort punctuation options so the longest match wins
-        for mark in sorted(actions.keys(), reverse=True):
-            if not literal and message.endswith(mark):
-                action = actions[mark]
-                break
-
-        # add punctuation if needed
-        if not action:
-            action = actions[default_punctuation]
-            if message and not (
-               literal or unicodedata.category(message[-1]) == "Po"
-               ):
-                message += default_punctuation
-
-        # failsafe checks to avoid unwanted reformatting and null strings
-        if message and not literal:
-
-            # decapitalize the first letter to improve matching
-            message = message[0].lower() + message[1:]
-
-            # iterate over all words in message, replacing typos
-            if "mudpy.linguistic" in universe.contents:
-                typos = universe.contents["mudpy.linguistic"].get("typos", {})
-            else:
-                typos = {}
-            words = message.split()
-            for index in range(len(words)):
-                word = words[index]
-                while unicodedata.category(word[0]) == "Po":
-                    word = word[1:]
-                while unicodedata.category(word[-1]) == "Po":
-                    word = word[:-1]
-                if word in typos.keys():
-                    words[index] = words[index].replace(word, typos[word])
-            message = " ".join(words)
-
-            # capitalize the first letter
-            message = message[0].upper() + message[1:]
-
-    # tell the area
-    if message:
-        actor.echo_to_location(
-            actor.get("name") + " " + action + 's, "' + message + '"'
-        )
-        actor.send("You " + action + ', "' + message + '"')
-
-    # there was no message
-    else:
-        actor.send("What do you want to say?")
-
-
-def command_chat(actor):
-    """Toggle chat mode."""
-    mode = actor.get("mode")
-    if not mode:
-        actor.set("mode", "chat")
-        actor.send("Entering chat mode (use $(grn)!chat$(nrm) to exit).")
-    elif mode == "chat":
-        actor.remove_facet("mode")
-        actor.send("Exiting chat mode.")
-    else:
-        actor.send("Sorry, but you're already busy with something else!")
-
-
-def command_show(actor, parameters):
-    """Show program data."""
-    message = ""
-    arguments = parameters.split()
-    if not parameters:
-        message = "What do you want to show?"
-    elif arguments[0] == "time":
-        message = universe.groups["internal"]["counters"].get(
-            "elapsed"
-        ) + " increments elapsed since the world was created."
-    elif arguments[0] == "groups":
-        message = "These are the element groups:$(eol)"
-        groups = list(universe.groups.keys())
-        groups.sort()
-        for group in groups:
-            message += "$(eol)   $(grn)" + group + "$(nrm)"
-    elif arguments[0] == "files":
-        message = "These are the current files containing the universe:$(eol)"
-        filenames = sorted(universe.files)
-        for filename in filenames:
-            if universe.files[filename].is_writeable():
-                status = "rw"
-            else:
-                status = "ro"
-            message += ("$(eol)   $(red)(%s) $(grn)%s$(nrm)" %
-                        (status, filename))
-            if universe.files[filename].flags:
-                message += (" $(yel)[%s]$(nrm)" %
-                            ",".join(universe.files[filename].flags))
-    elif arguments[0] == "group":
-        if len(arguments) != 2:
-            message = "You must specify one group."
-        elif arguments[1] in universe.groups:
-            message = ('These are the elements in the "' + arguments[1]
-                       + '" group:$(eol)')
-            elements = [
-                (
-                    universe.groups[arguments[1]][x].key
-                ) for x in universe.groups[arguments[1]].keys()
-            ]
-            elements.sort()
-            for element in elements:
-                message += "$(eol)   $(grn)" + element + "$(nrm)"
-        else:
-            message = 'Group "' + arguments[1] + '" does not exist.'
-    elif arguments[0] == "file":
-        if len(arguments) != 2:
-            message = "You must specify one file."
-        elif arguments[1] in universe.files:
-            message = ('These are the nodes in the "' + arguments[1]
-                       + '" file:$(eol)')
-            elements = sorted(universe.files[arguments[1]].data)
-            for element in elements:
-                message += "$(eol)   $(grn)" + element + "$(nrm)"
-        else:
-            message = 'File "%s" does not exist.' % arguments[1]
-    elif arguments[0] == "element":
-        if len(arguments) != 2:
-            message = "You must specify one element."
-        elif arguments[1].strip(".") in universe.contents:
-            element = universe.contents[arguments[1].strip(".")]
-            message = ('These are the properties of the "' + arguments[1]
-                       + '" element (in "' + element.origin.source
-                       + '"):$(eol)')
-            facets = element.facets()
-            for facet in sorted(facets):
-                message += ("$(eol)   $(grn)%s: $(red)%s$(nrm)" %
-                            (facet, str(facets[facet])))
-        else:
-            message = 'Element "' + arguments[1] + '" does not exist.'
-    elif arguments[0] == "result":
-        if len(arguments) < 2:
-            message = "You need to specify an expression."
-        else:
-            try:
-                message = repr(eval(" ".join(arguments[1:])))
-            except Exception as e:
-                message = ("$(red)Your expression raised an exception...$(eol)"
-                           "$(eol)$(bld)%s$(nrm)" % e)
-    elif arguments[0] == "log":
-        if len(arguments) == 4:
-            if re.match(r"^\d+$", arguments[3]) and int(arguments[3]) >= 0:
-                stop = int(arguments[3])
-            else:
-                stop = -1
-        else:
-            stop = 0
-        if len(arguments) >= 3:
-            if re.match(r"^\d+$", arguments[2]) and int(arguments[2]) > 0:
-                start = int(arguments[2])
-            else:
-                start = -1
-        else:
-            start = 10
-        if len(arguments) >= 2:
-            if (re.match(r"^\d+$", arguments[1])
-                    and 0 <= int(arguments[1]) <= 9):
-                level = int(arguments[1])
-            else:
-                level = -1
-        elif 0 <= actor.owner.account.get("loglevel", 0) <= 9:
-            level = actor.owner.account.get("loglevel", 0)
-        else:
-            level = 1
-        if level > -1 and start > -1 and stop > -1:
-            message = get_loglines(level, start, stop)
-        else:
-            message = ("When specified, level must be 0-9 (default 1), "
-                       "start and stop must be >=1 (default 10 and 1).")
-    else:
-        message = '''I don't know what "''' + parameters + '" is.'
-    actor.send(message)
-
-
-def command_create(actor, parameters):
-    """Create an element if it does not exist."""
-    if not parameters:
-        message = "You must at least specify an element to create."
-    elif not actor.owner:
-        message = ""
-    else:
-        arguments = parameters.split()
-        if len(arguments) == 1:
-            arguments.append("")
-        if len(arguments) == 2:
-            element, filename = arguments
-            if element in universe.contents:
-                message = 'The "' + element + '" element already exists.'
-            else:
-                message = ('You create "' +
-                           element + '" within the universe.')
-                logline = actor.owner.account.get(
-                    "name"
-                ) + " created an element: " + element
-                if filename:
-                    logline += " in file " + filename
-                    if filename not in universe.files:
-                        message += (
-                            ' Warning: "' + filename + '" is not yet '
-                            "included in any other file and will not be read "
-                            "on startup unless this is remedied.")
-                Element(element, universe, filename)
-                log(logline, 6)
-        elif len(arguments) > 2:
-            message = "You can only specify an element and a filename."
-    actor.send(message)
-
-
-def command_destroy(actor, parameters):
-    """Destroy an element if it exists."""
-    if actor.owner:
-        if not parameters:
-            message = "You must specify an element to destroy."
-        else:
-            if parameters not in universe.contents:
-                message = 'The "' + parameters + '" element does not exist.'
-            else:
-                universe.contents[parameters].destroy()
-                message = ('You destroy "' + parameters
-                           + '" within the universe.')
-                log(
-                    actor.owner.account.get(
-                        "name"
-                    ) + " destroyed an element: " + parameters,
-                    6
-                )
-        actor.send(message)
-
-
-def command_set(actor, parameters):
-    """Set a facet of an element."""
-    if not parameters:
-        message = "You must specify an element, a facet and a value."
-    else:
-        arguments = parameters.split(" ", 2)
-        if len(arguments) == 1:
-            message = ('What facet of element "' + arguments[0]
-                       + '" would you like to set?')
-        elif len(arguments) == 2:
-            message = ('What value would you like to set for the "' +
-                       arguments[1] + '" facet of the "' + arguments[0]
-                       + '" element?')
-        else:
-            element, facet, value = arguments
-            if element not in universe.contents:
-                message = 'The "' + element + '" element does not exist.'
-            else:
-                try:
-                    universe.contents[element].set(facet, value)
-                except PermissionError:
-                    message = ('The "%s" element is kept in read-only file '
-                               '"%s" and cannot be altered.' %
-                               (element, universe.contents[
-                                        element].origin.source))
-                except ValueError:
-                    message = ('Value "%s" of type "%s" cannot be coerced '
-                               'to the correct datatype for facet "%s".' %
-                               (value, type(value), facet))
-                else:
-                    message = ('You have successfully (re)set the "' + facet
-                               + '" facet of element "' + element
-                               + '". Try "show element ' +
-                               element + '" for verification.')
-    actor.send(message)
-
-
-def command_delete(actor, parameters):
-    """Delete a facet from an element."""
-    if not parameters:
-        message = "You must specify an element and a facet."
-    else:
-        arguments = parameters.split(" ")
-        if len(arguments) == 1:
-            message = ('What facet of element "' + arguments[0]
-                       + '" would you like to delete?')
-        elif len(arguments) != 2:
-            message = "You may only specify an element and a facet."
-        else:
-            element, facet = arguments
-            if element not in universe.contents:
-                message = 'The "' + element + '" element does not exist.'
-            elif facet not in universe.contents[element].facets():
-                message = ('The "' + element + '" element has no "' + facet
-                           + '" facet.')
-            else:
-                universe.contents[element].remove_facet(facet)
-                message = ('You have successfully deleted the "' + facet
-                           + '" facet of element "' + element
-                           + '". Try "show element ' +
-                           element + '" for verification.')
-    actor.send(message)
-
-
-def command_error(actor, input_data):
-    """Generic error for an unrecognized command word."""
-
-    # 90% of the time use a generic error
-    if random.randrange(10):
-        message = '''I'm not sure what "''' + input_data + '''" means...'''
-
-    # 10% of the time use the classic diku error
-    else:
-        message = "Arglebargle, glop-glyf!?!"
-
-    # send the error message
-    actor.send(message)
-
-
 def daemonize(universe):
     """Fork and disassociate from everything."""
 
@@ -2384,6 +1910,7 @@ def create_pidfile(universe):
     if file_name:
         if not os.path.isabs(file_name):
             file_name = os.path.join(universe.startdir, file_name)
+        os.makedirs(os.path.dirname(file_name), exist_ok=True)
         file_descriptor = codecs.open(file_name, "w", "utf-8")
         file_descriptor.write(pid + "\n")
         file_descriptor.flush()
@@ -2472,9 +1999,6 @@ def setup():
         log(*logline)
     universe.setup_loglines = []
 
-    # log an initial message
-    log("Started mudpy with command line: " + " ".join(sys.argv))
-
     # fork and disassociate
     daemonize(universe)
 
@@ -2487,6 +2011,17 @@ def setup():
     # make the pidfile
     create_pidfile(universe)
 
+    # load and store diagnostic info
+    universe.versions = mudpy.version.Versions("mudpy")
+
+    # log startup diagnostic messages
+    log("On %s at %s" % (universe.versions.python_version, sys.executable), 1)
+    log("Import path: %s" % ", ".join(sys.path), 1)
+    log("Installed dependencies: %s" % universe.versions.dependencies_text, 1)
+    log("Other python packages: %s" % universe.versions.environment_text, 1)
+    log("Started %s with command line: %s" % (
+        universe.versions.version, " ".join(sys.argv)), 1)
+
     # pass the initialized universe back
     return universe