~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/store.py

  • Committer: Aaron Bentley
  • Date: 2005-09-13 02:42:07 UTC
  • mto: (1185.1.16)
  • mto: This revision was merged to the branch mainline in revision 1390.
  • Revision ID: aaron.bentley@utoronto.ca-20050913024207-489d573af4b76c4d
Fixed issues with pull not having a default location after branch

Show diffs side-by-side

added added

removed removed

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