~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/hashcache.py

  • Committer: Martin Pool
  • Date: 2005-09-12 09:50:44 UTC
  • Revision ID: mbp@sourcefrog.net-20050912095044-6acfdb5611729987
- no tests in bzrlib.fetch anymore

Show diffs side-by-side

added added

removed removed

Lines of Context:
30
30
CACHE_HEADER = "### bzr hashcache v5\n"
31
31
 
32
32
import os, stat, time
33
 
import sha
34
33
 
35
 
from bzrlib.osutils import sha_file, pathjoin, safe_unicode
 
34
from bzrlib.osutils import sha_file
36
35
from bzrlib.trace import mutter, warning
37
36
from bzrlib.atomicfile import AtomicFile
38
 
from bzrlib.errors import BzrError
39
 
 
40
 
 
41
 
FP_MTIME_COLUMN = 1
42
 
FP_CTIME_COLUMN = 2
43
 
FP_MODE_COLUMN = 5
 
37
 
 
38
 
 
39
 
44
40
 
45
41
def _fingerprint(abspath):
46
42
    try:
55
51
    # we discard any high precision because it's not reliable; perhaps we
56
52
    # could do better on some systems?
57
53
    return (fs.st_size, long(fs.st_mtime),
58
 
            long(fs.st_ctime), fs.st_ino, fs.st_dev, fs.st_mode)
 
54
            long(fs.st_ctime), fs.st_ino, fs.st_dev)
59
55
 
60
56
 
61
57
class HashCache(object):
94
90
    """
95
91
    needs_write = False
96
92
 
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)
 
93
    def __init__(self, basedir):
 
94
        self.basedir = basedir
100
95
        self.hit_count = 0
101
96
        self.miss_count = 0
102
97
        self.stat_count = 0
104
99
        self.removed_count = 0
105
100
        self.update_count = 0
106
101
        self._cache = {}
107
 
        self._mode = mode
108
 
        self._cache_file_name = safe_unicode(cache_file_name)
 
102
 
109
103
 
110
104
    def cache_file_name(self):
111
 
        return self._cache_file_name
 
105
        return os.sep.join([self.basedir, '.bzr', 'stat-cache'])
 
106
 
 
107
 
 
108
 
112
109
 
113
110
    def clear(self):
114
111
        """Discard all cached information.
118
115
            self.needs_write = True
119
116
            self._cache = {}
120
117
 
 
118
 
121
119
    def scan(self):
122
120
        """Scan all files and remove entries where the cache entry is obsolete.
123
121
        
124
122
        Obsolete entries are those where the file has been modified or deleted
125
123
        since the entry was inserted.        
126
124
        """
127
 
        # FIXME optimisation opportunity, on linux [and check other oses]:
128
 
        # rather than iteritems order, stat in inode order.
129
125
        prep = [(ce[1][3], path, ce) for (path, ce) in self._cache.iteritems()]
130
126
        prep.sort()
131
127
        
132
128
        for inum, path, cache_entry in prep:
133
 
            abspath = pathjoin(self.root, path)
 
129
            abspath = os.sep.join([self.basedir, path])
134
130
            fp = _fingerprint(abspath)
135
131
            self.stat_count += 1
136
132
            
143
139
                del self._cache[path]
144
140
 
145
141
 
 
142
 
146
143
    def get_sha1(self, path):
147
144
        """Return the sha1 of a file.
148
145
        """
149
 
        abspath = pathjoin(self.root, path)
 
146
        abspath = os.sep.join([self.basedir, path])
150
147
        self.stat_count += 1
151
148
        file_fp = _fingerprint(abspath)
152
149
        
168
165
            return cache_sha1
169
166
        
170
167
        self.miss_count += 1
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))
 
168
        digest = sha_file(file(abspath, 'rb', buffering=65000))
180
169
 
181
170
        now = int(time.time())
182
 
        if file_fp[FP_MTIME_COLUMN] >= now or file_fp[FP_CTIME_COLUMN] >= now:
 
171
        if file_fp[1] >= now or file_fp[2] >= now:
183
172
            # changed too recently; can't be cached.  we can
184
173
            # return the result and it could possibly be cached
185
174
            # 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.
194
175
            self.danger_count += 1 
195
176
            if cache_fp:
196
177
                self.removed_count += 1
200
181
            self.update_count += 1
201
182
            self.needs_write = True
202
183
            self._cache[path] = (digest, file_fp)
 
184
        
203
185
        return digest
204
186
        
 
187
 
 
188
 
 
189
 
205
190
    def write(self):
206
191
        """Write contents of cache to file."""
207
 
        outf = AtomicFile(self.cache_file_name(), 'wb', new_mode=self._mode)
 
192
        outf = AtomicFile(self.cache_file_name(), 'wb')
208
193
        try:
209
194
            print >>outf, CACHE_HEADER,
210
195
 
222
207
        finally:
223
208
            if not outf.closed:
224
209
                outf.abort()
 
210
        
 
211
 
225
212
 
226
213
    def read(self):
227
214
        """Reinstate cache from file.
236
223
        try:
237
224
            inf = file(fn, 'rb', buffering=65000)
238
225
        except IOError, e:
239
 
            mutter("failed to open %s: %s", fn, e)
 
226
            mutter("failed to open %s: %s" % (fn, e))
240
227
            # better write it now so it is valid
241
228
            self.needs_write = True
242
229
            return
244
231
 
245
232
        hdr = inf.readline()
246
233
        if hdr != CACHE_HEADER:
247
 
            mutter('cache header marker not found at top of %s;'
248
 
                   ' discarding cache', fn)
 
234
            mutter('cache header marker not found at top of %s; discarding cache'
 
235
                   % fn)
249
236
            self.needs_write = True
250
237
            return
251
238
 
258
245
 
259
246
            pos += 3
260
247
            fields = l[pos:].split(' ')
261
 
            if len(fields) != 7:
 
248
            if len(fields) != 6:
262
249
                warning("bad line in hashcache: %r" % l)
263
250
                continue
264
251