/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2052.3.2 by John Arbash Meinel
Change Copyright .. by Canonical to Copyright ... Canonical
1
# Copyright (C) 2005, 2006 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
846 by Martin Pool
- start adding refactored/simplified hash cache
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
846 by Martin Pool
- start adding refactored/simplified hash cache
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
846 by Martin Pool
- start adding refactored/simplified hash cache
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
16
953 by Martin Pool
- refactor imports and stats for hashcache
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.
864 by Martin Pool
doc
22
23
# TODO: Perhaps return more details on the file to avoid statting it
24
# again: nonexistent, file type, size, etc
25
1213 by Martin Pool
- move import in hashcache
26
# TODO: Perhaps use a Python pickle instead of a text file; might be faster.
27
864 by Martin Pool
doc
28
29
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
30
CACHE_HEADER = "### bzr hashcache v5\n"
859 by Martin Pool
- add HashCache.write and a simple test for it
31
953 by Martin Pool
- refactor imports and stats for hashcache
32
import os, stat, time
1092.2.6 by Robert Collins
symlink support updated to work
33
import sha
953 by Martin Pool
- refactor imports and stats for hashcache
34
3368.2.1 by Ian Clatworthy
first cut at working tree content filtering
35
from bzrlib.filters import sha_file_by_name
36
from bzrlib.osutils import pathjoin, safe_unicode
953 by Martin Pool
- refactor imports and stats for hashcache
37
from bzrlib.trace import mutter, warning
1213 by Martin Pool
- move import in hashcache
38
from bzrlib.atomicfile import AtomicFile
1185.59.8 by Denys Duchier
hashcache: missing import for BzrError
39
from bzrlib.errors import BzrError
1540.1.1 by Martin Pool
[patch] stat-cache fixes from Denys
40
41
1185.59.10 by Denys Duchier
hashcache: new constants and improved comment
42
FP_MTIME_COLUMN = 1
43
FP_CTIME_COLUMN = 2
1092.2.6 by Robert Collins
symlink support updated to work
44
FP_MODE_COLUMN = 5
859 by Martin Pool
- add HashCache.write and a simple test for it
45
846 by Martin Pool
- start adding refactored/simplified hash cache
46
47
48
class HashCache(object):
49
    """Cache for looking up file SHA-1.
50
51
    Files are considered to match the cached value if the fingerprint
52
    of the file has not changed.  This includes its mtime, ctime,
53
    device number, inode number, and size.  This should catch
54
    modifications or replacement of the file by a new one.
55
56
    This may not catch modifications that do not change the file's
57
    size and that occur within the resolution window of the
58
    timestamps.  To handle this we specifically do not cache files
59
    which have changed since the start of the present second, since
60
    they could undetectably change again.
61
62
    This scheme may fail if the machine's clock steps backwards.
63
    Don't do that.
64
65
    This does not canonicalize the paths passed in; that should be
66
    done by the caller.
67
860 by Martin Pool
- refactor hashcache to use just one dictionary
68
    _cache
69
        Indexed by path, points to a two-tuple of the SHA-1 of the file.
70
        and its fingerprint.
846 by Martin Pool
- start adding refactored/simplified hash cache
71
72
    stat_count
73
        number of times files have been statted
74
75
    hit_count
76
        number of times files have been retrieved from the cache, avoiding a
77
        re-read
78
        
79
    miss_count
80
        number of misses (times files have been completely re-read)
81
    """
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
82
    needs_write = False
83
3368.2.4 by Ian Clatworthy
make content filter lookup a tree responsibility
84
    def __init__(self, root, cache_file_name, mode=None,
85
            content_filter_stack_provider=None):
86
        """Create a hash cache in base dir, and set the file mode to mode.
87
3368.2.5 by Ian Clatworthy
incorporate jameinel's review feedback
88
        :param content_filter_stack_provider: a function that takes a
89
            path (relative to the top of the tree) and a file-id as
90
            parameters and returns a stack of ContentFilter's.
91
            If None, no content filtering is performed.
3368.2.4 by Ian Clatworthy
make content filter lookup a tree responsibility
92
        """
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
93
        self.root = safe_unicode(root)
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
94
        self.root_utf8 = self.root.encode('utf8') # where is the filesystem encoding ?
846 by Martin Pool
- start adding refactored/simplified hash cache
95
        self.hit_count = 0
96
        self.miss_count = 0
97
        self.stat_count = 0
98
        self.danger_count = 0
