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 if node.startswith("_"):
66 facet_pos = node.rfind(".") + 1
67 prefix = node[:facet_pos].strip(".")
69 element = self.universe.contents[prefix]
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(
81 universe=self.universe
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)
88 """Write the data, if necessary."""
90 private_umask = 0o0077
91 private_file_mode = 0o0600
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)
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))
105 if "mudpy.limit" in self.universe.contents:
106 max_count = self.universe.contents["mudpy.limit"].get(
110 if os.path.exists(self.source) and max_count:
112 for candidate in os.listdir(os.path.dirname(self.source)):
114 os.path.basename(self.source) +
115 r"""\.\d+$""", candidate
117 backups.append(int(candidate.split(".")[-1]))
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)
127 self.source + "." + str(old_backup),
128 self.source + "." + str(old_backup + 1)
130 if not os.path.exists(self.source + ".0"):
131 os.rename(self.source, self.source + ".0")
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)
142 old_umask = os.umask(normal_umask)
143 file_descriptor = open(self.source, "w")
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()
151 # unset the modified flag
152 self.modified = False
154 def is_writeable(self):
155 """Returns True if the _lock is False."""
157 return not self.data.get("_lock", False)
171 """Return an absolute file path based on configuration."""
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)
177 # if a universe was provided, try to get some defaults from there
181 universe, "contents") and "mudpy.filing" in universe.contents:
182 filing = universe.contents["mudpy.filing"]
184 prefix = filing.get("prefix")
186 search = filing.get("search")
188 stash = filing.get("stash")
190 # if there's only one file loaded, try to work around a chicken<egg
191 elif hasattr(universe, "files") and len(
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
197 # try for a fallback default directory
199 stash = data_file.get(".mudpy.filing.stash", "")
201 # try for a fallback root path
203 prefix = data_file.get(".mudpy.filing.prefix", "")
205 # try for a fallback search path
207 search = data_file.get(".mudpy.filing.search", "")
209 # another fallback root path, this time from the universe startdir
210 if hasattr(universe, "startdir"):
212 prefix = universe.startdir
213 elif not os.path.isabs(prefix):
214 prefix = os.path.join(universe.startdir, prefix)
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
220 # make sure it's absolute
221 prefix = os.path.realpath(prefix)
223 # if there's no search path, just use the root path and etc
225 search = [prefix, "etc"]
227 # work on a copy of the search path, to avoid modifying the caller's
231 # if there's no default path, use the last component of the search path
235 # if an existing file or directory reference was supplied, prepend it
237 if os.path.isdir(relative):
238 search = [relative] + search
240 search = [os.path.dirname(relative)] + search
242 # make the search path entries absolute and throw away any dupes
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)
250 # start hunting for the file now
251 for each_path in clean_search:
253 # construct the candidate path
254 candidate = os.path.join(each_path, file_name)
256 # if the file exists and is readable, we're done
257 if os.path.isfile(candidate):
258 file_name = os.path.realpath(candidate)
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"))
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)
273 # and normalize it last thing before returning
274 file_name = os.path.realpath(file_name)