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

  • Committer: Jelmer Vernooij
  • Date: 2009-05-14 11:11:02 UTC
  • mto: (4290.1.9 rio-serializer2)
  • mto: This revision was merged to the branch mainline in revision 4368.
  • Revision ID: jelmer@samba.org-20090514111102-v9dxbsj3r83jkato
Provide custom implementation of _read_stanza_utf8 in Pyrex.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
# \subsection{\emph{rio} - simple text metaformat}
 
18
#
 
19
# \emph{r} stands for `restricted', `reproducible', or `rfc822-like'.
 
20
#
 
21
# The stored data consists of a series of \emph{stanzas}, each of which contains
 
22
# \emph{fields} identified by an ascii name, with Unicode or string contents.
 
23
# The field tag is constrained to alphanumeric characters.
 
24
# There may be more than one field in a stanza with the same name.
 
25
#
 
26
# The format itself does not deal with character encoding issues, though
 
27
# the result will normally be written in Unicode.
 
28
#
 
29
# The format is intended to be simple enough that there is exactly one character
 
30
# stream representation of an object and vice versa, and that this relation
 
31
# will continue to hold for future versions of bzr.
 
32
 
 
33
import re
 
34
 
 
35
from bzrlib.iterablefile import IterableFile
 
36
 
 
37
# XXX: some redundancy is allowing to write stanzas in isolation as well as
 
38
# through a writer object.
 
39
 
 
40
class RioWriter(object):
 
41
    def __init__(self, to_file):
 
42
        self._soft_nl = False
 
43
        self._to_file = to_file
 
44
 
 
45
    def write_stanza(self, stanza):
 
46
        if self._soft_nl:
 
47
            self._to_file.write('\n')
 
48
        stanza.write(self._to_file)
 
49
        self._soft_nl = True
 
50
 
 
51
 
 
52
class RioReader(object):
 
53
    """Read stanzas from a file as a sequence
 
54
 
 
55
    to_file can be anything that can be enumerated as a sequence of
 
56
    lines (with newlines.)
 
57
    """
 
58
    def __init__(self, from_file):
 
59
        self._from_file = from_file
 
60
 
 
61
    def __iter__(self):
 
62
        while True:
 
63
            s = read_stanza(self._from_file)
 
64
            if s is None:
 
65
                break
 
66
            else:
 
67
                yield s
 
68
 
 
69
 
 
70
def rio_file(stanzas, header=None):
 
71
    """Produce a rio IterableFile from an iterable of stanzas"""
 
72
    def str_iter():
 
73
        if header is not None:
 
74
            yield header + '\n'
 
75
        first_stanza = True
 
76
        for s in stanzas:
 
77
            if first_stanza is not True:
 
78
                yield '\n'
 
79
            for line in s.to_lines():
 
80
                yield line
 
81
            first_stanza = False
 
82
    return IterableFile(str_iter())
 
83
 
 
84
 
 
85
def read_stanzas(from_file):
 
86
    while True:
 
87
        s = read_stanza(from_file)
 
88
        if s is None:
 
89
            break
 
90
        else:
 
91
            yield s
 
92
 
 
93
class Stanza(object):
 
94
    """One stanza for rio.
 
95
 
 
96
    Each stanza contains a set of named fields.
 
97
 
 
98
    Names must be non-empty ascii alphanumeric plus _.  Names can be repeated
 
99
    within a stanza.  Names are case-sensitive.  The ordering of fields is
 
100
    preserved.
 
101
 
 
102
    Each field value must be either an int or a string.
 
103
    """
 
104
 
 
105
    __slots__ = ['items']
 
106
 
 
107
    def __init__(self, **kwargs):
 
108
        """Construct a new Stanza.
 
109
 
 
110
        The keyword arguments, if any, are added in sorted order to the stanza.
 
111
        """
 
112
        self.items = []
 
113
        if kwargs:
 
114
            for tag, value in sorted(kwargs.items()):
 
115
                self.add(tag, value)
 
116
 
 
117
    def add(self, tag, value):
 
118
        """Append a name and value to the stanza."""
 
119
        if not valid_tag(tag):
 
120
            raise ValueError("invalid tag %r" % (tag,))
 
121
        if isinstance(value, str):
 
122
            value = unicode(value)
 
123
        elif isinstance(value, unicode):
 
124
            pass
 
125
        ## elif isinstance(value, (int, long)):
 
126
        ##    value = str(value)           # XXX: python2.4 without L-suffix
 
127
        else:
 
128
            raise TypeError("invalid type for rio value: %r of type %s"
 
129
                            % (value, type(value)))
 
130
        self.items.append((tag, value))
 
131
 
 
132
    def __contains__(self, find_tag):
 
133
        """True if there is any field in this stanza with the given tag."""
 
