~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/hashcache.py

  • Committer: Martin Pool
  • Date: 2006-06-15 05:36:34 UTC
  • mto: This revision was merged to the branch mainline in revision 1797.
  • Revision ID: mbp@sourcefrog.net-20060615053634-4fd52ba691855659
Clean up many exception classes.

Errors indicating a user error are now shown with is_user_error on the
exception; use this rather than hardcoding a list of exceptions that should be
handled this way.

Exceptions now inherit from BzrNewException where possible to use consistent
formatting method.

Remove rather obsolete docstring test on Branch.missing_revisions.

Remove dead code from find_merge_base.


Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# (C) 2005 Canonical Ltd
 
1
# Copyright (C) 2005, 2006 by Canonical Ltd
2
2
 
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
30
30
CACHE_HEADER = "### bzr hashcache v5\n"
31
31
 
32
32
import os, stat, time
 
33
import sha
33
34
 
34
 
from bzrlib.osutils import sha_file
 
35
from bzrlib.osutils import sha_file, pathjoin, safe_unicode
35
36
from bzrlib.trace import mutter, warning
36
37
from bzrlib.atomicfile import AtomicFile
37
 
 
38
 
 
39
 
 
 
38
from bzrlib.errors import BzrError
 
39
 
 
40
 
 
41
FP_MTIME_COLUMN = 1
 
42
FP_CTIME_COLUMN = 2
 
43
FP_MODE_COLUMN = 5
40
44
 
41
45
def _fingerprint(abspath):
42
46
    try:
51
55
    # we discard any high precision because it's not reliable; perhaps we
52
56
    # could do better on some systems?
53
57
    return (fs.st_size, long(fs.st_mtime),
54
 
            long(fs.st_ctime), fs.st_ino, fs.st_dev)
 
58
            long(fs.st_ctime), fs.st_ino, fs.st_dev, fs.st_mode)
55
59
 
56
60
 
57
61
class HashCache(object):
90
94
    """
91
95
    needs_write = False
92
96
 
93
 
    def __init__(self, basedir):
94
 
        self.basedir = basedir
 
97
    def __init__(self, root, cache_file_name, mode=None):
 
98
        """Create a hash cache in base dir, and set the file mode to mode."""
 
99
        self.root = safe_unicode(root)
95
100
        self.hit_count = 0
96
101
        self.miss_count = 0
97
102
        self.stat_count = 0
99
104
        self.removed_count = 0
100
105
        self.update_count = 0
101
106
        self._cache = {}
102
 
 
 
107
        self._mode = mode
 
108
        self._cache_file_name = safe_unicode(cache_file_name)
103
109
 
104
110
    def cache_file_name(self):
105
 
        return os.sep.join([self.basedir, '.bzr', 'stat-cache'])
106
 
 
107
 
 
108
 
 
 
111
        return self._cache_file_name
109
112
 
110
113
    def clear(self):
111
114
        """Discard all cached information.
115
118
            self.needs_write = True
116
119
            self._cache = {}
117
120
 
118
 
 
119
121
    def scan(self):
120
122
        """Scan all files and remove entries where the cache entry is obsolete.
121
123
        
122
124
        Obsolete entries are those where the file has been modified or deleted
123
125
        since the entry was inserted.        
124
126
        """
 
127
        # FIXME optimisation opportunity, on linux [and check other oses]:
 
128
        # rather than iteritems order, stat in inode order.
125
129
        prep = [(ce[1][3], path, ce) for (path, ce) in self._cache.iteritems()]
126
130
        prep.sort()
127
131
        
128
132
        for inum, path, cache_entry in prep:
129
 
            abspath = os.sep.join([self.basedir, path])
 
133
            abspath = pathjoin(self.root, path)
130
134
            fp = _fingerprint(abspath)
131
135
            self.stat_count += 1
132
136
            
139
143
                del self._cache[path]
140
144
 
141
145
 
142
 
 
143
146
    def get_sha1(self, path):
144
147
        """Return the sha1 of a file.
145
148
        """
