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.
20 """A file containing universe elements."""
22 def __init__(self, filename, universe):
23 self.filename = filename
24 self.universe = universe
28 """Read a file and create elements accordingly."""
29 self.data = configparser.RawConfigParser()
31 if os.access(self.filename, os.R_OK):
32 self.data.read(self.filename)
33 if not hasattr(self.universe, "files"):
34 self.universe.files = {}
35 self.universe.files[self.filename] = self
37 if self.data.has_option("__control__", "include_files"):
38 for included in makelist(
39 self.data.get("__control__", "include_files")
43 relative=self.filename,
44 universe=self.universe
46 if included not in includes:
47 includes.append(included)
48 if self.data.has_option("__control__", "include_dirs"):
50 os.path.join(x, "__init__.mpy") for x in makelist(
51 self.data.get("__control__", "include_dirs")
56 relative=self.filename,
57 universe=self.universe
59 if included not in includes:
60 includes.append(included)
61 if self.data.has_option("__control__", "default_files"):
63 self.data.get("__control__", "default_files")
65 for key in origins.keys():
66 origins[key] = find_file(
68 relative=self.filename,
69 universe=self.universe
71 if origins[key] not in includes:
72 includes.append(origins[key])
73 self.universe.default_origins[key] = origins[key]
74 if key not in self.universe.categories:
75 self.universe.categories[key] = {}
76 if self.data.has_option("__control__", "private_files"):
78 self.data.get("__control__", "private_files")
82 relative=self.filename,
83 universe=self.universe
85 if item not in includes:
87 if item not in self.universe.private_files:
88 self.universe.private_files.append(item)
89 for section in self.data.sections():
90 if section != "__control__":
91 mudpy.misc.Element(section, self.universe, self.filename)
92 for include_file in includes:
93 if not os.path.isabs(include_file):
94 include_file = find_file(
96 relative=self.filename,
97 universe=self.universe
99 if (include_file not in self.universe.files or not
100 self.universe.files[include_file].is_writeable()):
101 DataFile(include_file, self.universe)
104 """Write the data, if necessary."""
106 # when modified, writeable and has content or the file exists
107 if self.modified and self.is_writeable() and (
108 self.data.sections() or os.path.exists(self.filename)
111 # make parent directories if necessary
112 if not os.path.exists(os.path.dirname(self.filename)):
113 os.makedirs(os.path.dirname(self.filename))
116 if self.data.has_option("__control__", "backup_count"):
117 max_count = self.data.has_option(
118 "__control__", "backup_count")
120 max_count = self.universe.categories[
124 ].getint("default_backup_count")
125 if os.path.exists(self.filename) and max_count:
127 for candidate in os.listdir(os.path.dirname(self.filename)):
129 os.path.basename(self.filename) +
130 """\.\d+$""", candidate
132 backups.append(int(candidate.split(".")[-1]))
135 for old_backup in backups:
136 if old_backup >= max_count - 1:
137 os.remove(self.filename + "." + old_backup)
138 elif not os.path.exists(
139 self.filename + "." + old_backup + 1
142 self.filename + "." + old_backup,
143 self.filename + "." + old_backup + 1
145 if not os.path.exists(self.filename + ".0"):
146 os.rename(self.filename, self.filename + ".0")
149 file_descriptor = codecs.open(self.filename, "w", "utf-8")
151 # if it's marked private, chmod it appropriately
152 if self.filename in self.universe.private_files and oct(
153 stat.S_IMODE(os.stat(self.filename)[stat.ST_MODE])
155 os.chmod(self.filename, 0o0600)
157 # write it back sorted, instead of using configparser
158 sections = self.data.sections()
160 for section in sections:
161 file_descriptor.write("[" + section + "]\n")
162 options = self.data.options(section)
164 for option in options:
165 file_descriptor.write(
167 self.data.get(section, option) + "\n"
169 file_descriptor.write("\n")
171 # flush and close the file
172 file_descriptor.flush()
173 file_descriptor.close()
175 # unset the modified flag
176 self.modified = False
178 def is_writeable(self):
179 """Returns True if the __control__ read_only is False."""
180 return not self.data.has_option(
181 "__control__", "read_only"
182 ) or not self.data.getboolean(
183 "__control__", "read_only"
195 """Return an absolute file path based on configuration."""
197 # make sure to get rid of any surrounding quotes first thing
199 file_name = file_name.strip("\"'")
201 # this is all unnecessary if it's already absolute
202 if file_name and os.path.isabs(file_name):
203 return os.path.realpath(file_name)
205 # when no file name is specified, look for <argv[0]>.conf
207 file_name = os.path.basename(sys.argv[0]) + ".conf"
209 # if a universe was provided, try to get some defaults from there
215 ) and "internal:storage" in universe.contents:
216 storage = universe.categories["internal"]["storage"]
218 root_path = storage.get("root_path").strip("\"'")
220 search_path = storage.getlist("search_path")
222 default_dir = storage.get("default_dir").strip("\"'")
224 # if there's only one file loaded, try to work around a chicken<egg
225 elif hasattr(universe, "files") and len(
227 ) == 1 and not universe.files[
228 list(universe.files.keys())[0]].is_writeable():
229 data_file = universe.files[list(universe.files.keys())[0]].data
231 # try for a fallback default directory
232 if not default_dir and data_file.has_option(
236 default_dir = data_file.get(
241 # try for a fallback root path
242 if not root_path and data_file.has_option(
246 root_path = data_file.get(
251 # try for a fallback search path
252 if not search_path and data_file.has_option(
256 search_path = makelist(
257 data_file.get("internal:storage",
258 "search_path").strip("\"'")
261 # another fallback root path, this time from the universe startdir
262 if not root_path and hasattr(universe, "startdir"):
263 root_path = universe.startdir
265 # when no root path is specified, assume the current working directory
267 root_path = os.getcwd()
269 # otherwise, make sure it's absolute
270 elif not os.path.isabs(root_path):
271 root_path = os.path.realpath(root_path)
273 # if there's no search path, just use the root path and etc
275 search_path = [root_path, "etc"]
277 # work on a copy of the search path, to avoid modifying the caller's
279 search_path = search_path[:]
281 # if there's no default path, use the last element of the search path
283 default_dir = search_path[-1]
285 # if an existing file or directory reference was supplied, prepend it
287 relative = relative.strip("\"'")
288 if os.path.isdir(relative):
289 search_path = [relative] + search_path
291 search_path = [os.path.dirname(relative)] + search_path
293 # make the search path entries absolute and throw away any dupes
294 clean_search_path = []
295 for each_path in search_path:
296 each_path = each_path.strip("\"'")
297 if not os.path.isabs(each_path):
298 each_path = os.path.realpath(os.path.join(root_path, each_path))
299 if each_path not in clean_search_path:
300 clean_search_path.append(each_path)
302 # start hunting for the file now
303 for each_path in clean_search_path:
305 # if the file exists and is readable, we're done
306 if os.path.isfile(os.path.join(each_path, file_name)):
307 file_name = os.path.realpath(os.path.join(each_path, file_name))
310 # it didn't exist after all, so use the default path instead
311 if not os.path.isabs(file_name):
312 file_name = os.path.join(default_dir, file_name)
313 if not os.path.isabs(file_name):
314 file_name = os.path.join(root_path, file_name)
316 # and normalize it last thing before returning
317 file_name = os.path.realpath(file_name)
319 # normalize the resulting file path and hand it back
324 """Turn string into list type."""
325 if value[0] + value[-1] == "[]":
327 elif value[0] + value[-1] == "\"\"":
334 """Turn string into dict type."""
335 if value[0] + value[-1] == "{}":
337 elif value.find(":") > 0:
338 return eval("{" + value + "}")