~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/hashcache.py

  • Committer: Martin Pool
  • Date: 2005-07-07 10:31:36 UTC
  • Revision ID: mbp@sourcefrog.net-20050707103135-9b4d911d8df6e880
- fix pwk help

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# along with this program; if not, write to the Free Software
15
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 
20
 
# it preserves the nice property that any caller will always get up-to-date
21
 
# data except in unavoidable cases.
22
 
 
23
 
# TODO: Perhaps return more details on the file to avoid statting it
24
 
# again: nonexistent, file type, size, etc
25
 
 
26
 
# TODO: Perhaps use a Python pickle instead of a text file; might be faster.
27
 
 
28
 
 
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
36
 
from bzrlib.trace import mutter, warning
37
 
from bzrlib.atomicfile import AtomicFile
38
 
 
39
 
 
40
 
FP_MODE_COLUMN = 5
 
17
 
 
18
 
41
19
 
42
20
def _fingerprint(abspath):
 
21
    import os, stat
 
22
 
43
23
    try:
44
24
        fs = os.lstat(abspath)
45
25
    except OSError:
49
29
    if stat.S_ISDIR(fs.st_mode):
50
30
        return None
51
31
 
52
 
    # we discard any high precision because it's not reliable; perhaps we
53
 
    # could do better on some systems?
54
 
    return (fs.st_size, long(fs.st_mtime),
55
 
            long(fs.st_ctime), fs.st_ino, fs.st_dev, fs.st_mode)
 
32
    return (fs.st_size, fs.st_mtime,
 
33
            fs.st_ctime, fs.st_ino, fs.st_dev)
56
34
 
57
35
 
58
36
class HashCache(object):
75
53
    This does not canonicalize the paths passed in; that should be
76
54
    done by the caller.
77
55
 
78
 
    _cache
79
 
        Indexed by path, points to a two-tuple of the SHA-1 of the file.
80
 
        and its fingerprint.
 
56
    cache_sha1
 
57
        Indexed by path, gives the SHA-1 of the file.
 
58
 
 
59
    validator
 
60
        Indexed by path, gives the fingerprint of the file last time it was read.
81
61
 
82
62
    stat_count
83
63
        number of times files have been statted
89
69
    miss_count
90
70
        number of misses (times files have been completely re-read)
91
71
    """
92
 
    needs_write = False
93
 
 
94
72
    def __init__(self, basedir):
95
73
        self.basedir = basedir
96
74
        self.hit_count = 0
97
75
        self.miss_count = 0
98
76
        self.stat_count = 0
99
77
        self.danger_count = 0
100
 
        self.removed_count = 0
101
 
        self.update_count = 0
102
 
        self._cache = {}
 
78
        self.cache_sha1 = {}
 
79
        self.validator = {}
103
80
 
104
 
    def cache_file_name(self):
105
 
        # FIXME: duplicate path logic here, this should be 
106
 
        # something like 'branch.controlfile'.
107
 
        return os.sep.join([self.basedir, '.bzr', 'stat-cache'])
108
81
 
109
82
    def clear(self):
110
 
        """Discard all cached information.
111
 
 
112
 
        This does not reset the counters."""
113
 
        if self._cache:
114
 
            self.needs_write = True
115
 
            self._cache = {}
116
 
 
117
 
 
118
 
    def scan(self):
119
 
        """Scan all files and remove entries where the cache entry is obsolete.
120
 
        
121
 
        Obsolete entries are those where the file has been modified or deleted
122
 
        since the entry was inserted.        
123
 
        """
124
 
        prep = [(ce[1][3], path, ce) for (path, ce) in self._cache.iteritems()]
125
 
        prep.sort()
126
 
        
127
 
        for inum, path, cache_entry in prep:
128
 
            abspath = os.sep.join([self.basedir, path])
129
 
            fp = _fingerprint(abspath)
130
 
            self.stat_count += 1
131
 
            
132
 
            cache_fp = cache_entry[1]
133
 
    
134
 
            if (not fp) or (cache_fp != fp):
135
 
                # not here or not a regular file anymore
136
 
                self.removed_count += 1
137
 
                self.needs_write = True
138
 
                del self._cache[path]
 
83
        """Discard all cached information."""
 
84
        self.validator = {}
 
85
        self.cache_sha1 = {}
139
86
 
140
87
 
141
88
    def get_sha1(self, path):
142
 
        """Return the sha1 of a file.
 
89
        """Return the hex SHA-1 of the contents of the file at path.
 
90
 
 
91
        XXX: If the file does not exist or is not a plain file???
143
92
        """
144
 
        abspath = os.sep.join([self.basedir, path])
 
93
 
 
94
        import os, time
 
95
        from bzrlib.osutils import sha_file
 
96
        
 
97
        abspath = os.path.join(self.basedir, path)
 
98
        fp = _fingerprint(abspath)
 
99
        cache_fp = self.validator.get(path)
 
100
 
145
101
        self.stat_count += 1
146
 
        file_fp = _fingerprint(abspath)
147
 
        
148
 
        if not file_fp:
149
 
            # not a regular file or not existing
150
 
            if path in self._cache:
151
 
                self.removed_count += 1
152
 
                self.needs_write = True
153
 
                del self._cache[path]
154
 
            return None        
155
 
 
156
 
        if path in self._cache:
157
 
            cache_sha1, cache_fp = self._cache[path]
158
 
        else:
159
 
            cache_sha1, cache_fp = None, None
160
 
 
161
 
        if cache_fp == file_fp:
 
102
 
 
103
        if not fp:
 
104
            # not a regular file
 
105
            return None
 
106
        elif cache_fp and (cache_fp == fp):
162
107
            self.hit_count += 1
163
 
            return cache_sha1
164
 
        
165
 
        self.miss_count += 1
166
 
 
167
 
 
168
 
        mode = file_fp[FP_MODE_COLUMN]
169
 
        if stat.S_ISREG(mode):
170
 
            digest = sha_file(file(abspath, 'rb', buffering=65000))
171
 
        elif stat.S_ISLNK(mode):
172
 
            link_target = os.readlink(abspath)
173
 
            digest = sha.new(os.readlink(abspath)).hexdigest()
174
 
        else:
175
 
            raise BzrError("file %r: unknown file stat mode: %o"%(abspath,mode))
176
 
 
177
 
        now = int(time.time())
178
 
        if file_fp[1] >= now or file_fp[2] >= now:
179
 
            # changed too recently; can't be cached.  we can
180
 
            # return the result and it could possibly be cached
181
 
            # next time.
182
 
            self.danger_count += 1 
183
 
            if cache_fp:
184
 
                self.removed_count += 1
185
 
                self.needs_write = True
186
 
                del self._cache[path]
187
 
        else:
188
 
            self.update_count += 1
189
 
            self.needs_write = True
190
 
            self._cache[path] = (digest, file_fp)
191
 
        return digest
192
 
        
193
 
    def write(self):
194
 
        """Write contents of cache to file."""
195
 
        outf = AtomicFile(self.cache_file_name(), 'wb')
196
 
        try:
197
 
            print >>outf, CACHE_HEADER,
198
 
 
199
 
            for path, c  in self._cache.iteritems():
200
 
                assert '//' not in path, path
201
 
                outf.write(path.encode('utf-8'))
202
 
                outf.write('// ')
203
 
                print >>outf, c[0],     # hex sha1
204
 
                for fld in c[1]:
205
 
                    print >>outf, "%d" % fld,
206
 
                print >>outf
207
 
 
208
 
            outf.commit()
209
 
            self.needs_write = False
210
 
        finally:
211
 
            if not outf.closed:
212
 
                outf.abort()
213
 
        
214
 
 
215
 
 
216
 
    def read(self):
217
 
        """Reinstate cache from file.
218
 
 
219
 
        Overwrites existing cache.
220
 
 
221
 
        If the cache file has the wrong version marker, this just clears 
222
 
        the cache."""
223
 
        self._cache = {}
224
 
 
225
 
        fn = self.cache_file_name()
226
 
        try:
227
 
            inf = file(fn, 'rb', buffering=65000)
228
 
        except IOError, e:
229
 
            mutter("failed to open %s: %s" % (fn, e))
230
 
            # better write it now so it is valid
231
 
            self.needs_write = True
232
 
            return
233
 
 
234
 
 
235
 
        hdr = inf.readline()
236
 
        if hdr != CACHE_HEADER:
237
 
            mutter('cache header marker not found at top of %s; discarding cache'
238
 
                   % fn)
239
 
            self.needs_write = True
240
 
            return
241
 
 
242
 
        for l in inf:
243
 
            pos = l.index('// ')
244
 
            path = l[:pos].decode('utf-8')
245
 
            if path in self._cache:
246
 
                warning('duplicated path %r in cache' % path)
247
 
                continue
248
 
 
249
 
            pos += 3
250
 
            fields = l[pos:].split(' ')
251
 
            if len(fields) != 7:
252
 
                warning("bad line in hashcache: %r" % l)
253
 
                continue
254
 
 
255
 
            sha1 = fields[0]
256
 
            if len(sha1) != 40:
257
 
                warning("bad sha1 in hashcache: %r" % sha1)
258
 
                continue
259
 
 
260
 
            fp = tuple(map(long, fields[1:]))
261
 
 
262
 
            self._cache[path] = (sha1, fp)
263
 
 
264
 
        self.needs_write = False
265
 
           
266
 
 
267
 
 
268
 
        
 
108
            return self.cache_sha1[path]
 
109
        else:
 
110
            self.miss_count += 1
 
111
            digest = sha_file(file(abspath, 'rb'))
 
112
 
 
113
            now = int(time.time())
 
114
            if fp[1] >= now or fp[2] >= now:
 
115
                # changed too recently; can't be cached.  we can
 
116
                # return the result and it could possibly be cached
 
117
                # next time.
 
118
                self.danger_count += 1 
 
119
                if cache_fp:
 
120
                    del self.validator[path]
 
121
                    del self.cache_sha1[path]
 
122
            else:
 
123
                self.validator[path] = fp
 
124
                self.cache_sha1[path] = digest
 
125
 
 
126
            return digest
 
127