/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 brzlib/rio.py

  • Committer: Jelmer Vernooij
  • Date: 2017-05-21 12:41:27 UTC
  • mto: This revision was merged to the branch mainline in revision 6623.
  • Revision ID: jelmer@jelmer.uk-20170521124127-iv8etg0vwymyai6y
s/bzr/brz/ in apport config.

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