134
        for tag, value in self.items:
 
135
            if tag == find_tag:
 
136
                return True
 
137
        return False
 
138
 
 
139
    def __len__(self):
 
140
        """Return number of pairs in the stanza."""
 
141
        return len(self.items)
 
142
 
 
143
    def __eq__(self, other):
 
144
        if not isinstance(other, Stanza):
 
145
            return False
 
146
        return self.items == other.items
 
147
 
 
148
    def __ne__(self, other):
 
149
        return not self.__eq__(other)
 
150
 
 
151
    def __repr__(self):
 
152
        return "Stanza(%r)" % self.items
 
153
 
 
154
    def iter_pairs(self):
 
155
        """Return iterator of tag, value pairs."""
 
156
        return iter(self.items)
 
157
 
 
158
    def to_lines(self):
 
159
        """Generate sequence of lines for external version of this file.
 
160
 
 
161
        The lines are always utf-8 encoded strings.
 
162
        """
 
163
        if not self.items:
 
164
            # max() complains if sequence is empty
 
165
            return []
 
166
        result = []
 
167
        for tag, value in self.items:
 
168
            if value == '':
 
169
                result.append(tag + ': \n')
 
170
            elif '\n' in value:
 
171
                # don't want splitlines behaviour on empty lines
 
172
                val_lines = value.split('\n')
 
173
                result.append(tag + ': ' + val_lines[0].encode('utf-8') + '\n')
 
174
                for line in val_lines[1:]:
 
175
                    result.append('\t' + line.encode('utf-8') + '\n')
 
176
            else:
 
177
                result.append(tag + ': ' + value.encode('utf-8') + '\n')
 
178
        return result
 
179
 
 
180
    def to_string(self):
 
181
        """Return stanza as a single string"""
 
182
        return ''.join(self.to_lines())
 
183
 
 
184
    def to_unicode(self):
 
185
        """Return stanza as a single Unicode string.
 
186
 
 
187
        This is most useful when adding a Stanza to a parent Stanza
 
188
        """
 
189
        if not self.items:
 
190
            return u''
 
191
 
 
192
        result = []
 
193
        for tag, value in self.items:
 
194
            if value == '':
 
195
                result.append(tag + ': \n')
 
196
            elif '\n' in value:
 
197
                # don't want splitlines behaviour on empty lines
 
198
                val_lines = value.split('\n')
 
199
                result.append(tag + ': ' + val_lines[0] + '\n')
 
200
                for line in val_lines[1:]:
 
201
                    result.append('\t' + line + '\n')
 
202
            else:
 
203
                result.append(tag + ': ' + value + '\n')
 
204
        return u''.join(result)
 
205
 
 
206
    def write(self, to_file):
 
207
        """Write stanza to a file"""
 
208
        to_file.writelines(self.to_lines())
 
209
 
 
210
    def get(self, tag):
 
211
        """Return the value for a field wih given tag.
 
212
 
 
213
        If there is more than one value, only the first is returned.  If the
 
214
        tag is not present, KeyError is raised.
 
215
        """
 
216
        for t, v in self.items:
 
217
            if t == tag:
 
218
                return v
 
219
        else:
 
220
            raise KeyError(tag)
 
221
 
 
222
    __getitem__ = get
 
223
 
 
224
    def get_all(self, tag):
 
225
        r = []
 
226
        for t, v in self.items:
 
227
            if t == tag:
 
228
                r.append(v)
 
229
        return r
 
230
 
 
231
    def as_dict(self):
 
232
        """Return a dict containing the unique values of the stanza.
 
233
        """
 
234
        d = {}
 
235
        for tag, value in self.items:
 
236
            d[tag] = value
 
237
        return d
 
238
 
 
239
 
 
240
def valid_tag(tag):
 
241
    return _valid_tag(tag)
 
242
 
 
243
 
 
244
def read_stanza(line_iter):
 
245
    """Return new Stanza read from list of lines or a file
 
246
 
 
247
    Returns one Stanza that was read, or returns None at end of file.  If a
 
248
    blank line follows the stanza, it is consumed.  It's not an error for
 
249
    there to be no blank at end of file.  If there is a blank file at the
 
250
    start of the input this is really an empty stanza and that is returned.
 
251
 
 
252
    Only the stanza lines and the trailing blank (if any) are consumed
 
253
    from the line_iter.
 
254
 
 
255
    The raw lines must be in utf-8 encoding.
 
256
    """
 
257
    return _read_stanza_utf8(line_iter)
 
258
 
 
259
 
 
260
def read_stanza_unicode(unicode_iter):
 
