~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/store.py

  • Committer: mbp at sourcefrog
  • Date: 2005-04-11 02:53:57 UTC
  • Revision ID: mbp@sourcefrog.net-20050411025357-af577721308648ae
- remove profiler temporary file when done

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
2
 
#
 
1
 
 
2
 
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
#
 
7
 
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
 
# TODO: Could remember a bias towards whether a particular store is typically
18
 
# compressed or not.
19
 
 
20
 
"""
21
 
Stores are the main data-storage mechanism for Bazaar.
 
17
"""Stores are the main data-storage mechanism for Bazaar-NG.
22
18
 
23
19
A store is a simple write-once container indexed by a universally
24
 
unique ID.
25
 
"""
26
 
 
27
 
import os
28
 
from cStringIO import StringIO
29
 
import urllib
30
 
from zlib import adler32
31
 
 
32
 
import bzrlib
33
 
from bzrlib import (
34
 
    errors,
35
 
    osutils,
36
 
    symbol_versioning,
37
 
    urlutils,
38
 
    )
39
 
from bzrlib.errors import BzrError, UnlistableStore, TransportNotPossible
40
 
from bzrlib.symbol_versioning import (
41
 
    deprecated_function,
42
 
    )
43
 
from bzrlib.trace import mutter
44
 
from bzrlib.transport import Transport
45
 
from bzrlib.transport.local import LocalTransport
 
20
unique ID, which is typically the SHA-1 of the content."""
 
21
 
 
22
__copyright__ = "Copyright (C) 2005 Canonical Ltd."
 
23
__author__ = "Martin Pool <mbp@canonical.com>"
 
24
 
 
25
import os, tempfile, types, osutils, gzip, errno
 
26
from stat import ST_SIZE
 
27
from StringIO import StringIO
 
28
from trace import mutter
46
29
 
47
30
######################################################################
48
31
# stores
51
34
    pass
52
35
 
53
36
 
54
 
class Store(object):
55
 
    """This class represents the abstract storage layout for saving information.
56
 
    
 
37
class ImmutableStore:
 
38
    """Store that holds files indexed by unique names.
 
39
 
57
40
    Files can be added, but not modified once they are in.  Typically
58
41
    the hash is used as the name, or something else known to be unique,
59
42
    such as a UUID.
 
43
 
 
44
    >>> st = ImmutableScratchStore()
 
45
 
 
46
    >>> st.add(StringIO('hello'), 'aa')
 
47
    >>> 'aa' in st
 
48
    True
 
49
    >>> 'foo' in st
 
50
    False
 
51
 
 
52
    You are not allowed to add an id that is already present.
 
53
 
 
54
    Entries can be retrieved as files, which may then be read.
 
55
 
 
56
    >>> st.add(StringIO('goodbye'), '123123')
 
57
    >>> st['123123'].read()
 
58
    'goodbye'
 
59
 
 
60
    :todo: Atomic add by writing to a temporary file and renaming.
 
61
 
 
62
    :todo: Perhaps automatically transform to/from XML in a method?
 
63
           Would just need to tell the constructor what class to
 
64
           use...
 
65
 
 
66
    :todo: Even within a simple disk store like this, we could
 
67
           gzip the files.  But since many are less than one disk
 
68
           block, that might not help a lot.
 
69
 
60
70
    """
61
71
 
 
72
    def __init__(self, basedir):
 
73
        """ImmutableStore constructor."""
 
74
        self._basedir = basedir
 
75
 
 
76
    def _path(self, id):
 
77
        return os.path.join(self._basedir, id)
 
78
 
 
79
    def __repr__(self):
 
80
        return "%s(%r)" % (self.__class__.__name__, self._basedir)
 
81
 
 
82
    def add(self, f, fileid, compressed=True):
 
83
        """Add contents of a file into the store.
 
