Change utils.file.AtomicFile into a wrapper instead of a subclass.

This commit is contained in:
Valentin Lorentz 2012-08-04 17:01:36 +02:00
parent 174a5a4b1f
commit 9de7316f02

View File

@ -115,7 +115,7 @@ def chunks(fd, size):
## yield chunk ## yield chunk
## chunk = fd.read(size) ## chunk = fd.read(size)
class AtomicFile(file): class AtomicFile(object):
"""Used for files that need to be atomically written -- i.e., if there's a """Used for files that need to be atomically written -- i.e., if there's a
failure, the original file remains, unmodified. mode must be 'w' or 'wb'""" failure, the original file remains, unmodified. mode must be 'w' or 'wb'"""
class default(object): # Holder for values. class default(object): # Holder for values.
@ -152,18 +152,31 @@ class AtomicFile(file):
self.tempFilename = os.path.join(tmpDir, tempFilename) self.tempFilename = os.path.join(tmpDir, tempFilename)
# This doesn't work because of the uncollectable garbage effect. # This doesn't work because of the uncollectable garbage effect.
# self.__parent = super(AtomicFile, self) # self.__parent = super(AtomicFile, self)
super(AtomicFile, self).__init__(self.tempFilename, mode) self._fd = open(self.tempFilename, mode)
@property
def closed(self):
return self._fd.closed
def close(self):
return self._fd.close()
def write(self, data):
return self._fd.write(data)
def writelines(self, lines):
return self._fd.writelines(lines)
def rollback(self): def rollback(self):
if not self.closed: if not self.closed:
super(AtomicFile, self).close() self._fd.close()
if os.path.exists(self.tempFilename): if os.path.exists(self.tempFilename):
os.remove(self.tempFilename) os.remove(self.tempFilename)
self.rolledback = True self.rolledback = True
def close(self): def close(self):
if not self.rolledback: if not self.rolledback:
super(AtomicFile, self).close() self._fd.close()
# We don't mind writing an empty file if the file we're overwriting # We don't mind writing an empty file if the file we're overwriting
# doesn't exist. # doesn't exist.
newSize = os.path.getsize(self.tempFilename) newSize = os.path.getsize(self.tempFilename)