/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/hashcache.py

  • Committer: Robert Collins
  • Date: 2007-04-19 02:27:44 UTC
  • mto: This revision was merged to the branch mainline in revision 2426.
  • Revision ID: robertc@robertcollins.net-20070419022744-pfdqz42kp1wizh43
``make docs`` now creates a man page at ``man1/bzr.1`` fixing bug 107388.
(Robert Collins)

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
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
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
 
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 
20
20
# it preserves the nice property that any caller will always get up-to-date
21
21
# data except in unavoidable cases.
22
22
 
26
26
# TODO: Perhaps use a Python pickle instead of a text file; might be faster.
27
27
 
28
28
 
29
 
CACHE_HEADER = b"### bzr hashcache v5\n"
30
 
 
31
 
import os
32
 
import stat
33
 
import time
34
 
 
35
 
from . import (
36
 
    atomicfile,
37
 
    errors,
38
 
    filters as _mod_filters,
39
 
    osutils,
40
 
    trace,
41
 
    )
 
29
 
 
30
CACHE_HEADER = "### bzr hashcache v5\n"
 
31
 
 
32
import os, stat, time
 
33
import sha
 
34
 
 
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
42
39
 
43
40
 
44
41
FP_MTIME_COLUMN = 1
46
43
FP_MODE_COLUMN = 5
47
44
 
48
45
 
 
46
 
49
47
class HashCache(object):
50
48
    """Cache for looking up file SHA-1.
51
49
 
76
74
    hit_count
77
75
        number of times files have been retrieved from the cache, avoiding a
78
76
        re-read
79
 
 
 
77
        
80
78
    miss_count
81
79
        number of misses (times files have been completely re-read)
82
80
    """
83
81
    needs_write = False
84
82
 
85
 
    def __init__(self, root, cache_file_name, mode=None,
86
 
                 content_filter_stack_provider=None):
87
 
        """Create a hash cache in base dir, and set the file mode to mode.
88
 
 
89
 
        :param content_filter_stack_provider: a function that takes a
90
 
            path (relative to the top of the tree) and a file-id as
91
 
            parameters and returns a stack of ContentFilters.
92
 
            If None, no content filtering is performed.
93
 
        """
94
 
        if not isinstance(root, str):
95
 
            raise ValueError("Base dir for hashcache must be text")
96
 
        self.root = 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)
 
86
        self.root_utf8 = self.root.encode('utf8') # where is the filesystem encoding ?
97
87
        self.hit_count = 0
98
88
        self.miss_count = 0
99
89
        self.stat_count = 0
102
92
        self.update_count = 0
103
93
        self._cache = {}
104
94
        self._mode = mode
105
 
        self._cache_file_name = cache_file_name
106
 
        self._filter_provider = content_filter_stack_provider
 
95
        self._cache_file_name = safe_unicode(cache_file_name)
107
96
 
108
97
    def cache_file_name(self):
109
98
        return self._cache_file_name
118
107
 
119
108
    def scan(self):
120
109
        """Scan all files and remove entries where the cache entry is obsolete.
121
 
 
 
110
        
122
111
        Obsolete entries are those where the file has been modified or deleted
123
 
        since the entry was inserted.
 
112
        since the entry was inserted.        
124
113
        """
125
 
        # Stat in inode order as optimisation for at least linux.
126
 
        def inode_order(path_and_cache):
127
 
            return path_and_cache[1][1][3]
128
 
        for path, cache_val in sorted(self._cache.items(), key=inode_order):
129
 
            abspath = osutils.pathjoin(self.root, path)
 
114
        # FIXME optimisation opportunity, on linux [and check other oses]:
 
115
        # rather than iteritems order, stat in inode order.
 
116
        prep = [(ce[1][3], path, ce) for (path, ce) in self._cache.iteritems()]
 
117
        prep.sort()
 
118
        
 
119
        for inum, path, cache_entry in prep:
 
120
            abspath = pathjoin(self.root, path)
130
121
            fp = self._fingerprint(abspath)
131
122
            self.stat_count += 1
132
 
 
133
 
            if not fp or cache_val[1] != fp:
 
123
            
 
124
            cache_fp = cache_entry[1]
 
125
    
 
126
            if (not fp) or (cache_fp != fp):
134
127
                # not here or not a regular file anymore
135
128
                self.removed_count += 1
136
129
                self.needs_write = True
139
132
    def get_sha1(self, path, stat_value=None):
140
133
        """Return the sha1 of a file.
141
134
        """
