~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/hashcache.py

  • Committer: Martin Pool
  • Date: 2009-01-13 03:06:36 UTC
  • mfrom: (3932.2.3 1.11)
  • mto: This revision was merged to the branch mainline in revision 3937.
  • Revision ID: mbp@sourcefrog.net-20090113030636-dqx4t8yaaqgdvam5
MergeĀ 1.11rc1

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006 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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
 
 
17
 
from __future__ import absolute_import
18
 
 
19
 
# TODO: Up-front, stat all files in order and remove those which are deleted or
20
 
# out-of-date.  Don't actually re-read them until they're needed.  That ought
21
 
# to bring all the inodes into core so that future stats to them are fast, and
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
# TODO: Up-front, stat all files in order and remove those which are deleted or 
 
18
# out-of-date.  Don't actually re-read them until they're needed.  That ought 
 
19
# to bring all the inodes into core so that future stats to them are fast, and 
22
20
# it preserves the nice property that any caller will always get up-to-date
23
21
# data except in unavoidable cases.
24
22
 
31
29
 
32
30
CACHE_HEADER = "### bzr hashcache v5\n"
33
31
 
34
 
import os
35
 
import stat
36
 
import time
 
32
import os, stat, time
37
33
 
38
 
from bzrlib import (
39
 
    atomicfile,
40
 
    errors,
41
 
    filters as _mod_filters,
42
 
    osutils,
43
 
    trace,
44
 
    )
 
34
from bzrlib.osutils import sha_file, sha_string, pathjoin, safe_unicode
 
35
from bzrlib.trace import mutter, warning
 
36
from bzrlib.atomicfile import AtomicFile
 
37
from bzrlib.errors import BzrError
45
38
 
46
39
 
47
40
FP_MTIME_COLUMN = 1
80
73
    hit_count
81
74
        number of times files have been retrieved from the cache, avoiding a
82
75
        re-read
83
 
 
 
76
        
84
77
    miss_count
85
78
        number of misses (times files have been completely re-read)
86
79
    """
87
80
    needs_write = False
88
81
 
89
 
    def __init__(self, root, cache_file_name, mode=None,
90
 
            content_filter_stack_provider=None):
91
 
        """Create a hash cache in base dir, and set the file mode to mode.
92
 
 
93
 
        :param content_filter_stack_provider: a function that takes a
94
 
            path (relative to the top of the tree) and a file-id as
95
 
            parameters and returns a stack of ContentFilters.
96
 
            If None, no content filtering is performed.
97
 
        """
98
 
        self.root = osutils.safe_unicode(root)
 
82
    def __init__(self, root, cache_file_name, mode=None):
 
83
        """Create a hash cache in base dir, and set the file mode to mode."""
 
84
        self.root = safe_unicode(root)
99
85
        self.root_utf8 = self.root.encode('utf8') # where is the filesystem encoding ?
100
86
        self.hit_count = 0
101
87
        self.miss_count = 0
105
91
        self.update_count = 0
106
92
        self._cache = {}
107
93
        self._mode = mode
108
 
        self._cache_file_name = osutils.safe_unicode(cache_file_name)
109
 
        self._filter_provider = content_filter_stack_provider
 
94
        self._cache_file_name = safe_unicode(cache_file_name)
110
95
 
111
96
    def cache_file_name(self):
112
97
        return self._cache_file_name
121
106
 
122
107
    def scan(self):
123
108
        """Scan all files and remove entries where the cache entry is obsolete.
124
 
 
 
109
        
125
110
        Obsolete entries are those where the file has been modified or deleted
126
 
        since the entry was inserted.
 
111
        since the entry was inserted.        
127
112
        """
128
113
        # FIXME optimisation opportunity, on linux [and check other oses]:
129
114
        # rather than iteritems order, stat in inode order.
130
115
        prep = [(ce[1][3], path, ce) for (path, ce) in self._cache.iteritems()]
131
116
        prep.sort()
132
 
 
 
117
        
133
118
        for inum, path, cache_entry in prep:
134
 
            abspath = osutils.pathjoin(self.root, path)
 
119
            abspath = pathjoin(self.root, path)
135
120
            fp = self._fingerprint(abspath)
136
121
            self.stat_count += 1
137
 
 
 
122
            
138
123
            cache_fp = cache_entry[1]
139
 
 
 
124
    
140
125
            if (not fp) or (cache_fp != fp):
141
126
                # not here or not a regular file anymore
142
127
                self.removed_count += 1
147
132
        """Return the sha1 of a file.
