~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/atomicfile.py

  • Committer: Martin Pool
  • Date: 2005-05-12 02:19:09 UTC
  • Revision ID: mbp@sourcefrog.net-20050512021909-acb201f8ffc52b41
doc

Show diffs side-by-side

added added

removed removed

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