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.
21 """A file containing universe elements."""
23 def __init__(self, filename, universe):
24 self.filename = filename
25 self.universe = universe
30 """Read a file and create elements accordingly."""
31 # TODO(fungi): remove this indirection after the YAML transition
32 if self.filename.endswith('.yaml'):
38 """Read a file and create elements accordingly."""
39 # TODO(fungi): remove this parameter after the YAML transition
43 self.data = yaml.load(open(self.filename))
44 except FileNotFoundError:
45 # it's normal if the file is one which doesn't exist yet
47 mudpy.misc.log("Couldn't read %s file." % self.filename, 6)
49 # happens when we're not far enough along in the init process
51 if not hasattr(self.universe, "files"):
52 self.universe.files = {}
53 self.universe.files[self.filename] = self
55 if "__control__" in self.data:
56 if "include_files" in self.data["__control__"]:
57 for included in makelist(
58 self.data["__control__"]["include_files"]):
61 relative=self.filename,
62 universe=self.universe)
63 if included not in includes:
64 includes.append(included)
65 if "include_dirs" in self.data["__control__"]:
67 os.path.join(x, "__init__.mpy") for x in makelist(
68 self.data["__control__"]["include_dirs"]
73 relative=self.filename,
74 universe=self.universe
76 if included not in includes:
77 includes.append(included)
78 if "default_files" in self.data["__control__"]:
80 self.data["__control__"]["default_files"]
82 for key in origins.keys():
83 origins[key] = find_file(
85 relative=self.filename,
86 universe=self.universe
88 if origins[key] not in includes:
89 includes.append(origins[key])
90 self.universe.default_origins[key] = origins[key]
91 if key not in self.universe.categories:
92 self.universe.categories[key] = {}
93 if "private_files" in self.data["__control__"]:
95 self.data["__control__"]["private_files"]
99 relative=self.filename,
100 universe=self.universe
102 if item not in includes:
103 includes.append(item)
104 if item not in self.universe.private_files:
105 self.universe.private_files.append(item)
106 for element in self.data:
107 if element != "__control__":
108 mudpy.misc.Element(element, self.universe, self.filename)
109 for include_file in includes:
110 if not os.path.isabs(include_file):
111 include_file = find_file(
113 relative=self.filename,
114 universe=self.universe
116 if (include_file not in self.universe.files or not
117 self.universe.files[include_file].is_writeable()):
118 DataFile(include_file, self.universe)
120 # TODO(fungi): remove this method after the YAML transition
122 """Read a file and create elements accordingly."""
124 self.modified = False
125 self.data = configparser.RawConfigParser()
126 if os.access(self.filename, os.R_OK):
127 self.data.read(self.filename)
128 if not hasattr(self.universe, "files"):
129 self.universe.files = {}
130 self.universe.files[self.filename] = self
132 if self.data.has_option("__control__", "include_files"):
133 for included in makelist(
134 self.data.get("__control__", "include_files")
136 included = find_file(
138 relative=self.filename,
139 universe=self.universe
141 if included not in includes:
142 includes.append(included)
143 if self.data.has_option("__control__", "include_dirs"):
145 os.path.join(x, "__init__.mpy") for x in makelist(
146 self.data.get("__control__", "include_dirs")
149 included = find_file(
151 relative=self.filename,
152 universe=self.universe
154 if included not in includes:
155 includes.append(included)
156 if self.data.has_option("__control__", "default_files"):
158 self.data.get("__control__", "default_files")
160 for key in origins.keys():
161 origins[key] = find_file(
163 relative=self.filename,
164 universe=self.universe
166 if origins[key] not in includes:
167 includes.append(origins[key])
168 self.universe.default_origins[key] = origins[key]
169 if key not in self.universe.categories:
170 self.universe.categories[key] = {}
171 if self.data.has_option("__control__", "private_files"):
172 for item in makelist(
173 self.data.get("__control__", "private_files")
177 relative=self.filename,
178 universe=self.universe
180 if item not in includes:
181 includes.append(item)
182 if item not in self.universe.private_files:
183 self.universe.private_files.append(item)
184 for section in self.data.sections():
185 if section != "__control__":
186 mudpy.misc.Element(section, self.universe, self.filename)
187 for include_file in includes:
188 if not os.path.isabs(include_file):
189 include_file = find_file(
191 relative=self.filename,
192 universe=self.universe
194 if (include_file not in self.universe.files or not
195 self.universe.files[include_file].is_writeable()):
196 DataFile(include_file, self.universe)
198 # TODO(fungi): this should support writing YAML
200 """Write the data, if necessary."""
202 # when modified, writeable and has content or the file exists
203 if self.modified and self.is_writeable() and (
204 self.data.sections() or os.path.exists(self.filename)
207 # make parent directories if necessary
208 if not os.path.exists(os.path.dirname(self.filename)):
209 os.makedirs(os.path.dirname(self.filename))
212 if self.data.has_option("__control__", "backup_count"):
213 max_count = self.data.has_option(
214 "__control__", "backup_count")
216 max_count = self.universe.categories[
220 ].getint("default_backup_count")
221 if os.path.exists(self.filename) and max_count:
223 for candidate in os.listdir(os.path.dirname(self.filename)):
225 os.path.basename(self.filename) +
226 """\.\d+$""", candidate
228 backups.append(int(candidate.split(".")[-1]))
231 for old_backup in backups:
232 if old_backup >= max_count - 1:
233 os.remove(self.filename + "." + old_backup)
234 elif not os.path.exists(
235 self.filename + "." + old_backup + 1
238 self.filename + "." + old_backup,
239 self.filename + "." + old_backup + 1
241 if not os.path.exists(self.filename + ".0"):
242 os.rename(self.filename, self.filename + ".0")
245 file_descriptor = codecs.open(self.filename, "w", "utf-8")
247 # if it's marked private, chmod it appropriately
248 if self.filename in self.universe.private_files and oct(
249 stat.S_IMODE(os.stat(self.filename)[stat.ST_MODE])
251 os.chmod(self.filename, 0o0600)
253 # write it back sorted, instead of using configparser
254 sections = self.data.sections()
256 for section in sections:
257 file_descriptor.write("[" + section + "]\n")
258 options = self.data.options(section)
260 for option in options:
261 file_descriptor.write(
263 self.data.get(section, option) + "\n"
265 file_descriptor.write("\n")
267 # flush and close the file
268 file_descriptor.flush()
269 file_descriptor.close()
271 # unset the modified flag
272 self.modified = False
274 def is_writeable(self):
275 """Returns True if the __control__ read_only is False."""
276 # TODO(fungi): remove this indirection after the YAML transition
277 if self._format == "yaml":
279 return not self.data["__control__"].get("read_only", False)
283 return not self.data.has_option(
284 "__control__", "read_only"
285 ) or not self.data.getboolean(
286 "__control__", "read_only"
298 """Return an absolute file path based on configuration."""
300 # make sure to get rid of any surrounding quotes first thing
302 file_name = file_name.strip("\"'")
304 # this is all unnecessary if it's already absolute
305 if file_name and os.path.isabs(file_name):
306 return os.path.realpath(file_name)
308 # when no file name is specified, look for <argv[0]>.conf
310 file_name = os.path.basename(sys.argv[0]) + ".conf"
312 # if a universe was provided, try to get some defaults from there
318 ) and "internal:storage" in universe.contents:
319 storage = universe.categories["internal"]["storage"]
321 root_path = storage.get("root_path").strip("\"'")
323 search_path = storage.getlist("search_path")
325 default_dir = storage.get("default_dir").strip("\"'")
327 # if there's only one file loaded, try to work around a chicken<egg
328 elif hasattr(universe, "files") and len(
330 ) == 1 and not universe.files[
331 list(universe.files.keys())[0]].is_writeable():
332 data_file = universe.files[list(universe.files.keys())[0]].data
334 # try for a fallback default directory
335 if not default_dir and data_file.has_option(
339 default_dir = data_file.get(
344 # try for a fallback root path
345 if not root_path and data_file.has_option(
349 root_path = data_file.get(
354 # try for a fallback search path
355 if not search_path and data_file.has_option(
359 search_path = makelist(
360 data_file.get("internal:storage",
361 "search_path").strip("\"'")
364 # another fallback root path, this time from the universe startdir
365 if not root_path and hasattr(universe, "startdir"):
366 root_path = universe.startdir
368 # when no root path is specified, assume the current working directory
370 root_path = os.getcwd()
372 # otherwise, make sure it's absolute
373 elif not os.path.isabs(root_path):
374 root_path = os.path.realpath(root_path)
376 # if there's no search path, just use the root path and etc
378 search_path = [root_path, "etc"]
380 # work on a copy of the search path, to avoid modifying the caller's
382 search_path = search_path[:]
384 # if there's no default path, use the last element of the search path
386 default_dir = search_path[-1]
388 # if an existing file or directory reference was supplied, prepend it
390 relative = relative.strip("\"'")
391 if os.path.isdir(relative):
392 search_path = [relative] + search_path
394 search_path = [os.path.dirname(relative)] + search_path
396 # make the search path entries absolute and throw away any dupes
397 clean_search_path = []
398 for each_path in search_path:
399 each_path = each_path.strip("\"'")
400 if not os.path.isabs(each_path):
401 each_path = os.path.realpath(os.path.join(root_path, each_path))
402 if each_path not in clean_search_path:
403 clean_search_path.append(each_path)
405 # start hunting for the file now
406 for each_path in clean_search_path:
408 # if the file exists and is readable, we're done
409 if os.path.isfile(os.path.join(each_path, file_name)):
410 file_name = os.path.realpath(os.path.join(each_path, file_name))
413 # it didn't exist after all, so use the default path instead
414 if not os.path.isabs(file_name):
415 file_name = os.path.join(default_dir, file_name)
416 if not os.path.isabs(file_name):
417 file_name = os.path.join(root_path, file_name)
419 # and normalize it last thing before returning
420 file_name = os.path.realpath(file_name)
422 # normalize the resulting file path and hand it back
427 """Turn string into list type."""
428 if value[0] + value[-1] == "[]":
430 elif value[0] + value[-1] == "\"\"":
437 """Turn string into dict type."""
438 if value[0] + value[-1] == "{}":
440 elif value.find(":") > 0:
441 return eval("{" + value + "}")