~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/store.py

  • Committer: Martin Pool
  • Date: 2005-05-30 01:39:13 UTC
  • Revision ID: mbp@sourcefrog.net-20050530013913-4ac43c29e1302170
- make sure any bzr output is flushed before 
  running external diff

Show diffs side-by-side

added added

removed removed

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