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

Last change on this file since 2561 was 2551, checked in by broder, 15 years ago

Add an iter method to invirt.common.struct.

File size: 4.1 KB
Line 
1from __future__ import with_statement
2
3import unittest
4from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN
5import contextlib as clib
6import subprocess
7
8class InvirtConfigError(AttributeError):
9    pass
10
11class struct(object):
12    'A simple namespace object.'
13    def __init__(self, d = {}, __prefix = None, **kwargs):
14        'd is the dictionary or the items-iterable to update my __dict__ with.'
15        dct = {}
16        dct.update(d)
17        dct.update(kwargs)
18        self.__dict__.update(dct)
19        self.__keys = set(dct)
20        self.__prefix = __prefix
21    def __getattr__(self, key):
22        # XX ideally these would point a frame higher on the stack.
23        prefix = self.__prefix
24        if prefix is not None:
25            raise InvirtConfigError('missing configuration variable %s%s'
26                                    % (prefix, key))
27        else:
28            raise AttributeError("anonymous struct has no member '%s'"
29                                 % (key,))
30    def __iter__(self):
31        for i in self.__keys:
32            yield i
33
34def dicts2struct(x, prefix = None):
35    """
36    Given a tree of lists/dicts, perform a deep traversal to transform all the
37    dicts to structs.
38    """
39    if prefix is not None:
40        def newprefix(k): return prefix + str(k) + '.'
41    else:
42        def newprefix(k): return prefix
43    if type(x) == dict:
44        return struct(((k, dicts2struct(v, newprefix(k)))
45                       for k,v in x.iteritems()),
46                      prefix)
47    elif type(x) == list:
48        return [dicts2struct(v, newprefix(i)) for i, v in enumerate(x)]
49    elif x is None:
50        return struct({}, prefix)
51    else:
52        return x
53
54@clib.contextmanager
55def lock_file(path, exclusive = True):
56    with clib.closing(file(path, 'w')) as f:
57        if exclusive:
58            locktype = LOCK_EX
59        else:
60            locktype = LOCK_SH
61        flock(f, locktype)
62        try:
63            yield
64        finally:
65            flock(f, LOCK_UN)
66
67def captureOutput(popen_args, stdin_str=None, *args, **kwargs):
68    """Capture stdout from a command.
69
70    This method will proxy the arguments to subprocess.Popen. It
71    returns the output from the command if the call succeeded and
72    raises an exception if the process returns a non-0 value.
73
74    This is intended to be a variant on the subprocess.check_call
75    function that also allows you access to the output from the
76    command.
77    """
78    if 'stdin' not in kwargs:
79        kwargs['stdin'] = subprocess.PIPE
80    if 'stdout' not in kwargs:
81        kwargs['stdout'] = subprocess.PIPE
82    if 'stderr' not in kwargs:
83        kwargs['stderr'] = subprocess.STDOUT
84    p = subprocess.Popen(popen_args, *args, **kwargs)
85    out, _ = p.communicate(stdin_str)
86    if p.returncode:
87        raise subprocess.CalledProcessError(p.returncode, popen_args, out)
88    return out
89
90#
91# Exceptions.
92#
93
94class InvalidInput(Exception):
95    """Exception for user-provided input is invalid but maybe in good faith.
96
97    This would include setting memory to negative (which might be a
98    typo) but not setting an invalid boot CD (which requires bypassing
99    the select box).
100    """
101    def __init__(self, err_field, err_value, expl=None):
102        Exception.__init__(self, expl)
103        self.err_field = err_field
104        self.err_value = err_value
105
106class CodeError(Exception):
107    """Exception for internal errors or bad faith input."""
108    pass
109
110#
111# Tests.
112#
113
114class common_tests(unittest.TestCase):
115    def test_dicts2structs(self):
116        dicts = {
117                'atom': 0,
118                'dict': { 'atom': 'atom', 'list': [1,2,3] },
119                'list': [ 'atom', {'key': 'value'} ]
120                }
121        structs = dicts2struct(dicts, '')
122        self.assertEqual(structs.atom,        dicts['atom'])
123        self.assertEqual(structs.dict.atom,   dicts['dict']['atom'])
124        self.assertEqual(structs.dict.list,   dicts['dict']['list'])
125        self.assertEqual(structs.list[0],     dicts['list'][0])
126        self.assertEqual(structs.list[1].key, dicts['list'][1]['key'])
127        self.assertEqual(set(structs), set(['atom', 'dict', 'list']))
128
129if __name__ == '__main__':
130    unittest.main()
Note: See TracBrowser for help on using the repository browser.