/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/store.py

  • Committer: Robert Collins
  • Date: 2005-09-28 04:58:18 UTC
  • mto: (1092.2.19)
  • mto: This revision was merged to the branch mainline in revision 1391.
  • Revision ID: robertc@robertcollins.net-20050928045818-c5ce6c7cc796f6fc
patch from Rob Weir to correct bzr-man.py

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 by Canonical Development Ltd
 
2
 
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
 
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
 
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
"""
 
18
Stores are the main data-storage mechanism for Bazaar-NG.
 
19
 
 
20
A store is a simple write-once container indexed by a universally
 
21
unique ID.
 
22
"""
 
23
 
 
24
import errno
 
25
import gzip
 
26
import os
 
27
import tempfile
 
28
import types
 
29
from stat import ST_SIZE
 
30
from StringIO import StringIO
 
31
 
 
32
from bzrlib.errors import BzrError
 
33
from bzrlib.trace import mutter
 
34
import bzrlib.ui
 
35
import bzrlib.osutils as osutils
 
36
 
 
37
 
 
38
######################################################################
 
39
# stores
 
40
 
 
41
class StoreError(Exception):
 
42
    pass
 
43
 
 
44
 
 
45
class ImmutableStore(object):
 
46
    """Store that holds files indexed by unique names.
 
47
 
 
48
    Files can be added, but not modified once they are in.  Typically
 
49
    the hash is used as the name, or something else known to be unique,
 
50
    such as a UUID.
 
51
 
 
52
    >>> st = ImmutableScratchStore()
 
53
 
 
54
    >>> st.add(StringIO('hello'), 'aa')
 
55
    >>> 'aa' in st
 
56
    True
 
57
    >>> 'foo' in st
 
58
    False
 
59
 
 
60
    You are not allowed to add an id that is already present.
 
61
 
 
62
    Entries can be retrieved as files, which may then be read.
 
63
 
 
64
    >>> st.add(StringIO('goodbye'), '123123')
 
65
    >>> st['123123'].read()
 
66
    'goodbye'
 
67
 
 
68
    TODO: Atomic add by writing to a temporary file and renaming.
 
69
 
 
70
    In bzr 0.0.5 and earlier, files within the store were marked
 
71
    readonly on disk.  This is no longer done but existing stores need
 
72
    to be accomodated.
 
73
    """
 
74
 
 
75
    def __init__(self, basedir):
 
76
        self._basedir = basedir
 
77
 
 
78
    def _path(self, entry_id):
 
79
        if not isinstance(entry_id, basestring):
 
80
            raise TypeError(type(entry_id))
 
81
        if '\\' in entry_id or '/' in entry_id:
 
82
            raise ValueError("invalid store id %r" % entry_id)
 
83
        return os.path.join(self._basedir, entry_id)
 
84
 
 
85
    def __repr__(self):
 
86
        return "%s(%r)" % (self.__class__.__name__, self._basedir)
 
87
 
 
88
    def add(self, f, fileid, compressed=True):
 
89
        """Add contents of a file into the store.
 
90
 
 
91
        f -- An open file, or file-like object."""
 
92
        # FIXME: Only works on files that will fit in memory
 
93
        
 
94
        from bzrlib.atomicfile import AtomicFile
 
95
        
 
96
        mutter("add store entry %r" % (fileid))
 
97
        if isinstance(f, types.StringTypes):
 
98
            content = f
 
99
        else:
 
100
            content = f.read()
 
101
            
 
102
        p = self._path(fileid)
 
103
        if os.access(p, os.F_OK) or os.access(p + '.gz', os.F_OK):
 
104
            raise BzrError("store %r already contains id %r" % (self._basedir, fileid))
 
105
 
 
106
        fn = p
 
107
        if compressed:
 
108
            fn = fn + '.gz'
 
109
            
 
110
        af = AtomicFile(fn, 'wb')
 
111
        try:
 
112
            if compressed:
 
113
                gf = gzip.GzipFile(mode='wb', fileobj=af)
 
114
                gf.write(content)
 
115
                gf.close()
 
116
            else:
 
117
                af.write(content)
 
118
            af.commit()
 
119
        finally:
 
120
            af.close()
 
121
 
 
122
 
 
123
    def copy_multi(self, other, ids, permit_failure=False):
 
124
        """Copy texts for ids from other into self.
 
125
 
 
126
        If an id is present in self, it is skipped.
 
127
 
 
128
        Returns (count_copied, failed), where failed is a collection of ids
 
129
        that could not be copied.
 
130
        """
 
131
        pb = bzrlib.ui.ui_factory.progress_bar()
 
132
        
 
133
        pb.update('preparing to copy')
 
