~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/atomicfile.py

  • Committer: Martin Pool
  • Date: 2005-09-12 09:00:11 UTC
  • Revision ID: mbp@sourcefrog.net-20050912090011-97e81abfaeeb8948
- fix bug in Inventory.copy() 
  
  must copy inventory top-down so that directories are added before
  their children

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):
 
58
        """Close the file and move to final name."""
49
59
        import sys, os
50
60
        
 
61
        if self.closed:
 
62
            raise Exception('%r is already closed' % self)
 
63
 
 
64
        self.closed = True
51
65
        self.f.close()
 
66
        self.f = None
 
67
        
52
68
        if sys.platform == 'win32':
53
 
            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
                
54
77
        os.rename(self.tmpfilename, self.realfilename)
55
78
 
 
79
 
56
80
    def abort(self):
 
81
        """Discard temporary file without committing changes."""
57
82
        import os
 
83
 
 
84
        if self.closed:
 
85
            raise Exception('%r is already closed' % self)
 
86
 
 
87
        self.closed = True
58
88
        self.f.close()
 
89
        self.f = None
59
90
        os.remove(self.tmpfilename)
60
 
        
 
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)
61
102