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

Last change on this file since 2904 was 2592, checked in by broder, 15 years ago

Subclass invirt.common.struct from dict, instead of rolling our own
almost-dict thing.

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