~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/rio.py

  • Committer: Martin Pool
  • Date: 2006-03-06 03:57:18 UTC
  • mto: This revision was merged to the branch mainline in revision 1593.
  • Revision ID: mbp@sourcefrog.net-20060306035718-a50bae3c32eec48a
Change LockDirs to format "lock-name/held/info"

For the moment, auto-create the top-level directory when it's needed.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 Canonical Ltd
2
 
#
3
 
# This program is free software; you can redistribute it and/or modify
4
 
# it under the terms of the GNU General Public License as published by
5
 
# the Free Software Foundation; either version 2 of the License, or
6
 
# (at your option) any later version.
7
 
#
8
 
# This program is distributed in the hope that it will be useful,
9
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
 
# GNU General Public License for more details.
12
 
#
13
 
# You should have received a copy of the GNU General Public License
14
 
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
1
# Copyright (C) 2005 by Canonical Ltd
 
2
#
 
3
# Distributed under the GNU General Public Licence v2
16
4
 
17
5
# \subsection{\emph{rio} - simple text metaformat}
18
6
32
20
 
33
21
import re
34
22
 
35
 
from bzrlib.iterablefile import IterableFile
36
 
 
37
23
# XXX: some redundancy is allowing to write stanzas in isolation as well as
38
24
# through a writer object.  
39
25
 
44
30
 
45
31
    def write_stanza(self, stanza):
46
32
        if self._soft_nl:
47
 
            self._to_file.write('\n')
 
33
            print >>self._to_file
48
34
        stanza.write(self._to_file)
49
35
        self._soft_nl = True
50
36
 
66
52
            else:
67
53
                yield s
68
54
 
69
 
 
70
 
def rio_file(stanzas, header=None):
71
 
    """Produce a rio IterableFile from an iterable of stanzas"""
72
 
    def str_iter():
73
 
        if header is not None:
74
 
            yield header + '\n'
75
 
        first_stanza = True
76
 
        for s in stanzas:
77
 
            if first_stanza is not True:
78
 
                yield '\n'
79
 
            for line in s.to_lines():
80
 
                yield line
81
 
            first_stanza = False
82
 
    return IterableFile(str_iter())
83
 
 
84
 
 
85
55
def read_stanzas(from_file):
86
56
    while True:
87
57
        s = read_stanza(from_file)
116
86
 
117
87
    def add(self, tag, value):
118
88
        """Append a name and value to the stanza."""
119
 
        if not valid_tag(tag):
120
 
            raise ValueError("invalid tag %r" % (tag,))
 
89
        assert valid_tag(tag), \
 
90
            ("invalid tag %r" % tag)
121
91
        if isinstance(value, str):
122
92
            value = unicode(value)
123
93
        elif isinstance(value, unicode):
165
135
            return []
166
136
        result = []
167
137
        for tag, value in self.items:
 
138
            assert isinstance(tag, str)
 
139
            assert isinstance(value, unicode)
168
140
            if value == '':
169
141
                result.append(tag + ': \n')
170
142
            elif '\n' in value:
181
153
        """Return stanza as a single string"""
182
154
        return ''.join(self.to_lines())
183
155
 
184
 
    def to_unicode(self):
185
 
        """Return stanza as a single Unicode string.
186
 
 
187
 
        This is most useful when adding a Stanza to a parent Stanza
188
 
        """
189
 
        if not self.items:
190
 
            return u''
191
 
 
192
 
        result = []
193
 
        for tag, value in self.items:
194
 
            if value == '':
195
 
                result.append(tag + ': \n')
196
 
            elif '\n' in value:
197
 
                # don't want splitlines behaviour on empty lines
198
 
                val_lines = value.split('\n')
199
 
                result.append(tag + ': ' + val_lines[0] + '\n')
200
 
                for line in val_lines[1:]:
201
 
                    result.append('\t' + line + '\n')
202
 
            else:
203
 
                result.append(tag + ': ' + value + '\n')
204
 
        return u''.join(result)
205
 
 
206
156
    def write(self, to_file):
207
157
        """Write stanza to a file"""
208
158
        to_file.writelines(self.to_lines())
233
183
        """
234
184
        d = {}
235
185
        for tag, value in self.items:
 
186
            assert tag not in d
236
187
            d[tag] = value
237
188
        return d
238
189
         
254
205
 
255
206
    The raw lines must be in utf-8 encoding.
256
207
    """
257
 
    unicode_iter = (line.decode('utf-8') for line in line_iter)
258
 
    return read_stanza_unicode(unicode_iter)
259
 
 
260
 
 
261
 
def read_stanza_unicode(unicode_iter):
262
 
    """Read a Stanza from a list of lines or a file.
263
 
 
264
 
    The lines should already be in unicode form. This returns a single
265
 
    stanza that was read. If there is a blank line at the end of the Stanza,
266
 
    it is consumed. It is not an error for there to be no blank line at
267
 
    the end of the iterable. If there is a blank line at the beginning,
268
 
    this is treated as an empty Stanza and None is returned.
269
 
 
270
 
    Only the stanza lines and the trailing blank (if any) are consumed
271
 
    from the unicode_iter
272
 
 
273
 
    :param unicode_iter: A iterable, yeilding Unicode strings. See read_stanza
274
 
        if you have a utf-8 encoded string.
275
 
    :return: A Stanza object if there are any lines in the file.
276
 
        None otherwise
277
 
    """
 
