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

  • Committer: Breezy landing bot
  • Author(s): Colin Watson
  • Date: 2020-11-16 21:47:08 UTC
  • mfrom: (7521.1.1 remove-lp-workaround)
  • Revision ID: breezy.the.bot@gmail.com-20201116214708-jos209mgxi41oy15
Remove breezy.git workaround for bazaar.launchpad.net.

Merged from https://code.launchpad.net/~cjwatson/brz/remove-lp-workaround/+merge/393710

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