1
# Copyright (C) 2004, 2005 by Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23
from warnings import warn
25
from bzrlib.osutils import rename
27
# not forksafe - but we dont fork.
30
class AtomicFile(object):
31
"""A file that does an atomic-rename to move into place.
33
This also causes hardlinks to break when it's written out.
35
Open this as for a regular file, then use commit() to move into
36
place or abort() to cancel.
38
An encoding can be specified; otherwise the default is ascii.
41
__slots__ = ['closed', 'f', 'tmpfilename', 'realfilename', 'write']
43
def __init__(self, filename, mode='wb', new_mode=0666):
45
assert mode in ('wb', 'wt'), \
46
"invalid AtomicFile mode %r" % mode
49
#self.tmpfilename = '%s.%d.%s.tmp' % (filename, os.getpid(),
50
# socket.gethostname())
52
# This is 'broken' on NFS: it wmay collide with another NFS client.
53
# however, we use this to write files within a directory that we have
54
# locked, so it being racy on NFS is not a concern. The only other
55
# files we use this for are .bzr.ignore, which can race anyhow.
56
self.tmpfilename = '%s.%d.tmp' % (filename, _pid)
58
self.realfilename = filename
60
# Use a low level fd operation to avoid chmodding later.
61
fd = os.open(self.tmpfilename, os.O_EXCL | os.O_CREAT | os.O_WRONLY,
63
# open a normal python file to get the text vs binary support needed
67
self.f = os.fdopen(fd, mode)
72
self.write = self.f.write
75
return '%s(%r)' % (self.__class__.__name__,
79
"""Close the file and move to final name."""
81
raise Exception('%r is already closed' % self)
86
rename(self.tmpfilename, self.realfilename)
89
"""Discard temporary file without committing changes."""
92
raise Exception('%r is already closed' % self)
97
os.remove(self.tmpfilename)
100
"""Discard the file unless already committed."""
101
if self.f is not None:
105
if self.f is not None:
106
warn("%r leaked" % self)