~bzr-pqm/bzr/bzr.dev

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# Copyright (C) 2005 by Canonical Ltd
#
# Distributed under the GNU General Public Licence v2

# \subsection{\emph{rio} - simple text metaformat}
# 
# \emph{r} stands for `restricted', `reproducible', or `rfc822-like'.
# 
# The stored data consists of a series of \emph{stanzas}, each of which contains
# \emph{fields} identified by an ascii name, with Unicode or string contents.
# The field tag is constrained to alphanumeric characters.  
# There may be more than one field in a stanza with the same name.
# 
# The format itself does not deal with character encoding issues, though
# the result will normally be written in Unicode.
# 
# The format is intended to be simple enough that there is exactly one character
# stream representation of an object and vice versa, and that this relation
# will continue to hold for future versions of bzr.

import re

from bzrlib.iterablefile import IterableFile

# XXX: some redundancy is allowing to write stanzas in isolation as well as
# through a writer object.  

class RioWriter(object):
    def __init__(self, to_file):
        self._soft_nl = False
        self._to_file = to_file

    def write_stanza(self, stanza):
        if self._soft_nl:
            print >>self._to_file
        stanza.write(self._to_file)
        self._soft_nl = True


class RioReader(object):
    """Read stanzas from a file as a sequence
    
    to_file can be anything that can be enumerated as a sequence of 
    lines (with newlines.)
    """
    def __init__(self, from_file):
        self._from_file = from_file

    def __iter__(self):
        while True:
            s = read_stanza(self._from_file)
            if s is None:
                break
            else:
                yield s


def rio_file(stanzas, header=None):
    """Produce a rio IterableFile from an iterable of stanzas"""
    def str_iter():
        if header is not None:
            yield header + '\n'
        first_stanza = True
        for s in stanzas:
            if first_stanza is not True:
                yield '\n'
            for line in s.to_lines():
                yield line
            first_stanza = False
    return IterableFile(str_iter())


def read_stanzas(from_file):
    while True:
        s = read_stanza(from_file)
        if s is None:
            break
        else:
            yield s

class Stanza(object):
    """One stanza for rio.

    Each stanza contains a set of named fields.  
    
    Names must be non-empty ascii alphanumeric plus _.  Names can be repeated
    within a stanza.  Names are case-sensitive.  The ordering of fields is
    preserved.

    Each field value must be either an int or a string.
    """

    __slots__ = ['items']

    def __init__(self, **kwargs):
        """Construct a new Stanza.

        The keyword arguments, if any, are added in sorted order to the stanza.
        """
        self.items = []
        if kwargs:
            for tag, value in sorted(kwargs.items()):
                self.add(tag, value)

    def add(self, tag, value):
        """Append a name and value to the stanza."""
        assert valid_tag(tag), \
            ("invalid tag %r" % tag)
        if isinstance(value, str):
            value = unicode(value)
        elif isinstance(value, unicode):
            pass
        ## elif isinstance(value, (int, long)):
        ##    value = str(value)           # XXX: python2.4 without L-suffix
        else:
            raise TypeError("invalid type for rio value: %r of type %s"
                            % (value, type(value)))
        self.items.append((tag, value))
        
    def __contains__(self, find_tag):
        """True if there is any field in this stanza with the given tag."""
        for tag, value in self.items:
            if tag == find_tag:
                return True
        return False

    def __len__(self):
        """Return number of pairs in the stanza."""
        return len(self.items)

    def __eq__(self, other):
        if not isinstance(other, Stanza):
            return False
        return self.items == other.items

    def __ne__(self, other):
        return not self.__eq__(other)

    def __repr__(self):
        return "Stanza(%r)" % self.items

    def iter_pairs(self):
        """Return iterator of tag, value pairs."""
        return iter(self.items)

    def to_lines(self):
        """Generate sequence of lines for external version of this file.
        
        The lines are always utf-8 encoded strings.
        """
        if not self.items:
            # max() complains if sequence is empty
            return []
        result = []
        for tag, value in self.items:
            assert isinstance(tag, str), type(tag)
            assert isinstance(value, unicode)
            if value == '':
                result.append(tag + ': \n')
            elif '\n' in value:
                # don't want splitlines behaviour on empty lines
                val_lines = value.split('\n')
                result.append(tag + ': ' + val_lines[0].encode('utf-8') + '\n')
                for line in val_lines[1:]:
                    result.append('\t' + line.encode('utf-8') + '\n')
            else:
                result.append(tag + ': ' + value.encode('utf-8') + '\n')
        return result

    def to_string(self):
        """Return stanza as a single string"""
        return ''.join(self.to_lines())

    def to_unicode(self):
        """Return stanza as a single Unicode string.

        This is most useful when adding a Stanza to a parent Stanza
        """
        if not self.items:
            return u''

        result = []
        for tag, value in self.items:
            if value == '':
                result.append(tag + ': \n')
            elif '\n' in value:
                # don't want splitlines behaviour on empty lines
                val_lines = value.split('\n')
                result.append(tag + ': ' + val_lines[0] + '\n')
                for line in val_lines[1:]:
                    result.append('\t' + line + '\n')
            else:
                result.append(tag + ': ' + value + '\n')
        return u''.join(result)

    def write(self, to_file):
        """Write stanza to a file"""
        to_file.writelines(self.to_lines())

    def get(self, tag):
        """Return the value for a field wih given tag.

        If there is more than one value, only the first is returned.  If the
        tag is not present, KeyError is raised.
        """
        for t, v in self.items:
            if t == tag:
                return v
        else:
            raise KeyError(tag)

    __getitem__ = get

    def get_all(self, tag):
        r = []
        for t, v in self.items:
            if t == tag:
                r.append(v)
        return r

    def as_dict(self):
        """Return a dict containing the unique values of the stanza.
        """
        d = {}
        for tag, value in self.items:
            assert tag not in d
            d[tag] = value
        return d
         
