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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
1
# Copyright (C) 2005 by Canonical Ltd
3
# Distributed under the GNU General Public Licence v2
17
5
# \subsection{\emph{rio} - simple text metaformat}
19
7
# \emph{r} stands for `restricted', `reproducible', or `rfc822-like'.
117
91
def add(self, tag, value):
118
92
"""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):
93
assert valid_tag(tag), \
94
("invalid tag %r" % tag)
95
if isinstance(value, (str, unicode)):
125
97
## elif isinstance(value, (int, long)):
126
98
## 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)))
100
raise ValueError("invalid value %r" % value)
130
101
self.items.append((tag, value))
132
103
def __contains__(self, find_tag):
156
127
return iter(self.items)
158
129
def to_lines(self):
159
"""Generate sequence of lines for external version of this file.
161
The lines are always utf-8 encoded strings.
130
"""Generate sequence of lines for external version of this file."""
163
131
if not self.items:
164
132
# max() complains if sequence is empty
167
135
for tag, value in self.items:
136
assert isinstance(value, (str, unicode))
169
138
result.append(tag + ': \n')
170
139
elif '\n' in value:
171
140
# don't want splitlines behaviour on empty lines
172
141
val_lines = value.split('\n')
173
result.append(tag + ': ' + val_lines[0].encode('utf-8') + '\n')
142
result.append(tag + ': ' + val_lines[0] + '\n')
174
143
for line in val_lines[1:]:
175
result.append('\t' + line.encode('utf-8') + '\n')
144
result.append('\t' + line + '\n')
177
result.append(tag + ': ' + value.encode('utf-8') + '\n')
146
result.append(tag + ': ' + value + '\n')
180
149
def to_string(self):
181
150
"""Return stanza as a single string"""
182
151
return ''.join(self.to_lines())
184
def to_unicode(self):
185
"""Return stanza as a single Unicode string.
187
This is most useful when adding a Stanza to a parent Stanza
193
for tag, value in self.items:
195
result.append(tag + ': \n')
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')
203
result.append(tag + ': ' + value + '\n')
204
return u''.join(result)
206
153
def write(self, to_file):
207
154
"""Write stanza to a file"""
208
155
to_file.writelines(self.to_lines())
252
191
Only the stanza lines and the trailing blank (if any) are consumed
253
192
from the line_iter.
255
The raw lines must be in utf-8 encoding.
257
unicode_iter = (line.decode('utf-8') for line in line_iter)
258
return read_stanza_unicode(unicode_iter)
261
def read_stanza_unicode(unicode_iter):
262
"""Read a Stanza from a list of lines or a file.
264
The lines should already be in unicode form. This returns a single
265
stanza that was read. If there is a blank line at the end of the Stanza,
266
it is consumed. It is not an error for there to be no blank line at
267
the end of the iterable. If there is a blank line at the beginning,
268
this is treated as an empty Stanza and None is returned.
270
Only the stanza lines and the trailing blank (if any) are consumed
271
from the unicode_iter
273
:param unicode_iter: A iterable, yeilding Unicode strings. See read_stanza
274
if you have a utf-8 encoded string.
275
:return: A Stanza object if there are any lines in the file.
278
195
stanza = Stanza()
280
197
accum_value = None
282
# TODO: jam 20060922 This code should raise real errors rather than
283
# using 'assert' to process user input, or raising ValueError
284
# rather than a more specific error.
286
for line in unicode_iter:
287
if line is None or line == '':
198
for line in line_iter:
199
if line == None or line == '':
288
200
break # end of file
290
202
break # end of stanza
203
assert line[-1] == '\n'
292
205
if line[0] == '\t': # continues previous value
300
213
colon_index = line.index(': ')
301
214
except ValueError:
302
raise ValueError('tag/value separator not found in line %r'
304
tag = str(line[:colon_index])
305
if not valid_tag(tag):
306
raise ValueError("invalid rio tag %r" % (tag,))
215
raise ValueError('tag/value separator not found in line %r' % real_l)
216
tag = line[:colon_index]
217
assert valid_tag(tag), \
218
"invalid rio tag %r" % tag
307
219
accum_value = line[colon_index+2:-1]
309
220
if tag is not None: # add last tag-value
310
221
stanza.add(tag, accum_value)
312
223
else: # didn't see any content
316
def to_patch_lines(stanza, max_width=72):
317
"""Convert a stanza into RIO-Patch format lines.
319
RIO-Patch is a RIO variant designed to be e-mailed as part of a patch.
320
It resists common forms of damage such as newline conversion or the removal
321
of trailing whitespace, yet is also reasonably easy to read.
323
:param max_width: The maximum number of characters per physical line.
324
:return: a list of lines
327
raise ValueError(max_width)
328
max_rio_width = max_width - 4
330
for pline in stanza.to_lines():
331
for line in pline.split('\n')[:-1]:
332
line = re.sub('\\\\', '\\\\\\\\', line)
334
partline = line[:max_rio_width]
335
line = line[max_rio_width:]
336
if len(line) > 0 and line[0] != [' ']:
338
break_index = partline.rfind(' ', -20)
340
break_index = partline.rfind('-', -20)
343
break_index = partline.rfind('/', -20)
345
line = partline[break_index:] + line
346
partline = partline[:break_index]
349
partline = re.sub('\r', '\\\\r', partline)
353
elif re.search(' $', partline):
356
lines.append('# ' + partline + '\n')
362
def _patch_stanza_iter(line_iter):
367
return map[match.group(0)]
370
for line in line_iter:
371
if line.startswith('# '):
373
elif line.startswith('#'):
376
raise ValueError("bad line %r" % (line,))
377
if last_line is not None and len(line) > 2:
379
line = re.sub('\r', '', line)
380
line = re.sub('\\\\(.|\n)', mapget, line)
381
if last_line is None:
385
if last_line[-1] == '\n':
388
if last_line is not None:
392
def read_patch_stanza(line_iter):
393
"""Convert an iterable of RIO-Patch format lines into a Stanza.
395
RIO-Patch is a RIO variant designed to be e-mailed as part of a patch.
396
It resists common forms of damage such as newline conversion or the removal
397
of trailing whitespace, yet is also reasonably easy to read.
401
return read_stanza(_patch_stanza_iter(line_iter))