1
# Copyright (C) 2005 by Canonical Development Ltd
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.
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.
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
18
An implementation the primary storage type CompressedTextStore.
20
This store keeps compressed versions of the full text. It does not
21
do any sort of delta compression.
24
import os, tempfile, gzip
27
from bzrlib.trace import mutter
28
from bzrlib.errors import BzrError
30
from StringIO import StringIO
31
from stat import ST_SIZE
33
class CompressedTextStore(bzrlib.store.Store):
34
"""Store that holds files indexed by unique names.
36
Files can be added, but not modified once they are in. Typically
37
the hash is used as the name, or something else known to be unique,
40
Files are stored gzip compressed, with no delta compression.
42
>>> st = ScratchCompressedTextStore()
44
>>> st.add(StringIO('hello'), 'aa')
50
You are not allowed to add an id that is already present.
52
Entries can be retrieved as files, which may then be read.
54
>>> st.add(StringIO('goodbye'), '123123')
55
>>> st['123123'].read()
59
def __init__(self, basedir):
60
super(CompressedTextStore, self).__init__(basedir)
62
def _check_fileid(self, fileid):
63
if '\\' in fileid or '/' in fileid:
64
raise ValueError("invalid store id %r" % fileid)
66
def _relpath(self, fileid):
67
self._check_fileid(fileid)
70
def add(self, f, fileid):
71
"""Add contents of a file into the store.
73
f -- An open file, or file-like object."""
74
# TODO: implement an add_multi which can do some of it's
75
# own piplelining, and possible take advantage of
76
# transport.put_multi(). The problem is that
77
# entries potentially need to be compressed as they
78
# are received, which implies translation, which
79
# means it isn't as straightforward as we would like.
80
from cStringIO import StringIO
81
from bzrlib.osutils import pumpfile
83
mutter("add store entry %r" % (fileid))
84
if isinstance(f, basestring):
87
fn = self._relpath(fileid)
88
if self._transport.has(fn):
89
raise BzrError("store %r already contains id %r" % (self._transport.base, fileid))
93
gf = gzip.GzipFile(mode='wb', fileobj=sio)
94
# if pumpfile handles files that don't fit in ram,
95
# so will this function
96
if isinstance(f, basestring):
102
self._transport.put(fn, sio)
104
def _do_copy(self, other, to_copy, pb, permit_failure=False):
105
if isinstance(other, CompressedTextStore):
106
return self._copy_multi_text(other, to_copy, pb,
107
permit_failure=permit_failure)
108
return super(CompressedTextStore, self)._do_copy(other, to_copy,
109
pb, permit_failure=permit_failure)
111
def _copy_multi_text(self, other, to_copy, pb,
112
permit_failure=False):
113
# Because of _transport, we can no longer assume
114
# that they are on the same filesystem, we can, however
115
# assume that we only need to copy the exact bytes,
116
# we don't need to process the files.
121
for fileid, has in zip(to_copy, self.has(to_copy)):
123
new_to_copy.add(fileid)
126
to_copy = new_to_copy
128
paths = [self._relpath(fileid) for fileid in to_copy]
129
count = other._transport.copy_to(paths, self._transport, pb=pb)
130
assert count == len(to_copy)
133
def __contains__(self, fileid):
135
fn = self._relpath(fileid)
136
return self._transport.has(fn)
138
def has(self, fileids, pb=None):
139
"""Return True/False for each entry in fileids.
141
:param fileids: A List or generator yielding file ids.
142
:return: A generator or list returning True/False for each entry.
144
relpaths = (self._relpath(fid) for fid in fileids)
145
return self._transport.has_multi(relpaths, pb=pb)
147
def get(self, fileids, ignore_missing=False, pb=None):
148
"""Return a set of files, one for each requested entry.
150
TODO: Write some tests to make sure that ignore_missing is
153
TODO: What should the exception be for a missing file?
154
KeyError, or NoSuchFile?
157
# This next code gets a bit hairy because it can allow
158
# to not request a file which doesn't seem to exist.
159
# Also, the same fileid may be requested twice, so we
160
# can't just build up a map.
161
rel_paths = [self._relpath(fid) for fid in fileids]
166
for path, has in zip(rel_paths,
167
self._transport.has_multi(rel_paths)):
169
existing_paths.append(path)
170
is_requested.append(True)
172
is_requested.append(False)
174
existing_paths = rel_paths
175
is_requested = [True for x in rel_paths]
178
for f in self._transport.get_multi(existing_paths, pb=pb):
179
assert count < len(is_requested)
180
while not is_requested[count]:
183
if hasattr(f, 'tell'):
184
yield gzip.GzipFile(mode='rb', fileobj=f)
186
from cStringIO import StringIO
187
sio = StringIO(f.read())
188
yield gzip.GzipFile(mode='rb', fileobj=sio)
191
while count < len(is_requested):
196
# TODO: case-insensitive?
197
for f in self._transport.list_dir('.'):
204
return len([f for f in self._transport.list_dir('.')])
207
def __getitem__(self, fileid):
208
"""Returns a file reading from a particular entry."""
209
fn = self._relpath(fileid)
210
# This will throw if the file doesn't exist.
212
f = self._transport.get(fn)
214
raise KeyError('This store (%s) does not contain %s' % (self, fileid))
216
# gzip.GzipFile.read() requires a tell() function
217
# but some transports return objects that cannot seek
218
# so buffer them in a StringIO instead
219
if hasattr(f, 'tell'):
220
return gzip.GzipFile(mode='rb', fileobj=f)
222
from cStringIO import StringIO
223
sio = StringIO(f.read())
224
return gzip.GzipFile(mode='rb', fileobj=sio)
227
def total_size(self):
228
"""Return (count, bytes)
230
This is the (compressed) size stored on disk, not the size of
234
relpaths = [self._relpath(fid) for fid in self]
235
for st in self._transport.stat_multi(relpaths):
241
class ScratchCompressedTextStore(CompressedTextStore):
242
"""Self-destructing test subclass of CompressedTextStore.
244
The Store only exists for the lifetime of the Python object.
245
Obviously you should not put anything precious in it.
248
from transport import transport
249
super(ScratchCompressedTextStore, self).__init__(transport(tempfile.mkdtemp()))
252
self._transport.delete_multi(self._transport.list_dir('.'))
253
os.rmdir(self._transport.base)
254
mutter("%r destroyed" % self)