84
 
 
85
        :param f: An open file, or file-like object."""
 
86
        # FIXME: Only works on smallish files
 
87
        # TODO: Can be optimized by copying at the same time as
 
88
        # computing the sum.
 
89
        mutter("add store entry %r" % (fileid))
 
90
        if isinstance(f, types.StringTypes):
 
91
            content = f
 
92
        else:
 
93
            content = f.read()
 
94
 
 
95
        p = self._path(fileid)
 
96
        if os.access(p, os.F_OK) or os.access(p + '.gz', os.F_OK):
 
97
            bailout("store %r already contains id %r" % (self._basedir, fileid))
 
98
 
 
99
        if compressed:
 
100
            f = gzip.GzipFile(p + '.gz', 'wb')
 
101
            os.chmod(p + '.gz', 0444)
 
102
        else:
 
103
            f = file(p, 'wb')
 
104
            os.chmod(p, 0444)
 
105
            
 
106
        f.write(content)
 
107
        f.close()
 
108
 
 
109
 
 
110
    def __contains__(self, fileid):
 
111
        """"""
 
112
        p = self._path(fileid)
 
113
        return (os.access(p, os.R_OK)
 
114
                or os.access(p + '.gz', os.R_OK))
 
115
 
 
116
    # TODO: Guard against the same thing being stored twice, compressed and uncompresse
 
117
 
 
118
    def __iter__(self):
 
119
        for f in os.listdir(self._basedir):
 
120
            if f[-3:] == '.gz':
 
121
                # TODO: case-insensitive?
 
122
                yield f[:-3]
 
123
            else:
 
124
                yield f
 
125
 
62
126
    def __len__(self):
63
 
        raise NotImplementedError('Children should define their length')
64
 
 
65
 
    def get(self, fileid, suffix=None):
66
 
        """Returns a file reading from a particular entry.
67
 
        
68
 
        If suffix is present, retrieve the named suffix for fileid.
69
 
        """
70
 
        raise NotImplementedError
 
127
        return len(os.listdir(self._basedir))
71
128
 
72
129
    def __getitem__(self, fileid):
73
 
        """DEPRECATED. Please use .get(fileid) instead."""
74
 
        raise NotImplementedError
75
 
 
76
 
    #def __contains__(self, fileid):
77
 
    #    """Deprecated, please use has_id"""
78
 
    #    raise NotImplementedError
79
 
 
80
 
    def __iter__(self):
81
 
        raise NotImplementedError
82
 
 
83
 
    def add(self, f, fileid):
84
 
        """Add a file object f to the store accessible from the given fileid"""
85
 
        raise NotImplementedError('Children of Store must define their method of adding entries.')
86
 
 
87
 
    def has_id(self, fileid, suffix=None):
88
 
        """Return True or false for the presence of fileid in the store.
89
 
        
90
 
        suffix, if present, is a per file suffix, i.e. for digital signature 
91
 
        data."""
92
 
        raise NotImplementedError
93
 
 
94
 
    def listable(self):
95
 
        """Return True if this store is able to be listed."""
96
 
        return (getattr(self, "__iter__", None) is not None)
97
 
 
98
 
    def copy_all_ids(self, store_from, pb=None):
99
 
        """Copy all the file ids from store_from into self."""
100
 
        if not store_from.listable():
101
 
            raise UnlistableStore(store_from)
102
 
        ids = []
103
 
        for count, file_id in enumerate(store_from):
104
 
            if pb:
105
 
                pb.update('listing files', count, count)
106
 
            ids.append(file_id)
107
 
        if pb:
108
 
            pb.clear()
109
 
        mutter('copy_all ids: %r', ids)
110
 
        self.copy_multi(store_from, ids, pb=pb)
111
 
 
112
 
    def copy_multi(self, other, ids, pb=None, permit_failure=False):
113
 
        """Copy texts for ids from other into self.
114
 
 
115
 
        If an id is present in self, it is skipped.  A count of copied
