~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/hashcache.py

  • Committer: Martin Pool
  • Date: 2007-07-05 00:29:29 UTC
  • mto: This revision was merged to the branch mainline in revision 2588.
  • Revision ID: mbp@sourcefrog.net-20070705002929-sj9snyfyp6mygxvq
fix up more run_bzr callers

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