/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.
50
45
 
51
46
    def write_stanza(self, stanza):
52
47
        if self._soft_nl:
53
 
            self._to_file.write(b'\n')
 
48
            self._to_file.write('\n')
54
49
        stanza.write(self._to_file)
55
50
        self._soft_nl = True
56
51
 
77
72
    """Produce a rio IterableFile from an iterable of stanzas"""
78
73
    def str_iter():
79
74
        if header is not None:
80
 
            yield header + b'\n'
 
75
            yield header + '\n'
81
76
        first_stanza = True
82
77
        for s in stanzas:
83
78
            if first_stanza is not True:
84
 
                yield b'\n'
 
79
                yield '\n'
85
80
            for line in s.to_lines():
86
81
                yield line
87
82
            first_stanza = False
124
119
        """Append a name and value to the stanza."""
125
120
        if not valid_tag(tag):
126
121
            raise ValueError("invalid tag %r" % (tag,))
127
 
        if isinstance(value, bytes):
128
 
            value = value.decode('ascii')
129
 
        elif isinstance(value, text_type):
 
122
        if isinstance(value, str):
 
123
            value = unicode(value)
 
124
        elif isinstance(value, unicode):
130
125
            pass
 
126
        ## elif isinstance(value, (int, long)):
 
127
        ##    value = str(value)           # XXX: python2.4 without L-suffix
131
128
        else:
132
129
            raise TypeError("invalid type for rio value: %r of type %s"
133
130
                            % (value, type(value)))
174
171
            # max() complains if sequence is empty
175
172
            return []
176
173
        result = []
177
 
        for text_tag, text_value in self.items:
178
 
            tag = text_tag.encode('ascii')
179
 
            value = text_value.encode('utf-8')
180
 
            if value == b'':
181
 
                result.append(tag + b': \n')
182
 
            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:
183
178
                # don't want splitlines behaviour on empty lines
184
 
                val_lines = value.split(b'\n')
185
 
                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')
186
181
                for line in val_lines[1:]:
187
 
                    result.append(b'\t' + line + b'\n')
 
182
                    result.append('\t' + line.encode('utf-8') + '\n')
188
183
            else:
189
 
                result.append(tag + b': ' + value + b'\n')
 
184
                result.append(tag + ': ' + value.encode('utf-8') + '\n')
190
185
        return result
191
186
 
192
187
    def to_string(self):
193
188
        """Return stanza as a single string"""
194
 
        return b''.join(self.to_lines())
 
189
        return ''.join(self.to_lines())
195
190
 
196
191
    def to_unicode(self):
197
192
        """Return stanza as a single Unicode string.
304
299
    max_rio_width = max_width - 4
305
300
    lines = []
306
301
    for pline in stanza.to_lines():
307
 
        for line in pline.split(b'\n')[:-1]:
308
 
            line = re.sub(b'\\\\', b'\\\\\\\\', line)
 
302
        for line in pline.split('\n')[:-1]:
 
303
            line = re.sub('\\\\', '\\\\\\\\', line)
309
304
            while len(line) > 0:
310
305
                partline = line[:max_rio_width]
311
306
                line = line[max_rio_width:]
312
 
                if len(line) > 0 and line[:1] != [b' ']:
 
307
                if len(line) > 0 and line[0] != [' ']:
313
308
                    break_index = -1
314
 
                    break_index = partline.rfind(b' ', -20)
 
309
                    break_index = partline.rfind(' ', -20)
315
310
                    if break_index < 3:
316
 
                        break_index = partline.rfind(b'-', -20)
 
311
                        break_index = partline.rfind('-', -20)
317
312
                        break_index += 1
318
313
                    if break_index < 3:
319
 
                        break_index = partline.rfind(b'/', -20)
 
314
                        break_index = partline.rfind('/', -20)
320
315
                    if break_index >= 3:
321
316
                        line = partline[break_index:] + line
322
317
                        partline = partline[:break_index]
323
318
                if len(line) > 0:
324
 
                    line = b'  ' + line
325
 
                partline = re.sub(b'\r', b'\\\\r', partline)
 
319
                    line = '  ' + line
 
320
                partline = re.sub('\r', '\\\\r', partline)
326
321
                blank_line = False
327
322
                if len(line) > 0:
328
 
                    partline += b'\\'
329
 
                elif re.search(b' $', partline):
330
 
                    partline += b'\\'
 
323
                    partline += '\\'
 
324
                elif re.search(' $', partline):
 
325
                    partline += '\\'
331
326
                    blank_line = True
332
 
                lines.append(b'# ' + partline + b'\n')
 
327
                lines.append('# ' + partline + '\n')
333
328
                if blank_line:
334
 
                    lines.append(b'#   \n')
 
329
                    lines.append('#   \n')
335
330
    return lines
336
331
 
337
332
 
338
333
def _patch_stanza_iter(line_iter):
339
 
    map = {b'\\\\': b'\\',
340
 
           b'\\r' : b'\r',
341
 
           b'\\\n': b''}
 
334
    map = {'\\\\': '\\',
 
335
           '\\r' : '\r',
 
336
           '\\\n': ''}
342
337
    def mapget(match):
343
338
        return map[match.group(0)]
344
339
 
345
340
    last_line = None
346
341
    for line in line_iter:
347
 
        if line.startswith(b'# '):
 
342
        if line.startswith('# '):
348
343
            line = line[2:]
349
 
        elif line.startswith(b'#'):
 
344
        elif line.startswith('#'):
350
345
            line = line[1:]
351
346
        else:
352
347
            raise ValueError("bad line %r" % (line,))
353
348
        if last_line is not None and len(line) > 2:
354
349
            line = line[2:]
355
 
        line = re.sub(b'\r', b'', line)
356
 
        line = re.sub(b'\\\\(.|\n)', mapget, line)
 
350
        line = re.sub('\r', '', line)
 
351
        line = re.sub('\\\\(.|\n)', mapget, line)
357
352
        if last_line is None:
358
353
            last_line = line
359
354
        else:
360
355
            last_line += line
361
 
        if last_line[-1:] == b'\n':
 
356
        if last_line[-1] == '\n':
362
357
            yield last_line
363
358
            last_line = None
364
359
    if last_line is not None:
378
373
 
379
374
 
380
375
try:
381
 
    from ._rio_pyx import (
 
376
    from bzrlib._rio_pyx import (
382
377
        _read_stanza_utf8,
383
378
        _read_stanza_unicode,
384
379
        _valid_tag,
385
380
        )
386
 
except ImportError as e:
 
381
except ImportError, e:
387
382
    osutils.failed_to_load_extension(e)
388
 
    from ._rio_py import (
 
383
    from bzrlib._rio_py import (
389
384
       _read_stanza_utf8,
390
385
       _read_stanza_unicode,
391
386
       _valid_tag,