~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-08 22:14:09 UTC
  • Revision ID: mbp@sourcefrog.net-20050408221409-a99bd4796a56f42edbf3f13a
selected-file diff

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 by Canonical Development Ltd
 
1
 
2
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
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-NG.
 
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.trace import mutter
36
 
import bzrlib.transport as transport
37
 
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
38
29
 
39
30
######################################################################
40
31
# stores
43
34
    pass
44
35
 
45
36
 
46
 
class Store(object):
47
 
    """This class represents the abstract storage layout for saving information.
48
 
    
 
37
class ImmutableStore:
 
38
    """Store that holds files indexed by unique names.
 
39
 
49
40
    Files can be added, but not modified once they are in.  Typically
50
41
    the hash is used as the name, or something else known to be unique,
51
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
 
52
70
    """
53
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
 
54
126
    def __len__(self):
55
 
        raise NotImplementedError('Children should define their length')
56
 
 
57
 
    def get(self, fileid, suffix=None):
58
 
        """Returns a file reading from a particular entry.
59
 
        
60
 
        If suffix is present, retrieve the named suffix for fileid.
61
 
        """
62
 
        raise NotImplementedError
 
127
        return len(os.listdir(self._basedir))
63
128
 
64
129
    def __getitem__(self, fileid):
65
 
        """DEPRECATED. Please use .get(fileid) instead."""
66
 
        raise NotImplementedError
67
 
 
68
 
    #def __contains__(self, fileid):
69
 
    #    """Deprecated, please use has_id"""
70
 
    #    raise NotImplementedError
71
 
 
72
 
    def __iter__(self):
73
 
        raise NotImplementedError
74
 
 
75
 
    def add(self, f, fileid):
76
 
        """Add a file object f to the store accessible from the given fileid"""
77
 
        raise NotImplementedError('Children of Store must define their method of adding entries.')
78
 
 
79
 
    def has_id(self, fileid, suffix=None):
80
 
        """Return True or false for the presence of fileid in the store.
81
 
        
82
 
        suffix, if present, is a per file suffix, i.e. for digital signature 
83
 
        data."""
84
 
        raise NotImplementedError
85
 
 
86
 
    def listable(self):
87
 
        """Return True if this store is able to be listed."""
88
 
        return hasattr(self, "__iter__")
89
 
 
90
 
    def copy_multi(self, other, ids, pb=None, permit_failure=False):
91
 
        """Copy texts for ids from other into self.
92
 
 
93
 
        If an id is present in self, it is skipped.  A count of copied
94
 
        ids is returned, which may be less than len(ids).
95
 
 
96
 
        :param other: Another Store object
97
 
        :param ids: A list of entry ids to be copied
98
 
        :param pb: A ProgressBar object, if none is given, the default will be created.
99
 
        :param permit_failure: Allow missing entries to be ignored
100
 
        :return: (n_copied, [failed]) The number of entries copied successfully,
101
 
            followed by a list of entries which could not be copied (because they
102
 
            were missing)
103
 
        """
104
 
        if pb is None:
105
 
            pb = bzrlib.ui.ui_factory.progress_bar()
106
 
        pb.update('preparing to copy')
107
 
        failed = set()
108
 
        count = 0
109
 
        ids = list(ids) # get the list for showing a length.
110
 
        for fileid in ids:
111
 
            count += 1
112
 
            if self.has_id(fileid):
113
 
                continue
114
 
            try:
115
 
                self._copy_one(fileid, None, other, pb)
116
 
                for suffix in self._suffixes:
117
 
                    try:
118
 
                        self._copy_one(fileid, suffix, other, pb)
119
 
                    except KeyError:
120
 
                        pass
121
 
                pb.update('copy', count, len(ids))
122
 
            except KeyError:
123
 
                if permit_failure:
124
 
                    failed.add(fileid)
125
 
                else:
126
 
                    raise
127
 
        assert count == len(ids)
128
 
        pb.clear()
129
 
        return count, failed
130
 
 
131
 
    def _copy_one(self, fileid, suffix, other, pb):
132
 
        """Most generic copy-one object routine.