148
133
        """
149
134
        if path.__class__ is str:
150
 
            abspath = osutils.pathjoin(self.root_utf8, path)
 
135
            abspath = pathjoin(self.root_utf8, path)
151
136
        else:
152
 
            abspath = osutils.pathjoin(self.root, path)
 
137
            abspath = pathjoin(self.root, path)
153
138
        self.stat_count += 1
154
139
        file_fp = self._fingerprint(abspath, stat_value)
155
 
 
 
140
        
156
141
        if not file_fp:
157
142
            # not a regular file or not existing
158
143
            if path in self._cache:
159
144
                self.removed_count += 1
160
145
                self.needs_write = True
161
146
                del self._cache[path]
162
 
            return None
 
147
            return None        
163
148
 
164
149
        if path in self._cache:
165
150
            cache_sha1, cache_fp = self._cache[path]
171
156
            ## mutter("now = %s", time.time())
172
157
            self.hit_count += 1
173
158
            return cache_sha1
174
 
 
 
159
        
175
160
        self.miss_count += 1
176
161
 
177
162
        mode = file_fp[FP_MODE_COLUMN]
178
163
        if stat.S_ISREG(mode):
179
 
            if self._filter_provider is None:
180
 
                filters = []
181
 
            else:
182
 
                filters = self._filter_provider(path=path, file_id=None)
183
 
            digest = self._really_sha1_file(abspath, filters)
 
164
            digest = self._really_sha1_file(abspath)
184
165
        elif stat.S_ISLNK(mode):
185
 
            target = osutils.readlink(osutils.safe_unicode(abspath))
186
 
            digest = osutils.sha_string(target.encode('UTF-8'))
 
166
            digest = sha_string(os.readlink(abspath))
187
167
        else:
188
 
            raise errors.BzrError("file %r: unknown file stat mode: %o"
189
 
                                  % (abspath, mode))
 
168
            raise BzrError("file %r: unknown file stat mode: %o"%(abspath,mode))
190
169
 
191
170
        # window of 3 seconds to allow for 2s resolution on windows,
192
171
        # unsynchronized file servers, etc.
219
198
            self._cache[path] = (digest, file_fp)
220
199
        return digest
221
200
 
222
 
    def _really_sha1_file(self, abspath, filters):
 
201
    def _really_sha1_file(self, abspath):
223
202
        """Calculate the SHA1 of a file by reading the full text"""
224
 
        return _mod_filters.internal_size_sha_file_byname(abspath, filters)[1]
225
 
 
 
203
        return sha_file(file(abspath, 'rb', buffering=65000))
 
204
        
226
205
    def write(self):
227
206
        """Write contents of cache to file."""
228
 
        outf = atomicfile.AtomicFile(self.cache_file_name(), 'wb',
229
 
                                     new_mode=self._mode)
 
207
        outf = AtomicFile(self.cache_file_name(), 'wb', new_mode=self._mode)
230
208
        try:
231
209
            outf.write(CACHE_HEADER)
232
210
 
249
227
 
250
228
        Overwrites existing cache.
251
229
 
252
 
        If the cache file has the wrong version marker, this just clears
 
230
        If the cache file has the wrong version marker, this just clears 
253
231
        the cache."""
254
232
        self._cache = {}
255
233
 
257
235
        try:
258
236
            inf = file(fn, 'rb', buffering=65000)
259
237
        except IOError, e:
260
 
            trace.mutter("failed to open %s: %s", fn, e)
 
238
            mutter("failed to open %s: %s", fn, e)
261
239
            # better write it now so it is valid
262
240
            self.needs_write = True
263
241
            return
264
242
 
265
243
        hdr = inf.readline()
266
244
        if hdr != CACHE_HEADER:
267
 
            trace.mutter('cache header marker not found at top of %s;'
268
 
                         ' discarding cache', fn)
 
245
            mutter('cache header marker not found at top of %s;'
 
246
                   ' discarding cache', fn)
269
247
            self.needs_write = True
270
248
            return
271
249
 
273
251
            pos = l.index('// ')
274
252
            path = l[:pos].decode('utf-8')
275
253
            if path in self._cache:
276
 
                trace.warning('duplicated path %r in cache' % path)
 
254
                warning('duplicated path %r in cache' % path)
277
255
                continue
278
256
 
279
257
            pos += 3
280
258
            fields = l[pos:].split(' ')
281
259
            if len(fields) != 7:
282
 
                trace.warning("bad line in hashcache: %r" % l)
 
260
                warning("bad line in hashcache: %r" % l)
283
261
                continue
284
262
 
285
263
            sha1 = fields[0]
286
264
            if len(sha1) != 40:
287
 
                trace.warning("bad sha1 in hashcache: %r" % sha1)
 
265
                warning("bad sha1 in hashcache: %r" % sha1)
288
266
                continue
289
267
 
290
268
            fp = tuple(map(long, fields[1:]))
291
269
 
292
270
            self._cache[path] = (sha1, fp)
293
271
 
294
 
        # GZ 2009-09-20: Should really use a try/finally block to ensure close
295
 
        inf.close()
296
 
 
297
272
        self.needs_write = False
298
273
 
299
274
    def _cutoff_time(self):
303
278
        undetectably modified and so can't be cached.
304
279
        """
305
280
        return int(time.time()) - 3
306
 
 
 
281
           
307
282
    def _fingerprint(self, abspath, stat_value=None):
308
283
        if stat_value is None:
309
284
            try:
316
291
        # we discard any high precision because it's not reliable; perhaps we
317
292
        # could do better on some systems?
318
293
        return (stat_value.st_size, long(stat_value.st_mtime),
319
 
                long(stat_value.st_ctime), stat_value.st_ino,
 
294
                long(stat_value.st_ctime), stat_value.st_ino, 
320
295
                stat_value.st_dev, stat_value.st_mode)