~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/atomicfile.py

  • Committer: Martin Pool
  • Date: 2005-05-20 02:16:01 UTC
  • Revision ID: mbp@sourcefrog.net-20050520021601-d931cce5b66227a3
- bzr diff finds a branch from the first parameter,
  if any are given

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