134
        to_copy = [id for id in ids if id not in self]
 
135
        if isinstance(other, ImmutableStore):
 
136
            return self.copy_multi_immutable(other, to_copy, pb, 
 
137
                                             permit_failure=permit_failure)
 
138
        count = 0
 
139
        failed = set()
 
140
        for id in to_copy:
 
141
            count += 1
 
142
            pb.update('copy', count, len(to_copy))
 
143
            if not permit_failure:
 
144
                self.add(other[id], id)
 
145
            else:
 
146
                try:
 
147
                    entry = other[id]
 
148
                except KeyError:
 
149
                    failed.add(id)
 
150
                    continue
 
151
                self.add(entry, id)
 
152
                
 
153
        if not permit_failure:
 
154
            assert count == len(to_copy)
 
155
        pb.clear()
 
156
        return count, failed
 
157
 
 
158
    def copy_multi_immutable(self, other, to_copy, pb, permit_failure=False):
 
159
        from shutil import copyfile
 
160
        count = 0
 
161
        failed = set()
 
162
        for id in to_copy:
 
163
            p = self._path(id)
 
164
            other_p = other._path(id)
 
165
            try:
 
166
                copyfile(other_p, p)
 
167
            except IOError, e:
 
168
                if e.errno == errno.ENOENT:
 
169
                    if not permit_failure:
 
170
                        copyfile(other_p+".gz", p+".gz")
 
171
                    else:
 
172
                        try:
 
173
                            copyfile(other_p+".gz", p+".gz")
 
174
                        except IOError, e:
 
175
                            if e.errno == errno.ENOENT:
 
176
                                failed.add(id)
 
177
                            else:
 
178
                                raise
 
179
                else:
 
180
                    raise
 
181
            
 
182
            count += 1
 
183
            pb.update('copy', count, len(to_copy))
 
184
        assert count == len(to_copy)
 
185
        pb.clear()
 
186
        return count, failed
 
187
    
 
188
 
 
189
    def __contains__(self, fileid):
 
190
        """"""
 
191
        p = self._path(fileid)
 
192
        return (os.access(p, os.R_OK)
 
193
                or os.access(p + '.gz', os.R_OK))
 
194
 
 
195
    # TODO: Guard against the same thing being stored twice, compressed and uncompresse
 
196
 
 
197
    def __iter__(self):
 
198
        for f in os.listdir(self._basedir):
 
199
            if f[-3:] == '.gz':
 
200
                # TODO: case-insensitive?
 
201
                yield f[:-3]
 
202
            else:
 
203
                yield f
 
204
 
 
205
    def __len__(self):
 
206
        return len(os.listdir(self._basedir))
 
207
 
 
208
 
 
209
    def __getitem__(self, fileid):
 
210
        """Returns a file reading from a particular entry."""
 
211
        p = self._path(fileid)
 
212
        try:
 
213
            return gzip.GzipFile(p + '.gz', 'rb')
 
214
        except IOError, e:
 
215
            if e.errno != errno.ENOENT:
 
216
                raise
 
217
 
 
218
        try:
 
219
            return file(p, 'rb')
 
220
        except IOError, e:
 
221
            if e.errno != errno.ENOENT:
 
222
                raise
 
223
 
 
224
        raise KeyError(fileid)
 
225
 
 
226
 
 
227
    def total_size(self):
 
228
        """Return (count, bytes)
 
229
 
 
230
        This is the (compressed) size stored on disk, not the size of
 
231
        the content."""
 
232
        total = 0
 
233
        count = 0
 
234
        for fid in self:
 
235
            count += 1
 
236
            p = self._path(fid)
 
237
            try:
 
238
                total += os.stat(p)[ST_SIZE]
 
239
            except OSError:
 
240
                total += os.stat(p + '.gz')[ST_SIZE]
 
241
                
 
242
        return count, total
 
243
 
 
244
 
 
245
 
 
246
 
 
247
class ImmutableScratchStore(ImmutableStore):
 
248
    """Self-destructing test subclass of ImmutableStore.
 
249
 
 
250
    The Store only exists for the lifetime of the Python object.
 
251
 Obviously you should not put anything precious in it.
 
252
    """
 
253
    def __init__(self):
 
254
        ImmutableStore.__init__(self, tempfile.mkdtemp())
 
255
 
 
256
    def __del__(self):
 
257
        for f in os.listdir(self._basedir):
 
258
            fpath = os.path.join(self._basedir, f)
 
259
            # needed on windows, and maybe some other filesystems
 
260
            os.chmod(fpath, 0600)
 
261
            os.remove(fpath)
 
262
        os.rmdir(self._basedir)
 
263
        mutter("%r destroyed" % self)