/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: Jelmer Vernooij
  • Date: 2020-04-05 19:11:34 UTC
  • mto: (7490.7.16 work)
  • mto: This revision was merged to the branch mainline in revision 7501.
  • Revision ID: jelmer@jelmer.uk-20200405191134-0aebh8ikiwygxma5
Populate the .gitignore file.

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