1 """Data interface functions for the mudpy engine."""
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.
17 """A file containing universe elements."""
19 def __init__(self, filename, universe):
20 self.filename = filename
21 self.universe = universe
26 """Read a file and create elements accordingly."""
29 self.data = yaml.load(open(self.filename))
30 except FileNotFoundError:
31 # it's normal if the file is one which doesn't exist yet
33 mudpy.misc.log("Couldn't read %s file." % self.filename, 6)
35 # happens when we're not far enough along in the init process
37 if not hasattr(self.universe, "files"):
38 self.universe.files = {}
39 self.universe.files[self.filename] = self
41 if "__control__" in self.data:
42 if "include_files" in self.data["__control__"]:
43 for included in self.data["__control__"]["include_files"]:
46 relative=self.filename,
47 universe=self.universe)
48 if included not in includes:
49 includes.append(included)
50 if "include_dirs" in self.data["__control__"]:
52 os.path.join(x, "__init__.yaml") for x in
53 self.data["__control__"]["include_dirs"]
57 relative=self.filename,
58 universe=self.universe
60 if included not in includes:
61 includes.append(included)
62 if "default_files" in self.data["__control__"]:
63 origins = self.data["__control__"]["default_files"]
64 for key in origins.keys():
65 origins[key] = find_file(
67 relative=self.filename,
68 universe=self.universe
70 if origins[key] not in includes:
71 includes.append(origins[key])
72 self.universe.default_origins[key] = origins[key]
73 if key not in self.universe.categories:
74 self.universe.categories[key] = {}
75 if "private_files" in self.data["__control__"]:
76 for item in self.data["__control__"]["private_files"]:
79 relative=self.filename,
80 universe=self.universe
82 if item not in includes:
84 if item not in self.universe.private_files:
85 self.universe.private_files.append(item)
86 for element in self.data:
87 if element != "__control__":
88 mudpy.misc.Element(element, self.universe, self.filename)
89 for include_file in includes:
90 if not os.path.isabs(include_file):
91 include_file = find_file(
93 relative=self.filename,
94 universe=self.universe
96 if (include_file not in self.universe.files or not
97 self.universe.files[include_file].is_writeable()):
98 DataFile(include_file, self.universe)
101 """Write the data, if necessary."""
103 # when modified, writeable and has content or the file exists
104 if self.modified and self.is_writeable() and (
105 self.data or os.path.exists(self.filename)
108 # make parent directories if necessary
109 if not os.path.exists(os.path.dirname(self.filename)):
110 os.makedirs(os.path.dirname(self.filename))
113 if "__control__" in self.data and "backup_count" in self.data[
115 max_count = self.data["__control__"]["backup_count"]
117 max_count = self.universe.categories[
121 ].get("default_backup_count")
122 if os.path.exists(self.filename) and max_count:
124 for candidate in os.listdir(os.path.dirname(self.filename)):
126 os.path.basename(self.filename) +
127 """\.\d+$""", candidate
129 backups.append(int(candidate.split(".")[-1]))
132 for old_backup in backups:
133 if old_backup >= max_count - 1:
134 os.remove(self.filename + "." + str(old_backup))
135 elif not os.path.exists(
136 self.filename + "." + str(old_backup + 1)
139 self.filename + "." + str(old_backup),
140 self.filename + "." + str(old_backup + 1)
142 if not os.path.exists(self.filename + ".0"):
143 os.rename(self.filename, self.filename + ".0")
146 file_descriptor = open(self.filename, "w")
148 # if it's marked private, chmod it appropriately
149 if self.filename in self.universe.private_files and oct(
150 stat.S_IMODE(os.stat(self.filename)[stat.ST_MODE])
152 os.chmod(self.filename, 0o0600)
154 # write and close the file
155 yaml.dump(self.data, allow_unicode=True, default_flow_style=False,
156 stream=file_descriptor)
157 file_descriptor.close()
159 # unset the modified flag
160 self.modified = False
162 def is_writeable(self):
163 """Returns True if the __control__ read_only is False."""
165 return not self.data["__control__"].get("read_only", False)
178 """Return an absolute file path based on configuration."""
180 # make sure to get rid of any surrounding quotes first thing
182 file_name = file_name.strip("\"'")
184 # this is all unnecessary if it's already absolute
185 if file_name and os.path.isabs(file_name):
186 return os.path.realpath(file_name)
188 # if a universe was provided, try to get some defaults from there
194 ) and "internal:storage" in universe.contents:
195 storage = universe.categories["internal"]["storage"]
197 root_path = storage.get("root_path").strip("\"'")
199 search_path = storage.get("search_path")
201 default_dir = storage.get("default_dir").strip("\"'")
203 # if there's only one file loaded, try to work around a chicken<egg
204 elif hasattr(universe, "files") and len(
206 ) == 1 and not universe.files[
207 list(universe.files.keys())[0]].is_writeable():
208 data_file = universe.files[list(universe.files.keys())[0]].data
210 # try for a fallback default directory
212 default_dir = data_file.get(
213 "internal:storage", "").get("default_dir", "")
215 # try for a fallback root path
217 root_path = data_file.get(
218 "internal:storage", "").get("root_path", "")
220 # try for a fallback search path
222 search_path = data_file.get(
223 "internal:storage", "").get("search_path", "")
225 # another fallback root path, this time from the universe startdir
226 if not root_path and hasattr(universe, "startdir"):
227 root_path = universe.startdir
229 # when no root path is specified, assume the current working directory
231 root_path = os.getcwd()
233 # otherwise, make sure it's absolute
234 elif not os.path.isabs(root_path):
235 root_path = os.path.realpath(root_path)
237 # if there's no search path, just use the root path and etc
239 search_path = [root_path, "etc"]
241 # work on a copy of the search path, to avoid modifying the caller's
243 search_path = search_path[:]
245 # if there's no default path, use the last element of the search path
247 default_dir = search_path[-1]
249 # if an existing file or directory reference was supplied, prepend it
251 relative = relative.strip("\"'")
252 if os.path.isdir(relative):
253 search_path = [relative] + search_path
255 search_path = [os.path.dirname(relative)] + search_path
257 # make the search path entries absolute and throw away any dupes
258 clean_search_path = []
259 for each_path in search_path:
260 each_path = each_path.strip("\"'")
261 if not os.path.isabs(each_path):
262 each_path = os.path.realpath(os.path.join(root_path, each_path))
263 if each_path not in clean_search_path:
264 clean_search_path.append(each_path)
266 # start hunting for the file now
267 for each_path in clean_search_path:
269 # if the file exists and is readable, we're done
270 if os.path.isfile(os.path.join(each_path, file_name)):
271 file_name = os.path.realpath(os.path.join(each_path, file_name))
274 # it didn't exist after all, so use the default path instead
275 if not os.path.isabs(file_name):
276 file_name = os.path.join(default_dir, file_name)
277 if not os.path.isabs(file_name):
278 file_name = os.path.join(root_path, file_name)
280 # and normalize it last thing before returning
281 file_name = os.path.realpath(file_name)
283 # normalize the resulting file path and hand it back