133
 
        
134
 
        Subclasses can override this to provide an optimised
135
 
        copy between their own instances. Such overriden routines
136
 
        should call this if they have no optimised facility for a 
137
 
        specific 'other'.
138
 
        """
139
 
        mutter('Store._copy_one: %r', fileid)
140
 
        f = other.get(fileid, suffix)
141
 
        self.add(f, fileid, suffix)
142
 
 
143
 
 
144
 
class TransportStore(Store):
145
 
    """A TransportStore is a Store superclass for Stores that use Transports."""
146
 
 
147
 
    def add(self, f, fileid, suffix=None):
148
 
        """Add contents of a file into the store.
149
 
 
150
 
        f -- A file-like object, or string
151
 
        """
152
 
        mutter("add store entry %r", fileid)
153
 
        
154
 
        names = self._id_to_names(fileid, suffix)
155
 
        if self._transport.has_any(names):
156
 
            raise BzrError("store %r already contains id %r" 
157
 
                           % (self._transport.base, fileid))
158
 
 
159
 
        # Most of the time, just adding the file will work
160
 
        # if we find a time where it fails, (because the dir
161
 
        # doesn't exist), then create the dir, and try again
162
 
        self._add(names[0], f)
163
 
 
164
 
 
165
 
    def _add(self, relpath, f):
166
 
        """Actually add the file to the given location.
167
 
        This should be overridden by children.
168
 
        """
169
 
        raise NotImplementedError('children need to implement this function.')
170
 
 
171
 
    def _check_fileid(self, fileid):
172
 
        if not isinstance(fileid, basestring):
173
 
            raise TypeError('Fileids should be a string type: %s %r' % (type(fileid), fileid))
174
 
        if '\\' in fileid or '/' in fileid:
175
 
            raise ValueError("invalid store id %r" % fileid)
176
 
 
177
 
    def _id_to_names(self, fileid, suffix):
178
 
        """Return the names in the expected order"""
179
 
        if suffix is not None:
180
 
            fn = self._relpath(fileid, [suffix])
181
 
        else:
182
 
            fn = self._relpath(fileid)
183
 
 
184
 
        # FIXME RBC 20051128 this belongs in TextStore.
185
 
        fn_gz = fn + '.gz'
186
 
        if self._compressed:
187
 
            return fn_gz, fn
188
 
        else:
189
 
            return fn, fn_gz
190
 
 
191
 
    def has_id(self, fileid, suffix=None):
192
 
        """See Store.has_id."""
193
 
        return self._transport.has_any(self._id_to_names(fileid, suffix))
194
 
 
195
 
    def _get_name(self, fileid, suffix=None):
196
 
        """A special check, which returns the name of an existing file.
197
 
        
198
 
        This is similar in spirit to 'has_id', but it is designed
199
 
        to return information about which file the store has.
200
 
        """
201
 
        for name in self._id_to_names(fileid, suffix=suffix):
202
 
            if self._transport.has(name):
203
 
                return name
204
 
        return None
205
 
 
206
 
    def _get(self, filename):
207
 
        """Return an vanilla file stream for clients to read from.
208
 
 
209
 
        This is the body of a template method on 'get', and should be 
210
 
        implemented by subclasses.
