1 """Data interface functions for the mudpy engine."""
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.
17 """A file containing universe elements and their facets."""
26 self.universe = universe
31 self.relative = relative
35 """Read a file, create elements and poplulate facets accordingly."""
37 self.source = find_file(
38 self.source, relative=self.relative, universe=self.universe)
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
44 log_entry = ("File %s is unavailable." % self.source, 6)
46 mudpy.misc.log(*log_entry)
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
54 for node in list(self.data):
56 for included in self.data["_load"]:
60 universe=self.universe)
61 if included not in includes:
62 includes.append(included)
64 facet_pos = node.rfind(".") + 1
66 mudpy.misc.Element(node, self.universe, self, old_style=True)
68 prefix = node[:facet_pos].strip(".")
70 element = self.universe.contents[prefix]
72 element = mudpy.misc.Element(prefix, self.universe, self)
73 element.set(node[facet_pos:], self.data[node])
74 if prefix.startswith("mudpy.movement."):
75 self.universe.directions.add(
76 prefix[prefix.rfind(".") + 1:])
77 for include_file in includes:
78 if not os.path.isabs(include_file):
79 include_file = find_file(
82 universe=self.universe
84 if (include_file not in self.universe.files or not
85 self.universe.files[include_file].is_writeable()):
86 Data(include_file, self.universe)
89 """Write the data, if necessary."""
91 private_umask = 0o0077
92 private_file_mode = 0o0600
94 # when modified, writeable and has content or the file exists
95 if self.modified and self.is_writeable() and (
96 self.data or os.path.exists(self.source)
99 # make parent directories if necessary
100 if not os.path.exists(os.path.dirname(self.source)):
101 old_umask = os.umask(normal_umask)
102 os.makedirs(os.path.dirname(self.source))
106 if "mudpy.limit" in self.universe.contents:
107 max_count = self.universe.contents["mudpy.limit"].get(
111 if os.path.exists(self.source) and max_count:
113 for candidate in os.listdir(os.path.dirname(self.source)):
115 os.path.basename(self.source) +
116 r"""\.\d+$""", candidate
118 backups.append(int(candidate.split(".")[-1]))
121 for old_backup in backups:
122 if old_backup >= max_count - 1:
123 os.remove(self.source + "." + str(old_backup))
124 elif not os.path.exists(
125 self.source + "." + str(old_backup + 1)
128 self.source + "." + str(old_backup),
129 self.source + "." + str(old_backup + 1)
131 if not os.path.exists(self.source + ".0"):
132 os.rename(self.source, self.source + ".0")
135 if "private" in self.flags:
136 old_umask = os.umask(private_umask)
137 file_descriptor = open(self.source, "w")
138 if oct(stat.S_IMODE(os.stat(
139 self.source)[stat.ST_MODE])) != private_file_mode:
140 # if it's marked private, chmod it appropriately
141 os.chmod(self.source, private_file_mode)
143 old_umask = os.umask(normal_umask)
144 file_descriptor = open(self.source, "w")
147 # write and close the file
148 yaml.safe_dump(self.data, allow_unicode=True,
149 default_flow_style=False, stream=file_descriptor)
150 file_descriptor.close()
152 # unset the modified flag
153 self.modified = False
155 def is_writeable(self):
156 """Returns True if the _lock is False."""
158 return not self.data.get("_lock", False)
172 """Return an absolute file path based on configuration."""
174 # this is all unnecessary if it's already absolute
175 if file_name and os.path.isabs(file_name):
176 return os.path.realpath(file_name)
178 # if a universe was provided, try to get some defaults from there
182 universe, "contents") and "mudpy.filing" in universe.contents:
183 filing = universe.contents["mudpy.filing"]
185 prefix = filing.get("prefix")
187 search = filing.get("search")
189 stash = filing.get("stash")
191 # if there's only one file loaded, try to work around a chicken<egg
192 elif hasattr(universe, "files") and len(
194 ) == 1 and not universe.files[
195 list(universe.files.keys())[0]].is_writeable():
196 data_file = universe.files[list(universe.files.keys())[0]].data
198 # try for a fallback default directory
200 stash = data_file.get(".mudpy.filing.stash", "")
202 # try for a fallback root path
204 prefix = data_file.get(".mudpy.filing.prefix", "")
206 # try for a fallback search path
208 search = data_file.get(".mudpy.filing.search", "")
210 # another fallback root path, this time from the universe startdir
211 if hasattr(universe, "startdir"):
213 prefix = universe.startdir
214 elif not os.path.isabs(prefix):
215 prefix = os.path.join(universe.startdir, prefix)
217 # when no root path is specified, assume the current working directory
221 # make sure it's absolute
222 prefix = os.path.realpath(prefix)
224 # if there's no search path, just use the root path and etc
226 search = [prefix, "etc"]
228 # work on a copy of the search path, to avoid modifying the caller's
232 # if there's no default path, use the last component of the search path
236 # if an existing file or directory reference was supplied, prepend it
238 if os.path.isdir(relative):
239 search = [relative] + search
241 search = [os.path.dirname(relative)] + search
243 # make the search path entries absolute and throw away any dupes
245 for each_path in search:
246 if not os.path.isabs(each_path):
247 each_path = os.path.realpath(os.path.join(prefix, each_path))
248 if each_path not in clean_search:
249 clean_search.append(each_path)
251 # start hunting for the file now
252 for each_path in clean_search:
254 # construct the candidate path
255 candidate = os.path.join(each_path, file_name)
257 # if the file exists and is readable, we're done
258 if os.path.isfile(candidate):
259 file_name = os.path.realpath(candidate)
262 # if the path is a directory, look for an __init__ file
263 if os.path.isdir(candidate):
264 file_name = os.path.realpath(
265 os.path.join(candidate, "__init__.yaml"))
268 # it didn't exist after all, so use the default path instead
269 if not os.path.isabs(file_name):
270 file_name = os.path.join(stash, file_name)
271 if not os.path.isabs(file_name):
272 file_name = os.path.join(prefix, file_name)
274 # and normalize it last thing before returning
275 file_name = os.path.realpath(file_name)
277 # normalize the resulting file path and hand it back