116
 
        ids is returned, which may be less than len(ids).
117
 
 
118
 
        :param other: Another Store object
119
 
        :param ids: A list of entry ids to be copied
120
 
        :param pb: A ProgressBar object, if none is given, the default will be created.
121
 
        :param permit_failure: Allow missing entries to be ignored
122
 
        :return: (n_copied, [failed]) The number of entries copied successfully,
123
 
            followed by a list of entries which could not be copied (because they
124
 
            were missing)
125
 
        """
126
 
        if pb:
127
 
            pb.update('preparing to copy')
128
 
        failed = set()
129
 
        count = 0
130
 
        for fileid in ids:
131
 
            count += 1
132
 
            if self.has_id(fileid):
133
 
                continue
134
 
            try:
135
 
                self._copy_one(fileid, None, other, pb)
136
 
                for suffix in self._suffixes:
137
 
                    try:
138
 
                        self._copy_one(fileid, suffix, other, pb)
139
 
                    except KeyError:
140
 
                        pass
141
 
                if pb:
142
 
                    pb.update('copy', count, len(ids))
143
 
            except KeyError:
144
 
                if permit_failure:
145
 
                    failed.add(fileid)
146
 
                else:
147
 
                    raise
148
 
        assert count == len(ids)
149
 
        if pb:
150
 
            pb.clear()
151
 
        return count, failed
152
 
 
153
 
    def _copy_one(self, fileid, suffix, other, pb):
154
 
        """Most generic copy-one object routine.
155
 
        
156
 
        Subclasses can override this to provide an optimised
157
 
        copy between their own instances. Such overriden routines
158
 
        should call this if they have no optimised facility for a 
159
 
        specific 'other'.
160
 
        """
161
 
        mutter('Store._copy_one: %r', fileid)
162
 
        f = other.get(fileid, suffix)
163
 
        self.add(f, fileid, suffix)
164
 
 
165
 
 
166
 
class TransportStore(Store):
167
 
    """A TransportStore is a Store superclass for Stores that use Transports."""
168
 
 
169
 
    def add(self, f, fileid, suffix=None):
170
 
        """Add contents of a file into the store.
171
 
 
172
 
        f -- A file-like object
173
 
        """
174
 
        mutter("add store entry %r", fileid)
175
 
        names = self._id_to_names(fileid, suffix)
176
 
        if self._transport.has_any(names):
177
 
            raise BzrError("store %r already contains id %r" 
178
 
                           % (self._transport.base, fileid))
179
 
 
180
 
        # Most of the time, just adding the file will work
181
 
        # if we find a time where it fails, (because the dir
182
 
        # doesn't exist), then create the dir, and try again
183
 
        self._add(names[0], f)
184
 
 
185
 
    def _add(self, relpath, f):
186
 
        """Actually add the file to the given location.
187
 
        This should be overridden by children.
188
 
        """
189
 
        raise NotImplementedError('children need to implement this function.')
190
 
 
191
 
    def _check_fileid(self, fileid):
192
 
        if not isinstance(fileid, basestring):
193
 
            raise TypeError('Fileids should be a string type: %s %r' % (type(fileid), fileid))
194
 
        if '\\' in fileid or '/' in fileid:
195
 
            raise ValueError("invalid store id %r" % fileid)
196
 
 
197
 
    def _id_to_names(self, fileid, suffix):
198
 
        """Return the names in the expected order"""
199
 
        if suffix is not None:
200
 
            fn = self._relpath(fileid, [suffix])
201
 
        else:
202
 
            fn = self._relpath(fileid)
203
 
 
204
 
        # FIXME RBC 20051128 this belongs in TextStore.
205
 
        fn_gz = fn + '.gz'
206
 
        if self._compressed:
207
 
            return fn_gz, fn
208
 
        else:
209
 
            return fn, fn_gz
210
 
 
211
 
    def has_id(self, fileid, suffix=None):
212
 
        """See Store.has_id."""
213
 
        return self._transport.has_any(self._id_to_names(fileid, suffix))
214
 
 
215
 
    def _get_name(self, fileid, suffix=None):
216
 
        """A special check, which returns the name of an existing file.
