/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: Marius Kruger
  • Date: 2010-07-10 21:28:56 UTC
  • mto: (5384.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5385.
  • Revision ID: marius.kruger@enerweb.co.za-20100710212856-uq4ji3go0u5se7hx
* Update documentation
* add NEWS

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