211
 
        """
212
 
        raise NotImplementedError
213
 
 
214
 
    def get(self, fileid, suffix=None):
215
 
        """See Store.get()."""
216
 
        names = self._id_to_names(fileid, suffix)
217
 
        for name in names:
218
 
            try:
219
 
                return self._get(name)
220
 
            except errors.NoSuchFile:
221
 
                pass
222
 
        raise KeyError(fileid)
223
 
 
224
 
    def __init__(self, a_transport, prefixed=False, compressed=False,
225
 
                 dir_mode=None, file_mode=None):
226
 
        assert isinstance(a_transport, transport.Transport)
227
 
        super(TransportStore, self).__init__()
228
 
        self._transport = a_transport
229
 
        self._prefixed = prefixed
230
 
        # FIXME RBC 20051128 this belongs in TextStore.
231
 
        self._compressed = compressed
232
 
        self._suffixes = set()
233
 
 
234
 
        # It is okay for these to be None, it just means they
235
 
        # will just use the filesystem defaults
236
 
        self._dir_mode = dir_mode
237
 
        self._file_mode = file_mode
238
 
 
239
 
    def _iter_files_recursive(self):
240
 
        """Iterate through the files in the transport."""
241
 
        for quoted_relpath in self._transport.iter_files_recursive():
242
 
            yield urllib.unquote(quoted_relpath)
243
 
 
244
 
    def __iter__(self):
245
 
        for relpath in self._iter_files_recursive():
246
 
            # worst case is one of each suffix.
247
 
            name = os.path.basename(relpath)
248
 
            if name.endswith('.gz'):
249
 
                name = name[:-3]
250
 
            skip = False
251
 
            for count in range(len(self._suffixes)):
252
 
                for suffix in self._suffixes:
253
 
                    if name.endswith('.' + suffix):
254
 
                        skip = True
255
 
            if not skip:
256
 
                yield name
257
 
 
258
 
    def __len__(self):
259
 
        return len(list(self.__iter__()))
260
 
 
261
 
    def _relpath(self, fileid, suffixes=None):
262
 
        self._check_fileid(fileid)
263
 
        if suffixes:
264
 
            for suffix in suffixes:
265
 
                if not suffix in self._suffixes:
266
 
                    raise ValueError("Unregistered suffix %r" % suffix)
267
 
                self._check_fileid(suffix)
268
 
        else:
269
 
            suffixes = []
270
 
        if self._prefixed:
271
 
            path = [hash_prefix(fileid) + fileid]
272
 
        else:
273
 
            path = [fileid]
274
 
        path.extend(suffixes)
275
 
        return transport.urlescape(u'.'.join(path))
276
 
 
277
 
    def __repr__(self):
278
 
        if self._transport is None:
279
 
            return "%s(None)" % (self.__class__.__name__)
280
 
        else:
281
 
            return "%s(%r)" % (self.__class__.__name__, self._transport.base)
282
 
 
283
 
    __str__ = __repr__
284
 
 
285
 
    def listable(self):
286
 
        """Return True if this store is able to be listed."""
287
 
        return self._transport.listable()
288
 
 
289
 
    def register_suffix(self, suffix):
290
 
        """Register a suffix as being expected in this store."""
291
 
        self._check_fileid(suffix)
292
 
        if suffix == 'gz':
293
 
            raise ValueError('You cannot register the "gz" suffix.')
294
 
        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
295
139
 
296
140
    def total_size(self):
297
141
        """Return (count, bytes)
300
144
        the content."""
301
145
        total = 0
302
146
        count = 0
303
 
        for relpath in self._transport.iter_files_recursive():
 
147
        for fid in self:
304
148
            count += 1
305
 
            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]
306
154
                
307
155
        return count, total
308
156
 
309
157
 
310
 
def ImmutableMemoryStore():
311
 
    return bzrlib.store.text.TextStore(transport.memory.MemoryTransport())
312
 
        
313
 
 
314
 
def copy_all(store_from, store_to):
315
 
    """Copy all ids from one store to another."""
316
 
    # TODO: Optional progress indicator
317
 
    if not store_from.listable():
318
 
        raise UnlistableStore(store_from)
319
 
    ids = [f for f in store_from]
320
 
    mutter('copy_all ids: %r', ids)
321
 
    store_to.copy_multi(store_from, ids)
322
 
 
323
 
def hash_prefix(fileid):
324
 
    return "%02x/" % (adler32(fileid) & 0xff)
325
 
 
 
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)