953 by Martin Pool
- refactor imports and stats for hashcache
99
        self.removed_count = 0
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
100
        self.update_count = 0
860 by Martin Pool
- refactor hashcache to use just one dictionary
101
        self._cache = {}
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
102
        self._mode = mode
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
103
        self._cache_file_name = safe_unicode(cache_file_name)
3368.2.4 by Ian Clatworthy
make content filter lookup a tree responsibility
104
        self._cfs_provider = content_filter_stack_provider
846 by Martin Pool
- start adding refactored/simplified hash cache
105
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
106
    def cache_file_name(self):
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
107
        return self._cache_file_name
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
108
846 by Martin Pool
- start adding refactored/simplified hash cache
109
    def clear(self):
860 by Martin Pool
- refactor hashcache to use just one dictionary
110
        """Discard all cached information.
111
112
        This does not reset the counters."""
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
113
        if self._cache:
114
            self.needs_write = True
115
            self._cache = {}
846 by Martin Pool
- start adding refactored/simplified hash cache
116
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
117
    def scan(self):
118
        """Scan all files and remove entries where the cache entry is obsolete.
119
        
120
        Obsolete entries are those where the file has been modified or deleted
121
        since the entry was inserted.        
122
        """
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
123
        # FIXME optimisation opportunity, on linux [and check other oses]:
124
        # rather than iteritems order, stat in inode order.
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
125
        prep = [(ce[1][3], path, ce) for (path, ce) in self._cache.iteritems()]
953 by Martin Pool
- refactor imports and stats for hashcache
126
        prep.sort()
127
        
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
128
        for inum, path, cache_entry in prep:
1534.4.51 by Robert Collins
Test the disk layout of format3 working trees.
129
            abspath = pathjoin(self.root, path)
1845.1.3 by Martin Pool
Improvements to hashcache testing:
130
            fp = self._fingerprint(abspath)
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
131
            self.stat_count += 1
132
            
133
            cache_fp = cache_entry[1]
134
    
135
            if (not fp) or (cache_fp != fp):
136
                # not here or not a regular file anymore
137
                self.removed_count += 1
138
                self.needs_write = True
139
                del self._cache[path]
140
2012.1.7 by Aaron Bentley
Get tree._iter_changed down to ~ 1 stat per file
141
    def get_sha1(self, path, stat_value=None):
953 by Martin Pool
- refactor imports and stats for hashcache
142
        """Return the sha1 of a file.
846 by Martin Pool
- start adding refactored/simplified hash cache
143
        """
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
144
        if path.__class__ is str:
145
            abspath = pathjoin(self.root_utf8, path)
146
        else:
147
            abspath = pathjoin(self.root, path)
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
148
        self.stat_count += 1
2012.1.7 by Aaron Bentley
Get tree._iter_changed down to ~ 1 stat per file
149
        file_fp = self._fingerprint(abspath, stat_value)
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
150
        
151
        if not file_fp:
152
            # not a regular file or not existing
153
            if path in self._cache:
154
                self.removed_count += 1
155
                self.needs_write = True
156
                del self._cache[path]
157
            return None        
953 by Martin Pool
- refactor imports and stats for hashcache
158
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
159
        if path in self._cache:
160
            cache_sha1, cache_fp = self._cache[path]
860 by Martin Pool
- refactor hashcache to use just one dictionary
161
        else:
162
            cache_sha1, cache_fp = None, None
846 by Martin Pool
- start adding refactored/simplified hash cache
163
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
164
        if cache_fp == file_fp:
1845.1.2 by mbp at sourcefrog
Use larger time window on hashcache to be safe with fractional times
165
            ## mutter("hashcache hit for %s %r -> %s", path, file_fp, cache_sha1)
166
            ## mutter("now = %s", time.time())
846 by Martin Pool
- start adding refactored/simplified hash cache
167
            self.hit_count += 1
860 by Martin Pool
- refactor hashcache to use just one dictionary
168
            return cache_sha1
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
169
        
170
        self.miss_count += 1
1092.2.6 by Robert Collins
symlink support updated to work
171
172
        mode = file_fp[FP_MODE_COLUMN]
173
        if stat.S_ISREG(mode):
3368.2.4 by Ian Clatworthy
make content filter lookup a tree responsibility
174
            if self._cfs_provider is None:
3368.2.5 by Ian Clatworthy
incorporate jameinel's review feedback
175
                filters = []
