/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: Andrew Bennetts
  • Date: 2011-06-09 07:38:32 UTC
  • mto: This revision was merged to the branch mainline in revision 5964.
  • Revision ID: andrew.bennetts@canonical.com-20110609073832-dt6oww033iexli4l
Fix thinko in wording regarding stacking invariants and revisions with multiple parents.

Show diffs side-by-side

added added

removed removed

Lines of Context:
32
32
 
33
33
import re
34
34
 
35
 
from . import osutils
36
 
from .iterablefile import IterableFile
 
35
from bzrlib import osutils
 
36
from bzrlib.iterablefile import IterableFile
37
37
 
38
38
# XXX: some redundancy is allowing to write stanzas in isolation as well as
39
39
# through a writer object.
40
40
 
41
 
 
42
41
class RioWriter(object):
43
 
 
44
42
    def __init__(self, to_file):
45
43
        self._soft_nl = False
46
44
        self._to_file = to_file
47
45
 
48
46
    def write_stanza(self, stanza):
49
47
        if self._soft_nl:
50
 
            self._to_file.write(b'\n')
 
48
            self._to_file.write('\n')
51
49
        stanza.write(self._to_file)
52
50
        self._soft_nl = True
53
51
 
58
56
    to_file can be anything that can be enumerated as a sequence of
59
57
    lines (with newlines.)
60
58
    """
61
 
 
62
59
    def __init__(self, from_file):
63
60
        self._from_file = from_file
64
61
 
75
72
    """Produce a rio IterableFile from an iterable of stanzas"""
76
73
    def str_iter():
77
74
        if header is not None:
78
 
            yield header + b'\n'
 
75
            yield header + '\n'
79
76
        first_stanza = True
80
77
        for s in stanzas:
81
78
            if first_stanza is not True:
82
 
                yield b'\n'
 
79
                yield '\n'
83
80
            for line in s.to_lines():
84
81
                yield line
85
82
            first_stanza = False
87
84
 
88
85
 
89
86
def read_stanzas(from_file):
90
 
 
91
87
    while True:
92
88
        s = read_stanza(from_file)
93
89
        if s is None:
94
90
            break
95
 
        yield s
96
 
 
97
 
 
98
 
def read_stanzas_unicode(from_file):
99
 
 
100
 
    while True:
101
 
        s = read_stanza_unicode(from_file)
102
 
        if s is None:
103
 
            break
104
 
        yield s
105
 
 
 
91
        else:
 
92
            yield s
106
93
 
107
94
class Stanza(object):
108
95
    """One stanza for rio.
132
119
        """Append a name and value to the stanza."""
133
120
        if not valid_tag(tag):
134
121
            raise ValueError("invalid tag %r" % (tag,))
135
 
        if isinstance(value, bytes):
136
 
            value = value.decode('ascii')
137
 
        elif isinstance(value, str):
 
122
        if isinstance(value, str):
 
123
            value = unicode(value)
 
124
        elif isinstance(value, unicode):
138
125
            pass
 
126
        ## elif isinstance(value, (int, long)):
 
127
        ##    value = str(value)           # XXX: python2.4 without L-suffix
139
128
        else:
140
129
            raise TypeError("invalid type for rio value: %r of type %s"
141
130
                            % (value, type(value)))
182
171
            # max() complains if sequence is empty
183
172
            return []
184
173
        result = []
185
 
        for text_tag, text_value in self.items:
186
 
            tag = text_tag.encode('ascii')
187
 
            value = text_value.encode('utf-8', 'surrogateescape')
188
 
            if value == b'':
189
 
                result.append(tag + b': \n')
190
 
            elif b'\n' in value:
 
174
        for tag, value in self.items:
 
175
            if value == '':
 
176
                result.append(tag + ': \n')
 
177
            elif '\n' in value:
191
178
                # don't want splitlines behaviour on empty lines
192
 
                val_lines = value.split(b'\n')
193
 
                result.append(tag + b': ' + val_lines[0] + b'\n')
 
179
                val_lines = value.split('\n')
 
180
                result.append(tag + ': ' + val_lines[0].encode('utf-8') + '\n')
194
181
                for line in val_lines[1:]:
195
 
                    result.append(b'\t' + line + b'\n')
 
182
                    result.append('\t' + line.encode('utf-8') + '\n')
196
183
            else:
197
 
                result.append(tag + b': ' + value + b'\n')
 
184
                result.append(tag + ': ' + value.encode('utf-8') + '\n')
198
185
        return result
199
186
 
200
187
    def to_string(self):
201
188
        """Return stanza as a single string"""