_tag_re = re.compile(r'^[-a-zA-Z0-9_]+$')
def valid_tag(tag):
    return bool(_tag_re.match(tag))


def read_stanza(line_iter):
    """Return new Stanza read from list of lines or a file
    
    Returns one Stanza that was read, or returns None at end of file.  If a
    blank line follows the stanza, it is consumed.  It's not an error for
    there to be no blank at end of file.  If there is a blank file at the
    start of the input this is really an empty stanza and that is returned. 

    Only the stanza lines and the trailing blank (if any) are consumed
    from the line_iter.

    The raw lines must be in utf-8 encoding.
    """
    unicode_iter = (line.decode('utf-8') for line in line_iter)
    return read_stanza_unicode(unicode_iter)


def read_stanza_unicode(unicode_iter):
    """Read a Stanza from a list of lines or a file.

    The lines should already be in unicode form. This returns a single
    stanza that was read. If there is a blank line at the end of the Stanza,
    it is consumed. It is not an error for there to be no blank line at
    the end of the iterable. If there is a blank line at the beginning,
    this is treated as an empty Stanza and None is returned.

    Only the stanza lines and the trailing blank (if any) are consumed
    from the unicode_iter

    :param unicode_iter: A iterable, yeilding Unicode strings. See read_stanza
        if you have a utf-8 encoded string.
    :return: A Stanza object if there are any lines in the file.
        None otherwise
    """
    stanza = Stanza()
    tag = None
    accum_value = None
    
    # TODO: jam 20060922 This code should raise real errors rather than
    #       using 'assert' to process user input, or raising ValueError
    #       rather than a more specific error.

    for line in unicode_iter:
        if line is None or line == '':
            break       # end of file
        if line == '\n':
            break       # end of stanza
        assert line.endswith('\n')
        real_l = line
        if line[0] == '\t': # continues previous value
            if tag is None:
                raise ValueError('invalid continuation line %r' % real_l)
            accum_value += '\n' + line[1:-1]
        else: # new tag:value line
            if tag is not None:
                stanza.add(tag, accum_value)
            try:
                colon_index = line.index(': ')
            except ValueError:
                raise ValueError('tag/value separator not found in line %r'
                                 % real_l)
            tag = str(line[:colon_index])
            assert valid_tag(tag), \
                    "invalid rio tag %r" % tag
            accum_value = line[colon_index+2:-1]

    if tag is not None: # add last tag-value
        stanza.add(tag, accum_value)
        return stanza
    else:     # didn't see any content
        return None