-
Notifications
You must be signed in to change notification settings - Fork 0
/
dependency_resolver.py
90 lines (79 loc) · 2.58 KB
/
dependency_resolver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
### Old Code
def resolve_dependencies(dependencies):
order = []
for i in dependencies:
print 'processing %s' % i
if i in order:
print '%s is in order' % i
index = order.index(i)
if dependencies[i]:
for j in dependencies[i]:
order.insert(index,j)
else:
order.insert(0,i)
else:
if dependencies[i]:
for j in dependencies[i]:
order.append(j)
order.append(i)
print order
print order
### NewCode
class Service:
def __init__(self, name):
self.name = name
self.dependencies = []
def add_dependency(self, service):
self.dependencies.append(service)
def __repr__(self):
return '{ ' + ', '.join(self.dependencies) + ' }'
def initialize_service(service):
serviceObj = Service(service)
services[service] = serviceObj
def build_dependency(service, dependency):
if service not in services:
initialize_service(service)
for i in dependency:
if i not in services:
initialize_service(i)
services[service].add_dependency(i)
def resolve(resolver):
for i in resolver:
if i not in resolved_dependencies:
for dependency in services[i].dependencies:
try:
resolve(dependency)
except Exception:
print "Circular dependency"
resolved_dependencies.append(i)
def resolve_and_print(dependencies):
for service,dependency in dependencies.iteritems():
build_dependency(service, dependency)
print services
resolve(services)
print resolved_dependencies
print ''
dependencies = { '1' : [ '2', '5'], '2' : ['5' , '3'], '3' : [], '4': ['2', '3'], '5': ['3']}
services = {}
resolved_dependencies = []
resolve_and_print(dependencies)
dependencies = { '1': ['9'], '4': ['5'], '9': [ '4' ]}
services = {}
resolved_dependencies = []
resolve_and_print(dependencies)
dependencies = { '1': ['2'], '4': ['5']}
services = {}
resolved_dependencies = []
resolve_and_print(dependencies)
dependencies = { '1': ['2'], '2' : ['3']}
services = {}
resolved_dependencies = []
resolve_and_print(dependencies)
dependencies = { '1' : [ '2', '5'], '2' : ['5' , '3']}
services = {}
resolved_dependencies = []
resolve_and_print(dependencies)
dependencies = { '1' : [ '2', '5'], '2' : ['5' , '3'], '3' : [], '5': ['8'], '4': ['5'], '9': [ '4' ]}
services = {}
resolved_dependencies = []
resolve_and_print(dependencies)