~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/atomicfile.py

  • Committer: Martin Pool
  • Date: 2005-05-11 08:01:27 UTC
  • Revision ID: mbp@sourcefrog.net-20050511080127-4829697fc2ac64f1
- put back support for running diff or status on 
  only selected files.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
 
18
18
 
19
 
from warnings import warn
20
 
from osutils import rename
21
 
import errno
22
 
 
23
 
class AtomicFile(object):
 
19
class AtomicFile:
24
20
    """A file that does an atomic-rename to move into place.
25
21
 
26
22
    This also causes hardlinks to break when it's written out.
40
36
                                             socket.gethostname())
41
37
        self.realfilename = filename
42
38
        
 
39
        self.f = open(self.tmpfilename, mode)
 
40
 
43
41
        if encoding:
44
42
            import codecs
45
 
            self.f = codecs.open(self.tmpfilename, mode, encoding)
46
 
        else:
47
 
            self.f = open(self.tmpfilename, mode)
48
 
 
 
43
            self.f = codecs.EncodedFile(self.f, encoding)
 
44
        
49
45
        self.write = self.f.write
50
 
        self.closed = False
51
 
 
52
 
 
53
 
    def __repr__(self):
54
 
        return '%s(%r)' % (self.__class__.__name__,
55
 
                           self.realfilename)
56
 
    
 
46
        self.closed = property(self.f.closed)
57
47
 
58
48
    def commit(self):
59
 
        """Close the file and move to final name."""
60
49
        import sys, os
61
50
        
62
 
        if self.closed:
63
 
            raise Exception('%r is already closed' % self)
64
 
 
65
 
        self.closed = True
66
51
        self.f.close()
67
 
        self.f = None
68
 
        
69
 
        try:
70
 
            stat = os.lstat(self.realfilename)
71
 
            os.chmod(self.tmpfilename, stat.st_mode)
72
 
        except OSError, e:
73
 
            if e.errno != errno.ENOENT:
74
 
                raise
75
 
        rename(self.tmpfilename, self.realfilename)
76
 
 
 
52
        if sys.platform == 'win32':
 
53
            os.remove(self.realfilename)
 
54
        os.rename(self.tmpfilename, self.realfilename)
77
55
 
78
56
    def abort(self):
79
 
        """Discard temporary file without committing changes."""
80
57
        import os
81
 
 
82
 
        if self.closed:
83
 
            raise Exception('%r is already closed' % self)
84
 
 
85
 
        self.closed = True
86
58
        self.f.close()
87
 
        self.f = None
88
59
        os.remove(self.tmpfilename)
89
 
 
90
 
 
91
 
    def close(self):
92
 
        """Discard the file unless already committed."""
93
 
        if not self.closed:
94
 
            self.abort()
95
 
 
96
 
 
97
 
    def __del__(self):
98
 
        if hasattr(self, 'closed') and not self.closed:
99
 
            warn("%r leaked" % self)
 
60
        
100
61