217
 
        
218
 
        This is similar in spirit to 'has_id', but it is designed
219
 
        to return information about which file the store has.
220
 
        """
221
 
        for name in self._id_to_names(fileid, suffix=suffix):
222
 
            if self._transport.has(name):
223
 
                return name
224
 
        return None
225
 
 
226
 
    def _get(self, filename):
227
 
        """Return an vanilla file stream for clients to read from.
228
 
 
229
 
        This is the body of a template method on 'get', and should be 
230
 
        implemented by subclasses.
231
 
        """
232
 
        raise NotImplementedError
233
 
 
234
 
    def get(self, fileid, suffix=None):
235
 
        """See Store.get()."""
236
 
        names = self._id_to_names(fileid, suffix)
237
 
        for name in names:
238
 
            try:
239
 
                return self._get(name)
240
 
            except errors.NoSuchFile:
241
 
                pass
242
 
        raise KeyError(fileid)
243
 
 
244
 
    def __init__(self, a_transport, prefixed=False, compressed=False,
245
 
                 dir_mode=None, file_mode=None,
246
 
                 escaped=False):
247
 
        assert isinstance(a_transport, Transport)
248
 
        super(TransportStore, self).__init__()
249
 
        self._transport = a_transport
250
 
        self._prefixed = prefixed
251
 
        # FIXME RBC 20051128 this belongs in TextStore.
252
 
        self._compressed = compressed
253
 
        self._suffixes = set()
254
 
        self._escaped = escaped
255
 
 
256
 
        # It is okay for these to be None, it just means they
257
 
        # will just use the filesystem defaults
258
 
        self._dir_mode = dir_mode
259
 
        self._file_mode = file_mode
260
 
 
261
 
    def _unescape(self, file_id):
262
 
        """If filename escaping is enabled for this store, unescape and return the filename."""
263
 
        if self._escaped:
264
 
            return urllib.unquote(file_id)
265
 
        else:
266
 
            return file_id
267
 
 
268
 
    def _iter_files_recursive(self):
269
 
        """Iterate through the files in the transport."""
270
 
        for quoted_relpath in self._transport.iter_files_recursive():
271
 
            # transport iterator always returns quoted paths, regardless of
272
 
            # escaping
273
 
            yield urllib.unquote(quoted_relpath)
274
 
 
275
 
    def __iter__(self):
276
 
        for relpath in self._iter_files_recursive():
277
 
            # worst case is one of each suffix.
278
 
            name = os.path.basename(relpath)
279
 
            if name.endswith('.gz'):
280
 
                name = name[:-3]
281
 
            skip = False
282
 
            for count in range(len(self._suffixes)):
283
 
                for suffix in self._suffixes:
284
 
                    if name.endswith('.' + suffix):
285
 
                        skip = True
286
 
            if not skip:
287
 
                yield self._unescape(name)
288
 
 
289
 
    def __len__(self):
290
 
        return len(list(self.__iter__()))
291
 
 
292
 
    def _relpath(self, fileid, suffixes=None):
293
 
        self._check_fileid(fileid)
294
 
        if suffixes:
295
 
            for suffix in suffixes:
296
 
                if not suffix in self._suffixes:
297
 
                    raise ValueError("Unregistered suffix %r" % suffix)
298
 
                self._check_fileid(suffix)
299
 
        else:
300
 
            suffixes = []
301
 
        fileid = self._escape_file_id(fileid)
302
 
        if self._prefixed:
303
 
            # hash_prefix adds the '/' separator
304
 
            prefix = self.hash_prefix(fileid, escaped=True)
305
 
        else:
306
 
            prefix = ''
307
 
        path = prefix + fileid
308
 
        full_path = u'.'.join([path] + suffixes)
309
 
        return urlutils.escape(full_path)
310
 
 
311
 
    def _escape_file_id(self, file_id):
312
 
        """Turn a file id into a filesystem safe string.
