~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/atomicfile.py

  • Committer: Martin Pool
  • Date: 2005-05-26 16:02:02 UTC
  • Revision ID: mbp@sourcefrog.net-20050526160202-355eeff057a8d659
- AtomicFile emits a warning if it is gc'd without being closed
- also use codecs.open rather than EncodedFile
- more checks in AtomicFile

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