/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: Martin Pool
  • Date: 2006-02-21 06:02:01 UTC
  • mto: This revision was merged to the branch mainline in revision 1569.
  • Revision ID: mbp@sourcefrog.net-20060221060201-5f260bfe331bdc42
New Transport.rename that mustn't overwrite
Change LockDir.is_held to be a property

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 by Canonical Ltd
 
2
#
 
3
# Distributed under the GNU General Public Licence v2
 
4
 
 
5
# \subsection{\emph{rio} - simple text metaformat}
 
6
 
7
# \emph{r} stands for `restricted', `reproducible', or `rfc822-like'.
 
8
 
9
# The stored data consists of a series of \emph{stanzas}, each of which contains
 
10
# \emph{fields} identified by an ascii name, with Unicode or string contents.
 
11
# The field tag is constrained to alphanumeric characters.  
 
12
# There may be more than one field in a stanza with the same name.
 
13
 
14
# The format itself does not deal with character encoding issues, though
 
15
# the result will normally be written in Unicode.
 
16
 
17
# The format is intended to be simple enough that there is exactly one character
 
18
# stream representation of an object and vice versa, and that this relation
 
19
# will continue to hold for future versions of bzr.
 
20
 
 
21
import re
 
22
 
 
23
# XXX: some redundancy is allowing to write stanzas in isolation as well as
 
24
# through a writer object.  
 
25
 
 
26
class RioWriter(object):
 
27
    def __init__(self, to_file):
 
28
        self._soft_nl = False
 
29
        self._to_file = to_file
 
30
 
 
31
    def write_stanza(self, stanza):
 
32
        if self._soft_nl:
 
33
            print >>self._to_file
 
34
        stanza.write(self._to_file)
 
35
        self._soft_nl = True
 
36
 
 
37
 
 
38
class RioReader(object):
 
39
    """Read stanzas from a file as a sequence
 
40
    
 
41
    to_file can be anything that can be enumerated as a sequence of 
 
42
    lines (with newlines.)
 
43
    """
 
44
    def __init__(self, from_file):
 
45
        self._from_file = from_file
 
46
 
 
47
    def __iter__(self):
 
48
        while True:
 
49
            s = read_stanza(self._from_file)
 
50
            if s is None:
 
51
                break
 
52
            else:
 
53
                yield s
 
54
 
 
55
def read_stanzas(from_file):
 
56
    while True:
 
57
        s = read_stanza(from_file)
 
58
        if s is None:
 
59
            break
 
60
        else:
 
61
            yield s
 
62
 
 
63
class Stanza(object):
 
64
    """One stanza for rio.
 
65
 
 
66
    Each stanza contains a set of named fields.  
 
67
    
 
68
    Names must be non-empty ascii alphanumeric plus _.  Names can be repeated
 
69
    within a stanza.  Names are case-sensitive.  The ordering of fields is
 
70
    preserved.
 
71
 
 
72
    Each field value must be either an int or a string.
 
73
    """
 
74
 
 
75
    __slots__ = ['items']
 
76
 
 
77
    def __init__(self, **kwargs):
 
78
        """Construct a new Stanza.
 
79
 
 
80
        The keyword arguments, if any, are added in sorted order to the stanza.
 
81
        """
 
82
        self.items = []
 
83
        if kwargs:
 
84
            for tag, value in sorted(kwargs.items()):
 
85
                self.add(tag, value)
 
86
 
 
87
    def add(self, tag, value):
 
88
        """Append a name and value to the stanza."""
 
89
        assert valid_tag(tag), \
 
90
            ("invalid tag %r" % tag)
 
91
        if isinstance(value, (str, unicode)):
 
92
            pass
 
93
        ## elif isinstance(value, (int, long)):
 
94
        ##    value = str(value)           # XXX: python2.4 without L-suffix
 
95
        else:
 
96
            raise TypeError("invalid type for rio value: %r of type %s"
 
97
                            % (value, type(value)))
 
98
        self.items.append((tag, value))
 
99
        
 
100
    def __contains__(self, find_tag):
 
101
        """True if there is any field in this stanza with the given tag."""
 
102
        for tag, value in self.items:
 
103
            if tag == find_tag:
 
104
                return True
 
105
        return False
 
106
 
 
107
    def __len__(self):
 
108
        """Return number of pairs in the stanza."""
 
109
        return len(self.items)
 
110
 
 
111
    def __eq__(self, other):
 
112
        if not isinstance(other, Stanza):
 
