~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/atomicfile.py

  • Committer: Martin Pool
  • Date: 2005-06-28 05:33:40 UTC
  • Revision ID: mbp@sourcefrog.net-20050628053340-ea73b03fbcde9c46
- Remove XMLMixin class in favour of simple pack_xml, unpack_xml functions
  called as needed.  

- Avoid importing xml and ElementTree library unless needed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
 
18
18
 
19
 
class AtomicFile:
 
19
from warnings import warn
 
20
 
 
21
 
 
22
class AtomicFile(object):
20
23
    """A file that does an atomic-rename to move into place.
21
24
 
22
25
    This also causes hardlinks to break when it's written out.
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
 
 
64
        self.closed = True
52
65
        self.f.close()
 
66
        self.f = None
 
67
        
53
68
        if sys.platform == 'win32':
54
 
            os.remove(self.realfilename)
 
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
                
55
77
        os.rename(self.tmpfilename, self.realfilename)
56
78
 
 
79
 
57
80
    def abort(self):
58
81
        """Discard temporary file without committing changes."""
59
82
        import os
 
83
 
 
84
        if self.closed:
 
85
            raise Exception('%r is already closed' % self)
 
86
 
 
87
        self.closed = True
60
88
        self.f.close()
 
89
        self.f = None
61
90
        os.remove(self.tmpfilename)
62
91
 
 
92
 
63
93
    def close(self):
64
94
        """Discard the file unless already committed."""
65
95
        if not self.closed:
66
96
            self.abort()
67
 
        
 
97
 
 
98
 
 
99
    def __del__(self):
 
100
        if not self.closed:
 
101
            warn("%r leaked" % self)
68
102