~launchpad-results/launchpad-results/trunk

« back to all changes in this revision

Viewing changes to lib/lpresults/repository/state.py

  • Committer: Marc Tardif
  • Date: 2011-08-09 15:46:45 UTC
  • Revision ID: marc.tardif@canonical.com-20110809154645-i151emhk6onjggx5
Added hardware for systems and system units.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright 2010-2011 Canonical Ltd.  This software is licensed under the
 
2
# GNU Affero General Public License version 3 (see the file LICENSE).
 
3
 
 
4
__metaclass__ = type
 
5
 
 
6
__all__ = [
 
7
    "State",
 
8
    ]
 
9
 
 
10
 
 
11
_state_types = {}
 
12
 
 
13
 
 
14
def register_state(state):
 
15
    """Register a class to be an implementation for L{State}s.
 
16
 
 
17
    The class's C{__state_name__} must be defined as a string and
 
18
    C{__state_parent__} as a class.
 
19
    """
 
20
    if "__state_name__" not in state.__dict__:
 
21
        state.__state_name__ = ""
 
22
    if "__state_parent__" not in state.__dict__:
 
23
        state.__state_parent__ = None
 
24
 
 
25
    _state_types[state] = {}
 
26
    if state.__state_parent__ is not None:
 
27
        if state.__state_parent__ not in _state_types:
 
28
            raise RuntimeError("%r state ancestor does not exist already"
 
29
                % state.__state_parent__)
 
30
 
 
31
        if state.__state_name__ in _state_types[state.__state_parent__]:
 
32
            raise RuntimeError("%s state name already in ancestor %r"
 
33
                % (state.__state_name__, state.__state_parent__))
 
34
 
 
35
        _state_types[state.__state_parent__][state.__state_name__] = state
 
36
 
 
37
 
 
38
class StateMeta(type):
 
39
 
 
40
    def __init__(cls, name, bases, dict):
 
41
        super(StateMeta, cls).__init__(name, bases, dict)
 
42
        register_state(cls)
 
43
 
 
44
 
 
45
class State:
 
46
 
 
47
    __metaclass__ = StateMeta
 
48
 
 
49
    __slots__ = ("parent",)
 
50
 
 
51
    def __init__(self, parent=None):
 
52
        self.parent = parent
 
53
 
 
54
    @property
 
55
    def depth(self):
 
56
        depth = 0
 
57
        state = self.parent
 
58
        while state is not None:
 
59
            depth += 1
 
60
            state = state.parent
 
61
 
 
62
        return depth
 
63
 
 
64
    def getSibling(self):
 
65
        cls = self.__class__
 
66
        return cls(self.parent)
 
67
 
 
68
    def getChild(self, name=""):
 
69
        cls = self.__class__
 
70
        children = _state_types[cls]
 
71
        if not children:
 
72
            raise Exception("State has no children: %s" % cls)
 
73
 
 
74
        if name not in children:
 
75
            raise Exception("State does not have child: %s" % name)
 
76
 
 
77
        return children[name](self)
 
78
 
 
79
    def handleEntry(self, result, *args):
 
80
        pass