14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
from warnings import warn
21
from bzrlib.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.
31
27
An encoding can be specified; otherwise the default is ascii.
34
def __init__(self, filename, mode='wb', encoding=None, new_mode=None):
30
def __init__(self, filename, mode='wb', encoding=None):
35
31
if mode != 'wb' and mode != 'wt':
36
32
raise ValueError("invalid AtomicFile mode %r" % mode)
39
35
self.tmpfilename = '%s.%d.%s.tmp' % (filename, os.getpid(),
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
51
self._new_mode = new_mode
55
return '%s(%r)' % (self.__class__.__name__,
46
self.closed = property(self.f.closed)
60
"""Close the file and move to final name."""
63
raise Exception('%r is already closed' % self)
70
if self._new_mode is None:
71
self._new_mode = os.lstat(self.realfilename).st_mode
73
if e.errno != errno.ENOENT:
76
os.chmod(self.tmpfilename, self._new_mode)
78
rename(self.tmpfilename, self.realfilename)
52
if sys.platform == 'win32':
53
os.remove(self.realfilename)
54
os.rename(self.tmpfilename, self.realfilename)
82
"""Discard temporary file without committing changes."""
85
raise Exception('%r is already closed' % self)
90
59
os.remove(self.tmpfilename)
94
"""Discard the file unless already committed."""
100
if hasattr(self, 'closed') and not self.closed:
101
warn("%r leaked" % self)