8386842c4d3ace3b97b9e6e54e662184b52902cb
[mudpy.git] / lib / mudpy / data.py
1 """Data interface functions for the mudpy engine."""
2
3 # Copyright (c) 2004-2015 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."""
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 and create elements 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 element in self.data:
88             if element != "__control__":
89                 mudpy.misc.Element(element, self.universe, self.filename)
90         for include_file in includes:
91             if not os.path.isabs(include_file):
92                 include_file = find_file(
93                     include_file,
94                     relative=self.filename,
95                     universe=self.universe
96                 )
97             if (include_file not in self.universe.files or not
98                     self.universe.files[include_file].is_writeable()):
99                 DataFile(include_file, self.universe)
100
101     def save(self):
102         """Write the data, if necessary."""
103         normal_umask = 0o0022
104         private_umask = 0o0077
105         private_file_mode = 0o0600
106
107         # when modified, writeable and has content or the file exists
108         if self.modified and self.is_writeable() and (
109            self.data or os.path.exists(self.filename)
110            ):
111
112             # make parent directories if necessary
113             if not os.path.exists(os.path.dirname(self.filename)):
114                 old_umask = os.umask(normal_umask)
115                 os.makedirs(os.path.dirname(self.filename))
116                 os.umask(old_umask)
117
118             # backup the file
119             if "__control__" in self.data and "backup_count" in self.data[
120                     "__control__"]:
121                 max_count = self.data["__control__"]["backup_count"]
122             else:
123                 max_count = self.universe.categories[
124                     "internal"
125                 ][
126                     "limits"
127                 ].get("default_backup_count")
128             if os.path.exists(self.filename) and max_count:
129                 backups = []
130                 for candidate in os.listdir(os.path.dirname(self.filename)):
131                     if re.match(
132                        os.path.basename(self.filename) +
133                        """\.\d+$""", candidate
134                        ):
135                         backups.append(int(candidate.split(".")[-1]))
136                 backups.sort()
137                 backups.reverse()
138                 for old_backup in backups:
139                     if old_backup >= max_count - 1:
140                         os.remove(self.filename + "." + str(old_backup))
141                     elif not os.path.exists(
142                         self.filename + "." + str(old_backup + 1)
143                     ):
144                         os.rename(
145                             self.filename + "." + str(old_backup),
146                             self.filename + "." + str(old_backup + 1)
147                         )
148                 if not os.path.exists(self.filename + ".0"):
149                     os.rename(self.filename, self.filename + ".0")
150
151             # our data file
152             if self.filename in self.universe.private_files:
153                 old_umask = os.umask(private_umask)
154                 file_descriptor = open(self.filename, "w")
155                 if oct(stat.S_IMODE(os.stat(
156                         self.filename)[stat.ST_MODE])) != private_file_mode:
157                     # if it's marked private, chmod it appropriately
158                     os.chmod(self.filename, private_file_mode)
159             else:
160                 old_umask = os.umask(normal_umask)
161                 file_descriptor = open(self.filename, "w")
162             os.umask(old_umask)
163
164             # write and close the file
165             yaml.safe_dump(self.data, allow_unicode=True,
166                            default_flow_style=False, stream=file_descriptor)
167             file_descriptor.close()
168
169             # unset the modified flag
170             self.modified = False
171
172     def is_writeable(self):
173         """Returns True if the __control__ read_only is False."""
174         try:
175             return not self.data["__control__"].get("read_only", False)
176         except KeyError:
177             return True
178
179
180 def find_file(
181     file_name=None,
182     root_path=None,
183     search_path=None,
184     default_dir=None,
185     relative=None,
186     universe=None
187 ):
188     """Return an absolute file path based on configuration."""
189
190     # make sure to get rid of any surrounding quotes first thing
191     if file_name:
192         file_name = file_name.strip("\"'")
193
194     # this is all unnecessary if it's already absolute
195     if file_name and os.path.isabs(file_name):
196         return os.path.realpath(file_name)
197
198     # if a universe was provided, try to get some defaults from there
199     if universe:
200
201         if hasattr(
202            universe,
203            "contents"
204            ) and "internal:storage" in universe.contents:
205             storage = universe.categories["internal"]["storage"]
206             if not root_path:
207                 root_path = storage.get("root_path").strip("\"'")
208             if not search_path:
209                 search_path = storage.get("search_path")
210             if not default_dir:
211                 default_dir = storage.get("default_dir").strip("\"'")
212
213         # if there's only one file loaded, try to work around a chicken<egg
214         elif hasattr(universe, "files") and len(
215             universe.files
216         ) == 1 and not universe.files[
217                 list(universe.files.keys())[0]].is_writeable():
218             data_file = universe.files[list(universe.files.keys())[0]].data
219
220             # try for a fallback default directory
221             if not default_dir:
222                 default_dir = data_file.get(
223                     "internal:storage", "").get("default_dir", "")
224
225             # try for a fallback root path
226             if not root_path:
227                 root_path = data_file.get(
228                     "internal:storage", "").get("root_path", "")
229
230             # try for a fallback search path
231             if not search_path:
232                 search_path = data_file.get(
233                     "internal:storage", "").get("search_path", "")
234
235         # another fallback root path, this time from the universe startdir
236         if not root_path and hasattr(universe, "startdir"):
237             root_path = universe.startdir
238
239     # when no root path is specified, assume the current working directory
240     if not root_path:
241         root_path = os.getcwd()
242
243     # otherwise, make sure it's absolute
244     elif not os.path.isabs(root_path):
245         root_path = os.path.realpath(root_path)
246
247     # if there's no search path, just use the root path and etc
248     if not search_path:
249         search_path = [root_path, "etc"]
250
251     # work on a copy of the search path, to avoid modifying the caller's
252     else:
253         search_path = search_path[:]
254
255     # if there's no default path, use the last element of the search path
256     if not default_dir:
257         default_dir = search_path[-1]
258
259     # if an existing file or directory reference was supplied, prepend it
260     if relative:
261         relative = relative.strip("\"'")
262         if os.path.isdir(relative):
263             search_path = [relative] + search_path
264         else:
265             search_path = [os.path.dirname(relative)] + search_path
266
267     # make the search path entries absolute and throw away any dupes
268     clean_search_path = []
269     for each_path in search_path:
270         each_path = each_path.strip("\"'")
271         if not os.path.isabs(each_path):
272             each_path = os.path.realpath(os.path.join(root_path, each_path))
273         if each_path not in clean_search_path:
274             clean_search_path.append(each_path)
275
276     # start hunting for the file now
277     for each_path in clean_search_path:
278
279         # if the file exists and is readable, we're done
280         if os.path.isfile(os.path.join(each_path, file_name)):
281             file_name = os.path.realpath(os.path.join(each_path, file_name))
282             break
283
284     # it didn't exist after all, so use the default path instead
285     if not os.path.isabs(file_name):
286         file_name = os.path.join(default_dir, file_name)
287     if not os.path.isabs(file_name):
288         file_name = os.path.join(root_path, file_name)
289
290     # and normalize it last thing before returning
291     file_name = os.path.realpath(file_name)
292
293     # normalize the resulting file path and hand it back
294     return file_name