~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/container.py

Start implementing container format reading and writing.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
 
 
22
# XXX: probably rename this to pack.py
 
23
 
 
24
from bzrlib import errors
 
25
 
 
26
 
 
27
FORMAT_ONE = "bzr pack format 1"
 
28
 
 
29
 
 
30
class ContainerReader(object):
 
31
    """A class for reading Bazaar's container format."""
 
32
 
 
33
    def __init__(self, reader_func):
 
34
        """Constructor.
 
35
 
 
36
        :param reader_func: a callable that takes one optional argument,
 
37
            ``size``, and returns at most that many bytes.  When the callable
 
38
            returns an empty string, then at most that many bytes are read.
 
39
        """
 
40
        self.reader_func = reader_func
 
41
 
 
42
    def iter_records(self):
 
43
        """Iterate over the container, yielding each record as it is read.
 
44
 
 
45
        Each yielded record will be a 2-tuple of (names, bytes), where names is
 
46
        a ``list`` and bytes is a ``str`.
 
47
        """
 
48
        format = self._read_line()
 
49
        if format != FORMAT_ONE:
 
50
            raise errors.UnknownContainerFormatError(format)
 
51
        return self._iter_records()
 
52
    
 
53
    def _iter_records(self):
 
54
        while True:
 
55
            record_kind = self.reader_func(1)
 
56
            if record_kind == 'B':
 
57
                # Bytes record.
 
58
                yield self._read_bytes_record()
 
59
            elif record_kind == 'E':
 
60
                # End marker.  There are no more records.
 
61
                return
 
62
            elif record_kind == '':
 
63
                # End of stream encountered, but no End Marker record seen, so
 
64
                # this container is incomplete.
 
65
                raise errors.UnexpectedEndOfContainerError()
 
66
            else:
 
67
                # Unknown record type.
 
68
                raise errors.UnknownRecordTypeError(record_kind)
 
69
 
 
70
    def _read_bytes_record(self):
 
71
        length = int(self._read_line())
 
72
        names = []
 
73
        while True:
 
74
            name = self._read_line()
 
75
            if name == '':
 
76
                break
 
77
            names.append(name)
 
78
        bytes = self.reader_func(length)
 
79
        # XXX: deal with case where len(bytes) != length
 
80
        return names, bytes
 
81
 
 
82
    def _read_line(self):
 
83
        """Read a line from the input stream.
 
84
 
 
85
        This is a simple but inefficient implementation that just reads one byte
 
86
        at a time.  Lines should not be very long, so this is probably
 
87
        tolerable.
 
88
 
 
89
        :returns: a line, without the trailing newline
 
90
        """
 
91
        # XXX: Have a maximum line length, to prevent malicious input from
 
92
        # consuming an unreasonable amount of resources?
 
93
        #   -- Andrew Bennetts, 2007-05-07.
 
94
        line = ''
 
95
        while not line.endswith('\n'):
 
96
            line += self.reader_func(1)
 
97
        return line[:-1]
 
98
 
 
99
 
 
100
class ContainerWriter(object):
 
101
    """A class for writing containers."""
 
102
 
 
103
    def __init__(self, write_func):
 
104
        """Constructor.
 
105
 
 
106
        :param write_func: a callable that will be called when this
 
107
            ContainerWriter needs to write some bytes.
 
108
        """
 
109
        self.write_func = write_func
 
110
 
 
111
    def begin(self):
 
112
        """Begin writing a container."""
 
113
        self.write_func(FORMAT_ONE + "\n")
 
114
 
 
115
    def end(self):
 
116
        """Finish writing a container."""
 
117
        self.write_func("E")
 
118
 
 
119
    def add_bytes_record(self, bytes, names):
 
120
        """Add a Bytes record with the given names."""
 
121
        # Kind marker
 
122
        self.write_func("B")
 
123
        # Length
 
124
        self.write_func(str(len(bytes)) + "\n")
 
125
        # Names
 
126
        for name in names:
 
127
            self.write_func(name + "\n")
 
128
        # End of headers
 
129
        self.write_func("\n")
 
130
        # Finally, the contents.
 
131
        self.write_func(bytes)
 
132