~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/store.py

  • Committer: Martin Pool
  • Date: 2005-06-10 06:29:35 UTC
  • Revision ID: mbp@sourcefrog.net-20050610062935-cd2fc37ca7ae1e09
- split out proposed progress module

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
 
"""
18
 
Stores are the main data-storage mechanism for Bazaar-NG.
 
17
"""Stores are the main data-storage mechanism for Bazaar-NG.
19
18
 
20
19
A store is a simple write-once container indexed by a universally
21
 
unique ID.
22
 
"""
 
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>"
23
24
 
24
25
import os, tempfile, types, osutils, gzip, errno
25
26
from stat import ST_SIZE
26
27
from StringIO import StringIO
27
 
from bzrlib.errors import BzrError
28
 
from bzrlib.trace import mutter
29
 
import bzrlib.ui
30
 
from bzrlib.remotebranch import get_url
 
28
from trace import mutter
31
29
 
32
30
######################################################################
33
31
# stores
36
34
    pass
37
35
 
38
36
 
39
 
class Store(object):
40
 
    """An abstract store that holds files indexed by unique names.
 
37
class ImmutableStore(object):
 
38
    """Store that holds files indexed by unique names.
41
39
 
42
40
    Files can be added, but not modified once they are in.  Typically
43
41
    the hash is used as the name, or something else known to be unique,
58
56
    >>> st.add(StringIO('goodbye'), '123123')
59
57
    >>> st['123123'].read()
60
58
    'goodbye'
61
 
    """
62
 
 
63
 
    def total_size(self):
64
 
        """Return (count, bytes)
65
 
 
66
 
        This is the (compressed) size stored on disk, not the size of
67
 
        the content."""
68
 
        total = 0
69
 
        count = 0
70
 
        for fid in self:
71
 
            count += 1
72
 
            total += self._item_size(fid)
73
 
        return count, total
74
 
 
75
 
 
76
 
class ImmutableStore(Store):
77
 
    """Store that stores files on disk.
78
59
 
79
60
    TODO: Atomic add by writing to a temporary file and renaming.
80
 
    TODO: Guard against the same thing being stored twice, compressed and
81
 
          uncompressed during copy_multi_immutable - the window is for a
82
 
          matching store with some crack code that lets it offer a 
83
 
          non gz FOO and then a fz FOO.
84
 
 
85
 
    In bzr 0.0.5 and earlier, files within the store were marked
86
 
    readonly on disk.  This is no longer done but existing stores need
87
 
    to be accomodated.
 
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
 
88
70
    """
89
71
 
90
72
    def __init__(self, basedir):
91
 
        super(ImmutableStore, self).__init__()
 
73
        """ImmutableStore constructor."""
92
74
        self._basedir = basedir
93
75
 
94
76
    def _path(self, id):
95
 
        if '\\' in id or '/' in id:
96
 
            raise ValueError("invalid store id %r" % id)
 
77
        assert '/' not in id
97
78
        return os.path.join(self._basedir, id)
98
79
 
99
80
    def __repr__(self):
103
84
        """Add contents of a file into the store.
104
85
 
105
86
        f -- An open file, or file-like object."""
106
 
        # FIXME: Only works on files that will fit in memory
107
 
        
108
 
        from bzrlib.atomicfile import AtomicFile
109
 
        
 
87
        # FIXME: Only works on smallish files
 
88
        # TODO: Can be optimized by copying at the same time as
 
89
        # computing the sum.
110
90
        mutter("add store entry %r" % (fileid))
111
91
        if isinstance(f, types.StringTypes):
112
92
            content = f
113
93
        else:
114
94
            content = f.read()
115
 
            
 
95
 
116
96
        p = self._path(fileid)
117
97
        if os.access(p, os.F_OK) or os.access(p + '.gz', os.F_OK):
118
 
            raise BzrError("store %r already contains id %r" % (self._basedir, fileid))
 
98
            bailout("store %r already contains id %r" % (self._basedir, fileid))
119
99
 
120
 
        fn = p
121
100
        if compressed:
122
 
            fn = fn + '.gz'
 
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)
123
106
            
124
 
        af = AtomicFile(fn, 'wb')
125
 
        try:
126
 
            if compressed:
127
 
                gf = gzip.GzipFile(mode='wb', fileobj=af)
128
 
                gf.write(content)
129
 
                gf.close()
130
 
            else:
131
 
                af.write(content)
132
 
            af.commit()
133
 
        finally:
134
 
            af.close()
135
 
 
136
 
 
137
 
    def copy_multi(self, other, ids, permit_failure=False):
 
107
        f.write(content)
 
108
        f.close()
 
109
 
 
110
    def copy_multi(self, other, ids):
138
111
        """Copy texts for ids from other into self.
139
112
 
140
 
        If an id is present in self, it is skipped.
141
 
 
142
 
        Returns (count_copied, failed), where failed is a collection of ids
143
 
        that could not be copied.
 
113
        If an id is present in self, it is skipped.  A count of copied
 
114
        ids is returned, which may be less than len(ids).
144
115
        """
145
 
        pb = bzrlib.ui.ui_factory.progress_bar()
146
 
        
147
 
        pb.update('preparing to copy')
148
 
        to_copy = [id for id in ids if id not in self]
149
 
        if isinstance(other, ImmutableStore):
150
 
            return self.copy_multi_immutable(other, to_copy, pb)
151
 
        count = 0
152
 
        failed = set()
153
 
        for id in to_copy:
154
 
            count += 1
155
 
            pb.update('copy', count, len(to_copy))
156
 
            if not permit_failure:
157
 
                self.add(other[id], id)
158
 
            else:
159
 
                try:
160
 
                    entry = other[id]
