~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/hashcache.py

  • Committer: Jelmer Vernooij
  • Date: 2015-11-15 02:30:05 UTC
  • mto: This revision was merged to the branch mainline in revision 6609.
  • Revision ID: jelmer@jelmer.uk-20151115023005-fcfi763b5eu1ne2o
Fix auodoc_rstx when running with LANG=C.

Show diffs side-by-side

added added

removed removed

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