Rename internal:limits element to .mudpy.limit
[mudpy.git] / lib / mudpy / data.py
index b7d173b..02a9139 100644 (file)
@@ -1,11 +1,9 @@
-# -*- coding: utf-8 -*-
 """Data interface functions for the mudpy engine."""
 
-# Copyright (c) 2004-2014 Jeremy Stanley <fungi@yuggoth.org>. Permission
+# Copyright (c) 2004-2016 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.
 
-import codecs
 import os
 import re
 import stat
@@ -16,7 +14,7 @@ import yaml
 
 class DataFile:
 
-    """A file containing universe elements."""
+    """A file containing universe elements and their facets."""
 
     def __init__(self, filename, universe):
         self.filename = filename
@@ -25,17 +23,18 @@ class DataFile:
         self.load()
 
     def load(self):
-        """Read a file and create elements accordingly."""
+        """Read a file, create elements and poplulate facets accordingly."""
         self.modified = False
         try:
-            self.data = yaml.load(open(self.filename))
+            self.data = yaml.safe_load(open(self.filename))
         except FileNotFoundError:
             # it's normal if the file is one which doesn't exist yet
+            log_entry = ("File %s is unavailable." % self.filename, 6)
             try:
-                mudpy.misc.log("Couldn't read %s file." % self.filename, 6)
+                mudpy.misc.log(*log_entry)
             except NameError:
                 # happens when we're not far enough along in the init process
-                pass
+                self.universe.setup_loglines.append(log_entry)
         if not hasattr(self.universe, "files"):
             self.universe.files = {}
         self.universe.files[self.filename] = self
@@ -85,9 +84,21 @@ class DataFile:
                         includes.append(item)
                     if item not in self.universe.private_files:
                         self.universe.private_files.append(item)
-        for element in self.data:
-            if element != "__control__":
-                mudpy.misc.Element(element, self.universe, self.filename)
+        for node in list(self.data):
+            if node == "__control__":
+                continue
+            facet_pos = node.rfind(".") + 1
+            if not facet_pos:
+                mudpy.misc.Element(node, self.universe, self.filename,
+                                   old_style=True)
+            else:
+                prefix = node[:facet_pos].strip(".")
+                try:
+                    element = self.universe.contents[prefix]
+                except KeyError:
+                    element = mudpy.misc.Element(prefix, self.universe,
+                        self.filename)
+                element.set(node[facet_pos:], self.data[node])
         for include_file in includes:
             if not os.path.isabs(include_file):
                 include_file = find_file(
@@ -101,6 +112,9 @@ class DataFile:
 
     def save(self):
         """Write the data, if necessary."""
+        normal_umask = 0o0022
+        private_umask = 0o0077
+        private_file_mode = 0o0600
 
         # when modified, writeable and has content or the file exists
         if self.modified and self.is_writeable() and (
@@ -109,18 +123,17 @@ class DataFile:
 
             # make parent directories if necessary
             if not os.path.exists(os.path.dirname(self.filename)):
+                old_umask = os.umask(normal_umask)
                 os.makedirs(os.path.dirname(self.filename))
+                os.umask(old_umask)
 
             # backup the file
             if "__control__" in self.data and "backup_count" in self.data[
                     "__control__"]:
                 max_count = self.data["__control__"]["backup_count"]
             else:
-                max_count = self.universe.categories[
-                    "internal"
-                ][
-                    "limits"
-                ].get("default_backup_count")
+                max_count = self.universe.contents["mudpy.limit"].get(
+                    "backups")
             if os.path.exists(self.filename) and max_count:
                 backups = []
                 for candidate in os.listdir(os.path.dirname(self.filename)):
@@ -133,29 +146,33 @@ class DataFile:
                 backups.reverse()
                 for old_backup in backups:
                     if old_backup >= max_count - 1:
-                        os.remove(self.filename + "." + old_backup)
+                        os.remove(self.filename + "." + str(old_backup))
                     elif not os.path.exists(
-                        self.filename + "." + old_backup + 1
+                        self.filename + "." + str(old_backup + 1)
                     ):
                         os.rename(
-                            self.filename + "." + old_backup,
-                            self.filename + "." + old_backup + 1
+                            self.filename + "." + str(old_backup),
+                            self.filename + "." + str(old_backup + 1)
                         )
                 if not os.path.exists(self.filename + ".0"):
                     os.rename(self.filename, self.filename + ".0")
 
             # our data file
-            file_descriptor = codecs.open(self.filename, "w", "utf-8")
-
-            # if it's marked private, chmod it appropriately
-            if self.filename in self.universe.private_files and oct(
-               stat.S_IMODE(os.stat(self.filename)[stat.ST_MODE])
-               ) != 0o0600:
-                os.chmod(self.filename, 0o0600)
+            if self.filename in self.universe.private_files:
+                old_umask = os.umask(private_umask)
+                file_descriptor = open(self.filename, "w")
+                if oct(stat.S_IMODE(os.stat(
+                        self.filename)[stat.ST_MODE])) != private_file_mode:
+                    # if it's marked private, chmod it appropriately
+                    os.chmod(self.filename, private_file_mode)
+            else:
+                old_umask = os.umask(normal_umask)
+                file_descriptor = open(self.filename, "w")
+            os.umask(old_umask)
 
-            # write, flush and close the file
-            file_descriptor.write(yaml.dump(self.data))
-            file_descriptor.flush()
+            # write and close the file
+            yaml.safe_dump(self.data, allow_unicode=True,
+                           default_flow_style=False, stream=file_descriptor)
             file_descriptor.close()
 
             # unset the modified flag
@@ -244,7 +261,7 @@ def find_file(
     else:
         search_path = search_path[:]
 
-    # if there's no default path, use the last element of the search path
+    # if there's no default path, use the last component of the search path
     if not default_dir:
         default_dir = search_path[-1]