161
 
                except IndexError:
162
 
                    failed.add(id)
163
 
                    continue
164
 
                self.add(entry, id)
165
 
                
166
 
        if not permit_failure:
167
 
            assert count == len(to_copy)
168
 
        pb.clear()
169
 
        return count, failed
170
 
 
171
 
    def copy_multi_immutable(self, other, to_copy, pb, permit_failure=False):
172
 
        from shutil import copyfile
173
 
        count = 0
174
 
        failed = set()
175
 
        for id in to_copy:
176
 
            p = self._path(id)
177
 
            other_p = other._path(id)
178
 
            try:
179
 
                copyfile(other_p, p)
180
 
            except IOError, e:
181
 
                if e.errno == errno.ENOENT:
182
 
                    if not permit_failure:
183
 
                        copyfile(other_p+".gz", p+".gz")
184
 
                    else:
185
 
                        try:
186
 
                            copyfile(other_p+".gz", p+".gz")
187
 
                        except IOError, e:
188
 
                            if e.errno == errno.ENOENT:
189
 
                                failed.add(id)
190
 
                            else:
191
 
                                raise
192
 
                else:
193
 
                    raise
194
 
            
195
 
            count += 1
196
 
            pb.update('copy', count, len(to_copy))
197
 
        assert count == len(to_copy)
198
 
        pb.clear()
199
 
        return count, failed
 
116
        count = 0
 
117
        for id in ids:
 
118
            if id in self:
 
119
                continue
 
120
            self.add(other[id], id)
 
121
            count += 1
 
122
        return count
200
123
 
201
124
    def __contains__(self, fileid):
202
125
        """"""
204
127
        return (os.access(p, os.R_OK)
205
128
                or os.access(p + '.gz', os.R_OK))
206
129
 
207
 
    def _item_size(self, fid):
208
 
        p = self._path(fid)
209
 
        try:
210
 
            return os.stat(p)[ST_SIZE]
211
 
        except OSError:
212
 
            return os.stat(p + '.gz')[ST_SIZE]
 
130
    # TODO: Guard against the same thing being stored twice, compressed and uncompresse
213
131
 
214
132
    def __iter__(self):
215
133
        for f in os.listdir(self._basedir):
228
146
        try:
229
147
            return gzip.GzipFile(p + '.gz', 'rb')
230
148
        except IOError, e:
231
 
            if e.errno != errno.ENOENT:
232
 
                raise
233
 
 
234
 
        try:
235
 
            return file(p, 'rb')
236
 
        except IOError, e:
237
 
            if e.errno != errno.ENOENT:
238
 
                raise
239
 
 
240
 
        raise IndexError(fileid)
 
149
            if e.errno == errno.ENOENT:
 
150
                return file(p, 'rb')
 
151
            else:
 
152
                raise e
 
153
 
 
154
    def total_size(self):
 
155
        """Return (count, bytes)
 
156
 
 
157
        This is the (compressed) size stored on disk, not the size of
 
158
        the content."""
 
159
        total = 0
 
160
        count = 0
 
161
        for fid in self:
 
162
            count += 1
 
163
            p = self._path(fid)
 
164
            try:
 
165
                total += os.stat(p)[ST_SIZE]
 
166
            except OSError:
 
167
                total += os.stat(p + '.gz')[ST_SIZE]
 
168
                
 
169
        return count, total
 
170
 
 
171
 
241
172
 
242
173
 
243
174
class ImmutableScratchStore(ImmutableStore):
244
175
    """Self-destructing test subclass of ImmutableStore.
245
176
 
246
177
    The Store only exists for the lifetime of the Python object.
247
 
 Obviously you should not put anything precious in it.
 
178
    Obviously you should not put anything precious in it.
248
179
    """
249
180
    def __init__(self):
250
 
        super(ImmutableScratchStore, self).__init__(tempfile.mkdtemp())
 
181
        ImmutableStore.__init__(self, tempfile.mkdtemp())
251
182
 
252
183
    def __del__(self):
253
184
        for f in os.listdir(self._basedir):
257
188
            os.remove(fpath)
258
189
        os.rmdir(self._basedir)
259
190
        mutter("%r destroyed" % self)
260
 
 
261
 
 
262
 
class ImmutableMemoryStore(Store):
263
 
    """A memory only store."""
264
 
 
265
 
    def __init__(self):
266
 
        super(ImmutableMemoryStore, self).__init__()
267
 
        self._contents = {}
268
 
 
269
 
    def add(self, stream, fileid, compressed=True):
270
 
        if self._contents.has_key(fileid):
271
 
            raise StoreError("fileid %s already in the store" % fileid)
272
 
        self._contents[fileid] = stream.read()
273
 
 
274
 
    def __getitem__(self, fileid):
275
 
        """Returns a file reading from a particular entry."""
276
 
        if not self._contents.has_key(fileid):
277
 
            raise IndexError
278
 
        return StringIO(self._contents[fileid])
279
 
 
280
 
    def _item_size(self, fileid):
281
 
        return len(self._contents[fileid])
282
 
 
283
 
    def __iter__(self):
284
 
        return iter(self._contents.keys())
285
 
 
286
 
 
287
 
class RemoteStore(object):
288
 
 
289
 
    def __init__(self, baseurl):
290
 
        self._baseurl = baseurl
291
 
 
292
 
    def _path(self, name):
293
 
        if '/' in name:
294
 
            raise ValueError('invalid store id', name)
295
 
        return self._baseurl + '/' + name
296
 
        
297
 
    def __getitem__(self, fileid):
298
 
        p = self._path(fileid)
299
 
        try:
300
 
            return get_url(p, compressed=True)
301
 
        except:
302
 
            raise KeyError(fileid)