1
# Copyright (C) 2005 Canonical Ltd
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.
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.
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
17
# \subsection{\emph{rio} - simple text metaformat}
19
# \emph{r} stands for `restricted', `reproducible', or `rfc822-like'.
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.
26
# The format itself does not deal with character encoding issues, though
27
# the result will normally be written in Unicode.
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.
35
from bzrlib.iterablefile import IterableFile
37
# XXX: some redundancy is allowing to write stanzas in isolation as well as
38
# through a writer object.
40
class RioWriter(object):
41
def __init__(self, to_file):
43
self._to_file = to_file
45
def write_stanza(self, stanza):
47
self._to_file.write('\n')
48
stanza.write(self._to_file)
52
class RioReader(object):
53
"""Read stanzas from a file as a sequence
55
to_file can be anything that can be enumerated as a sequence of
56
lines (with newlines.)
58
def __init__(self, from_file):
59
self._from_file = from_file
63
s = read_stanza(self._from_file)
70
def rio_file(stanzas, header=None):
71
"""Produce a rio IterableFile from an iterable of stanzas"""
73
if header is not None:
77
if first_stanza is not True:
79
for line in s.to_lines():
82
return IterableFile(str_iter())
85
def read_stanzas(from_file):
87
s = read_stanza(from_file)
94
"""One stanza for rio.
96
Each stanza contains a set of named fields.
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
102
Each field value must be either an int or a string.
105
__slots__ = ['items']
107
def __init__(self, **kwargs):
108
"""Construct a new Stanza.
110
The keyword arguments, if any, are added in sorted order to the stanza.
114
for tag, value in sorted(kwargs.items()):
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):
125
## elif isinstance(value, (int, long)):
126
## value = str(value) # XXX: python2.4 without L-suffix
128
raise TypeError("invalid type for rio value: %r of type %s"
129
% (value, type(value)))
130
self.items.append((tag, value))
133
def from_pairs(cls, pairs):
138
def __contains__(self, find_tag):
139
"""True if there is any field in this stanza with the given tag."""
140
for tag, value in self.items:
146
"""Return number of pairs in the stanza."""
147
return len(self.items)
149
def __eq__(self, other):
150
if not isinstance(other, Stanza):
152
return self.items == other.items
154
def __ne__(self, other):
155
return not self.__eq__(other)
158
return "Stanza(%r)" % self.items
160
def iter_pairs(self):
161
"""Return iterator of tag, value pairs."""
162
return iter(self.items)
165
"""Generate sequence of lines for external version of this file.
167
The lines are always utf-8 encoded strings.
170
# max() complains if sequence is empty
173
for tag, value in self.items:
175
result.append(tag + ': \n')
177
# don't want splitlines behaviour on empty lines
178
val_lines = value.split('\n')
179
result.append(tag + ': ' + val_lines[0].encode('utf-8') + '\n')
180
for line in val_lines[1:]:
181
result.append('\t' + line.encode('utf-8') + '\n')
183
result.append(tag + ': ' + value.encode('utf-8') + '\n')
187
"""Return stanza as a single string"""
188
return ''.join(self.to_lines())
190
def to_unicode(self):
191
"""Return stanza as a single Unicode string.
193
This is most useful when adding a Stanza to a parent Stanza
199
for tag, value in self.items:
201
result.append(tag + u': \n')
203
# don't want splitlines behaviour on empty lines
204
val_lines = value.split(u'\n')
205
result.append(tag + u': ' + val_lines[0] + u'\n')
206
for line in val_lines[1:]:
207
result.append(u'\t' + line + u'\n')
209
result.append(tag + u': ' + value + u'\n')
210
return u''.join(result)
212
def write(self, to_file):
213
"""Write stanza to a file"""
214
to_file.writelines(self.to_lines())
217
"""Return the value for a field wih given tag.
219
If there is more than one value, only the first is returned. If the
220
tag is not present, KeyError is raised.
222
for t, v in self.items:
230
def get_all(self, tag):
232
for t, v in self.items:
238
"""Return a dict containing the unique values of the stanza.
241
for tag, value in self.items:
247
return _valid_tag(tag)
250
def read_stanza(line_iter):
251
"""Return new Stanza read from list of lines or a file
253
Returns one Stanza that was read, or returns None at end of file. If a
254
blank line follows the stanza, it is consumed. It's not an error for
255
there to be no blank at end of file. If there is a blank file at the
256
start of the input this is really an empty stanza and that is returned.
258
Only the stanza lines and the trailing blank (if any) are consumed
261
The raw lines must be in utf-8 encoding.
263
return _read_stanza_utf8(line_iter)
266
def read_stanza_unicode(unicode_iter):
267
"""Read a Stanza from a list of lines or a file.
269
The lines should already be in unicode form. This returns a single
270
stanza that was read. If there is a blank line at the end of the Stanza,
271
it is consumed. It is not an error for there to be no blank line at
272
the end of the iterable. If there is a blank line at the beginning,
273
this is treated as an empty Stanza and None is returned.
275
Only the stanza lines and the trailing blank (if any) are consumed
276
from the unicode_iter
278
:param unicode_iter: A iterable, yeilding Unicode strings. See read_stanza
279
if you have a utf-8 encoded string.
280
:return: A Stanza object if there are any lines in the file.
283
return _read_stanza_unicode(unicode_iter)
286
def to_patch_lines(stanza, max_width=72):
287
"""Convert a stanza into RIO-Patch format lines.
289
RIO-Patch is a RIO variant designed to be e-mailed as part of a patch.
290
It resists common forms of damage such as newline conversion or the removal
291
of trailing whitespace, yet is also reasonably easy to read.
293
:param max_width: The maximum number of characters per physical line.
294
:return: a list of lines
297
raise ValueError(max_width)
298
max_rio_width = max_width - 4
300
for pline in stanza.to_lines():
301
for line in pline.split('\n')[:-1]:
302
line = re.sub('\\\\', '\\\\\\\\', line)
304
partline = line[:max_rio_width]
305
line = line[max_rio_width:]
306
if len(line) > 0 and line[0] != [' ']:
308
break_index = partline.rfind(' ', -20)
310
break_index = partline.rfind('-', -20)
313
break_index = partline.rfind('/', -20)
315
line = partline[break_index:] + line
316
partline = partline[:break_index]
319
partline = re.sub('\r', '\\\\r', partline)
323
elif re.search(' $', partline):
326
lines.append('# ' + partline + '\n')
332
def _patch_stanza_iter(line_iter):
337
return map[match.group(0)]
340
for line in line_iter:
341
if line.startswith('# '):
343
elif line.startswith('#'):
346
raise ValueError("bad line %r" % (line,))
347
if last_line is not None and len(line) > 2:
349
line = re.sub('\r', '', line)
350
line = re.sub('\\\\(.|\n)', mapget, line)
351
if last_line is None:
355
if last_line[-1] == '\n':
358
if last_line is not None:
362
def read_patch_stanza(line_iter):
363
"""Convert an iterable of RIO-Patch format lines into a Stanza.
365
RIO-Patch is a RIO variant designed to be e-mailed as part of a patch.
366
It resists common forms of damage such as newline conversion or the removal
367
of trailing whitespace, yet is also reasonably easy to read.
371
return read_stanza(_patch_stanza_iter(line_iter))
375
from bzrlib._rio_pyx import (
377
_read_stanza_unicode,
381
from bzrlib._rio_py import (
383
_read_stanza_unicode,