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