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
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
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.
30
30
CACHE_HEADER = "### bzr hashcache v5\n"
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
39
filters as _mod_filters,
41
45
FP_MTIME_COLUMN = 1
75
79
number of times files have been retrieved from the cache, avoiding a
79
83
number of misses (times files have been completely re-read)
81
85
needs_write = False
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)
87
def __init__(self, root, cache_file_name, mode=None,
88
content_filter_stack_provider=None):
89
"""Create a hash cache in base dir, and set the file mode to mode.
91
:param content_filter_stack_provider: a function that takes a
92
path (relative to the top of the tree) and a file-id as
93
parameters and returns a stack of ContentFilters.
94
If None, no content filtering is performed.
96
self.root = osutils.safe_unicode(root)
97
self.root_utf8 = self.root.encode('utf8') # where is the filesystem encoding ?
87
99
self.miss_count = 0
88
100
self.stat_count = 0
91
103
self.update_count = 0
94
self._cache_file_name = safe_unicode(cache_file_name)
106
self._cache_file_name = osutils.safe_unicode(cache_file_name)
107
self._filter_provider = content_filter_stack_provider
96
109
def cache_file_name(self):
97
110
return self._cache_file_name
108
121
"""Scan all files and remove entries where the cache entry is obsolete.
110
123
Obsolete entries are those where the file has been modified or deleted
111
since the entry was inserted.
124
since the entry was inserted.
113
126
# FIXME optimisation opportunity, on linux [and check other oses]:
114
127
# rather than iteritems order, stat in inode order.
115
128
prep = [(ce[1][3], path, ce) for (path, ce) in self._cache.iteritems()]
118
131
for inum, path, cache_entry in prep:
119
abspath = pathjoin(self.root, path)
132
abspath = osutils.pathjoin(self.root, path)
120
133
fp = self._fingerprint(abspath)
121
134
self.stat_count += 1
123
136
cache_fp = cache_entry[1]
125
138
if (not fp) or (cache_fp != fp):
126
139
# not here or not a regular file anymore
127
140
self.removed_count += 1
128
141
self.needs_write = True
129
142
del self._cache[path]
131
def get_sha1(self, path):
144
def get_sha1(self, path, stat_value=None):
132
145
"""Return the sha1 of a file.
134
abspath = pathjoin(self.root, path)
147
if path.__class__ is str:
148
abspath = osutils.pathjoin(self.root_utf8, path)
150
abspath = osutils.pathjoin(self.root, path)
135
151
self.stat_count += 1
136
file_fp = self._fingerprint(abspath)
152
file_fp = self._fingerprint(abspath, stat_value)
139
155
# not a regular file or not existing
140
156
if path in self._cache:
141
157
self.removed_count += 1
142
158
self.needs_write = True
143
159
del self._cache[path]
146
162
if path in self._cache:
147
163
cache_sha1, cache_fp = self._cache[path]
153
169
## mutter("now = %s", time.time())
154
170
self.hit_count += 1
155
171
return cache_sha1
157
173
self.miss_count += 1
159
175
mode = file_fp[FP_MODE_COLUMN]
160
176
if stat.S_ISREG(mode):
161
digest = self._really_sha1_file(abspath)
177
if self._filter_provider is None:
180
filters = self._filter_provider(path=path, file_id=None)
181
digest = self._really_sha1_file(abspath, filters)
162
182
elif stat.S_ISLNK(mode):
163
digest = sha.new(os.readlink(abspath)).hexdigest()
183
target = osutils.readlink(osutils.safe_unicode(abspath))
184
digest = osutils.sha_string(target.encode('UTF-8'))
165
raise BzrError("file %r: unknown file stat mode: %o"%(abspath,mode))
186
raise errors.BzrError("file %r: unknown file stat mode: %o"
167
189
# window of 3 seconds to allow for 2s resolution on windows,
168
190
# unsynchronized file servers, etc.
195
217
self._cache[path] = (digest, file_fp)
198
def _really_sha1_file(self, abspath):
220
def _really_sha1_file(self, abspath, filters):
199
221
"""Calculate the SHA1 of a file by reading the full text"""
200
return sha_file(file(abspath, 'rb', buffering=65000))
222
return _mod_filters.internal_size_sha_file_byname(abspath, filters)[1]
203
225
"""Write contents of cache to file."""
204
outf = AtomicFile(self.cache_file_name(), 'wb', new_mode=self._mode)
226
outf = atomicfile.AtomicFile(self.cache_file_name(), 'wb',
206
229
outf.write(CACHE_HEADER)
208
231
for path, c in self._cache.iteritems():
209
assert '//' not in path, path
210
232
line_info = [path.encode('utf-8'), '// ', c[0], ' ']
211
233
line_info.append(' '.join([str(fld) for fld in c[1]]))
212
234
line_info.append('\n')
234
256
inf = file(fn, 'rb', buffering=65000)
235
257
except IOError, e:
236
mutter("failed to open %s: %s", fn, e)
258
trace.mutter("failed to open %s: %s", fn, e)
237
259
# better write it now so it is valid
238
260
self.needs_write = True
241
263
hdr = inf.readline()
242
264
if hdr != CACHE_HEADER:
243
mutter('cache header marker not found at top of %s;'
244
' discarding cache', fn)
265
trace.mutter('cache header marker not found at top of %s;'
266
' discarding cache', fn)
245
267
self.needs_write = True
249
271
pos = l.index('// ')
250
272
path = l[:pos].decode('utf-8')
251
273
if path in self._cache:
252
warning('duplicated path %r in cache' % path)
274
trace.warning('duplicated path %r in cache' % path)
256
278
fields = l[pos:].split(' ')
257
279
if len(fields) != 7:
258
warning("bad line in hashcache: %r" % l)
280
trace.warning("bad line in hashcache: %r" % l)
262
284
if len(sha1) != 40:
263
warning("bad sha1 in hashcache: %r" % sha1)
285
trace.warning("bad sha1 in hashcache: %r" % sha1)
266
288
fp = tuple(map(long, fields[1:]))
268
290
self._cache[path] = (sha1, fp)
292
# GZ 2009-09-20: Should really use a try/finally block to ensure close
270
295
self.needs_write = False
272
297
def _cutoff_time(self):
276
301
undetectably modified and so can't be cached.
278
303
return int(time.time()) - 3
280
def _fingerprint(self, abspath):
282
fs = os.lstat(abspath)
284
# might be missing, etc
286
if stat.S_ISDIR(fs.st_mode):
305
def _fingerprint(self, abspath, stat_value=None):
306
if stat_value is None:
308
stat_value = os.lstat(abspath)
310
# might be missing, etc
312
if stat.S_ISDIR(stat_value.st_mode):
288
314
# we discard any high precision because it's not reliable; perhaps we
289
315
# could do better on some systems?
290
return (fs.st_size, long(fs.st_mtime),
291
long(fs.st_ctime), fs.st_ino, fs.st_dev, fs.st_mode)
316
return (stat_value.st_size, long(stat_value.st_mtime),
317
long(stat_value.st_ctime), stat_value.st_ino,
318
stat_value.st_dev, stat_value.st_mode)