142
 
        abspath = osutils.pathjoin(self.root, path)
 
135
        if path.__class__ is str:
 
136
            abspath = pathjoin(self.root_utf8, path)
 
137
        else:
 
138
            abspath = pathjoin(self.root, path)
143
139
        self.stat_count += 1
144
140
        file_fp = self._fingerprint(abspath, stat_value)
145
 
 
 
141
        
146
142
        if not file_fp:
147
143
            # not a regular file or not existing
148
144
            if path in self._cache:
149
145
                self.removed_count += 1
150
146
                self.needs_write = True
151
147
                del self._cache[path]
152
 
            return None
 
148
            return None        
153
149
 
154
150
        if path in self._cache:
155
151
            cache_sha1, cache_fp = self._cache[path]
157
153
            cache_sha1, cache_fp = None, None
158
154
 
159
155
        if cache_fp == file_fp:
 
156
            ## mutter("hashcache hit for %s %r -> %s", path, file_fp, cache_sha1)
 
157
            ## mutter("now = %s", time.time())
160
158
            self.hit_count += 1
161
159
            return cache_sha1
162
 
 
 
160
        
163
161
        self.miss_count += 1
164
162
 
165
163
        mode = file_fp[FP_MODE_COLUMN]
166
164
        if stat.S_ISREG(mode):
167
 
            if self._filter_provider is None:
168
 
                filters = []
169
 
            else:
170
 
                filters = self._filter_provider(path=path)
171
 
            digest = self._really_sha1_file(abspath, filters)
 
165
            digest = self._really_sha1_file(abspath)
172
166
        elif stat.S_ISLNK(mode):
173
 
            target = osutils.readlink(abspath)
174
 
            digest = osutils.sha_string(target.encode('UTF-8'))
 
167
            digest = sha.new(os.readlink(abspath)).hexdigest()
175
168
        else:
176
 
            raise errors.BzrError("file %r: unknown file stat mode: %o"
177
 
                                  % (abspath, mode))
 
169
            raise BzrError("file %r: unknown file stat mode: %o"%(abspath,mode))
178
170
 
179
171
        # window of 3 seconds to allow for 2s resolution on windows,
180
172
        # unsynchronized file servers, etc.
199
191
                self.needs_write = True
200
192
                del self._cache[path]
201
193
        else:
202
 
            # mutter('%r added to cache: now=%f, mtime=%d, ctime=%d',
 
194
            ## mutter('%r added to cache: now=%f, mtime=%d, ctime=%d',
203
195
            ##        path, time.time(), file_fp[FP_MTIME_COLUMN],
204
 
            # file_fp[FP_CTIME_COLUMN])
 
196
            ##        file_fp[FP_CTIME_COLUMN])
205
197
            self.update_count += 1
206
198
            self.needs_write = True
207
199
            self._cache[path] = (digest, file_fp)
208
200
        return digest
209
201
 
210
 
    def _really_sha1_file(self, abspath, filters):
 
202
    def _really_sha1_file(self, abspath):
211
203
        """Calculate the SHA1 of a file by reading the full text"""
212
 
        return _mod_filters.internal_size_sha_file_byname(abspath, filters)[1]
213
 
 
 
204
        return sha_file(file(abspath, 'rb', buffering=65000))
 
205
        
214
206
    def write(self):
215
207
        """Write contents of cache to file."""
216
 
        with atomicfile.AtomicFile(self.cache_file_name(), 'wb',
217
 
                                   new_mode=self._mode) as outf:
 
208
        outf = AtomicFile(self.cache_file_name(), 'wb', new_mode=self._mode)
 
209
        try:
218
210
            outf.write(CACHE_HEADER)
219
211
 
220
 
            for path, c in self._cache.items():
221
 
                line_info = [path.encode('utf-8'), b'// ', c[0], b' ']
222
 
                line_info.append(b'%d %d %d %d %d %d' % c[1])
223
 
                line_info.append(b'\n')
224
 
                outf.write(b''.join(line_info))
 
212
            for path, c  in self._cache.iteritems():
 
213
                assert '//' not in path, path
 
214
                line_info = [path.encode('utf-8'), '// ', c[0], ' ']
 
215
                line_info.append(' '.join([str(fld) for fld in c[1]]))
 
216
                line_info.append('\n')
 
217
                outf.write(''.join(line_info))
 
218
            outf.commit()
225
219
            self.needs_write = False