3368.2.4 by Ian Clatworthy
make content filter lookup a tree responsibility
176
            else:
3368.2.5 by Ian Clatworthy
incorporate jameinel's review feedback
177
                filters = self._cfs_provider(path=path, file_id=None)
3368.2.4 by Ian Clatworthy
make content filter lookup a tree responsibility
178
            digest = self._really_sha1_file(abspath, filters)
1092.2.6 by Robert Collins
symlink support updated to work
179
        elif stat.S_ISLNK(mode):
180
            digest = sha.new(os.readlink(abspath)).hexdigest()
181
        else:
182
            raise BzrError("file %r: unknown file stat mode: %o"%(abspath,mode))
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
183
1845.1.2 by mbp at sourcefrog
Use larger time window on hashcache to be safe with fractional times
184
        # window of 3 seconds to allow for 2s resolution on windows,
185
        # unsynchronized file servers, etc.
1845.1.3 by Martin Pool
Improvements to hashcache testing:
186
        cutoff = self._cutoff_time()
1845.1.2 by mbp at sourcefrog
Use larger time window on hashcache to be safe with fractional times
187
        if file_fp[FP_MTIME_COLUMN] >= cutoff \
188
                or file_fp[FP_CTIME_COLUMN] >= cutoff:
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
189
            # changed too recently; can't be cached.  we can
190
            # return the result and it could possibly be cached
191
            # next time.
1185.59.10 by Denys Duchier
hashcache: new constants and improved comment
192
            #
193
            # the point is that we only want to cache when we are sure that any
194
            # subsequent modifications of the file can be detected.  If a
195
            # modification neither changes the inode, the device, the size, nor
196
            # the mode, then we can only distinguish it by time; therefore we
197
            # need to let sufficient time elapse before we may cache this entry
198
            # again.  If we didn't do this, then, for example, a very quick 1
199
            # byte replacement in the file might go undetected.
1845.1.2 by mbp at sourcefrog
Use larger time window on hashcache to be safe with fractional times
200
            ## mutter('%r modified too recently; not caching', path)
201
            self.danger_count += 1
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
202
            if cache_fp:
203
                self.removed_count += 1
204
                self.needs_write = True
205
                del self._cache[path]
846 by Martin Pool
- start adding refactored/simplified hash cache
206
        else:
1845.1.2 by mbp at sourcefrog
Use larger time window on hashcache to be safe with fractional times
207
            ## mutter('%r added to cache: now=%f, mtime=%d, ctime=%d',
208
            ##        path, time.time(), file_fp[FP_MTIME_COLUMN],
209
            ##        file_fp[FP_CTIME_COLUMN])
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
210
            self.update_count += 1
211
            self.needs_write = True
212
            self._cache[path] = (digest, file_fp)
213
        return digest
1845.1.3 by Martin Pool
Improvements to hashcache testing:
214
3368.2.4 by Ian Clatworthy
make content filter lookup a tree responsibility
215
    def _really_sha1_file(self, abspath, filters):
1845.1.3 by Martin Pool
Improvements to hashcache testing:
216
        """Calculate the SHA1 of a file by reading the full text"""
3368.2.4 by Ian Clatworthy
make content filter lookup a tree responsibility
217
        return sha_file_by_name(abspath, filters)
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
218
        
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
219
    def write(self):
859 by Martin Pool
- add HashCache.write and a simple test for it
220
        """Write contents of cache to file."""
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
221
        outf = AtomicFile(self.cache_file_name(), 'wb', new_mode=self._mode)
859 by Martin Pool
- add HashCache.write and a simple test for it
222
        try:
1908.4.8 by John Arbash Meinel
Small tweak to hashcache to make it write out faster
223
            outf.write(CACHE_HEADER)
859 by Martin Pool
- add HashCache.write and a simple test for it
224
860 by Martin Pool
- refactor hashcache to use just one dictionary
225
            for path, c  in self._cache.iteritems():
859 by Martin Pool
- add HashCache.write and a simple test for it
226
                assert '//' not in path, path
1908.4.8 by John Arbash Meinel
Small tweak to hashcache to make it write out faster
227
                line_info = [path.encode('utf-8'), '// ', c[0], ' ']
228
                line_info.append(' '.join([str(fld) for fld in c[1]]))
229
                line_info.append('\n')
230
                outf.write(''.join(line_info))
859 by Martin Pool
- add HashCache.write and a simple test for it
231
            outf.commit()
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
232
            self.needs_write = False
