Drop old-style Element support
[mudpy.git] / mudpy / data.py
1 """Data interface functions for the mudpy engine."""
2
3 # Copyright (c) 2004-2017 Jeremy Stanley <fungi@yuggoth.org>. Permission
4 # to use, copy, modify, and distribute this software is granted under
5 # terms provided in the LICENSE file distributed with this software.
6
7 import os
8 import re
9 import stat
10
11 import mudpy
12 import yaml
13
14
15 class Data:
16
17     """A file containing universe elements and their facets."""
18
19     def __init__(self,
20                  source,
21                  universe,
22                  flags=None,
23                  relative=None,
24                  ):
25         self.source = source
26         self.universe = universe
27         if flags is None:
28             self.flags = []
29         else:
30             self.flags = flags[:]
31         self.relative = relative
32         self.load()
33
34     def load(self):
35         """Read a file, create elements and poplulate facets accordingly."""
36         self.modified = False
37         self.source = find_file(
38                 self.source, relative=self.relative, universe=self.universe)
39         try:
40             self.data = yaml.safe_load(open(self.source))
41         except FileNotFoundError:
42             # it's normal if the file is one which doesn't exist yet
43             self.data = {}
44             log_entry = ("File %s is unavailable." % self.source, 6)
45             try:
46                 mudpy.misc.log(*log_entry)
47             except NameError:
48                 # happens when we're not far enough along in the init process
49                 self.universe.setup_loglines.append(log_entry)
50         if not hasattr(self.universe, "files"):
51             self.universe.files = {}
52         self.universe.files[self.source] = self
53         includes = []
54         for node in list(self.data):
55             if node == "_load":
56                 for included in self.data["_load"]:
57                     included = find_file(
58                         included,
59                         relative=self.source,
60                         universe=self.universe)
61                     if included not in includes:
62                         includes.append(included)
63                 continue
64             if node.startswith("_"):
65                 continue
66             facet_pos = node.rfind(".") + 1
67             prefix = node[:facet_pos].strip(".")
68             try:
69                 element = self.universe.contents[prefix]
70             except KeyError:
71                 element = mudpy.misc.Element(prefix, self.universe, self)
72             element.set(node[facet_pos:], self.data[node])
73             if prefix.startswith("mudpy.movement."):
74                 self.universe.directions.add(
75                     prefix[prefix.rfind(".") + 1:])
76         for include_file in includes:
77             if not os.path.isabs(include_file):
78                 include_file = find_file(
79                     include_file,
80                     relative=self.source,
81                     universe=self.universe
82                 )
83             if (include_file not in self.universe.files or not
84                     self.universe.files[include_file].is_writeable()):
85                 Data(include_file, self.universe)
86
87     def save(self):
88         """Write the data, if necessary."""
89         normal_umask = 0o0022
90         private_umask = 0o0077
91         private_file_mode = 0o0600
92
93         # when modified, writeable and has content or the file exists
94         if self.modified and self.is_writeable() and (
95            self.data or os.path.exists(self.source)
96            ):
97
98             # make parent directories if necessary
99             if not os.path.exists(os.path.dirname(self.source)):
100                 old_umask = os.umask(normal_umask)
101                 os.makedirs(os.path.dirname(self.source))
102                 os.umask(old_umask)
103
104             # backup the file
105             if "mudpy.limit" in self.universe.contents:
106                 max_count = self.universe.contents["mudpy.limit"].get(
107                     "backups", 0)
108             else:
109                 max_count = 0
110             if os.path.exists(self.source) and max_count:
111                 backups = []
112                 for candidate in os.listdir(os.path.dirname(self.source)):
113                     if re.match(
114                        os.path.basename(self.source) +
115                        r"""\.\d+$""", candidate
116                        ):
117                         backups.append(int(candidate.split(".")[-1]))
118                 backups.sort()
119                 backups.reverse()
120                 for old_backup in backups:
121                     if old_backup >= max_count - 1:
122                         os.remove(self.source + "." + str(old_backup))
123                     elif not os.path.exists(
124                         self.source + "." + str(old_backup + 1)
125                     ):
126                         os.rename(
127                             self.source + "." + str(old_backup),
128                             self.source + "." + str(old_backup + 1)
129                         )
130                 if not os.path.exists(self.source + ".0"):
131                     os.rename(self.source, self.source + ".0")
132
133             # our data file
134             if "private" in self.flags:
135                 old_umask = os.umask(private_umask)
136                 file_descriptor = open(self.source, "w")
137                 if oct(stat.S_IMODE(os.stat(
138                         self.source)[stat.ST_MODE])) != private_file_mode:
139                     # if it's marked private, chmod it appropriately
140                     os.chmod(self.source, private_file_mode)
141             else:
142                 old_umask = os.umask(normal_umask)
143                 file_descriptor = open(self.source, "w")
144             os.umask(old_umask)
145
146             # write and close the file
147             yaml.safe_dump(self.data, allow_unicode=True,
148                            default_flow_style=False, stream=file_descriptor)
149             file_descriptor.close()
150
151             # unset the modified flag
152             self.modified = False
153
154     def is_writeable(self):
155         """Returns True if the _lock is False."""
156         try:
157             return not self.data.get("_lock", False)
158         except KeyError:
159             return True
160
161
162 def find_file(
163     file_name=None,
164     category=None,
165     prefix=None,
166     relative=None,
167     search=None,
168     stash=None,
169     universe=None
170 ):
171     """Return an absolute file path based on configuration."""
172
173     # this is all unnecessary if it's already absolute
174     if file_name and os.path.isabs(file_name):
175         return os.path.realpath(file_name)
176
177     # if a universe was provided, try to get some defaults from there
178     if universe:
179
180         if hasattr(
181                 universe, "contents") and "mudpy.filing" in universe.contents:
182             filing = universe.contents["mudpy.filing"]
183             if not prefix:
184                 prefix = filing.get("prefix")
185             if not search:
186                 search = filing.get("search")
187             if not stash:
188                 stash = filing.get("stash")
189
190         # if there's only one file loaded, try to work around a chicken<egg
191         elif hasattr(universe, "files") and len(
192             universe.files
193         ) == 1 and not universe.files[
194                 list(universe.files.keys())[0]].is_writeable():
195             data_file = universe.files[list(universe.files.keys())[0]].data
196
197             # try for a fallback default directory
198             if not stash:
199                 stash = data_file.get(".mudpy.filing.stash", "")
200
201             # try for a fallback root path
202             if not prefix:
203                 prefix = data_file.get(".mudpy.filing.prefix", "")
204
205             # try for a fallback search path
206             if not search:
207                 search = data_file.get(".mudpy.filing.search", "")
208
209         # another fallback root path, this time from the universe startdir
210         if hasattr(universe, "startdir"):
211             if not prefix:
212                 prefix = universe.startdir
213             elif not os.path.isabs(prefix):
214                 prefix = os.path.join(universe.startdir, prefix)
215
216     # when no root path is specified, assume the current working directory
217     if (not prefix or prefix == ".") and hasattr(universe, "startdir"):
218         prefix = universe.startdir
219
220     # make sure it's absolute
221     prefix = os.path.realpath(prefix)
222
223     # if there's no search path, just use the root path and etc
224     if not search:
225         search = [prefix, "etc"]
226
227     # work on a copy of the search path, to avoid modifying the caller's
228     else:
229         search = search[:]
230
231     # if there's no default path, use the last component of the search path
232     if not stash:
233         stash = search[-1]
234
235     # if an existing file or directory reference was supplied, prepend it
236     if relative:
237         if os.path.isdir(relative):
238             search = [relative] + search
239         else:
240             search = [os.path.dirname(relative)] + search
241
242     # make the search path entries absolute and throw away any dupes
243     clean_search = []
244     for each_path in search:
245         if not os.path.isabs(each_path):
246             each_path = os.path.realpath(os.path.join(prefix, each_path))
247         if each_path not in clean_search:
248             clean_search.append(each_path)
249
250     # start hunting for the file now
251     for each_path in clean_search:
252
253         # construct the candidate path
254         candidate = os.path.join(each_path, file_name)
255
256         # if the file exists and is readable, we're done
257         if os.path.isfile(candidate):
258             file_name = os.path.realpath(candidate)
259             break
260
261         # if the path is a directory, look for an __init__ file
262         if os.path.isdir(candidate):
263             file_name = os.path.realpath(
264                     os.path.join(candidate, "__init__.yaml"))
265             break
266
267     # it didn't exist after all, so use the default path instead
268     if not os.path.isabs(file_name):
269         file_name = os.path.join(stash, file_name)
270     if not os.path.isabs(file_name):
271         file_name = os.path.join(prefix, file_name)
272
273     # and normalize it last thing before returning
274     file_name = os.path.realpath(file_name)
275     return file_name