226
 
            # mutter("write hash cache: %s hits=%d misses=%d stat=%d recent=%d updates=%d",
227
 
            #        self.cache_file_name(), self.hit_count, self.miss_count,
228
 
            # self.stat_count,
229
 
            # self.danger_count, self.update_count)
 
220
            ## mutter("write hash cache: %s hits=%d misses=%d stat=%d recent=%d updates=%d",
 
221
            ##        self.cache_file_name(), self.hit_count, self.miss_count,
 
222
            ##        self.stat_count,
 
223
            ##        self.danger_count, self.update_count)
 
224
        finally:
 
225
            outf.close()
230
226
 
231
227
    def read(self):
232
228
        """Reinstate cache from file.
233
229
 
234
230
        Overwrites existing cache.
235
231
 
236
 
        If the cache file has the wrong version marker, this just clears
 
232
        If the cache file has the wrong version marker, this just clears 
237
233
        the cache."""
238
234
        self._cache = {}
239
235
 
240
236
        fn = self.cache_file_name()
241
237
        try:
242
 
            inf = open(fn, 'rb', buffering=65000)
243
 
        except IOError as e:
244
 
            trace.mutter("failed to open %s: %s", fn, str(e))
 
238
            inf = file(fn, 'rb', buffering=65000)
 
239
        except IOError, e:
 
240
            mutter("failed to open %s: %s", fn, e)
245
241
            # better write it now so it is valid
246
242
            self.needs_write = True
247
243
            return
248
244
 
249
 
        with inf:
250
 
            hdr = inf.readline()
251
 
            if hdr != CACHE_HEADER:
252
 
                trace.mutter('cache header marker not found at top of %s;'
253
 
                             ' discarding cache', fn)
254
 
                self.needs_write = True
255
 
                return
256
 
 
257
 
            for l in inf:
258
 
                pos = l.index(b'// ')
259
 
                path = l[:pos].decode('utf-8')
260
 
                if path in self._cache:
261
 
                    trace.warning('duplicated path %r in cache' % path)
262
 
                    continue
263
 
 
264
 
                pos += 3
265
 
                fields = l[pos:].split(b' ')
266
 
                if len(fields) != 7:
267
 
                    trace.warning("bad line in hashcache: %r" % l)
268
 
                    continue
269
 
 
270
 
                sha1 = fields[0]
271
 
                if len(sha1) != 40:
272
 
                    trace.warning("bad sha1 in hashcache: %r" % sha1)
273
 
                    continue
274
 
 
275
 
                fp = tuple(map(int, fields[1:]))
276
 
 
277
 
                self._cache[path] = (sha1, fp)
 
245
        hdr = inf.readline()
 
246
        if hdr != CACHE_HEADER:
 
247
            mutter('cache header marker not found at top of %s;'
 
248
                   ' discarding cache', fn)
 
249
            self.needs_write = True
 
250
            return
 
251
 
 
252
        for l in inf:
 
253
            pos = l.index('// ')
 
254
            path = l[:pos].decode('utf-8')
 
255
            if path in self._cache:
 
256
                warning('duplicated path %r in cache' % path)
 
257
                continue
 
258
 
 
259
            pos += 3
 
260
            fields = l[pos:].split(' ')
 
261
            if len(fields) != 7:
 
262
                warning("bad line in hashcache: %r" % l)
 
263
                continue
 
264
 
 
265
            sha1 = fields[0]
 
266
            if len(sha1) != 40:
 
267
                warning("bad sha1 in hashcache: %r" % sha1)
 
268
                continue
 
269
 
 
270
            fp = tuple(map(long, fields[1:]))
 
271
 
 
272
            self._cache[path] = (sha1, fp)
278
273
 
279
274
        self.needs_write = False
280
275
 
285
280
        undetectably modified and so can't be cached.
286
281
        """
287
282
        return int(time.time()) - 3
288
 
 
 
283
           
289
284
    def _fingerprint(self, abspath, stat_value=None):
290
285
        if stat_value is None:
291
286
            try:
297
292
            return None
298
293
        # we discard any high precision because it's not reliable; perhaps we
299
294
        # could do better on some systems?
300
 
        return (stat_value.st_size, int(stat_value.st_mtime),
301
 
                int(stat_value.st_ctime), stat_value.st_ino,
 
295
        return (stat_value.st_size, long(stat_value.st_mtime),
 
296
                long(stat_value.st_ctime), stat_value.st_ino, 
302
297
                stat_value.st_dev, stat_value.st_mode)