1845.1.1 by mbp at sourcefrog
Refactor and improve hashcache tests
233
            ## mutter("write hash cache: %s hits=%d misses=%d stat=%d recent=%d updates=%d",
234
            ##        self.cache_file_name(), self.hit_count, self.miss_count,
235
            ##        self.stat_count,
236
            ##        self.danger_count, self.update_count)
859 by Martin Pool
- add HashCache.write and a simple test for it
237
        finally:
1755.3.1 by Robert Collins
Tune the time to build our kernel_like tree : make LocalTransport.put faster, AtomicFile faster, LocalTransport.append faster.
238
            outf.close()
862 by Martin Pool
- code to re-read hashcache from file
239
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
240
    def read(self):
862 by Martin Pool
- code to re-read hashcache from file
241
        """Reinstate cache from file.
242
243
        Overwrites existing cache.
244
245
        If the cache file has the wrong version marker, this just clears 
246
        the cache."""
247
        self._cache = {}
248
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
249
        fn = self.cache_file_name()
250
        try:
948 by Martin Pool
- more buffering when reading/writing hashcache
251
            inf = file(fn, 'rb', buffering=65000)
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
252
        except IOError, e:
1185.31.4 by John Arbash Meinel
Fixing mutter() calls to not have to do string processing.
253
            mutter("failed to open %s: %s", fn, e)
1214 by Martin Pool
- hashcache should be written out if it can't be read
254
            # better write it now so it is valid
255
            self.needs_write = True
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
256
            return
257
862 by Martin Pool
- code to re-read hashcache from file
258
        hdr = inf.readline()
259
        if hdr != CACHE_HEADER:
1185.31.4 by John Arbash Meinel
Fixing mutter() calls to not have to do string processing.
260
            mutter('cache header marker not found at top of %s;'
261
                   ' discarding cache', fn)
1214 by Martin Pool
- hashcache should be written out if it can't be read
262
            self.needs_write = True
862 by Martin Pool
- code to re-read hashcache from file
263
            return
264
265
        for l in inf:
266
            pos = l.index('// ')
267
            path = l[:pos].decode('utf-8')
268
            if path in self._cache:
269
                warning('duplicated path %r in cache' % path)
270
                continue
271
272
            pos += 3
273
            fields = l[pos:].split(' ')
1092.2.6 by Robert Collins
symlink support updated to work
274
            if len(fields) != 7:
862 by Martin Pool
- code to re-read hashcache from file
275
                warning("bad line in hashcache: %r" % l)
276
                continue
277
278
            sha1 = fields[0]
279
            if len(sha1) != 40:
280
                warning("bad sha1 in hashcache: %r" % sha1)
281
                continue
282
283
            fp = tuple(map(long, fields[1:]))
284
285
            self._cache[path] = (sha1, fp)
286
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
287
        self.needs_write = False
1845.1.3 by Martin Pool
Improvements to hashcache testing:
288
289
    def _cutoff_time(self):
290
        """Return cutoff time.
291
292
        Files modified more recently than this time are at risk of being
293
        undetectably modified and so can't be cached.
294
        """
295
        return int(time.time()) - 3
866 by Martin Pool
- use new path-based hashcache for WorkingTree- squash mtime/ctime to whole seconds- update and if necessary write out hashcache when WorkingTree object is created.
296
           
2012.1.18 by Aaron Bentley
rename fs param to stat_value
297
    def _fingerprint(self, abspath, stat_value=None):
298
        if stat_value is None:
2012.1.7 by Aaron Bentley
Get tree._iter_changed down to ~ 1 stat per file
299
            try:
2012.1.18 by Aaron Bentley
rename fs param to stat_value
300
                stat_value = os.lstat(abspath)
2012.1.7 by Aaron Bentley
Get tree._iter_changed down to ~ 1 stat per file
301
            except OSError:
302
                # might be missing, etc
303
                return None
2012.1.18 by Aaron Bentley
rename fs param to stat_value
304
        if stat.S_ISDIR(stat_value.st_mode):
1845.1.3 by Martin Pool
Improvements to hashcache testing:
305
            return None
306
        # we discard any high precision because it's not reliable; perhaps we
307
        # could do better on some systems?
2012.1.18 by Aaron Bentley
rename fs param to stat_value
308
        return (stat_value.st_size, long(stat_value.st_mtime),
309
                long(stat_value.st_ctime), stat_value.st_ino, 
310
                stat_value.st_dev, stat_value.st_mode)