/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: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

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