313
 
 
314
 
        This is similar to a plain urllib.quote, except
315
 
        it uses specific safe characters, so that it doesn't
316
 
        have to translate a lot of valid file ids.
317
 
        """
318
 
        if not self._escaped:
319
 
            return file_id
320
 
        if isinstance(file_id, unicode):
321
 
            file_id = file_id.encode('utf-8')
322
 
        # @ does not get escaped. This is because it is a valid
323
 
        # filesystem character we use all the time, and it looks
324
 
        # a lot better than seeing %40 all the time.
325
 
        safe = "abcdefghijklmnopqrstuvwxyz0123456789-_@,."
326
 
        r = [((c in safe) and c or ('%%%02x' % ord(c)))
327
 
             for c in file_id]
328
 
        return ''.join(r)
329
 
 
330
 
    def hash_prefix(self, fileid, escaped=False):
331
 
        # fileid should be unescaped
332
 
        if not escaped and self._escaped:
333
 
            fileid = self._escape_file_id(fileid)
334
 
        return "%02x/" % (adler32(fileid) & 0xff)
335
 
 
336
 
    def __repr__(self):
337
 
        if self._transport is None:
338
 
            return "%s(None)" % (self.__class__.__name__)
339
 
        else:
340
 
            return "%s(%r)" % (self.__class__.__name__, self._transport.base)
341
 
 
342
 
    __str__ = __repr__
343
 
 
344
 
    def listable(self):
345
 
        """Return True if this store is able to be listed."""
346
 
        return self._transport.listable()
347
 
 
348
 
    def register_suffix(self, suffix):
349
 
        """Register a suffix as being expected in this store."""
350
 
        self._check_fileid(suffix)
351
 
        if suffix == 'gz':
352
 
            raise ValueError('You cannot register the "gz" suffix.')
353
 
        self._suffixes.add(suffix)
 
130
        """Returns a file reading from a particular entry."""
 
131
        p = self._path(fileid)
 
132
        try:
 
133
            return gzip.GzipFile(p + '.gz', 'rb')
 
134
        except IOError, e:
 
135
            if e.errno == errno.ENOENT:
 
136
                return file(p, 'rb')
 
137
            else:
 
138
                raise e
354
139
 
355
140
    def total_size(self):
356
141
        """Return (count, bytes)
359
144
        the content."""
360
145
        total = 0
361
146
        count = 0
362
 
        for relpath in self._transport.iter_files_recursive():
 
147
        for fid in self:
363
148
            count += 1
364
 
            total += self._transport.stat(relpath).st_size
 
149
            p = self._path(fid)
 
150
            try:
 
151
                total += os.stat(p)[ST_SIZE]
 
152
            except OSError:
 
153
                total += os.stat(p + '.gz')[ST_SIZE]
365
154
                
366
155
        return count, total
 
156
 
 
157
 
 
158
 
 
159
 
 
160
class ImmutableScratchStore(ImmutableStore):
 
161
    """Self-destructing test subclass of ImmutableStore.
 
162
 
 
163
    The Store only exists for the lifetime of the Python object.
 
164
    Obviously you should not put anything precious in it.
 
165
    """
 
166
    def __init__(self):
 
167
        ImmutableStore.__init__(self, tempfile.mkdtemp())
 
168
 
 
169
    def __del__(self):
 
170
        for f in os.listdir(self._basedir):
 
171
            fpath = os.path.join(self._basedir, f)
 
172
            # needed on windows, and maybe some other filesystems
 
173
            os.chmod(fpath, 0600)
 
174
            os.remove(fpath)
 
175
        os.rmdir(self._basedir)
 
176
        mutter("%r destroyed" % self)