-
Notifications
You must be signed in to change notification settings - Fork 162
/
sort.go
67 lines (57 loc) · 1.79 KB
/
sort.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
package pkg
import (
"errors"
"fmt"
)
// Topologically sorts an array of packages
func Sort(releasePackages []Compilable) ([]Compilable, error) {
sortedPackages := []Compilable{}
incomingEdges, outgoingEdges := getEdgeMaps(releasePackages)
noIncomingEdgesSet := []Compilable{}
for pkg, edgeList := range incomingEdges {
if len(edgeList) == 0 {
noIncomingEdgesSet = append(noIncomingEdgesSet, pkg)
}
}
for len(noIncomingEdgesSet) > 0 {
elem := noIncomingEdgesSet[0]
noIncomingEdgesSet = noIncomingEdgesSet[1:]
sortedPackages = append([]Compilable{elem}, sortedPackages...)
for _, pkg := range outgoingEdges[elem] {
incomingEdges[pkg] = removeFromList(incomingEdges[pkg], elem)
if len(incomingEdges[pkg]) == 0 {
noIncomingEdgesSet = append(noIncomingEdgesSet, pkg)
}
}
}
for _, edges := range incomingEdges {
if len(edges) > 0 {
return nil, errors.New("Circular dependency detected while sorting packages")
}
}
return sortedPackages, nil
}
func removeFromList(packageList []Compilable, pkg Compilable) []Compilable {
for idx, elem := range packageList {
if elem == pkg {
return append(packageList[:idx], packageList[idx+1:]...)
}
}
panic(fmt.Sprintf("Expected %s to be in dependency graph", pkg.Name()))
}
func getEdgeMaps(releasePackages []Compilable) (map[Compilable][]Compilable, map[Compilable][]Compilable) {
incomingEdges := make(map[Compilable][]Compilable)
outgoingEdges := make(map[Compilable][]Compilable)
for _, pkg := range releasePackages {
incomingEdges[pkg] = []Compilable{}
}
for _, pkg := range releasePackages {
if pkg.Deps() != nil {
for _, dep := range pkg.Deps() {
incomingEdges[dep] = append(incomingEdges[dep], pkg)
outgoingEdges[pkg] = append(outgoingEdges[pkg], dep)
}
}
}
return incomingEdges, outgoingEdges
}