2506.2.1
by Andrew Bennetts
Start implementing container format reading and writing. |
1 |
# Copyright (C) 2007 Canonical 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 |
"""Container format for Bazaar data.
|
|
18 |
||
19 |
"Containers" and "records" are described in doc/developers/container-format.txt.
|
|
20 |
"""
|
|
21 |
||
2661.2.2
by Robert Collins
* ``bzrlib.pack.make_readv_reader`` allows readv based access to pack |
22 |
from cStringIO import StringIO |
2506.5.2
by Andrew Bennetts
Raise InvalidRecordError on invalid names. |
23 |
import re |
24 |
||
2506.2.1
by Andrew Bennetts
Start implementing container format reading and writing. |
25 |
from bzrlib import errors |
26 |
||
27 |
||
2535.3.26
by Andrew Bennetts
Revert merge of container-format changes rejected for bzr.dev (i.e. undo andrew.bennetts@canonical.com-20070717044423-cetp5spep142xsr4). |
28 |
FORMAT_ONE = "Bazaar pack format 1 (introduced in 0.18)" |
29 |
||
30 |
||
31 |
_whitespace_re = re.compile('[\t\n\x0b\x0c\r ]') |
|
2506.5.2
by Andrew Bennetts
Raise InvalidRecordError on invalid names. |
32 |
|
33 |
||
34 |
def _check_name(name): |
|
35 |
"""Do some basic checking of 'name'.
|
|
36 |
|
|
2535.3.26
by Andrew Bennetts
Revert merge of container-format changes rejected for bzr.dev (i.e. undo andrew.bennetts@canonical.com-20070717044423-cetp5spep142xsr4). |
37 |
At the moment, this just checks that there are no whitespace characters in a
|
38 |
name.
|
|
2506.5.2
by Andrew Bennetts
Raise InvalidRecordError on invalid names. |
39 |
|
40 |
:raises InvalidRecordError: if name is not valid.
|
|
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
41 |
:seealso: _check_name_encoding
|
2506.5.2
by Andrew Bennetts
Raise InvalidRecordError on invalid names. |
42 |
"""
|
2535.3.26
by Andrew Bennetts
Revert merge of container-format changes rejected for bzr.dev (i.e. undo andrew.bennetts@canonical.com-20070717044423-cetp5spep142xsr4). |
43 |
if _whitespace_re.search(name) is not None: |
2506.5.2
by Andrew Bennetts
Raise InvalidRecordError on invalid names. |
44 |
raise errors.InvalidRecordError("%r is not a valid name." % (name,)) |
45 |
||
46 |
||
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
47 |
def _check_name_encoding(name): |
48 |
"""Check that 'name' is valid UTF-8.
|
|
49 |
|
|
50 |
This is separate from _check_name because UTF-8 decoding is relatively
|
|
51 |
expensive, and we usually want to avoid it.
|
|
52 |
||
53 |
:raises InvalidRecordError: if name is not valid UTF-8.
|
|
54 |
"""
|
|
55 |
try: |
|
56 |
name.decode('utf-8') |
|
57 |
except UnicodeDecodeError, e: |
|
58 |
raise errors.InvalidRecordError(str(e)) |
|
59 |
||
60 |
||
2506.3.1
by Andrew Bennetts
More progress: |
61 |
class ContainerWriter(object): |
2698.1.1
by Robert Collins
Add records_written attribute to ContainerWriter's. (Robert Collins). |
62 |
"""A class for writing containers.
|
63 |
||
64 |
:attribute records_written: The number of user records added to the
|
|
65 |
container. This does not count the prelude or suffix of the container
|
|
66 |
introduced by the begin() and end() methods.
|
|
67 |
"""
|
|
2506.3.1
by Andrew Bennetts
More progress: |
68 |
|
69 |
def __init__(self, write_func): |
|
70 |
"""Constructor.
|
|
71 |
||
72 |
:param write_func: a callable that will be called when this
|
|
73 |
ContainerWriter needs to write some bytes.
|
|
74 |
"""
|
|
2661.2.1
by Robert Collins
* ``bzrlib.pack.ContainerWriter`` now returns an offset, length tuple to |
75 |
self._write_func = write_func |
76 |
self.current_offset = 0 |
|
2698.1.1
by Robert Collins
Add records_written attribute to ContainerWriter's. (Robert Collins). |
77 |
self.records_written = 0 |
2506.3.1
by Andrew Bennetts
More progress: |
78 |
|
79 |
def begin(self): |
|
80 |
"""Begin writing a container."""
|
|
2535.3.26
by Andrew Bennetts
Revert merge of container-format changes rejected for bzr.dev (i.e. undo andrew.bennetts@canonical.com-20070717044423-cetp5spep142xsr4). |
81 |
self.write_func(FORMAT_ONE + "\n") |
2506.3.1
by Andrew Bennetts
More progress: |
82 |
|
2661.2.1
by Robert Collins
* ``bzrlib.pack.ContainerWriter`` now returns an offset, length tuple to |
83 |
def write_func(self, bytes): |
84 |
self._write_func(bytes) |
|
85 |
self.current_offset += len(bytes) |
|
86 |
||
2506.3.1
by Andrew Bennetts
More progress: |
87 |
def end(self): |
88 |
"""Finish writing a container."""
|
|
89 |
self.write_func("E") |
|
90 |
||
91 |
def add_bytes_record(self, bytes, names): |
|
2661.2.1
by Robert Collins
* ``bzrlib.pack.ContainerWriter`` now returns an offset, length tuple to |
92 |
"""Add a Bytes record with the given names.
|
93 |
|
|
94 |
:param bytes: The bytes to insert.
|
|
2682.1.1
by Robert Collins
* The ``bzrlib.pack`` interface has changed to use tuples of bytestrings |
95 |
:param names: The names to give the inserted bytes. Each name is
|
96 |
a tuple of bytestrings. The bytestrings may not contain
|
|
97 |
whitespace.
|
|
2661.2.1
by Robert Collins
* ``bzrlib.pack.ContainerWriter`` now returns an offset, length tuple to |
98 |
:return: An offset, length tuple. The offset is the offset
|
99 |
of the record within the container, and the length is the
|
|
100 |
length of data that will need to be read to reconstitute the
|
|
101 |
record. These offset and length can only be used with the pack
|
|
102 |
interface - they might be offset by headers or other such details
|
|
103 |
and thus are only suitable for use by a ContainerReader.
|
|
104 |
"""
|
|
105 |
current_offset = self.current_offset |
|
2506.3.1
by Andrew Bennetts
More progress: |
106 |
# Kind marker
|
2776.2.1
by Robert Collins
25 percent time reduction in pack write logic. |
107 |
byte_sections = ["B"] |
2506.3.1
by Andrew Bennetts
More progress: |
108 |
# Length
|
2776.2.1
by Robert Collins
25 percent time reduction in pack write logic. |
109 |
byte_sections.append(str(len(bytes)) + "\n") |
2506.3.1
by Andrew Bennetts
More progress: |
110 |
# Names
|
2682.1.1
by Robert Collins
* The ``bzrlib.pack`` interface has changed to use tuples of bytestrings |
111 |
for name_tuple in names: |
2506.5.2
by Andrew Bennetts
Raise InvalidRecordError on invalid names. |
112 |
# Make sure we're writing valid names. Note that we will leave a
|
113 |
# half-written record if a name is bad!
|
|
2682.1.1
by Robert Collins
* The ``bzrlib.pack`` interface has changed to use tuples of bytestrings |
114 |
for name in name_tuple: |
115 |
_check_name(name) |
|
2776.2.1
by Robert Collins
25 percent time reduction in pack write logic. |
116 |
byte_sections.append('\x00'.join(name_tuple) + "\n") |
2506.3.1
by Andrew Bennetts
More progress: |
117 |
# End of headers
|
2776.2.1
by Robert Collins
25 percent time reduction in pack write logic. |
118 |
byte_sections.append("\n") |
2506.3.1
by Andrew Bennetts
More progress: |
119 |
# Finally, the contents.
|
2776.2.1
by Robert Collins
25 percent time reduction in pack write logic. |
120 |
byte_sections.append(bytes) |
121 |
# XXX: This causes a memory copy of bytes in size, but is usually
|
|
122 |
# faster than two write calls (12 vs 13 seconds to output a gig of
|
|
123 |
# 1k records.) - results may differ on significantly larger records
|
|
124 |
# like .iso's but as they should be rare in any case and thus not
|
|
125 |
# likely to be the common case. The biggest issue is causing extreme
|
|
126 |
# memory pressure in that case. One possibly improvement here is to
|
|
127 |
# check the size of the content before deciding to join here vs call
|
|
128 |
# write twice.
|
|
129 |
self.write_func(''.join(byte_sections)) |
|
2698.1.1
by Robert Collins
Add records_written attribute to ContainerWriter's. (Robert Collins). |
130 |
self.records_written += 1 |
2661.2.1
by Robert Collins
* ``bzrlib.pack.ContainerWriter`` now returns an offset, length tuple to |
131 |
# return a memo of where we wrote data to allow random access.
|
132 |
return current_offset, self.current_offset - current_offset |
|
2506.3.1
by Andrew Bennetts
More progress: |
133 |
|
134 |
||
2661.2.2
by Robert Collins
* ``bzrlib.pack.make_readv_reader`` allows readv based access to pack |
135 |
class ReadVFile(object): |
136 |
"""Adapt a readv result iterator to a file like protocol."""
|
|
137 |
||
138 |
def __init__(self, readv_result): |
|
139 |
self.readv_result = readv_result |
|
140 |
# the most recent readv result block
|
|
141 |
self._string = None |
|
142 |
||
143 |
def _next(self): |
|
144 |
if (self._string is None or |
|
145 |
self._string.tell() == self._string_length): |
|
146 |
length, data = self.readv_result.next() |
|
147 |
self._string_length = len(data) |
|
148 |
self._string = StringIO(data) |
|
149 |
||
150 |
def read(self, length): |
|
151 |
self._next() |
|
152 |
result = self._string.read(length) |
|
153 |
if len(result) < length: |
|
154 |
raise errors.BzrError('request for too much data from a readv hunk.') |
|
155 |
return result |
|
156 |
||
157 |
def readline(self): |
|
158 |
"""Note that readline will not cross readv segments."""
|
|
159 |
self._next() |
|
160 |
result = self._string.readline() |
|
161 |
if self._string.tell() == self._string_length and result[-1] != '\n': |
|
162 |
raise errors.BzrError('short readline in the readvfile hunk.') |
|
163 |
return result |
|
164 |
||
165 |
||
166 |
def make_readv_reader(transport, filename, requested_records): |
|
167 |
"""Create a ContainerReader that will read selected records only.
|
|
168 |
||
169 |
:param transport: The transport the pack file is located on.
|
|
170 |
:param filename: The filename of the pack file.
|
|
171 |
:param requested_records: The record offset, length tuples as returned
|
|
172 |
by add_bytes_record for the desired records.
|
|
173 |
"""
|
|
174 |
readv_blocks = [(0, len(FORMAT_ONE)+1)] |
|
175 |
readv_blocks.extend(requested_records) |
|
176 |
result = ContainerReader(ReadVFile( |
|
177 |
transport.readv(filename, readv_blocks))) |
|
178 |
return result |
|
179 |
||
180 |
||
2506.3.1
by Andrew Bennetts
More progress: |
181 |
class BaseReader(object): |
2506.2.1
by Andrew Bennetts
Start implementing container format reading and writing. |
182 |
|
2506.2.9
by Aaron Bentley
Use file-like objects as container input, not callables |
183 |
def __init__(self, source_file): |
2506.2.1
by Andrew Bennetts
Start implementing container format reading and writing. |
184 |
"""Constructor.
|
185 |
||
2506.2.12
by Andrew Bennetts
Update docstring for Aaron's changes. |
186 |
:param source_file: a file-like object with `read` and `readline`
|
187 |
methods.
|
|
2506.2.1
by Andrew Bennetts
Start implementing container format reading and writing. |
188 |
"""
|
2506.2.9
by Aaron Bentley
Use file-like objects as container input, not callables |
189 |
self._source = source_file |
190 |
||
191 |
def reader_func(self, length=None): |
|
192 |
return self._source.read(length) |
|
2506.2.1
by Andrew Bennetts
Start implementing container format reading and writing. |
193 |
|
2506.3.1
by Andrew Bennetts
More progress: |
194 |
def _read_line(self): |
2506.2.9
by Aaron Bentley
Use file-like objects as container input, not callables |
195 |
line = self._source.readline() |
196 |
if not line.endswith('\n'): |
|
197 |
raise errors.UnexpectedEndOfContainerError() |
|
198 |
return line.rstrip('\n') |
|
2506.3.1
by Andrew Bennetts
More progress: |
199 |
|
200 |
||
201 |
class ContainerReader(BaseReader): |
|
202 |
"""A class for reading Bazaar's container format."""
|
|
203 |
||
2506.2.1
by Andrew Bennetts
Start implementing container format reading and writing. |
204 |
def iter_records(self): |
205 |
"""Iterate over the container, yielding each record as it is read.
|
|
206 |
||
2506.6.2
by Andrew Bennetts
Docstring improvements. |
207 |
Each yielded record will be a 2-tuple of (names, callable), where names
|
208 |
is a ``list`` and bytes is a function that takes one argument,
|
|
209 |
``max_length``.
|
|
210 |
||
211 |
You **must not** call the callable after advancing the interator to the
|
|
212 |
next record. That is, this code is invalid::
|
|
213 |
||
214 |
record_iter = container.iter_records()
|
|
215 |
names1, callable1 = record_iter.next()
|
|
216 |
names2, callable2 = record_iter.next()
|
|
217 |
bytes1 = callable1(None)
|
|
218 |
|
|
219 |
As it will give incorrect results and invalidate the state of the
|
|
220 |
ContainerReader.
|
|
2506.3.1
by Andrew Bennetts
More progress: |
221 |
|
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
222 |
:raises ContainerError: if any sort of containter corruption is
|
223 |
detected, e.g. UnknownContainerFormatError is the format of the
|
|
224 |
container is unrecognised.
|
|
2506.6.2
by Andrew Bennetts
Docstring improvements. |
225 |
:seealso: ContainerReader.read
|
2506.2.1
by Andrew Bennetts
Start implementing container format reading and writing. |
226 |
"""
|
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
227 |
self._read_format() |
2506.2.1
by Andrew Bennetts
Start implementing container format reading and writing. |
228 |
return self._iter_records() |
229 |
||
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
230 |
def iter_record_objects(self): |
231 |
"""Iterate over the container, yielding each record as it is read.
|
|
232 |
||
233 |
Each yielded record will be an object with ``read`` and ``validate``
|
|
2506.6.2
by Andrew Bennetts
Docstring improvements. |
234 |
methods. Like with iter_records, it is not safe to use a record object
|
235 |
after advancing the iterator to yield next record.
|
|
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
236 |
|
237 |
:raises ContainerError: if any sort of containter corruption is
|
|
238 |
detected, e.g. UnknownContainerFormatError is the format of the
|
|
239 |
container is unrecognised.
|
|
2506.6.2
by Andrew Bennetts
Docstring improvements. |
240 |
:seealso: iter_records
|
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
241 |
"""
|
242 |
self._read_format() |
|
243 |
return self._iter_record_objects() |
|
244 |
||
2506.2.1
by Andrew Bennetts
Start implementing container format reading and writing. |
245 |
def _iter_records(self): |
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
246 |
for record in self._iter_record_objects(): |
247 |
yield record.read() |
|
248 |
||
249 |
def _iter_record_objects(self): |
|
2506.2.1
by Andrew Bennetts
Start implementing container format reading and writing. |
250 |
while True: |
251 |
record_kind = self.reader_func(1) |
|
252 |
if record_kind == 'B': |
|
253 |
# Bytes record.
|
|
2506.2.9
by Aaron Bentley
Use file-like objects as container input, not callables |
254 |
reader = BytesRecordReader(self._source) |
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
255 |
yield reader |
2506.2.1
by Andrew Bennetts
Start implementing container format reading and writing. |
256 |
elif record_kind == 'E': |
257 |
# End marker. There are no more records.
|
|
258 |
return
|
|
259 |
elif record_kind == '': |
|
260 |
# End of stream encountered, but no End Marker record seen, so
|
|
261 |
# this container is incomplete.
|
|
262 |
raise errors.UnexpectedEndOfContainerError() |
|
263 |
else: |
|
264 |
# Unknown record type.
|
|
265 |
raise errors.UnknownRecordTypeError(record_kind) |
|
266 |
||
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
267 |
def _read_format(self): |
268 |
format = self._read_line() |
|
2535.3.26
by Andrew Bennetts
Revert merge of container-format changes rejected for bzr.dev (i.e. undo andrew.bennetts@canonical.com-20070717044423-cetp5spep142xsr4). |
269 |
if format != FORMAT_ONE: |
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
270 |
raise errors.UnknownContainerFormatError(format) |
271 |
||
2506.2.6
by Andrew Bennetts
Add validate method to ContainerReader and BytesRecordReader. |
272 |
def validate(self): |
273 |
"""Validate this container and its records.
|
|
274 |
||
2506.2.7
by Andrew Bennetts
Change read/iter_records to return a callable, add more validation, and |
275 |
Validating consumes the data stream just like iter_records and
|
276 |
iter_record_objects, so you cannot call it after
|
|
277 |
iter_records/iter_record_objects.
|
|
2506.2.6
by Andrew Bennetts
Add validate method to ContainerReader and BytesRecordReader. |
278 |
|
279 |
:raises ContainerError: if something is invalid.
|
|
280 |
"""
|
|
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
281 |
all_names = set() |
282 |
for record_names, read_bytes in self.iter_records(): |
|
283 |
read_bytes(None) |
|
2682.1.1
by Robert Collins
* The ``bzrlib.pack`` interface has changed to use tuples of bytestrings |
284 |
for name_tuple in record_names: |
285 |
for name in name_tuple: |
|
286 |
_check_name_encoding(name) |
|
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
287 |
# Check that the name is unique. Note that Python will refuse
|
288 |
# to decode non-shortest forms of UTF-8 encoding, so there is no
|
|
289 |
# risk that the same unicode string has been encoded two
|
|
290 |
# different ways.
|
|
2682.1.1
by Robert Collins
* The ``bzrlib.pack`` interface has changed to use tuples of bytestrings |
291 |
if name_tuple in all_names: |
292 |
raise errors.DuplicateRecordNameError(name_tuple) |
|
293 |
all_names.add(name_tuple) |
|
2506.2.6
by Andrew Bennetts
Add validate method to ContainerReader and BytesRecordReader. |
294 |
excess_bytes = self.reader_func(1) |
295 |
if excess_bytes != '': |
|
296 |
raise errors.ContainerHasExcessDataError(excess_bytes) |
|
297 |
||
2506.3.1
by Andrew Bennetts
More progress: |
298 |
|
299 |
class BytesRecordReader(BaseReader): |
|
300 |
||
301 |
def read(self): |
|
2506.2.6
by Andrew Bennetts
Add validate method to ContainerReader and BytesRecordReader. |
302 |
"""Read this record.
|
303 |
||
2506.6.2
by Andrew Bennetts
Docstring improvements. |
304 |
You can either validate or read a record, you can't do both.
|
2506.2.6
by Andrew Bennetts
Add validate method to ContainerReader and BytesRecordReader. |
305 |
|
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
306 |
:returns: A tuple of (names, callable). The callable can be called
|
307 |
repeatedly to obtain the bytes for the record, with a max_length
|
|
308 |
argument. If max_length is None, returns all the bytes. Because
|
|
309 |
records can be arbitrarily large, using None is not recommended
|
|
310 |
unless you have reason to believe the content will fit in memory.
|
|
2506.2.6
by Andrew Bennetts
Add validate method to ContainerReader and BytesRecordReader. |
311 |
"""
|
2506.3.1
by Andrew Bennetts
More progress: |
312 |
# Read the content length.
|
313 |
length_line = self._read_line() |
|
314 |
try: |
|
315 |
length = int(length_line) |
|
316 |
except ValueError: |
|
317 |
raise errors.InvalidRecordError( |
|
318 |
"%r is not a valid length." % (length_line,)) |
|
319 |
||
320 |
# Read the list of names.
|
|
2506.2.1
by Andrew Bennetts
Start implementing container format reading and writing. |
321 |
names = [] |
322 |
while True: |
|
2682.1.1
by Robert Collins
* The ``bzrlib.pack`` interface has changed to use tuples of bytestrings |
323 |
name_line = self._read_line() |
324 |
if name_line == '': |
|
2506.2.1
by Andrew Bennetts
Start implementing container format reading and writing. |
325 |
break
|
2682.1.1
by Robert Collins
* The ``bzrlib.pack`` interface has changed to use tuples of bytestrings |
326 |
name_tuple = tuple(name_line.split('\x00')) |
327 |
for name in name_tuple: |
|
328 |
_check_name(name) |
|
329 |
names.append(name_tuple) |
|
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
330 |
|
331 |
self._remaining_length = length |
|
332 |
return names, self._content_reader |
|
333 |
||
334 |
def _content_reader(self, max_length): |
|
335 |
if max_length is None: |
|
336 |
length_to_read = self._remaining_length |
|
337 |
else: |
|
338 |
length_to_read = min(max_length, self._remaining_length) |
|
339 |
self._remaining_length -= length_to_read |
|
340 |
bytes = self.reader_func(length_to_read) |
|
341 |
if len(bytes) != length_to_read: |
|
2506.3.3
by Andrew Bennetts
Deal with EOF in the middle of a bytes record. |
342 |
raise errors.UnexpectedEndOfContainerError() |
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
343 |
return bytes |
2506.2.1
by Andrew Bennetts
Start implementing container format reading and writing. |
344 |
|
2506.2.6
by Andrew Bennetts
Add validate method to ContainerReader and BytesRecordReader. |
345 |
def validate(self): |
346 |
"""Validate this record.
|
|
347 |
||
348 |
You can either validate or read, you can't do both.
|
|
349 |
||
350 |
:raises ContainerError: if this record is invalid.
|
|
351 |
"""
|
|
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
352 |
names, read_bytes = self.read() |
2682.1.1
by Robert Collins
* The ``bzrlib.pack`` interface has changed to use tuples of bytestrings |
353 |
for name_tuple in names: |
354 |
for name in name_tuple: |
|
355 |
_check_name_encoding(name) |
|
2506.6.1
by Andrew Bennetts
Return a callable instead of a str from read, and add more validation. |
356 |
read_bytes(None) |
357 |