146
 
        abspath = os.sep.join([self.basedir, path])
 
149
        abspath = pathjoin(self.root, path)
147
150
        self.stat_count += 1
148
151
        file_fp = _fingerprint(abspath)
149
152
        
165
168
            return cache_sha1
166
169
        
167
170
        self.miss_count += 1
168
 
        digest = sha_file(file(abspath, 'rb', buffering=65000))
 
171
 
 
172
 
 
173
        mode = file_fp[FP_MODE_COLUMN]
 
174
        if stat.S_ISREG(mode):
 
175
            digest = sha_file(file(abspath, 'rb', buffering=65000))
 
176
        elif stat.S_ISLNK(mode):
 
177
            digest = sha.new(os.readlink(abspath)).hexdigest()
 
178
        else:
 
179
            raise BzrError("file %r: unknown file stat mode: %o"%(abspath,mode))
169
180
 
170
181
        now = int(time.time())
171
 
        if file_fp[1] >= now or file_fp[2] >= now:
 
182
        if file_fp[FP_MTIME_COLUMN] >= now or file_fp[FP_CTIME_COLUMN] >= now:
172
183
            # changed too recently; can't be cached.  we can
173
184
            # return the result and it could possibly be cached
174
185
            # next time.
 
186
            #
 
187
            # the point is that we only want to cache when we are sure that any
 
188
            # subsequent modifications of the file can be detected.  If a
 
189
            # modification neither changes the inode, the device, the size, nor
 
190
            # the mode, then we can only distinguish it by time; therefore we
 
191
            # need to let sufficient time elapse before we may cache this entry
 
192
            # again.  If we didn't do this, then, for example, a very quick 1
 
193
            # byte replacement in the file might go undetected.
175
194
            self.danger_count += 1 
176
195
            if cache_fp:
177
196
                self.removed_count += 1
181
200
            self.update_count += 1
182
201
            self.needs_write = True
183
202
            self._cache[path] = (digest, file_fp)
184
 
        
185
203
        return digest
186
204
        
187
 
 
188
 
 
189
 
 
190
205
    def write(self):
191
206
        """Write contents of cache to file."""
192
 
        outf = AtomicFile(self.cache_file_name(), 'wb')
 
207
        outf = AtomicFile(self.cache_file_name(), 'wb', new_mode=self._mode)
193
208
        try:
194
209
            print >>outf, CACHE_HEADER,
195
210
 
201
216
                for fld in c[1]:
202
217
                    print >>outf, "%d" % fld,
203
218
                print >>outf
204
 
 
205
219
            outf.commit()
206
220
            self.needs_write = False
 
221
            mutter("write hash cache: %s hits=%d misses=%d stat=%d recent=%d updates=%d",
 
222
                   self.cache_file_name(), self.hit_count, self.miss_count,
 
223
                   self.stat_count,
 
224
                   self.danger_count, self.update_count)
207
225
        finally:
208
226
            if not outf.closed:
209
227
                outf.abort()
210
 
        
211
 
 
212
228
 
213
229
    def read(self):
214
230
        """Reinstate cache from file.
223
239
        try:
224
240
            inf = file(fn, 'rb', buffering=65000)
225
241
        except IOError, e:
226
 
            mutter("failed to open %s: %s" % (fn, e))
 
242
            mutter("failed to open %s: %s", fn, e)
227
243
            # better write it now so it is valid
228
244
            self.needs_write = True
229
245
            return
231
247
 
232
248
        hdr = inf.readline()
233
249
        if hdr != CACHE_HEADER:
234
 
            mutter('cache header marker not found at top of %s; discarding cache'
235
 
                   % fn)
 
250
            mutter('cache header marker not found at top of %s;'
 
251
                   ' discarding cache', fn)
236
252
            self.needs_write = True
237
253
            return
238
254
 
245
261
 
246
262
            pos += 3
247
263
            fields = l[pos:].split(' ')
248
 
            if len(fields) != 6:
 
264
            if len(fields) != 7:
249
265
                warning("bad line in hashcache: %r" % l)
250
266
                continue
251
267