~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/rio.py

Merge bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 by Canonical Ltd
2
 
#
3
 
# Distributed under the GNU General Public Licence v2
 
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
4
16
 
5
17
# \subsection{\emph{rio} - simple text metaformat}
6
18
171
183
        """Return stanza as a single string"""
172
184
        return ''.join(self.to_lines())
173
185
 
 
186
    def to_unicode(self):
 
187
        """Return stanza as a single Unicode string.
 
188
 
 
189
        This is most useful when adding a Stanza to a parent Stanza
 
190
        """
 
191
        if not self.items:
 
192
            return u''
 
193
 
 
194
        result = []
 
195
        for tag, value in self.items:
 
196
            if value == '':
 
197
                result.append(tag + ': \n')
 
198
            elif '\n' in value:
 
199
                # don't want splitlines behaviour on empty lines
 
200
                val_lines = value.split('\n')
 
201
                result.append(tag + ': ' + val_lines[0] + '\n')
 
202
                for line in val_lines[1:]:
 
203
                    result.append('\t' + line + '\n')
 
204
            else:
 
205
                result.append(tag + ': ' + value + '\n')
 
206
        return u''.join(result)
 
207
 
174
208
    def write(self, to_file):
175
209
        """Write stanza to a file"""
176
210
        to_file.writelines(self.to_lines())
223
257
 
224
258
    The raw lines must be in utf-8 encoding.
225
259
    """
226
 
    items = []
 
260
    unicode_iter = (line.decode('utf-8') for line in line_iter)
 
261
    return read_stanza_unicode(unicode_iter)
 
262
 
 
263
 
 
264
def read_stanza_unicode(unicode_iter):
 
265
    """Read a Stanza from a list of lines or a file.
 
266
 
 
267
    The lines should already be in unicode form. This returns a single
 
268
    stanza that was read. If there is a blank line at the end of the Stanza,
 
269
    it is consumed. It is not an error for there to be no blank line at
 
270
    the end of the iterable. If there is a blank line at the beginning,
 
271
    this is treated as an empty Stanza and None is returned.
 
272
 
 
273
    Only the stanza lines and the trailing blank (if any) are consumed
 
274
    from the unicode_iter
 
275
 
 
276
    :param unicode_iter: A iterable, yeilding Unicode strings. See read_stanza
 
277
        if you have a utf-8 encoded string.
 
278
    :return: A Stanza object if there are any lines in the file.
 
279
        None otherwise
 
280
    """
227
281
    stanza = Stanza()
228
282
    tag = None
229
283
    accum_value = None
230
 
    for line in line_iter:
231
 
        if line == None or line == '':
 
284
    
 
285
    # TODO: jam 20060922 This code should raise real errors rather than
 
286
    #       using 'assert' to process user input, or raising ValueError
 
287
    #       rather than a more specific error.
 
288
 
 
289
    for line in unicode_iter:
 
290
        if line is None or line == '':
232
291
            break       # end of file
233
292
        if line == '\n':
234
293
            break       # end of stanza
235
 
        line = line.decode('utf-8')
236
 
        assert line[-1] == '\n'
 
294
        assert line.endswith('\n')
237
295
        real_l = line
238
296
        if line[0] == '\t': # continues previous value
239
297
            if tag is None:
245
303
            try:
246
304
                colon_index = line.index(': ')
247
305
            except ValueError:
248
 
                raise ValueError('tag/value separator not found in line %r' % real_l)
 
306
                raise ValueError('tag/value separator not found in line %r'
 
307
                                 % real_l)
249
308
            tag = str(line[:colon_index])
250
309
            assert valid_tag(tag), \
251
310
                    "invalid rio tag %r" % tag
252
311
            accum_value = line[colon_index+2:-1]
 
312
 
253
313
    if tag is not None: # add last tag-value
254
314
        stanza.add(tag, accum_value)
255
315
        return stanza
256
316
    else:     # didn't see any content
257
317
        return None    
 
318
 
 
319
def to_patch_lines(stanza, max_width=72):
 
320
    assert max_width > 6
 
321
    max_rio_width = max_width - 4
 
322
    lines = []
 
323
    for pline in stanza.to_lines():
 
324
        for line in pline.split('\n')[:-1]:
 
325
            line = re.sub('\\\\', '\\\\\\\\', line)
 
326
            while len(line) > 0:
 
327
                partline = line[:max_rio_width]
 
328
                line = line[max_rio_width:]
 
329
                if len(line) > 0 and line[0] != [' ']:
 
330
                    break_index = -1
 
331
                    break_index = partline.rfind(' ', -20)
 
332
                    if break_index < 3:
 
333
                        break_index = partline.rfind('-', -20)
 
334
                        break_index += 1
 
335
                    if break_index < 3:
 
336
                        break_index = partline.rfind('/', -20)
 
337
                    if break_index >= 3:
 
338
                        line = partline[break_index:] + line
 
339
                        partline = partline[:break_index]
 
340
                if len(line) > 0:
 
341
                    line = '  ' + line
 
342
                partline = re.sub('\r', '\\\\r', partline)
 
343
                blank_line = False
 
344
                if len(line) > 0:
 
345
                    partline += '\\'
 
346
                elif re.search(' $', partline):
 
347
                    partline += '\\'
 
348
                    blank_line = True
 
349
                lines.append('# ' + partline + '\n')
 
350
                if blank_line:
 
351
                    lines.append('#   \n')
 
352
    return lines
 
353
 
 
354
 
 
355
def _patch_stanza_iter(line_iter):
 
356
    map = {'\\\\': '\\',
 
357
           '\\r' : '\r',
 
358
           '\\\n': ''}
 
359
    def mapget(match):
 
360
        return map[match.group(0)]
 
361
 
 
362
    last_line = None
 
363
    for line in line_iter:
 
364
        if line.startswith('# '):
 
365
            line = line[2:]
 
366
        else:
 
367
            assert line.startswith('#')
 
368
            line = line[1:]
 
369
        if last_line is not None and len(line) > 2:
 
370
            line = line[2:]
 
371
        line = re.sub('\r', '', line)
 
372
        line = re.sub('\\\\(.|\n)', mapget, line)
 
373
        if last_line is None:
 
374
            last_line = line
 
375
        else:
 
376
            last_line += line
 
377
        if last_line[-1] == '\n':
 
378
            yield last_line
 
379
            last_line = None
 
380
    if last_line is not None:
 
381
        yield last_line
 
382
 
 
383
 
 
384
def read_patch_stanza(line_iter):
 
385
    return read_stanza(_patch_stanza_iter(line_iter))