Added help.
[zeroinstall/solver.git] / policy.py
blob8cbea1056bd212072e9e90627246d2a95a61e7e4
1 from interface import Interface, Implementation
3 class Selection:
4 implementation = None # Interface -> Implementation
5 constraints = None # Path -> [Constraints]
7 def __init__(self, parent, new_implementation):
8 """Create a Selection with all the choices of parent, plus
9 implementation. If this violates a constraint, throw an exception."""
11 self.implementation = {}
13 if new_implementation is not None:
14 assert isinstance(new_implementation, Implementation)
15 assert parent is not None
17 self.implementation[new_implementation.interface] = \
18 new_implementation
19 self.implementation.update(parent.implementation)
20 else:
21 assert parent is None
23 def __getitem__(self, iface):
24 assert isinstance(iface, Interface)
25 return self.implementation[iface]
27 def __iter__(self):
28 return iter(self.implementation)
30 def setup_bindings(self):
31 """Set environment variables to run this selection."""
32 for iface in self:
33 for d in self[iface].dependancies:
34 d.setup_bindings(self)
36 class Policy:
37 def choose_best(self, interface):
38 x = self.search(Selection(None, None), interface)
39 if not x:
40 raise Exception('No possible selections found')
41 return x
43 def search(self, decided, next):
44 #print "Trying to find implementation of", next
45 if next in decided:
46 # Two programs want the same interface. Can't have two
47 # different implementations of it, so just choose the
48 # one we already selected.
49 return decided
51 # Try each possible implementation in turn and see
52 # what works...
53 for x in next.implementations:
54 new_decided = Selection(decided, x)
55 for dep in x.dependancies:
56 found = self.search(new_decided, dep.get_interface())
57 if not found:
58 # TODO: backtrack?
59 break # Nothing to meet this found
60 new_decided = found
61 else:
62 return new_decided # Everything matched
63 # No implementation was suitable
64 return None