261
    """Read a Stanza from a list of lines or a file.
 
262
 
 
263
    The lines should already be in unicode form. This returns a single
 
264
    stanza that was read. If there is a blank line at the end of the Stanza,
 
265
    it is consumed. It is not an error for there to be no blank line at
 
266
    the end of the iterable. If there is a blank line at the beginning,
 
267
    this is treated as an empty Stanza and None is returned.
 
268
 
 
269
    Only the stanza lines and the trailing blank (if any) are consumed
 
270
    from the unicode_iter
 
271
 
 
272
    :param unicode_iter: A iterable, yeilding Unicode strings. See read_stanza
 
273
        if you have a utf-8 encoded string.
 
274
    :return: A Stanza object if there are any lines in the file.
 
275
        None otherwise
 
276
    """
 
277
    return _read_stanza_unicode(unicode_iter)
 
278
 
 
279
def to_patch_lines(stanza, max_width=72):
 
280
    """Convert a stanza into RIO-Patch format lines.
 
281
 
 
282
    RIO-Patch is a RIO variant designed to be e-mailed as part of a patch.
 
283
    It resists common forms of damage such as newline conversion or the removal
 
284
    of trailing whitespace, yet is also reasonably easy to read.
 
285
 
 
286
    :param max_width: The maximum number of characters per physical line.
 
287
    :return: a list of lines
 
288
    """
 
289
    if max_width <= 6:
 
290
        raise ValueError(max_width)
 
291
    max_rio_width = max_width - 4
 
292
    lines = []
 
293
    for pline in stanza.to_lines():
 
294
        for line in pline.split('\n')[:-1]:
 
295
            line = re.sub('\\\\', '\\\\\\\\', line)
 
296
            while len(line) > 0:
 
297
                partline = line[:max_rio_width]
 
298
                line = line[max_rio_width:]
 
299
                if len(line) > 0 and line[0] != [' ']:
 
300
                    break_index = -1
 
301
                    break_index = partline.rfind(' ', -20)
 
302
                    if break_index < 3:
 
303
                        break_index = partline.rfind('-', -20)
 
304
                        break_index += 1
 
305
                    if break_index < 3:
 
306
                        break_index = partline.rfind('/', -20)
 
307
                    if break_index >= 3:
 
308
                        line = partline[break_index:] + line
 
309
                        partline = partline[:break_index]
 
310
                if len(line) > 0:
 
311
                    line = '  ' + line
 
312
                partline = re.sub('\r', '\\\\r', partline)
 
313
                blank_line = False
 
314
                if len(line) > 0:
 
315
                    partline += '\\'
 
316
                elif re.search(' $', partline):
 
317
                    partline += '\\'
 
318
                    blank_line = True
 
319
                lines.append('# ' + partline + '\n')
 
320
                if blank_line:
 
321
                    lines.append('#   \n')
 
322
    return lines
 
323
 
 
324
 
 
325
def _patch_stanza_iter(line_iter):
 
326
    map = {'\\\\': '\\',
 
327
           '\\r' : '\r',
 
328
           '\\\n': ''}
 
329
    def mapget(match):
 
330
        return map[match.group(0)]
 
331
 
 
332
    last_line = None
 
333
    for line in line_iter:
 
334
        if line.startswith('# '):
 
335
            line = line[2:]
 
336
        elif line.startswith('#'):
 
337
            line = line[1:]
 
338
        else:
 
339
            raise ValueError("bad line %r" % (line,))
 
340
        if last_line is not None and len(line) > 2:
 
341
            line = line[2:]
 
342
        line = re.sub('\r', '', line)
 
343
        line = re.sub('\\\\(.|\n)', mapget, line)
 
344
        if last_line is None:
 
345
            last_line = line
 
346
        else:
 
347
            last_line += line
 
348
        if last_line[-1] == '\n':
 
349
            yield last_line
 
350
            last_line = None
 
351
    if last_line is not None:
 
352
        yield last_line
 
353
 
 
354
 
 
355
def read_patch_stanza(line_iter):
 
356
    """Convert an iterable of RIO-Patch format lines into a Stanza.
 
357
 
 
358
    RIO-Patch is a RIO variant designed to be e-mailed as part of a patch.
 
359
    It resists common forms of damage such as newline conversion or the removal
 
360
    of trailing whitespace, yet is also reasonably easy to read.
 
361
 
 
362
    :return: a Stanza
 
363
    """
 
364
    return read_stanza(_patch_stanza_iter(line_iter))
 
365
 
 
366
 
 
367
try:
 
368
    from bzrlib._rio_pyx import (
 
369
        _read_stanza_utf8,
 
370
        _read_stanza_unicode,
 
371
        _valid_tag,
 
372
        )
 
373
except ImportError:
 
374
    from bzrlib._rio_py import (
 
375
       _read_stanza_utf8,
 
376
       _read_stanza_unicode,
 
377
       _valid_tag,
 
378
       )