~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/hashcache.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-04-09 20:23:07 UTC
  • mfrom: (4265.1.4 bbc-merge)
  • Revision ID: pqm@pqm.ubuntu.com-20090409202307-n0depb16qepoe21o
(jam) Change _fetch_uses_deltas = False for CHK repos until we can
        write a better fix.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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
 
30
30
CACHE_HEADER = "### bzr hashcache v5\n"
31
31
 
32
32
import os, stat, time
33
 
import sha
34
33
 
35
 
from bzrlib.osutils import sha_file, pathjoin, safe_unicode
 
34
from bzrlib.filters import internal_size_sha_file_byname
 
35
from bzrlib.osutils import sha_file, sha_string, pathjoin, safe_unicode
36
36
from bzrlib.trace import mutter, warning
37
37
from bzrlib.atomicfile import AtomicFile
38
38
from bzrlib.errors import BzrError
74
74
    hit_count
75
75
        number of times files have been retrieved from the cache, avoiding a
76
76
        re-read
77
 
        
 
77
 
78
78
    miss_count
79
79
        number of misses (times files have been completely re-read)
80
80
    """
81
81
    needs_write = False
82
82
 
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."""
 
83
    def __init__(self, root, cache_file_name, mode=None,
 
84
            content_filter_stack_provider=None):
 
85
        """Create a hash cache in base dir, and set the file mode to mode.
 
86
 
 
87
        :param content_filter_stack_provider: a function that takes a
 
88
            path (relative to the top of the tree) and a file-id as
 
89
            parameters and returns a stack of ContentFilters.
 
90
            If None, no content filtering is performed.
 
91
        """
85
92
        self.root = safe_unicode(root)
86
93
        self.root_utf8 = self.root.encode('utf8') # where is the filesystem encoding ?
87
94
        self.hit_count = 0
93
100
        self._cache = {}
94
101
        self._mode = mode
95
102
        self._cache_file_name = safe_unicode(cache_file_name)
 
103
        self._filter_provider = content_filter_stack_provider
96
104
 
97
105
    def cache_file_name(self):
98
106
        return self._cache_file_name
107
115
 
108
116
    def scan(self):
109
117
        """Scan all files and remove entries where the cache entry is obsolete.
110
 
        
 
118
 
111
119
        Obsolete entries are those where the file has been modified or deleted
112
 
        since the entry was inserted.        
 
120
        since the entry was inserted.
113
121
        """
114
122
        # FIXME optimisation opportunity, on linux [and check other oses]:
115
123
        # rather than iteritems order, stat in inode order.
116
124
        prep = [(ce[1][3], path, ce) for (path, ce) in self._cache.iteritems()]
117
125
        prep.sort()
118
 
        
 
126
 
119
127
        for inum, path, cache_entry in prep:
120
128
            abspath = pathjoin(self.root, path)
121
129
            fp = self._fingerprint(abspath)
122
130
            self.stat_count += 1
123
 
            
 
131
 
124
132
            cache_fp = cache_entry[1]
125
 
    
 
133
 
126
134
            if (not fp) or (cache_fp != fp):
127
135
                # not here or not a regular file anymore
128
136
                self.removed_count += 1
138
146
            abspath = pathjoin(self.root, path)
139
147
        self.stat_count += 1
140
148
        file_fp = self._fingerprint(abspath, stat_value)
141
 
        
 
149
 
142
150
        if not file_fp:
143
151
            # not a regular file or not existing
144
152
            if path in self._cache:
145
153
                self.removed_count += 1
146
154
                self.needs_write = True
147
155
                del self._cache[path]
148
 
            return None        
 
156
            return None
149
157
 
150
158
        if path in self._cache:
151
159
            cache_sha1, cache_fp = self._cache[path]
157
165
            ## mutter("now = %s", time.time())
158
166
            self.hit_count += 1
159
167
            return cache_sha1
160
 
        
 
168
 
161
169
        self.miss_count += 1
162
170
 
163
171
        mode = file_fp[FP_MODE_COLUMN]
164
172
        if stat.S_ISREG(mode):
165
 
            digest = self._really_sha1_file(abspath)
 
173
            if self._filter_provider is None:
 
174
                filters = []
 
175
            else:
 
176
                filters = self._filter_provider(path=path, file_id=None)
 
177
            digest = self._really_sha1_file(abspath, filters)
166
178
        elif stat.S_ISLNK(mode):
167
 
            digest = sha.new(os.readlink(abspath)).hexdigest()
 
179
            digest = sha_string(os.readlink(abspath))
168
180
        else:
169
181
            raise BzrError("file %r: unknown file stat mode: %o"%(abspath,mode))
170
182
 
199
211
            self._cache[path] = (digest, file_fp)
200
212
        return digest
201
213
 
202
 
    def _really_sha1_file(self, abspath):
 
214
    def _really_sha1_file(self, abspath, filters):
203
215
        """Calculate the SHA1 of a file by reading the full text"""
204
 
        return sha_file(file(abspath, 'rb', buffering=65000))
205
 
        
 
216
        return internal_size_sha_file_byname(abspath, filters)[1]
 
217
 
206
218
    def write(self):
207
219
        """Write contents of cache to file."""
208
220
        outf = AtomicFile(self.cache_file_name(), 'wb', new_mode=self._mode)
210
222
            outf.write(CACHE_HEADER)
211
223
 
212
224
            for path, c  in self._cache.iteritems():
213
 
                assert '//' not in path, path
214
225
                line_info = [path.encode('utf-8'), '// ', c[0], ' ']
215
226
                line_info.append(' '.join([str(fld) for fld in c[1]]))
216
227
                line_info.append('\n')
229
240
 
230
241
        Overwrites existing cache.
231
242
 
232
 
        If the cache file has the wrong version marker, this just clears 
 
243
        If the cache file has the wrong version marker, this just clears
233
244
        the cache."""
234
245
        self._cache = {}
235
246
 
280
291
        undetectably modified and so can't be cached.
281
292
        """
282
293
        return int(time.time()) - 3
283
 
           
 
294
 
284
295
    def _fingerprint(self, abspath, stat_value=None):
285
296
        if stat_value is None:
286
297
            try:
293
304
        # we discard any high precision because it's not reliable; perhaps we
294
305
        # could do better on some systems?
295
306
        return (stat_value.st_size, long(stat_value.st_mtime),
296
 
                long(stat_value.st_ctime), stat_value.st_ino, 
 
307
                long(stat_value.st_ctime), stat_value.st_ino,
297
308
                stat_value.st_dev, stat_value.st_mode)