/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/pack.py

  • Committer: Aaron Bentley
  • Date: 2007-06-13 03:54:07 UTC
  • mto: (2520.5.2 bzr.mpbundle)
  • mto: This revision was merged to the branch mainline in revision 2631.
  • Revision ID: aaron.bentley@utoronto.ca-20070613035407-6tijerg0tti5wocg
Fix _get_bundle invocations

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
from bzrlib import errors
 
23
 
 
24
 
 
25
FORMAT_ONE = "bzr pack format 1"
 
26
 
 
27
 
 
28
class ContainerWriter(object):
 
29
    """A class for writing containers."""
 
30
 
 
31
    def __init__(self, write_func):
 
32
        """Constructor.
 
33
 
 
34
        :param write_func: a callable that will be called when this
 
35
            ContainerWriter needs to write some bytes.
 
36
        """
 
37
        self.write_func = write_func
 
38
 
 
39
    def begin(self):
 
40
        """Begin writing a container."""
 
41
        self.write_func(FORMAT_ONE + "\n")
 
42
 
 
43
    def end(self):
 
44
        """Finish writing a container."""
 
45
        self.write_func("E")
 
46
 
 
47
    def add_bytes_record(self, bytes, names):
 
48
        """Add a Bytes record with the given names."""
 
49
        # Kind marker
 
50
        self.write_func("B")
 
51
        # Length
 
52
        self.write_func(str(len(bytes)) + "\n")
 
53
        # Names
 
54
        for name in names:
 
55
            self.write_func(name + "\n")
 
56
        # End of headers
 
57
        self.write_func("\n")
 
58
        # Finally, the contents.
 
59
        self.write_func(bytes)
 
60
 
 
61
 
 
62
class BaseReader(object):
 
63
 
 
64
    def __init__(self, reader_func):
 
65
        """Constructor.
 
66
 
 
67
        :param reader_func: a callable that takes one optional argument,
 
68
            ``size``, and returns at most that many bytes.  When the callable
 
69
            returns less than the requested number of bytes, then the end of the
 
70
            file/stream has been reached.
 
71
        """
 
72
        self.reader_func = reader_func
 
73
 
 
74
    def _read_line(self):
 
75
        """Read a line from the input stream.
 
76
 
 
77
        This is a simple but inefficient implementation that just reads one byte
 
78
        at a time.  Lines should not be very long, so this is probably
 
79
        tolerable.
 
80
 
 
81
        :returns: a line, without the trailing newline
 
82
        """
 
83
        # XXX: Have a maximum line length, to prevent malicious input from
 
84
        # consuming an unreasonable amount of resources?
 
85
        #   -- Andrew Bennetts, 2007-05-07.
 
86
        line = ''
 
87
        while not line.endswith('\n'):
 
88
            byte = self.reader_func(1)
 
89
            if byte == '':
 
90
                raise errors.UnexpectedEndOfContainerError()
 
91
            line += byte
 
92
        return line[:-1]
 
93
 
 
94
 
 
95
class ContainerReader(BaseReader):
 
96
    """A class for reading Bazaar's container format."""
 
97
 
 
98
    def iter_records(self):
 
99
        """Iterate over the container, yielding each record as it is read.
 
100
 
 
101
        Each yielded record will be a 2-tuple of (names, bytes), where names is
 
102
        a ``list`` and bytes is a ``str`.
 
103
 
 
104
        :raises UnknownContainerFormatError: if the format of the container is
 
105
            unrecognised.
 
106
        """
 
107
        format = self._read_line()
 
108
        if format != FORMAT_ONE:
 
109
            raise errors.UnknownContainerFormatError(format)
 
110
        return self._iter_records()
 
111
    
 
112
    def _iter_records(self):
 
113
        while True:
 
114
            record_kind = self.reader_func(1)
 
115
            if record_kind == 'B':
 
116
                # Bytes record.
 
117
                reader = BytesRecordReader(self.reader_func)
 
118
                yield reader.read()
 
119
            elif record_kind == 'E':
 
120
                # End marker.  There are no more records.
 
121
                return
 
122
            elif record_kind == '':
 
123
                # End of stream encountered, but no End Marker record seen, so
 
124
                # this container is incomplete.
 
125
                raise errors.UnexpectedEndOfContainerError()
 
126
            else:
 
127
                # Unknown record type.
 
128
                raise errors.UnknownRecordTypeError(record_kind)
 
129
 
 
130
 
 
131
class ContainerWriter(object):
 
132
    """A class for writing containers."""
 
133
 
 
134
    def __init__(self, write_func):
 
135
        """Constructor.
 
136
 
 
137
        :param write_func: a callable that will be called when this
 
138
            ContainerWriter needs to write some bytes.
 
139
        """
 
140
        self.write_func = write_func
 
141
 
 
142
    def begin(self):
 
143
        """Begin writing a container."""
 
144
        self.write_func(FORMAT_ONE + "\n")
 
145
 
 
146
    def end(self):
 
147
        """Finish writing a container."""
 
148
        self.write_func("E")
 
149
 
 
150
    def add_bytes_record(self, bytes, names):
 
151
        """Add a Bytes record with the given names."""
 
152
        # Kind marker
 
153
        self.write_func("B")
 
154
        # Length
 
155
        self.write_func(str(len(bytes)) + "\n")
 
156
        # Names
 
157
        for name in names:
 
158
            self.write_func(name + "\n")
 
159
        # End of headers
 
160
        self.write_func("\n")
 
161
        # Finally, the contents.
 
162
        self.write_func(bytes)
 
163
 
 
164
 
 
165
class BytesRecordReader(BaseReader):
 
166
 
 
167
    def read(self):
 
168
        # Read the content length.
 
169
        length_line = self._read_line()
 
170
        try:
 
171
            length = int(length_line)
 
172
        except ValueError:
 
173
            raise errors.InvalidRecordError(
 
174
                "%r is not a valid length." % (length_line,))
 
175
        
 
176
        # Read the list of names.
 
177
        names = []
 
178
        while True:
 
179
            name = self._read_line()
 
180
            if name == '':
 
181
                break
 
182
            names.append(name)
 
183
        bytes = self.reader_func(length)
 
184
        if len(bytes) != length:
 
185
            raise errors.UnexpectedEndOfContainerError()
 
186
        return names, bytes
 
187