source: trunk/packages/invirt-base/python/invirt/common.py @ 1934

Last change on this file since 1934 was 1934, checked in by price, 16 years ago

invirt.common: give clearer error message on missing config variable

File size: 3.0 KB
Line 
1from __future__ import with_statement
2
3import unittest
4from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN
5import contextlib as clib
6
7class InvirtConfigError(AttributeError):
8    pass
9
10class struct(object):
11    'A simple namespace object.'
12    def __init__(self, d = {}, __prefix = None, **kwargs):
13        'd is the dictionary or the items-iterable to update my __dict__ with.'
14        self.__dict__.update(d)
15        self.__dict__.update(kwargs)
16        self.__prefix = __prefix
17    def __getattr__(self, key):
18        # XX ideally these would point a frame higher on the stack.
19        prefix = self.__prefix
20        if prefix is not None:
21            raise InvirtConfigError('missing configuration variable %s%s'
22                                    % (prefix, key))
23        else:
24            raise AttributeError("anonymous struct has no member '%s'"
25                                 % (key,))
26
27def dicts2struct(x, prefix = None):
28    """
29    Given a tree of lists/dicts, perform a deep traversal to transform all the
30    dicts to structs.
31    """
32    if prefix is not None:
33        def newprefix(k): return prefix + str(k) + '.'
34    else:
35        def newprefix(k): return prefix
36    if type(x) == dict:
37        return struct(((k, dicts2struct(v, newprefix(k)))
38                       for k,v in x.iteritems()),
39                      prefix)
40    elif type(x) == list:
41        return [dicts2struct(v, newprefix(i)) for i, v in enumerate(x)]
42    else:
43        return x
44
45@clib.contextmanager
46def lock_file(path, exclusive = True):
47    with clib.closing(file(path, 'w')) as f:
48        if exclusive:
49            locktype = LOCK_EX
50        else:
51            locktype = LOCK_SH
52        flock(f, locktype)
53        try:
54            yield
55        finally:
56            flock(f, LOCK_UN)
57
58#
59# Exceptions.
60#
61
62class InvalidInput(Exception):
63    """Exception for user-provided input is invalid but maybe in good faith.
64
65    This would include setting memory to negative (which might be a
66    typo) but not setting an invalid boot CD (which requires bypassing
67    the select box).
68    """
69    def __init__(self, err_field, err_value, expl=None):
70        Exception.__init__(self, expl)
71        self.err_field = err_field
72        self.err_value = err_value
73
74class CodeError(Exception):
75    """Exception for internal errors or bad faith input."""
76    pass
77
78#
79# Tests.
80#
81
82class common_tests(unittest.TestCase):
83    def test_dicts2structs(self):
84        dicts = {
85                'atom': 0,
86                'dict': { 'atom': 'atom', 'list': [1,2,3] },
87                'list': [ 'atom', {'key': 'value'} ]
88                }
89        structs = dicts2struct(dicts, '')
90        self.assertEqual(structs.atom,        dicts['atom'])
91        self.assertEqual(structs.dict.atom,   dicts['dict']['atom'])
92        self.assertEqual(structs.dict.list,   dicts['dict']['list'])
93        self.assertEqual(structs.list[0],     dicts['list'][0])
94        self.assertEqual(structs.list[1].key, dicts['list'][1]['key'])
95
96if __name__ == '__main__':
97    unittest.main()
Note: See TracBrowser for help on using the repository browser.