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.
28
24
Open this as for a regular file, then use commit() to move into
29
25
place or abort() to cancel.
31
An encoding can be specified; otherwise the default is ascii.
27
You may wish to wrap this in a codecs.EncodedFile to do unicode
34
def __init__(self, filename, mode='wb', encoding=None):
31
def __init__(self, filename, mode='wb'):
35
32
if mode != 'wb' and mode != 'wt':
36
33
raise ValueError("invalid AtomicFile mode %r" % mode)
39
self.tmpfilename = '%s.%d.%s.tmp' % (filename, os.getpid(),
36
self.tmpfilename = '%s.tmp.%d.%s' % (filename, os.getpid(),
40
37
socket.gethostname())
41
38
self.realfilename = filename
45
self.f = codecs.open(self.tmpfilename, mode, encoding)
47
self.f = open(self.tmpfilename, mode)
40
self.f = open(self.tmpfilename, mode)
49
41
self.write = self.f.write
54
return '%s(%r)' % (self.__class__.__name__,
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)
47
if sys.platform == 'win32':
48
os.remove(self.realfilename)
49
os.rename(self.tmpfilename, self.realfilename)
79
"""Discard temporary file without committing changes."""
83
raise Exception('%r is already closed' % self)
88
54
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)