argmap.py 8.47 KB
Newer Older
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
# Copyright 2012 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

try:
    from collections import OrderedDict
except ImportError:
37
    from kamaki.clients.commissioning.utils.ordereddict import OrderedDict
38
39
40
41
42
from itertools import chain
from cStringIO import StringIO

ARGMAP_MAGIC = '[=ARGMAP=]'

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
class arguments(object):
    __slots__ = ('args', 'kw')

    def __init__(self, *args, **kwargs):
        self.args = list(args)
        kw = OrderedDict()
        kwitems = kw.pop('kwitems', None)
        if kwitems is not None:
            kw.update(kwitems)
        kw.update(kwargs)
        self.kw = kw

    def __str__(self):
        return str(self.args) + '+' + str(self.kw)

    def __repr__(self):
        return repr(self.args) + '+' + repr(self.kw)

    def __getitem__(self, key):
        if (isinstance(key, int)
            or isinstance(key, long)
            or isinstance(key, slice)):
                return self.args[key]
        else:
            return self.kw[key]

    def __setitem__(self, key, value):
        if (isinstance(key, int)
            or isinstance(key, long)
            or isinstance(key, slice)):
                self.args[key] = value
        else:
            self.kw[key] = value

    def __delitem__(self, key):
        if (isinstance(key, int)
            or isinstance(key, long)
            or isinstance(key, slice)):
                del self.args[key]
        else:
                del self.kw[key]

    def iteritems(self):
        for item in self.args:
            yield None, item
        for k, v in self.kw:
            yield k, v

    def items(self):
        return list(self.iteritems())

    def iterkeys(self):
        return self.kw.iterkeys()

    def keys(self):
        return self.kw.keys()

    def itervalues(self):
        return chain(self.args, self.kw.itervalues())

    def values(self):
        return list(self.itervalues)

    def append(self, value):
        self.args.append(value)


def argmap_encode(obj, output):
    if obj is None:
        output('[=null]')
        return

    if isinstance(obj, basestring):
        if not obj:
            output('""')
        if isinstance(obj, unicode):
            obj = obj.encode('utf-8')
        output('"')
        start = 0
        while 1:
            end = obj.find(start) + 1
            if end < 0:
                break
            output(obj[start:end] + '"')
            start = end
        output(obj[start:])
        output('"')
        return

    if isinstance(obj, int) or isinstance(obj, long):
        output(str(obj))
        return

    if hasattr(obj, 'iteritems'):
        output('[')
        once = 1
        for k, v in obj.iteritems():
            if once:
                once = 0
            else:
                output(' ')
            if k is not None:
                argmap_encode(k)
                output('=')
            argmap_encode(v)
        output(']')

    if hasattr(obj, '__iter__'):
        output('[')
        once = 1
        for item in obj:
            if once:
                once = 0
            else:
                output(' ')
            argmap_encode(item)
        output(']')

    m = "Unsupported type '%s'" % (type(obj))
163
    m += ''
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


def argmap_decode(inputf, s=None):
    if isinstance(inputf, str):
        inputf = StringIO(inputf).read

    if s is None:
        s = inputf(1)

    while 1:
        if not s.isspace():
            break
        s = inputf(1)

    item = ''
    if s == '"':
        s = inputf(1)
        while 1:
            if s == '"':
                s = inputf(1)
                if s != '"':
                    return item, s
            item += s
            s = inputf(1)
    elif s == '[':
        item, s = argmap_decode_args(inputf)
        return item, s
    else:
        while 1:
            item += s
            s = inputf(1)
            if s in ' =]':
                return item, s


def argmap_decode_atom(inputf):
    s = inputf(4)
    if s != 'null':
        m = "Invalid atom '%s'" % (s,)
        raise ValueError(m)
    return None, None


def argmap_decode_args(inputf):
    args = []
    append = args.append
    s = inputf(1)
    key = None

    while 1:
        if s is None:
            s = inputf(1)

        if s == ']':
            if key is not None:
                append((None, key))
220
            args.append(ARGMAP_MAGIC)
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
            return args, None

        if s == '=':
            if key is None:
                atom, s = argmap_decode_atom(inputf)
                append((None, atom))
            else:
                value, s = argmap_decode(inputf)
                append((key, value))
                key = None
        elif s == ' ':
            if key is not None:
                append((None, key))
                key = None
            s = inputf(1)
        elif s == '':
            m = "EOF while scanning for ']'"
            raise ValueError(m)
        else:
            if key is not None:
                append((None, key))
            key, s = argmap_decode(inputf, s=s)


def argmap_check(obj):
    if hasattr(obj, 'keys') and callable(obj.keys):
        # this could cover both cases
        return ARGMAP_MAGIC in obj
    if hasattr(obj, '__len__'):
        length = len(obj)
251
        return length and obj[length - 1] == ARGMAP_MAGIC
252
253
    return False

254

255
256
257
258
259
260
261
262
263
264
265
266
def argmap_unzip_dict(argmap):
    if not hasattr(argmap, 'keys'):
        m = "argmap unzip dict: not a dict"
        raise TypeError(m)
    if ARGMAP_MAGIC not in argmap:
        m = "argmap unzip dict: magic not found"
        raise ValueError(m)
    args = argmap.pop(None, [])
    kw = OrderedDict(argmap)
    del kw[ARGMAP_MAGIC]
    return args, kw

267

268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
def argmap_unzip_list(argmap):
    if not argmap or argmap.pop() != ARGMAP_MAGIC:
        m = "argmap unzip list: magic not found"
        raise ValueError(m)

    args = []
    append = args.append
    kw = OrderedDict()
    for k, v in argmap:
        if k is None:
            append(v)
        else:
            kw[k] = v
    return args, kw

283

284
285
286
287
288
289
290
291
292
def argmap_unzip(argmap):
    if hasattr(argmap, 'keys'):
        return argmap_unzip_dict(argmap)
    elif hasattr(argmap, '__iter__'):
        return argmap_unzip_list(argmap)
    else:
        m = "argmap: cannot unzip type %s" % (type(argmap),)
        raise ValueError(m)

293

294
295
296
def argmap_zip_list(args, kw):
    return [(None, a) for a in args] + kw.items() + [ARGMAP_MAGIC]

297

298
299
300
301
302
303
304
305
306
def argmap_zip_dict(args, kw):
    argmap = OrderedDict()
    argmap.update(kw)
    argmap[ARGMAP_MAGIC] = ARGMAP_MAGIC
    argmap[None] = list(args) + (argmap[None] if None in argmap else [])
    return argmap

argmap_zip = argmap_zip_list

307

308
309
310
311
312
313
def argmap_list_to_dict(argmap):
    args, kw = argmap_unzip_list(argmap)
    kw[ARGMAP_MAGIC] = ARGMAP_MAGIC
    kw[None] = args
    return kw

314

315
316
317
318
def argmap_dict_to_list(argmap):
    args, kw = argmap_unzip_dict(argmap)
    return args + kw.items() + [ARGMAP_MAGIC]

319

320
321
322
323
324
325
def argmap_unpack_list(argmap):
    kw = argmap_list_to_dict(argmap)
    if len(kw) == 2:
        return kw[None]
    return kw

326

327
328
329
330
def argmap_unpack_dict(argmap):
    if hasattr(argmap, 'keys') and callable(argmap.keys):
        return argmap_dict_to_list(argmap)[:-1]
    return argmap[:-1]