~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/pack.py

  • Committer: Daniel Watkins
  • Date: 2007-07-31 10:33:33 UTC
  • mto: (2687.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 2689.
  • Revision ID: d.m.watkins@warwick.ac.uk-20070731103333-sdelcaazn0fxgaf3
Added tests for ExtendedTestResult.wasStrictlySuccessful.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Container format for Bazaar data.
18
18
 
19
 
"Containers" and "records" are described in
20
 
doc/developers/container-format.txt.
 
19
"Containers" and "records" are described in doc/developers/container-format.txt.
21
20
"""
22
21
 
23
 
from cStringIO import StringIO
24
22
import re
25
23
 
26
24
from bzrlib import errors
34
32
 
35
33
def _check_name(name):
36
34
    """Do some basic checking of 'name'.
37
 
 
 
35
    
38
36
    At the moment, this just checks that there are no whitespace characters in a
39
37
    name.
40
38
 
47
45
 
48
46
def _check_name_encoding(name):
49
47
    """Check that 'name' is valid UTF-8.
50
 
 
 
48
    
51
49
    This is separate from _check_name because UTF-8 decoding is relatively
52
50
    expensive, and we usually want to avoid it.
53
51
 
59
57
        raise errors.InvalidRecordError(str(e))
60
58
 
61
59
 
62
 
class ContainerSerialiser(object):
63
 
    """A helper class for serialising containers.
64
 
 
65
 
    It simply returns bytes from method calls to 'begin', 'end' and
66
 
    'bytes_record'.  You may find ContainerWriter to be a more convenient
67
 
    interface.
68
 
    """
 
60
class ContainerWriter(object):
 
61
    """A class for writing containers."""
 
62
 
 
63
    def __init__(self, write_func):
 
64
        """Constructor.
 
65
 
 
66
        :param write_func: a callable that will be called when this
 
67
            ContainerWriter needs to write some bytes.
 
68
        """
 
69
        self.write_func = write_func
69
70
 
70
71
    def begin(self):
71
 
        """Return the bytes to begin a container."""
72
 
        return FORMAT_ONE + "\n"
 
72
        """Begin writing a container."""
 
73
        self.write_func(FORMAT_ONE + "\n")
73
74
 
74
75
    def end(self):
75
 
        """Return the bytes to finish a container."""
76
 
        return "E"
 
76
        """Finish writing a container."""
 
77
        self.write_func("E")
77
78
 
78
 
    def bytes_record(self, bytes, names):
79
 
        """Return the bytes for a Bytes record with the given name and
80
 
        contents.
81
 
        """
 
79
    def add_bytes_record(self, bytes, names):
 
80
        """Add a Bytes record with the given names."""
82
81
        # Kind marker
83
 
        byte_sections = ["B"]
 
82
        self.write_func("B")
84
83
        # Length
85
 
        byte_sections.append(str(len(bytes)) + "\n")
 
84
        self.write_func(str(len(bytes)) + "\n")
86
85
        # Names
87
 
        for name_tuple in names:
 
86
        for name in names:
88
87
            # Make sure we're writing valid names.  Note that we will leave a
89
88
            # half-written record if a name is bad!
90
 
            for name in name_tuple:
91
 
                _check_name(name)
92
 
            byte_sections.append('\x00'.join(name_tuple) + "\n")
 
89
            _check_name(name)
 
90
            self.write_func(name + "\n")
93
91
        # End of headers
94
 
        byte_sections.append("\n")
 
92
        self.write_func("\n")
95
93
        # Finally, the contents.
96
 
        byte_sections.append(bytes)
97
 
        # XXX: This causes a memory copy of bytes in size, but is usually
98
 
        # faster than two write calls (12 vs 13 seconds to output a gig of
99
 
        # 1k records.) - results may differ on significantly larger records
100
 
        # like .iso's but as they should be rare in any case and thus not
101
 
        # likely to be the common case. The biggest issue is causing extreme
102
 
        # memory pressure in that case. One possibly improvement here is to
103
 
        # check the size of the content before deciding to join here vs call
104
 
        # write twice.
105
 
        return ''.join(byte_sections)
106
 
 
107
 
 
108
 
class ContainerWriter(object):
109
 
    """A class for writing containers to a file.
110
 
 
111
 
    :attribute records_written: The number of user records added to the
112
 
        container. This does not count the prelude or suffix of the container
113
 
        introduced by the begin() and end() methods.
114
 
    """
115
 
 
116
 
    def __init__(self, write_func):
117
 
        """Constructor.
118
 
 
119
 
        :param write_func: a callable that will be called when this
120
 
            ContainerWriter needs to write some bytes.
121
 
        """
122
 
        self._write_func = write_func
123
 
        self.current_offset = 0
124
 
        self.records_written = 0
125
 
        self._serialiser = ContainerSerialiser()
126
 
 
127
 
    def begin(self):
128
 
        """Begin writing a container."""
129
 
        self.write_func(self._serialiser.begin())
130
 
 
131
 
    def write_func(self, bytes):
132
 
        self._write_func(bytes)
133
 
        self.current_offset += len(bytes)
134
 
 
135
 
    def end(self):
136
 
        """Finish writing a container."""
137
 
        self.write_func(self._serialiser.end())
138
 
 
139
 
    def add_bytes_record(self, bytes, names):
140
 
        """Add a Bytes record with the given names.
141
 
 
142
 
        :param bytes: The bytes to insert.
143
 
        :param names: The names to give the inserted bytes. Each name is
144
 
            a tuple of bytestrings. The bytestrings may not contain
145
 
            whitespace.
146
 
        :return: An offset, length tuple. The offset is the offset
147
 
            of the record within the container, and the length is the
148
 
            length of data that will need to be read to reconstitute the
149
 
            record. These offset and length can only be used with the pack
150
 
            interface - they might be offset by headers or other such details
151
 
            and thus are only suitable for use by a ContainerReader.
152
 
        """
153
 
        current_offset = self.current_offset
154
 
        serialised_record = self._serialiser.bytes_record(bytes, names)
155
 
        self.write_func(serialised_record)
156
 
        self.records_written += 1
157
 
        # return a memo of where we wrote data to allow random access.
158
 
        return current_offset, self.current_offset - current_offset
159
 
 
160
 
 
161
 
class ReadVFile(object):
162
 
    """Adapt a readv result iterator to a file like protocol."""
163
 
 
164
 
    def __init__(self, readv_result):
165
 
        self.readv_result = readv_result
166
 
        # the most recent readv result block
167
 
        self._string = None
168
 
 
169
 
    def _next(self):
170
 
        if (self._string is None or
171
 
            self._string.tell() == self._string_length):
172
 
            length, data = self.readv_result.next()
173
 
            self._string_length = len(data)
174
 
            self._string = StringIO(data)
175
 
 
176
 
    def read(self, length):
177
 
        self._next()
178
 
        result = self._string.read(length)
179
 
        if len(result) < length:
180
 
            raise errors.BzrError('request for too much data from a readv hunk.')
181
 
        return result
182
 
 
183
 
    def readline(self):
184
 
        """Note that readline will not cross readv segments."""
185
 
        self._next()
186
 
        result = self._string.readline()
187
 
        if self._string.tell() == self._string_length and result[-1] != '\n':
188
 
            raise errors.BzrError('short readline in the readvfile hunk.')
189
 
        return result
190
 
 
191
 
 
192
 
def make_readv_reader(transport, filename, requested_records):
193
 
    """Create a ContainerReader that will read selected records only.
194
 
 
195
 
    :param transport: The transport the pack file is located on.
196
 
    :param filename: The filename of the pack file.
197
 
    :param requested_records: The record offset, length tuples as returned
198
 
        by add_bytes_record for the desired records.
199
 
    """
200
 
    readv_blocks = [(0, len(FORMAT_ONE)+1)]
201
 
    readv_blocks.extend(requested_records)
202
 
    result = ContainerReader(ReadVFile(
203
 
        transport.readv(filename, readv_blocks)))
204
 
    return result
 
94
        self.write_func(bytes)
205
95
 
206
96
 
207
97
class BaseReader(object):
234
124
        is a ``list`` and bytes is a function that takes one argument,
235
125
        ``max_length``.
236
126
 
237
 
        You **must not** call the callable after advancing the iterator to the
 
127
        You **must not** call the callable after advancing the interator to the
238
128
        next record.  That is, this code is invalid::
239
129
 
240
130
            record_iter = container.iter_records()
241
131
            names1, callable1 = record_iter.next()
242
132
            names2, callable2 = record_iter.next()
243
133
            bytes1 = callable1(None)
244
 
 
 
134
        
245
135
        As it will give incorrect results and invalidate the state of the
246
136
        ContainerReader.
247
137
 
248
 
        :raises ContainerError: if any sort of container corruption is
 
138
        :raises ContainerError: if any sort of containter corruption is
249
139
            detected, e.g. UnknownContainerFormatError is the format of the
250
140
            container is unrecognised.
251
141
        :seealso: ContainerReader.read
252
142
        """
253
143
        self._read_format()
254
144
        return self._iter_records()
255
 
 
 
145
    
256
146
    def iter_record_objects(self):
257
147
        """Iterate over the container, yielding each record as it is read.
258
148
 
260
150
        methods.  Like with iter_records, it is not safe to use a record object
261
151
        after advancing the iterator to yield next record.
262
152
 
263
 
        :raises ContainerError: if any sort of container corruption is
 
153
        :raises ContainerError: if any sort of containter corruption is
264
154
            detected, e.g. UnknownContainerFormatError is the format of the
265
155
            container is unrecognised.
266
156
        :seealso: iter_records
267
157
        """
268
158
        self._read_format()
269
159
        return self._iter_record_objects()
270
 
 
 
160
    
271
161
    def _iter_records(self):
272
162
        for record in self._iter_record_objects():
273
163
            yield record.read()
307
197
        all_names = set()
308
198
        for record_names, read_bytes in self.iter_records():
309
199
            read_bytes(None)
310
 
            for name_tuple in record_names:
311
 
                for name in name_tuple:
312
 
                    _check_name_encoding(name)
 
200
            for name in record_names:
 
201
                _check_name_encoding(name)
313
202
                # Check that the name is unique.  Note that Python will refuse
314
203
                # to decode non-shortest forms of UTF-8 encoding, so there is no
315
204
                # risk that the same unicode string has been encoded two
316
205
                # different ways.
317
 
                if name_tuple in all_names:
318
 
                    raise errors.DuplicateRecordNameError(name_tuple)
319
 
                all_names.add(name_tuple)
 
206
                if name in all_names:
 
207
                    raise errors.DuplicateRecordNameError(name)
 
208
                all_names.add(name)
320
209
        excess_bytes = self.reader_func(1)
321
210
        if excess_bytes != '':
322
211
            raise errors.ContainerHasExcessDataError(excess_bytes)
342
231
        except ValueError:
343
232
            raise errors.InvalidRecordError(
344
233
                "%r is not a valid length." % (length_line,))
345
 
 
 
234
        
346
235
        # Read the list of names.
347
236
        names = []
348
237
        while True:
349
 
            name_line = self._read_line()
350
 
            if name_line == '':
 
238
            name = self._read_line()
 
239
            if name == '':
351
240
                break
352
 
            name_tuple = tuple(name_line.split('\x00'))
353
 
            for name in name_tuple:
354
 
                _check_name(name)
355
 
            names.append(name_tuple)
 
241
            _check_name(name)
 
242
            names.append(name)
356
243
 
357
244
        self._remaining_length = length
358
245
        return names, self._content_reader
376
263
        :raises ContainerError: if this record is invalid.
377
264
        """
378
265
        names, read_bytes = self.read()
379
 
        for name_tuple in names:
380
 
            for name in name_tuple:
381
 
                _check_name_encoding(name)
 
266
        for name in names:
 
267
            _check_name_encoding(name)
382
268
        read_bytes(None)
383
269
 
384
 
 
385
 
class ContainerPushParser(object):
386
 
    """A "push" parser for container format 1.
387
 
 
388
 
    It accepts bytes via the ``accept_bytes`` method, and parses them into
389
 
    records which can be retrieved via the ``read_pending_records`` method.
390
 
    """
391
 
 
392
 
    def __init__(self):
393
 
        self._buffer = ''
394
 
        self._state_handler = self._state_expecting_format_line
395
 
        self._parsed_records = []
396
 
        self._reset_current_record()
397
 
        self.finished = False
398
 
 
399
 
    def _reset_current_record(self):
400
 
        self._current_record_length = None
401
 
        self._current_record_names = []
402
 
 
403
 
    def accept_bytes(self, bytes):
404
 
        self._buffer += bytes
405
 
        # Keep iterating the state machine until it stops consuming bytes from
406
 
        # the buffer.
407
 
        last_buffer_length = None
408
 
        cur_buffer_length = len(self._buffer)
409
 
        while cur_buffer_length != last_buffer_length:
410
 
            last_buffer_length = cur_buffer_length
411
 
            self._state_handler()
412
 
            cur_buffer_length = len(self._buffer)
413
 
 
414
 
    def read_pending_records(self, max=None):
415
 
        if max:
416
 
            records = self._parsed_records[:max]
417
 
            del self._parsed_records[:max]
418
 
            return records
419
 
        else:
420
 
            records = self._parsed_records
421
 
            self._parsed_records = []
422
 
            return records
423
 
 
424
 
    def _consume_line(self):
425
 
        """Take a line out of the buffer, and return the line.
426
 
 
427
 
        If a newline byte is not found in the buffer, the buffer is
428
 
        unchanged and this returns None instead.
429
 
        """
430
 
        newline_pos = self._buffer.find('\n')
431
 
        if newline_pos != -1:
432
 
            line = self._buffer[:newline_pos]
433
 
            self._buffer = self._buffer[newline_pos+1:]
434
 
            return line
435
 
        else:
436
 
            return None
437
 
 
438
 
    def _state_expecting_format_line(self):
439
 
        line = self._consume_line()
440
 
        if line is not None:
441
 
            if line != FORMAT_ONE:
442
 
                raise errors.UnknownContainerFormatError(line)
443
 
            self._state_handler = self._state_expecting_record_type
444
 
 
445
 
    def _state_expecting_record_type(self):
446
 
        if len(self._buffer) >= 1:
447
 
            record_type = self._buffer[0]
448
 
            self._buffer = self._buffer[1:]
449
 
            if record_type == 'B':
450
 
                self._state_handler = self._state_expecting_length
451
 
            elif record_type == 'E':
452
 
                self.finished = True
453
 
                self._state_handler = self._state_expecting_nothing
454
 
            else:
455
 
                raise errors.UnknownRecordTypeError(record_type)
456
 
 
457
 
    def _state_expecting_length(self):
458
 
        line = self._consume_line()
459
 
        if line is not None:
460
 
            try:
461
 
                self._current_record_length = int(line)
462
 
            except ValueError:
463
 
                raise errors.InvalidRecordError(
464
 
                    "%r is not a valid length." % (line,))
465
 
            self._state_handler = self._state_expecting_name
466
 
 
467
 
    def _state_expecting_name(self):
468
 
        encoded_name_parts = self._consume_line()
469
 
        if encoded_name_parts == '':
470
 
            self._state_handler = self._state_expecting_body
471
 
        elif encoded_name_parts:
472
 
            name_parts = tuple(encoded_name_parts.split('\x00'))
473
 
            for name_part in name_parts:
474
 
                _check_name(name_part)
475
 
            self._current_record_names.append(name_parts)
476
 
 
477
 
    def _state_expecting_body(self):
478
 
        if len(self._buffer) >= self._current_record_length:
479
 
            body_bytes = self._buffer[:self._current_record_length]
480
 
            self._buffer = self._buffer[self._current_record_length:]
481
 
            record = (self._current_record_names, body_bytes)
482
 
            self._parsed_records.append(record)
483
 
            self._reset_current_record()
484
 
            self._state_handler = self._state_expecting_record_type
485
 
 
486
 
    def _state_expecting_nothing(self):
487
 
        pass
488
 
 
489
 
    def read_size_hint(self):
490
 
        hint = 16384
491
 
        if self._state_handler == self._state_expecting_body:
492
 
            remaining = self._current_record_length - len(self._buffer)
493
 
            if remaining < 0:
494
 
                remaining = 0
495
 
            return max(hint, remaining)
496
 
        return hint
497
 
 
498
 
 
499
 
def iter_records_from_file(source_file):
500
 
    parser = ContainerPushParser()
501
 
    while True:
502
 
        bytes = source_file.read(parser.read_size_hint())
503
 
        parser.accept_bytes(bytes)
504
 
        for record in parser.read_pending_records():
505
 
            yield record
506
 
        if parser.finished:
507
 
            break
508