19
from warnings import warn
20
from osutils import rename
22
class AtomicFile(object):
20
23
"""A file that does an atomic-rename to move into place.
22
25
This also causes hardlinks to break when it's written out.
24
27
Open this as for a regular file, then use commit() to move into
25
28
place or abort() to cancel.
27
You may wish to wrap this in a codecs.EncodedFile to do unicode
30
An encoding can be specified; otherwise the default is ascii.
31
def __init__(self, filename, mode='wb'):
33
def __init__(self, filename, mode='wb', encoding=None):
32
34
if mode != 'wb' and mode != 'wt':
33
35
raise ValueError("invalid AtomicFile mode %r" % mode)
36
self.tmpfilename = '%s.tmp.%d.%s' % (filename, os.getpid(),
38
self.tmpfilename = '%s.%d.%s.tmp' % (filename, os.getpid(),
37
39
socket.gethostname())
38
40
self.realfilename = filename
40
self.f = open(self.tmpfilename, mode)
44
self.f = codecs.open(self.tmpfilename, mode, encoding)
46
self.f = open(self.tmpfilename, mode)
41
48
self.write = self.f.write
42
self.closed = property(f.closed)
53
return '%s(%r)' % (self.__class__.__name__,
58
"""Close the file and move to final name."""
62
raise Exception('%r is already closed' % self)
48
if sys.platform == 'win32':
49
os.remove(self.realfilename)
50
os.rename(self.tmpfilename, self.realfilename)
68
rename(self.tmpfilename, self.realfilename)
72
"""Discard temporary file without committing changes."""
76
raise Exception('%r is already closed' % self)
55
81
os.remove(self.tmpfilename)
85
"""Discard the file unless already committed."""
91
if hasattr(self, 'closed') and not self.closed:
92
warn("%r leaked" % self)