208
    items = []
278
209
    stanza = Stanza()
279
210
    tag = None
280
211
    accum_value = None
281
 
    
282
 
    # TODO: jam 20060922 This code should raise real errors rather than
283
 
    #       using 'assert' to process user input, or raising ValueError
284
 
    #       rather than a more specific error.
285
 
 
286
 
    for line in unicode_iter:
287
 
        if line is None or line == '':
 
212
    for line in line_iter:
 
213
        if line == None or line == '':
288
214
            break       # end of file
289
215
        if line == '\n':
290
216
            break       # end of stanza
 
217
        line = line.decode('utf-8')
 
218
        assert line[-1] == '\n'
291
219
        real_l = line
292
220
        if line[0] == '\t': # continues previous value
293
221
            if tag is None:
299
227
            try:
300
228
                colon_index = line.index(': ')
301
229
            except ValueError:
302
 
                raise ValueError('tag/value separator not found in line %r'
303
 
                                 % real_l)
304
 
            tag = str(line[:colon_index])
305
 
            if not valid_tag(tag):
306
 
                raise ValueError("invalid rio tag %r" % (tag,))
 
230
                raise ValueError('tag/value separator not found in line %r' % real_l)
 
231
            tag = line[:colon_index]
 
232
            assert valid_tag(tag), \
 
233
                    "invalid rio tag %r" % tag
307
234
            accum_value = line[colon_index+2:-1]
308
 
 
309
235
    if tag is not None: # add last tag-value
310
236
        stanza.add(tag, accum_value)
311
237
        return stanza
312
238
    else:     # didn't see any content
313
239
        return None    
314
 
 
315
 
 
316
 
def to_patch_lines(stanza, max_width=72):
317
 
    """Convert a stanza into RIO-Patch format lines.
318
 
 
319
 
    RIO-Patch is a RIO variant designed to be e-mailed as part of a patch.
320
 
    It resists common forms of damage such as newline conversion or the removal
321
 
    of trailing whitespace, yet is also reasonably easy to read.
322
 
 
323
 
    :param max_width: The maximum number of characters per physical line.
324
 
    :return: a list of lines
325
 
    """
326
 
    if max_width <= 6:
327
 
        raise ValueError(max_width)
328
 
    max_rio_width = max_width - 4
329
 
    lines = []
330
 
    for pline in stanza.to_lines():
331
 
        for line in pline.split('\n')[:-1]:
332
 
            line = re.sub('\\\\', '\\\\\\\\', line)
333
 
            while len(line) > 0:
334
 
                partline = line[:max_rio_width]
335
 
                line = line[max_rio_width:]
336
 
                if len(line) > 0 and line[0] != [' ']:
337
 
                    break_index = -1
338
 
                    break_index = partline.rfind(' ', -20)
339
 
                    if break_index < 3:
340
 
                        break_index = partline.rfind('-', -20)
341
 
                        break_index += 1
342
 
                    if break_index < 3:
343
 
                        break_index = partline.rfind('/', -20)
344
 
                    if break_index >= 3:
345
 
                        line = partline[break_index:] + line
346
 
                        partline = partline[:break_index]
347
 
                if len(line) > 0:
348
 
                    line = '  ' + line
349
 
                partline = re.sub('\r', '\\\\r', partline)
350
 
                blank_line = False
351
 
                if len(line) > 0:
352
 
                    partline += '\\'
353
 
                elif re.search(' $', partline):
354
 
                    partline += '\\'
355
 
                    blank_line = True
356
 
                lines.append('# ' + partline + '\n')
357
 
                if blank_line:
358
 
                    lines.append('#   \n')
359
 
    return lines
360
 
 
361
 
 
362
 
def _patch_stanza_iter(line_iter):
363
 
    map = {'\\\\': '\\',
364
 
           '\\r' : '\r',
365
 
           '\\\n': ''}
366
 
    def mapget(match):
367
 
        return map[match.group(0)]
368
 
 
369
 
    last_line = None
370
 
    for line in line_iter:
371
 
        if line.startswith('# '):
372
 
            line = line[2:]
373
 
        elif line.startswith('#'):
374
 
            line = line[1:]
375
 
        else:
376
 
            raise ValueError("bad line %r" % (line,))
377
 
        if last_line is not None and len(line) > 2:
378
 
            line = line[2:]
379
 
        line = re.sub('\r', '', line)
380
 
        line = re.sub('\\\\(.|\n)', mapget, line)
381
 
        if last_line is None:
382
 
            last_line = line
383
 
        else:
384
 
            last_line += line
385
 
        if last_line[-1] == '\n':
386
 
            yield last_line
387
 
            last_line = None
388
 
    if last_line is not None:
389
 
        yield last_line
390
 
 
391
 
 
392
 
def read_patch_stanza(line_iter):
393
 
    """Convert an iterable of RIO-Patch format lines into a Stanza.
394
 
 
395
 
    RIO-Patch is a RIO variant designed to be e-mailed as part of a patch.
396
 
    It resists common forms of damage such as newline conversion or the removal
397
 
    of trailing whitespace, yet is also reasonably easy to read.
398
 
 
399
 
    :return: a Stanza
400
 
    """
401
 
    return read_stanza(_patch_stanza_iter(line_iter))