19
from warnings import warn
20
from osutils import rename
23
class AtomicFile(object):
24
20
"""A file that does an atomic-rename to move into place.
26
22
This also causes hardlinks to break when it's written out.
40
36
socket.gethostname())
41
37
self.realfilename = filename
39
self.f = open(self.tmpfilename, mode)
45
self.f = codecs.open(self.tmpfilename, mode, encoding)
47
self.f = open(self.tmpfilename, mode)
43
self.f = codecs.EncodedFile(self.f, encoding)
49
45
self.write = self.f.write
54
return '%s(%r)' % (self.__class__.__name__,
46
self.closed = property(self.f.closed)
59
"""Close the file and move to final name."""
63
raise Exception('%r is already closed' % self)
70
stat = os.lstat(self.realfilename)
71
os.chmod(self.tmpfilename, stat.st_mode)
73
if e.errno != errno.ENOENT:
75
rename(self.tmpfilename, self.realfilename)
52
if sys.platform == 'win32':
53
os.remove(self.realfilename)
54
os.rename(self.tmpfilename, self.realfilename)
79
"""Discard temporary file without committing changes."""
83
raise Exception('%r is already closed' % self)
88
59
os.remove(self.tmpfilename)
92
"""Discard the file unless already committed."""
98
if hasattr(self, 'closed') and not self.closed:
99
warn("%r leaked" % self)