202
 
        return b''.join(self.to_lines())
 
189
        return ''.join(self.to_lines())
203
190
 
204
191
    def to_unicode(self):
205
192
        """Return stanza as a single Unicode string.
312
299
    max_rio_width = max_width - 4
313
300
    lines = []
314
301
    for pline in stanza.to_lines():
315
 
        for line in pline.split(b'\n')[:-1]:
316
 
            line = re.sub(b'\\\\', b'\\\\\\\\', line)
 
302
        for line in pline.split('\n')[:-1]:
 
303
            line = re.sub('\\\\', '\\\\\\\\', line)
317
304
            while len(line) > 0:
318
305
                partline = line[:max_rio_width]
319
306
                line = line[max_rio_width:]
320
 
                if len(line) > 0 and line[:1] != [b' ']:
 
307
                if len(line) > 0 and line[0] != [' ']:
321
308
                    break_index = -1
322
 
                    break_index = partline.rfind(b' ', -20)
 
309
                    break_index = partline.rfind(' ', -20)
323
310
                    if break_index < 3:
324
 
                        break_index = partline.rfind(b'-', -20)
 
311
                        break_index = partline.rfind('-', -20)
325
312
                        break_index += 1
326
313
                    if break_index < 3:
327
 
                        break_index = partline.rfind(b'/', -20)
 
314
                        break_index = partline.rfind('/', -20)
328
315
                    if break_index >= 3:
329
316
                        line = partline[break_index:] + line
330
317
                        partline = partline[:break_index]
331
318
                if len(line) > 0:
332
 
                    line = b'  ' + line
333
 
                partline = re.sub(b'\r', b'\\\\r', partline)
 
319
                    line = '  ' + line
 
320
                partline = re.sub('\r', '\\\\r', partline)
334
321
                blank_line = False
335
322
                if len(line) > 0:
336
 
                    partline += b'\\'
337
 
                elif re.search(b' $', partline):
338
 
                    partline += b'\\'
 
323
                    partline += '\\'
 
324
                elif re.search(' $', partline):
 
325
                    partline += '\\'
339
326
                    blank_line = True
340
 
                lines.append(b'# ' + partline + b'\n')
 
327
                lines.append('# ' + partline + '\n')
341
328
                if blank_line:
342
 
                    lines.append(b'#   \n')
 
329
                    lines.append('#   \n')
343
330
    return lines
344
331
 
345
332
 
346
333
def _patch_stanza_iter(line_iter):
347
 
    map = {b'\\\\': b'\\',
348
 
           b'\\r': b'\r',
349
 
           b'\\\n': b''}
350
 
 
 
334
    map = {'\\\\': '\\',
 
335
           '\\r' : '\r',
 
336
           '\\\n': ''}
351
337
    def mapget(match):
352
338
        return map[match.group(0)]
353
339
 
354
340
    last_line = None
355
341
    for line in line_iter:
356
 
        if line.startswith(b'# '):
 
342
        if line.startswith('# '):
357
343
            line = line[2:]
358
 
        elif line.startswith(b'#'):
 
344
        elif line.startswith('#'):
359
345
            line = line[1:]
360
346
        else:
361
347
            raise ValueError("bad line %r" % (line,))
362
348
        if last_line is not None and len(line) > 2:
363
349
            line = line[2:]
364
 
        line = re.sub(b'\r', b'', line)
365
 
        line = re.sub(b'\\\\(.|\n)', mapget, line)
 
350
        line = re.sub('\r', '', line)
 
351
        line = re.sub('\\\\(.|\n)', mapget, line)
366
352
        if last_line is None:
367
353
            last_line = line
368
354
        else:
369
355
            last_line += line
370
 
        if last_line[-1:] == b'\n':
 
356
        if last_line[-1] == '\n':
371
357
            yield last_line
372
358
            last_line = None
373
359
    if last_line is not None:
387
373
 
388
374
 
389
375
try:
390
 
    from ._rio_pyx import (
 
376
    from bzrlib._rio_pyx import (
391
377
        _read_stanza_utf8,
392
378
        _read_stanza_unicode,
393
379
        _valid_tag,
394
380
        )
395
 
except ImportError as e:
 
381
except ImportError, e:
396
382
    osutils.failed_to_load_extension(e)
397
 
    from ._rio_py import (
398
 
        _read_stanza_utf8,
399
 
        _read_stanza_unicode,
400
 
        _valid_tag,
401
 
        )
 
383
    from bzrlib._rio_py import (
 
384
       _read_stanza_utf8,
 
385
       _read_stanza_unicode,
 
386
       _valid_tag,
 
387
       )