113
            return False
 
114
        return self.items == other.items
 
115
 
 
116
    def __ne__(self, other):
 
117
        return not self.__eq__(other)
 
118
 
 
119
    def __repr__(self):
 
120
        return "Stanza(%r)" % self.items
 
121
 
 
122
    def iter_pairs(self):
 
123
        """Return iterator of tag, value pairs."""
 
124
        return iter(self.items)
 
125
 
 
126
    def to_lines(self):
 
127
        """Generate sequence of lines for external version of this file."""
 
128
        if not self.items:
 
129
            # max() complains if sequence is empty
 
130
            return []
 
131
        result = []
 
132
        for tag, value in self.items:
 
133
            assert isinstance(value, (str, unicode))
 
134
            if value == '':
 
135
                result.append(tag + ': \n')
 
136
            elif '\n' in value:
 
137
                # don't want splitlines behaviour on empty lines
 
138
                val_lines = value.split('\n')
 
139
                result.append(tag + ': ' + val_lines[0] + '\n')
 
140
                for line in val_lines[1:]:
 
141
                    result.append('\t' + line + '\n')
 
142
            else:
 
143
                result.append(tag + ': ' + value + '\n')
 
144
        return result
 
145
 
 
146
    def to_string(self):
 
147
        """Return stanza as a single string"""
 
148
        return ''.join(self.to_lines())
 
149
 
 
150
    def write(self, to_file):
 
151
        """Write stanza to a file"""
 
152
        to_file.writelines(self.to_lines())
 
153
 
 
154
    def get(self, tag):
 
155
        """Return the value for a field wih given tag.
 
156
 
 
157
        If there is more than one value, only the first is returned.  If the
 
158
        tag is not present, KeyError is raised.
 
159
        """
 
160
        for t, v in self.items:
 
161
            if t == tag:
 
162
                return v
 
163
        else:
 
164
            raise KeyError(tag)
 
165
 
 
166
    __getitem__ = get
 
167
 
 
168
    def get_all(self, tag):
 
169
        r = []
 
170
        for t, v in self.items:
 
171
            if t == tag:
 
172
                r.append(v)
 
173
        return r
 
174
 
 
175
    def as_dict(self):
 
176
        """Return a dict containing the unique values of the stanza.
 
177
        """
 
178
        d = {}
 
179
        for tag, value in self.items:
 
180
            assert tag not in d
 
181
            d[tag] = value
 
182
        return d
 
183
         
 
184
_tag_re = re.compile(r'^[-a-zA-Z0-9_]+$')
 
185
def valid_tag(tag):
 
186
    return bool(_tag_re.match(tag))
 
187
 
 
188
 
 
189
def read_stanza(line_iter):
 
190
    """Return new Stanza read from list of lines or a file
 
191
    
 
192
    Returns one Stanza that was read, or returns None at end of file.  If a
 
193
    blank line follows the stanza, it is consumed.  It's not an error for
 
194
    there to be no blank at end of file.  If there is a blank file at the
 
195
    start of the input this is really an empty stanza and that is returned. 
 
196
 
 
197
    Only the stanza lines and the trailing blank (if any) are consumed
 
198
    from the line_iter.
 
199
    """
 
200
    items = []
 
201
    stanza = Stanza()
 
202
    tag = None
 
203
    accum_value = None
 
204
    for line in line_iter:
 
205
        if line == None or line == '':
 
206
            break       # end of file
 
207
        if line == '\n':
 
208
            break       # end of stanza
 
209
        assert line[-1] == '\n'
 
210
        real_l = line
 
211
        if line[0] == '\t': # continues previous value
 
212
            if tag is None:
 
213
                raise ValueError('invalid continuation line %r' % real_l)
 
214
            accum_value += '\n' + line[1:-1]
 
215
        else: # new tag:value line
 
216
            if tag is not None:
 
217
                stanza.add(tag, accum_value)
 
218
            try:
 
219
                colon_index = line.index(': ')
 
220
            except ValueError:
 
221
                raise ValueError('tag/value separator not found in line %r' % real_l)
 
222
            tag = line[:colon_index]
 
223
            assert valid_tag(tag), \
 
224
                    "invalid rio tag %r" % tag
 
225
            accum_value = line[colon_index+2:-1]
 
226
    if tag is not None: # add last tag-value
 
227
        stanza.add(tag, accum_value)
 
228
        return stanza
 
229
    else:     # didn't see any content
 
230
        return None