1
# (C) 2005 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
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
20
def _fingerprint(abspath):
24
fs = os.lstat(abspath)
26
# might be missing, etc
29
if stat.S_ISDIR(fs.st_mode):
32
return (fs.st_size, fs.st_mtime,
33
fs.st_ctime, fs.st_ino, fs.st_dev)
36
class HashCache(object):
37
"""Cache for looking up file SHA-1.
39
Files are considered to match the cached value if the fingerprint
40
of the file has not changed. This includes its mtime, ctime,
41
device number, inode number, and size. This should catch
42
modifications or replacement of the file by a new one.
44
This may not catch modifications that do not change the file's
45
size and that occur within the resolution window of the
46
timestamps. To handle this we specifically do not cache files
47
which have changed since the start of the present second, since
48
they could undetectably change again.
50
This scheme may fail if the machine's clock steps backwards.
53
This does not canonicalize the paths passed in; that should be
57
Indexed by path, gives the SHA-1 of the file.
60
Indexed by path, gives the fingerprint of the file last time it was read.
63
number of times files have been statted
66
number of times files have been retrieved from the cache, avoiding a
70
number of misses (times files have been completely re-read)
72
def __init__(self, basedir):
73
self.basedir = basedir
83
"""Discard all cached information."""
88
def get_sha1(self, path):
89
"""Return the hex SHA-1 of the contents of the file at path.
91
XXX: If the file does not exist or is not a plain file???
95
from bzrlib.osutils import sha_file
97
abspath = os.path.join(self.basedir, path)
98
fp = _fingerprint(abspath)
99
cache_fp = self.validator.get(path)
106
elif cache_fp and (cache_fp == fp):
108
return self.cache_sha1[path]
111
digest = sha_file(file(abspath, 'rb'))
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
118
self.danger_count += 1
120
del self.validator[path]
121
del self.cache_sha1[path]
123
self.validator[path] = fp
124
self.cache_sha1[path] = digest