This repository has been archived by the owner on Oct 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
mapper.py
312 lines (258 loc) · 9.57 KB
/
mapper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
"""Core object-file mapping functionality."""
import functools
from pprint import pformat
import logging
from . import common, diskutils, exceptions, types, settings
from .bases import Container
log = logging.getLogger(__name__)
def file_required(method):
"""Decorate methods that require the file to exist."""
@functools.wraps(method)
def wrapped(self, *args, **kwargs):
if self.deleted:
msg = "File deleted: {}".format(self.path)
raise exceptions.DeletedFileError(msg)
if self.missing and not settings.fake:
msg = "File missing: {}".format(self.path)
raise exceptions.MissingFileError(msg)
return method(self, *args, **kwargs)
return wrapped
def prevent_recursion(method):
"""Decorate methods to prevent indirect recursive calls."""
@functools.wraps(method)
def wrapped(self, *args, **kwargs):
# pylint: disable=protected-access
if self._activity:
return None
self._activity = True
result = method(self, *args, **kwargs)
self._activity = False
return result
return wrapped
def prefix(obj):
"""Prefix a string with a fake designator if enabled."""
fake = "(fake) " if settings.fake else ""
name = obj if isinstance(obj, str) else "'{}'".format(obj)
return fake + name
class Mapper:
"""Utility class to map an object's attributes to a file.
To start mapping attributes to a file:
create -> [empty] -> FILE
When getting an attribute:
FILE -> read -> [text] -> parse -> [dict] -> load -> ATTRIBUTES
When setting an attribute:
ATTRIBUTES -> save -> [dict] -> dump -> [text] -> write -> FILE
After the mapped file is no longer needed:
delete -> [null] -> FILE
"""
def __init__(self, obj, path, attrs, *,
auto_create=True, auto_save=True,
auto_track=False, auto_resolve=False):
self._obj = obj
self.path = path
self.attrs = attrs
self.auto_create = auto_create
self.auto_save = auto_save
self.auto_track = auto_track
self.auto_resolve = auto_resolve
self.exists = diskutils.exists(self.path)
self.deleted = False
self.auto_save_after_load = False
self._activity = False
self._timestamp = 0
self._fake = ""
def __str__(self):
return str(self.path)
@property
def missing(self):
return not self.exists
@property
def modified(self):
"""Determine if the file has been modified."""
if settings.fake:
changes = self._timestamp is not None
return changes
elif not self.exists:
return True
else:
# TODO: this raises an exception is the file is missing
was = self._timestamp
now = diskutils.stamp(self.path)
return was != now
@modified.setter
@file_required
def modified(self, changes):
"""Mark the file as modified if there are changes."""
if changes:
log.debug("Marked %s as modified", prefix(self))
self._timestamp = 0
else:
if settings.fake or self.path is None:
self._timestamp = None
else:
self._timestamp = diskutils.stamp(self.path)
log.debug("Marked %s as unmodified", prefix(self))
@property
def text(self):
"""Get file contents as a string."""
log.info("Getting contents of %s...", prefix(self))
if settings.fake:
text = self._fake
else:
text = self._read()
log.trace("Text read: \n%s", text[:-1])
return text
@text.setter
def text(self, text):
"""Set file contents from a string."""
log.info("Setting contents of %s...", prefix(self))
if settings.fake:
self._fake = text
else:
self._write(text)
log.trace("Text wrote: \n%s", text.rstrip())
self.modified = True
@property
def data(self):
"""Get the file values as a dictionary."""
text = self._read()
try:
data = diskutils.parse(text, self.path)
except ValueError as e:
if not self.auto_resolve:
raise e from None
log.debug(e)
log.warning("Clearing invalid contents: %s", self.path)
self._write("")
return {}
log.trace("Parsed data: \n%s", pformat(data))
return data
@data.setter
def data(self, data):
"""Set the file values from a dictionary."""
text = diskutils.dump(data, self.path)
self._write(text)
def create(self):
"""Create a new file for the object."""
log.info("Creating %s for %r...", prefix(self), self._obj)
if self.exists:
log.warning("Already created: %s", self)
return
if not settings.fake:
diskutils.touch(self.path)
self.exists = True
self.deleted = False
@file_required
@prevent_recursion
def load(self):
"""Update the object's mapped attributes from its file."""
log.info("Loading %r from %s...", self._obj, prefix(self))
# Update all attributes
attrs2 = self.attrs.copy()
for name, data in self.data.items():
attrs2.pop(name, None)
# Find a matching converter
try:
converter = self.attrs[name]
except KeyError:
if self.auto_track:
converter = types.match(name, data)
self.attrs[name] = converter
else:
msg = "Ignored unknown file attribute: %s = %r"
log.warning(msg, name, data)
continue
# Convert the parsed value to the attribute's final type
attr = getattr(self._obj, name, None)
if isinstance(attr, converter) and \
issubclass(converter, Container):
attr.update_value(data, auto_track=self.auto_track)
else:
log.trace("Converting attribute %r using %r", name, converter)
attr = converter.to_value(data)
setattr(self._obj, name, attr)
self._remap(attr, self)
log.trace("Value loaded: %s = %r", name, attr)
# Add missing attributes
for name, converter in attrs2.items():
try:
existing_attr = getattr(self._obj, name)
except AttributeError:
value = converter.create_default()
msg = "Default value for missing object attribute: %s = %r"
log.warning(msg, name, value)
setattr(self._obj, name, value)
self._remap(value, self)
else:
if issubclass(converter, Container):
if isinstance(existing_attr, converter):
pass # TODO: Update 'existing_attr' values to replace None values
else:
msg = "Converting container attribute %r using %r"
log.trace(msg, name, converter)
value = converter.create_default()
setattr(self._obj, name, value)
self._remap(value, self)
else:
pass # TODO: Figure out when this case occurs
# Set meta attributes
self.modified = False
def _remap(self, obj, root):
"""Attach mapper on nested attributes."""
if isinstance(obj, Container):
common.set_mapper(obj, root)
if isinstance(obj, dict):
for obj2 in obj.values():
self._remap(obj2, root)
else:
assert isinstance(obj, list)
for obj2 in obj:
self._remap(obj2, root)
@file_required
@prevent_recursion
def save(self):
"""Format and save the object's mapped attributes to its file."""
log.info("Saving %r to %s...", self._obj, prefix(self))
# Format the data items
data = self.attrs.__class__()
for name, converter in self.attrs.items():
try:
value = getattr(self._obj, name)
except AttributeError:
data2 = converter.to_data(None)
msg = "Default data for missing object attribute: %s = %r"
log.warning(msg, name, data2)
else:
data2 = converter.to_data(value)
log.trace("Data to save: %s = %r", name, data2)
data[name] = data2
# Save the formatted to disk
self.data = data
# Set meta attributes
self.modified = True
self.auto_save_after_load = self.auto_save
def delete(self):
"""Delete the object's file from the file system."""
if self.exists:
log.info("Deleting %s...", prefix(self))
diskutils.delete(self.path)
else:
log.warning("Already deleted: %s", self)
self.exists = False
self.deleted = True
@file_required
def _read(self):
"""Read text from the object's file."""
if settings.fake:
return self._fake
elif not self.exists:
return ""
else:
return diskutils.read(self.path)
@file_required
def _write(self, text):
"""Write text to the object's file."""
if settings.fake:
self._fake = text
else:
diskutils.write(text, self.path)