/
dependency.go
83 lines (63 loc) · 1.61 KB
/
dependency.go
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
package plugin
import (
"fmt"
"strings"
"github.com/deckarep/golang-set"
api "github.com/dodo-cli/dodo-core/api/v1alpha3"
)
type ErrCircularDependency struct {
Dependencies map[dependency]mapset.Set
}
func (e ErrCircularDependency) Error() string {
lines := []string{"circular dependencies in plugins:"}
for dep := range e.Dependencies {
lines = append(lines, fmt.Sprintf("%s/%s", dep.t, dep.n))
}
return strings.Join(lines, "\n")
}
type dependency struct {
n string
t string
}
func asDependency(name *api.PluginName) dependency {
return dependency{n: name.Name, t: name.Type}
}
func ResolveDependencies(pluginMap map[string]map[string]Plugin) ([]Plugin, error) {
result := []Plugin{}
names := make(map[dependency]Plugin)
dependencies := make(map[dependency]mapset.Set)
for _, ps := range pluginMap {
for _, p := range ps {
info := p.PluginInfo()
if info == nil {
continue
}
deps := mapset.NewSet()
key := asDependency(info.Name)
names[key] = p
for _, dep := range info.Dependencies {
deps.Add(asDependency(dep))
}
dependencies[key] = deps
}
}
for len(dependencies) != 0 {
withoutDeps := mapset.NewSet()
for name, deps := range dependencies {
if deps.Cardinality() == 0 {
withoutDeps.Add(name)
}
}
if withoutDeps.Cardinality() == 0 {
return nil, ErrCircularDependency{Dependencies: dependencies}
}
for n := range withoutDeps.Iter() {
delete(dependencies, n.(dependency))
result = append(result, names[n.(dependency)])
}
for n, deps := range dependencies {
dependencies[n] = deps.Difference(withoutDeps)
}
}
return result, nil
}