~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/hashcache.py

  • Committer: John Arbash Meinel
  • Author(s): Mark Hammond
  • Date: 2008-09-09 17:02:21 UTC
  • mto: This revision was merged to the branch mainline in revision 3697.
  • Revision ID: john@arbash-meinel.com-20080909170221-svim3jw2mrz0amp3
An updated transparent icon for bzr.

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
 
33
import sha
37
34
 
38
 
from bzrlib import (
39
 
    atomicfile,
40
 
    errors,
41
 
    filters as _mod_filters,
42
 
    osutils,
43
 
    trace,
44
 
    )
 
35
from bzrlib.osutils import sha_file, pathjoin, safe_unicode
 
36
from bzrlib.trace import mutter, warning
 
37
from bzrlib.atomicfile import AtomicFile
 
38
from bzrlib.errors import BzrError
45
39
 
46
40
 
47
41
FP_MTIME_COLUMN = 1
80
74
    hit_count
81
75
        number of times files have been retrieved from the cache, avoiding a
82
76
        re-read
83
 
 
 
77
        
84
78
    miss_count
85
79
        number of misses (times files have been completely re-read)
86
80
    """
87
81
    needs_write = False
88
82
 
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)
 
83
    def __init__(self, root, cache_file_name, mode=None):
 
84
        """Create a hash cache in base dir, and set the file mode to mode."""
 
85
        self.root = safe_unicode(root)
99
86
        self.root_utf8 = self.root.encode('utf8') # where is the filesystem encoding ?
100
87
        self.hit_count = 0
101
88
        self.miss_count = 0
105
92
        self.update_count = 0
106
93
        self._cache = {}
107
94
        self._mode = mode
108
 
        self._cache_file_name = osutils.safe_unicode(cache_file_name)
109
 
        self._filter_provider = content_filter_stack_provider
 
95
        self._cache_file_name = safe_unicode(cache_file_name)
110
96
 
111
97
    def cache_file_name(self):
112
98
        return self._cache_file_name
121
107
 
122
108
    def scan(self):
123
109
        """Scan all files and remove entries where the cache entry is obsolete.
124
 
 
 
110
        
125
111
        Obsolete entries are those where the file has been modified or deleted
126
 
        since the entry was inserted.
 
112
        since the entry was inserted.        
127
113
        """
128
114
        # FIXME optimisation opportunity, on linux [and check other oses]:
129
115
        # rather than iteritems order, stat in inode order.
130
116
        prep = [(ce[1][3], path, ce) for (path, ce) in self._cache.iteritems()]
131
117
        prep.sort()
132
 
 
 
118
        
133
119
        for inum, path, cache_entry in prep:
134
 
            abspath = osutils.pathjoin(self.root, path)
 
120
            abspath = pathjoin(self.root, path)
135
121
            fp = self._fingerprint(abspath)
136
122
            self.stat_count += 1
137
 
 
 
123
            
138
124
            cache_fp = cache_entry[1]
139
 
 
 
125
    
140
126
            if (not fp) or (cache_fp != fp):
141
127
                # not here or not a regular file anymore
142
128
                self.removed_count += 1
147
133
        """Return the sha1 of a file.
