1 # -*- coding: utf-8 -*-
2 """Data interface functions for the mudpy engine."""
4 # Copyright (c) 2004-2014 Jeremy Stanley <fungi@yuggoth.org>. Permission
5 # to use, copy, modify, and distribute this software is granted under
6 # terms provided in the LICENSE file distributed with this software.
19 """A file containing universe elements."""
21 def __init__(self, filename, universe):
22 self.filename = filename
23 self.universe = universe
28 """Read a file and create elements accordingly."""
31 self.data = yaml.load(open(self.filename))
32 except FileNotFoundError:
33 # it's normal if the file is one which doesn't exist yet
35 mudpy.misc.log("Couldn't read %s file." % self.filename, 6)
37 # happens when we're not far enough along in the init process
39 if not hasattr(self.universe, "files"):
40 self.universe.files = {}
41 self.universe.files[self.filename] = self
43 if "__control__" in self.data:
44 if "include_files" in self.data["__control__"]:
45 for included in self.data["__control__"]["include_files"]:
48 relative=self.filename,
49 universe=self.universe)
50 if included not in includes:
51 includes.append(included)
52 if "include_dirs" in self.data["__control__"]:
54 os.path.join(x, "__init__.yaml") for x in
55 self.data["__control__"]["include_dirs"]
59 relative=self.filename,
60 universe=self.universe
62 if included not in includes:
63 includes.append(included)
64 if "default_files" in self.data["__control__"]:
65 origins = self.data["__control__"]["default_files"]
66 for key in origins.keys():
67 origins[key] = find_file(
69 relative=self.filename,
70 universe=self.universe
72 if origins[key] not in includes:
73 includes.append(origins[key])
74 self.universe.default_origins[key] = origins[key]
75 if key not in self.universe.categories:
76 self.universe.categories[key] = {}
77 if "private_files" in self.data["__control__"]:
78 for item in self.data["__control__"]["private_files"]:
81 relative=self.filename,
82 universe=self.universe
84 if item not in includes:
86 if item not in self.universe.private_files:
87 self.universe.private_files.append(item)
88 for element in self.data:
89 if element != "__control__":
90 mudpy.misc.Element(element, self.universe, self.filename)
91 for include_file in includes:
92 if not os.path.isabs(include_file):
93 include_file = find_file(
95 relative=self.filename,
96 universe=self.universe
98 if (include_file not in self.universe.files or not
99 self.universe.files[include_file].is_writeable()):
100 DataFile(include_file, self.universe)
103 """Write the data, if necessary."""
105 # when modified, writeable and has content or the file exists
106 if self.modified and self.is_writeable() and (
107 self.data or os.path.exists(self.filename)
110 # make parent directories if necessary
111 if not os.path.exists(os.path.dirname(self.filename)):
112 os.makedirs(os.path.dirname(self.filename))
115 if "__control__" in self.data and "backup_count" in self.data[
117 max_count = self.data["__control__"]["backup_count"]
119 max_count = self.universe.categories[
123 ].get("default_backup_count")
124 if os.path.exists(self.filename) and max_count:
126 for candidate in os.listdir(os.path.dirname(self.filename)):
128 os.path.basename(self.filename) +
129 """\.\d+$""", candidate
131 backups.append(int(candidate.split(".")[-1]))
134 for old_backup in backups:
135 if old_backup >= max_count - 1:
136 os.remove(self.filename + "." + old_backup)
137 elif not os.path.exists(
138 self.filename + "." + old_backup + 1
141 self.filename + "." + old_backup,
142 self.filename + "." + old_backup + 1
144 if not os.path.exists(self.filename + ".0"):
145 os.rename(self.filename, self.filename + ".0")
148 file_descriptor = codecs.open(self.filename, "w", "utf-8")
150 # if it's marked private, chmod it appropriately
151 if self.filename in self.universe.private_files and oct(
152 stat.S_IMODE(os.stat(self.filename)[stat.ST_MODE])
154 os.chmod(self.filename, 0o0600)
156 # write, flush and close the file
157 file_descriptor.write(yaml.dump(self.data))
158 file_descriptor.flush()
159 file_descriptor.close()
161 # unset the modified flag
162 self.modified = False
164 def is_writeable(self):
165 """Returns True if the __control__ read_only is False."""
167 return not self.data["__control__"].get("read_only", False)
180 """Return an absolute file path based on configuration."""
182 # make sure to get rid of any surrounding quotes first thing
184 file_name = file_name.strip("\"'")
186 # this is all unnecessary if it's already absolute
187 if file_name and os.path.isabs(file_name):
188 return os.path.realpath(file_name)
190 # if a universe was provided, try to get some defaults from there
196 ) and "internal:storage" in universe.contents:
197 storage = universe.categories["internal"]["storage"]
199 root_path = storage.get("root_path").strip("\"'")
201 search_path = storage.get("search_path")
203 default_dir = storage.get("default_dir").strip("\"'")
205 # if there's only one file loaded, try to work around a chicken<egg
206 elif hasattr(universe, "files") and len(
208 ) == 1 and not universe.files[
209 list(universe.files.keys())[0]].is_writeable():
210 data_file = universe.files[list(universe.files.keys())[0]].data
212 # try for a fallback default directory
214 default_dir = data_file.get(
215 "internal:storage", "").get("default_dir", "")
217 # try for a fallback root path
219 root_path = data_file.get(
220 "internal:storage", "").get("root_path", "")
222 # try for a fallback search path
224 search_path = data_file.get(
225 "internal:storage", "").get("search_path", "")
227 # another fallback root path, this time from the universe startdir
228 if not root_path and hasattr(universe, "startdir"):
229 root_path = universe.startdir
231 # when no root path is specified, assume the current working directory
233 root_path = os.getcwd()
235 # otherwise, make sure it's absolute
236 elif not os.path.isabs(root_path):
237 root_path = os.path.realpath(root_path)
239 # if there's no search path, just use the root path and etc
241 search_path = [root_path, "etc"]
243 # work on a copy of the search path, to avoid modifying the caller's
245 search_path = search_path[:]
247 # if there's no default path, use the last element of the search path
249 default_dir = search_path[-1]
251 # if an existing file or directory reference was supplied, prepend it
253 relative = relative.strip("\"'")
254 if os.path.isdir(relative):
255 search_path = [relative] + search_path
257 search_path = [os.path.dirname(relative)] + search_path
259 # make the search path entries absolute and throw away any dupes
260 clean_search_path = []
261 for each_path in search_path:
262 each_path = each_path.strip("\"'")
263 if not os.path.isabs(each_path):
264 each_path = os.path.realpath(os.path.join(root_path, each_path))
265 if each_path not in clean_search_path:
266 clean_search_path.append(each_path)
268 # start hunting for the file now
269 for each_path in clean_search_path:
271 # if the file exists and is readable, we're done
272 if os.path.isfile(os.path.join(each_path, file_name)):
273 file_name = os.path.realpath(os.path.join(each_path, file_name))
276 # it didn't exist after all, so use the default path instead
277 if not os.path.isabs(file_name):
278 file_name = os.path.join(default_dir, file_name)
279 if not os.path.isabs(file_name):
280 file_name = os.path.join(root_path, file_name)
282 # and normalize it last thing before returning
283 file_name = os.path.realpath(file_name)
285 # normalize the resulting file path and hand it back