148
134
        """
149
135
        if path.__class__ is str:
150
 
            abspath = osutils.pathjoin(self.root_utf8, path)
 
136
            abspath = pathjoin(self.root_utf8, path)
151
137
        else:
152
 
            abspath = osutils.pathjoin(self.root, path)
 
138
            abspath = pathjoin(self.root, path)
153
139
        self.stat_count += 1
154
140
        file_fp = self._fingerprint(abspath, stat_value)
155
 
 
 
141
        
156
142
        if not file_fp:
157
143
            # not a regular file or not existing
158
144
            if path in self._cache:
159
145
                self.removed_count += 1
160
146
                self.needs_write = True
161
147
                del self._cache[path]
162
 
            return None
 
148
            return None        
163
149
 
164
150
        if path in self._cache:
165
151
            cache_sha1, cache_fp = self._cache[path]
171
157
            ## mutter("now = %s", time.time())
172
158
            self.hit_count += 1
173
159
            return cache_sha1
174
 
 
 
160
        
175
161
        self.miss_count += 1
176
162
 
177
163
        mode = file_fp[FP_MODE_COLUMN]
178
164
        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)
 
165
            digest = self._really_sha1_file(abspath)
184
166
        elif stat.S_ISLNK(mode):
185
 
            target = osutils.readlink(osutils.safe_unicode(abspath))
186
 
            digest = osutils.sha_string(target.encode('UTF-8'))
 
167
            digest = sha.new(os.readlink(abspath)).hexdigest()
187
168
        else:
188
 
            raise errors.BzrError("file %r: unknown file stat mode: %o"
189
 
                                  % (abspath, mode))
 
169
            raise BzrError("file %r: unknown file stat mode: %o"%(abspath,mode))
190
170
 
191
171
        # window of 3 seconds to allow for 2s resolution on windows,
192
172
        # unsynchronized file servers, etc.
219
199
            self._cache[path] = (digest, file_fp)
220
200
        return digest
221
201
 
222
 
    def _really_sha1_file(self, abspath, filters):
 
202
    def _really_sha1_file(self, abspath):
223
203
        """Calculate the SHA1 of a file by reading the full text"""
224
 
        return _mod_filters.internal_size_sha_file_byname(abspath, filters)[1]
225
 
 
 
204
        return sha_file(file(abspath, 'rb', buffering=65000))
 
205
        
226
206
    def write(self):
227
207
        """Write contents of cache to file."""
228
 
        outf = atomicfile.AtomicFile(self.cache_file_name(), 'wb',
229
 
                                     new_mode=self._mode)
 
208
        outf = AtomicFile(self.cache_file_name(), 'wb', new_mode=self._mode)
230
209
        try:
231
210
            outf.write(CACHE_HEADER)
232
211
 
249
228
 
250
229
        Overwrites existing cache.
251
230
 
252
 
        If the cache file has the wrong version marker, this just clears
 
231
        If the cache file has the wrong version marker, this just clears 
253
232
        the cache."""
254
233
        self._cache = {}
255
234
 
257
236
        try:
258
237
            inf = file(fn, 'rb', buffering=65000)
259
238
        except IOError, e:
260
 
            trace.mutter("failed to open %s: %s", fn, e)
 
239
            mutter("failed to open %s: %s", fn, e)
261
240
            # better write it now so it is valid
262
241
            self.needs_write = True
263
242
            return
264
243
 
265
244
        hdr = inf.readline()
266
245
        if hdr != CACHE_HEADER:
267
 
            trace.mutter('cache header marker not found at top of %s;'
268
 
                         ' discarding cache', fn)
 
246
            mutter('cache header marker not found at top of %s;'
 
247
                   ' discarding cache', fn)
269
248
            self.needs_write = True
270
249
            return
271
250
 
273
252
            pos = l.index('// ')
274
253
            path = l[:pos].decode('utf-8')
275
254
            if path in self._cache:
276
 
                trace.warning('duplicated path %r in cache' % path)
 
255
                warning('duplicated path %r in cache' % path)
277
256
                continue
278
257
 
279
258
            pos += 3
280
259
            fields = l[pos:].split(' ')
281
260
            if len(fields) != 7:
282
 
                trace.warning("bad line in hashcache: %r" % l)
 
261
                warning("bad line in hashcache: %r" % l)
283
262
                continue
284
263
 
285
264
            sha1 = fields[0]
286
265
            if len(sha1) != 40:
287
 
                trace.warning("bad sha1 in hashcache: %r" % sha1)
 
266
                warning("bad sha1 in hashcache: %r" % sha1)
288
267
                continue
289
268
 
290
269
            fp = tuple(map(long, fields[1:]))
291
270
 
292
271
            self._cache[path] = (sha1, fp)
293
272
 
294
 
        # GZ 2009-09-20: Should really use a try/finally block to ensure close
295
 
        inf.close()
296
 
 
297
273
        self.needs_write = False
298
274
 
299
275
    def _cutoff_time(self):
303
279
        undetectably modified and so can't be cached.
304
280
        """
305
281
        return int(time.time()) - 3
306
 
 
 
282
           
307
283
    def _fingerprint(self, abspath, stat_value=None):
308
284
        if stat_value is None:
309
285
            try:
316
292
        # we discard any high precision because it's not reliable; perhaps we
317
293
        # could do better on some systems?
318
294
        return (stat_value.st_size, long(stat_value.st_mtime),
319
 
                long(stat_value.st_ctime), stat_value.st_ino,
 
295
                long(stat_value.st_ctime), stat_value.st_ino, 
320
296
                stat_value.st_dev, stat_value.st_mode)